account_manager_facade_impl_unittest.cc 36 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882
  1. // Copyright 2020 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. #include "components/account_manager_core/account_manager_facade_impl.h"
  5. #include <limits>
  6. #include <memory>
  7. #include "base/callback_helpers.h"
  8. #include "base/notreached.h"
  9. #include "base/run_loop.h"
  10. #include "base/test/bind.h"
  11. #include "base/test/gmock_callback_support.h"
  12. #include "base/test/metrics/histogram_tester.h"
  13. #include "base/test/mock_callback.h"
  14. #include "base/test/task_environment.h"
  15. #include "base/time/time.h"
  16. #include "chromeos/crosapi/mojom/account_manager.mojom.h"
  17. #include "components/account_manager_core/account.h"
  18. #include "components/account_manager_core/account_addition_options.h"
  19. #include "components/account_manager_core/account_addition_result.h"
  20. #include "components/account_manager_core/account_manager_facade.h"
  21. #include "components/account_manager_core/account_manager_test_util.h"
  22. #include "components/account_manager_core/account_manager_util.h"
  23. #include "components/account_manager_core/mock_account_manager_facade.h"
  24. #include "google_apis/gaia/oauth2_access_token_consumer.h"
  25. #include "google_apis/gaia/oauth2_access_token_fetcher.h"
  26. #include "mojo/public/cpp/bindings/pending_remote.h"
  27. #include "mojo/public/cpp/bindings/receiver.h"
  28. #include "mojo/public/cpp/bindings/receiver_set.h"
  29. #include "mojo/public/cpp/bindings/remote.h"
  30. #include "mojo/public/cpp/bindings/remote_set.h"
  31. #include "testing/gmock/include/gmock/gmock.h"
  32. #include "testing/gtest/include/gtest/gtest.h"
  33. namespace account_manager {
  34. namespace {
  35. using base::MockOnceCallback;
  36. using ::testing::_;
  37. using ::testing::Eq;
  38. using ::testing::Field;
  39. using ::testing::Invoke;
  40. using ::testing::WithArgs;
  41. constexpr char kTestAccountEmail[] = "test@gmail.com";
  42. constexpr char kAnotherTestAccountEmail[] = "another_test@gmail.com";
  43. constexpr char kFakeClientId[] = "fake-client-id";
  44. constexpr char kFakeClientSecret[] = "fake-client-secret";
  45. constexpr char kFakeAccessToken[] = "fake-access-token";
  46. constexpr char kFakeIdToken[] = "fake-id-token";
  47. constexpr char kMojoDisconnectionsAccountManagerRemote[] =
  48. "AccountManager.MojoDisconnections.AccountManagerRemote";
  49. constexpr char kMojoDisconnectionsAccountManagerObserverReceiver[] =
  50. "AccountManager.MojoDisconnections.AccountManagerObserverReceiver";
  51. constexpr char kMojoDisconnectionsAccountManagerAccessTokenFetcherRemote[] =
  52. "AccountManager.MojoDisconnections.AccessTokenFetcherRemote";
  53. void AccessTokenFetchSuccess(
  54. base::OnceCallback<void(crosapi::mojom::AccessTokenResultPtr)> callback) {
  55. crosapi::mojom::AccessTokenInfoPtr access_token_info =
  56. crosapi::mojom::AccessTokenInfo::New(kFakeAccessToken, base::Time::Now(),
  57. kFakeIdToken);
  58. crosapi::mojom::AccessTokenResultPtr result =
  59. crosapi::mojom::AccessTokenResult::NewAccessTokenInfo(
  60. std::move(access_token_info));
  61. std::move(callback).Run(std::move(result));
  62. }
  63. void AccessTokenFetchServiceError(
  64. base::OnceCallback<void(crosapi::mojom::AccessTokenResultPtr)> callback) {
  65. crosapi::mojom::AccessTokenResultPtr result =
  66. crosapi::mojom::AccessTokenResult::NewError(
  67. account_manager::ToMojoGoogleServiceAuthError(
  68. GoogleServiceAuthError(GoogleServiceAuthError::SERVICE_ERROR)));
  69. std::move(callback).Run(std::move(result));
  70. }
  71. class MockAccessTokenFetcher : public crosapi::mojom::AccessTokenFetcher {
  72. public:
  73. MockAccessTokenFetcher() : receiver_(this) {}
  74. MockAccessTokenFetcher(const MockAccessTokenFetcher&) = delete;
  75. MockAccessTokenFetcher& operator=(const MockAccessTokenFetcher&) = delete;
  76. ~MockAccessTokenFetcher() override = default;
  77. void Bind(
  78. mojo::PendingReceiver<crosapi::mojom::AccessTokenFetcher> receiver) {
  79. receiver_.Bind(std::move(receiver));
  80. }
  81. void ResetReceiver() { receiver_.reset(); }
  82. // crosapi::mojom::AccessTokenFetcher override.
  83. MOCK_METHOD(void,
  84. Start,
  85. (const std::vector<std::string>& scopes, StartCallback callback),
  86. (override));
  87. private:
  88. mojo::Receiver<crosapi::mojom::AccessTokenFetcher> receiver_;
  89. };
  90. class MockOAuthConsumer : public OAuth2AccessTokenConsumer {
  91. public:
  92. MockOAuthConsumer() = default;
  93. MockOAuthConsumer(const MockOAuthConsumer&) = delete;
  94. MockOAuthConsumer& operator=(const MockOAuthConsumer&) = delete;
  95. ~MockOAuthConsumer() override = default;
  96. // OAuth2AccessTokenConsumer overrides.
  97. MOCK_METHOD(void,
  98. OnGetTokenSuccess,
  99. (const TokenResponse& token_response),
  100. (override));
  101. MOCK_METHOD(void,
  102. OnGetTokenFailure,
  103. (const GoogleServiceAuthError& error),
  104. (override));
  105. std::string GetConsumerName() const override {
  106. return "account_manager_facade_impl_unittest";
  107. }
  108. };
  109. class FakeAccountManager : public crosapi::mojom::AccountManager {
  110. public:
  111. FakeAccountManager() = default;
  112. FakeAccountManager(const FakeAccountManager&) = delete;
  113. FakeAccountManager& operator=(const FakeAccountManager&) = delete;
  114. ~FakeAccountManager() override = default;
  115. void IsInitialized(IsInitializedCallback cb) override {
  116. std::move(cb).Run(is_initialized_);
  117. }
  118. void SetIsInitialized(bool is_initialized) {
  119. is_initialized_ = is_initialized;
  120. }
  121. void AddObserver(AddObserverCallback cb) override {
  122. mojo::Remote<crosapi::mojom::AccountManagerObserver> observer;
  123. std::move(cb).Run(observer.BindNewPipeAndPassReceiver());
  124. observers_.Add(std::move(observer));
  125. }
  126. void GetAccounts(GetAccountsCallback callback) override {
  127. std::vector<crosapi::mojom::AccountPtr> mojo_accounts;
  128. std::transform(std::begin(accounts_), std::end(accounts_),
  129. std::back_inserter(mojo_accounts), &ToMojoAccount);
  130. std::move(callback).Run(std::move(mojo_accounts));
  131. }
  132. void GetPersistentErrorForAccount(
  133. crosapi::mojom::AccountKeyPtr mojo_account_key,
  134. GetPersistentErrorForAccountCallback callback) override {
  135. absl::optional<AccountKey> account_key =
  136. FromMojoAccountKey(mojo_account_key);
  137. DCHECK(account_key.has_value());
  138. auto it = persistent_errors_.find(account_key.value());
  139. if (it != persistent_errors_.end()) {
  140. std::move(callback).Run(ToMojoGoogleServiceAuthError(it->second));
  141. return;
  142. }
  143. std::move(callback).Run(
  144. ToMojoGoogleServiceAuthError(GoogleServiceAuthError::AuthErrorNone()));
  145. }
  146. void ShowAddAccountDialog(crosapi::mojom::AccountAdditionOptionsPtr options,
  147. ShowAddAccountDialogCallback callback) override {
  148. show_add_account_dialog_calls_++;
  149. show_add_account_dialog_options_ = FromMojoAccountAdditionOptions(options);
  150. std::move(callback).Run(
  151. account_manager::ToMojoAccountAdditionResult(*add_account_result_));
  152. }
  153. void ShowReauthAccountDialog(const std::string& email,
  154. base::OnceClosure closure) override {
  155. show_reauth_account_dialog_calls_++;
  156. std::move(closure).Run();
  157. }
  158. void ShowManageAccountsSettings() override {
  159. show_manage_accounts_settings_calls_++;
  160. }
  161. void SetMockAccessTokenFetcher(
  162. std::unique_ptr<MockAccessTokenFetcher> mock_access_token_fetcher) {
  163. access_token_fetcher_ = std::move(mock_access_token_fetcher);
  164. }
  165. void CreateAccessTokenFetcher(
  166. crosapi::mojom::AccountKeyPtr mojo_account_key,
  167. const std::string& oauth_consumer_name,
  168. CreateAccessTokenFetcherCallback callback) override {
  169. if (!access_token_fetcher_)
  170. access_token_fetcher_ = std::make_unique<MockAccessTokenFetcher>();
  171. mojo::PendingRemote<crosapi::mojom::AccessTokenFetcher> pending_remote;
  172. access_token_fetcher_->Bind(
  173. pending_remote.InitWithNewPipeAndPassReceiver());
  174. std::move(callback).Run(std::move(pending_remote));
  175. }
  176. void ReportAuthError(
  177. crosapi::mojom::AccountKeyPtr account,
  178. crosapi::mojom::GoogleServiceAuthErrorPtr error) override {
  179. NOTIMPLEMENTED();
  180. }
  181. mojo::Remote<crosapi::mojom::AccountManager> CreateRemote() {
  182. mojo::Remote<crosapi::mojom::AccountManager> remote;
  183. receivers_.Add(this, remote.BindNewPipeAndPassReceiver());
  184. return remote;
  185. }
  186. void NotifyOnTokenUpsertedObservers(const Account& account) {
  187. for (auto& observer : observers_) {
  188. observer->OnTokenUpserted(ToMojoAccount(account));
  189. }
  190. }
  191. void NotifyOnAccountRemovedObservers(const Account& account) {
  192. for (auto& observer : observers_) {
  193. observer->OnAccountRemoved(ToMojoAccount(account));
  194. }
  195. }
  196. void SetAccounts(const std::vector<Account>& accounts) {
  197. accounts_ = accounts;
  198. }
  199. void SetPersistentErrorForAccount(const AccountKey& account,
  200. GoogleServiceAuthError error) {
  201. persistent_errors_.emplace(account, error);
  202. }
  203. void SetAccountAdditionResult(
  204. const account_manager::AccountAdditionResult& result) {
  205. add_account_result_ = std::make_unique<AccountAdditionResult>(result);
  206. }
  207. void ClearReceivers() { receivers_.Clear(); }
  208. void ClearObservers() { observers_.Clear(); }
  209. int show_add_account_dialog_calls() const {
  210. return show_add_account_dialog_calls_;
  211. }
  212. absl::optional<account_manager::AccountAdditionOptions>
  213. show_add_account_dialog_options() const {
  214. return show_add_account_dialog_options_;
  215. }
  216. int show_reauth_account_dialog_calls() const {
  217. return show_reauth_account_dialog_calls_;
  218. }
  219. int show_manage_accounts_settings_calls() const {
  220. return show_manage_accounts_settings_calls_;
  221. }
  222. private:
  223. int show_add_account_dialog_calls_ = 0;
  224. absl::optional<account_manager::AccountAdditionOptions>
  225. show_add_account_dialog_options_;
  226. int show_reauth_account_dialog_calls_ = 0;
  227. int show_manage_accounts_settings_calls_ = 0;
  228. bool is_initialized_ = false;
  229. std::vector<Account> accounts_;
  230. std::map<AccountKey, GoogleServiceAuthError> persistent_errors_;
  231. std::unique_ptr<AccountAdditionResult> add_account_result_;
  232. std::unique_ptr<MockAccessTokenFetcher> access_token_fetcher_;
  233. mojo::ReceiverSet<crosapi::mojom::AccountManager> receivers_;
  234. mojo::RemoteSet<crosapi::mojom::AccountManagerObserver> observers_;
  235. };
  236. MATCHER_P(AccountEq, expected_account, "") {
  237. return testing::ExplainMatchResult(
  238. testing::Field(&Account::key, testing::Eq(expected_account.key)),
  239. arg, result_listener) &&
  240. testing::ExplainMatchResult(
  241. testing::Field(&Account::raw_email,
  242. testing::StrEq(expected_account.raw_email)),
  243. arg, result_listener);
  244. }
  245. } // namespace
  246. class AccountManagerFacadeImplTest : public testing::Test {
  247. public:
  248. AccountManagerFacadeImplTest() = default;
  249. AccountManagerFacadeImplTest(const AccountManagerFacadeImplTest&) = delete;
  250. AccountManagerFacadeImplTest& operator=(const AccountManagerFacadeImplTest&) =
  251. delete;
  252. ~AccountManagerFacadeImplTest() override = default;
  253. protected:
  254. FakeAccountManager& account_manager() { return account_manager_; }
  255. base::HistogramTester& histogram_tester() { return histogram_tester_; }
  256. std::unique_ptr<AccountManagerFacadeImpl> CreateFacade() {
  257. base::RunLoop run_loop;
  258. auto result = std::make_unique<AccountManagerFacadeImpl>(
  259. account_manager().CreateRemote(),
  260. /*remote_version=*/std::numeric_limits<uint32_t>::max(),
  261. /*account_manager_for_tests=*/nullptr, run_loop.QuitClosure());
  262. run_loop.Run();
  263. return result;
  264. }
  265. private:
  266. base::test::SingleThreadTaskEnvironment task_environment_;
  267. FakeAccountManager account_manager_;
  268. base::HistogramTester histogram_tester_;
  269. };
  270. TEST_F(AccountManagerFacadeImplTest, InitializationStatusIsCorrectlySet) {
  271. // This will wait for an initialization callback to be called.
  272. std::unique_ptr<AccountManagerFacadeImpl> account_manager_facade =
  273. CreateFacade();
  274. EXPECT_TRUE(account_manager_facade->IsInitialized());
  275. }
  276. TEST_F(AccountManagerFacadeImplTest, OnTokenUpsertedIsPropagatedToObservers) {
  277. std::unique_ptr<AccountManagerFacadeImpl> account_manager_facade =
  278. CreateFacade();
  279. testing::StrictMock<MockAccountManagerFacadeObserver> observer;
  280. account_manager_facade->AddObserver(&observer);
  281. Account account = CreateTestGaiaAccount(kTestAccountEmail);
  282. base::RunLoop run_loop;
  283. EXPECT_CALL(observer, OnAccountUpserted(AccountEq(account)))
  284. .WillOnce(base::test::RunClosure(run_loop.QuitClosure()));
  285. account_manager().NotifyOnTokenUpsertedObservers(account);
  286. run_loop.Run();
  287. }
  288. TEST_F(AccountManagerFacadeImplTest, OnAccountRemovedIsPropagatedToObservers) {
  289. std::unique_ptr<AccountManagerFacadeImpl> account_manager_facade =
  290. CreateFacade();
  291. testing::StrictMock<MockAccountManagerFacadeObserver> observer;
  292. account_manager_facade->AddObserver(&observer);
  293. Account account = CreateTestGaiaAccount(kTestAccountEmail);
  294. base::RunLoop run_loop;
  295. EXPECT_CALL(observer, OnAccountRemoved(AccountEq(account)))
  296. .WillOnce(base::test::RunClosure(run_loop.QuitClosure()));
  297. account_manager().NotifyOnAccountRemovedObservers(account);
  298. run_loop.Run();
  299. }
  300. TEST_F(
  301. AccountManagerFacadeImplTest,
  302. GetAccountsReturnsEmptyListOfAccountsWhenAccountManagerMojoServiceIsEmpty) {
  303. std::unique_ptr<AccountManagerFacadeImpl> account_manager_facade =
  304. CreateFacade();
  305. account_manager().SetAccounts({});
  306. MockOnceCallback<void(const std::vector<Account>&)> callback;
  307. base::RunLoop run_loop;
  308. EXPECT_CALL(callback, Run(testing::IsEmpty()))
  309. .WillOnce(base::test::RunClosure(run_loop.QuitClosure()));
  310. account_manager_facade->GetAccounts(callback.Get());
  311. run_loop.Run();
  312. }
  313. TEST_F(AccountManagerFacadeImplTest, GetAccountsCorrectlyMarshalsTwoAccounts) {
  314. std::unique_ptr<AccountManagerFacadeImpl> account_manager_facade =
  315. CreateFacade();
  316. Account account1 = CreateTestGaiaAccount(kTestAccountEmail);
  317. Account account2 = CreateTestGaiaAccount(kAnotherTestAccountEmail);
  318. account_manager().SetAccounts({account1, account2});
  319. MockOnceCallback<void(const std::vector<Account>&)> callback;
  320. base::RunLoop run_loop;
  321. EXPECT_CALL(callback, Run(testing::ElementsAre(AccountEq(account1),
  322. AccountEq(account2))))
  323. .WillOnce(base::test::RunClosure(run_loop.QuitClosure()));
  324. account_manager_facade->GetAccounts(callback.Get());
  325. run_loop.Run();
  326. }
  327. TEST_F(AccountManagerFacadeImplTest,
  328. GetAccountsIsSafeToCallBeforeAccountManagerFacadeIsInitialized) {
  329. Account account = CreateTestGaiaAccount(kTestAccountEmail);
  330. account_manager().SetAccounts({account});
  331. // |CreateFacade| waits for the AccountManagerFacadeImpl's initialization
  332. // sequence to be finished. To avoid this, create it directly here.
  333. auto account_manager_facade = std::make_unique<AccountManagerFacadeImpl>(
  334. account_manager().CreateRemote(),
  335. /*remote_version=*/std::numeric_limits<uint32_t>::max(),
  336. /*account_manager_for_tests=*/nullptr);
  337. MockOnceCallback<void(const std::vector<Account>&)> callback;
  338. base::RunLoop run_loop;
  339. EXPECT_CALL(callback, Run(testing::ElementsAre(AccountEq(account))))
  340. .WillOnce(base::test::RunClosure(run_loop.QuitClosure()));
  341. account_manager_facade->GetAccounts(callback.Get());
  342. run_loop.Run();
  343. }
  344. // Regression test for https://crbug.com/1287297
  345. // Do not return empty accounts when the remote is not available.
  346. TEST_F(AccountManagerFacadeImplTest, GetAccountsHangsWhenRemoteIsNull) {
  347. base::HistogramTester tester;
  348. auto account_manager_facade = std::make_unique<AccountManagerFacadeImpl>(
  349. mojo::Remote<crosapi::mojom::AccountManager>(),
  350. /*remote_version=*/std::numeric_limits<uint32_t>::max(),
  351. /*account_manager_for_tests=*/nullptr);
  352. bool callback_was_dropped = false;
  353. // scoped_closure that sets `callback_was_dropped` when it is destroyed.
  354. base::ScopedClosureRunner scoped_closure(base::BindLambdaForTesting(
  355. [&callback_was_dropped]() { callback_was_dropped = true; }));
  356. // Pass ownership of the scoped closure to the main callback, so that the
  357. // scoped closure is run when the callback is destroyed.
  358. // This callback should not be run.
  359. base::OnceCallback<void(const std::vector<Account>&)> dropped_callback =
  360. base::BindLambdaForTesting(
  361. [scoped_closure = std::move(scoped_closure)](
  362. const std::vector<Account>&) { NOTREACHED(); });
  363. EXPECT_FALSE(callback_was_dropped);
  364. account_manager_facade->GetAccounts(std::move(dropped_callback));
  365. // `dropped_callback` was destroyed without being run.
  366. EXPECT_TRUE(callback_was_dropped);
  367. tester.ExpectUniqueSample(
  368. AccountManagerFacadeImpl::GetAccountsMojoStatusHistogramNameForTesting(),
  369. /*sample=*/AccountManagerFacadeImpl::FacadeMojoStatus::kNoRemote,
  370. /*expected_count=*/1);
  371. }
  372. TEST_F(AccountManagerFacadeImplTest, GetPersistentErrorMarshalsAuthErrorNone) {
  373. std::unique_ptr<AccountManagerFacadeImpl> account_manager_facade =
  374. CreateFacade();
  375. Account account = CreateTestGaiaAccount(kTestAccountEmail);
  376. MockOnceCallback<void(const GoogleServiceAuthError&)> callback;
  377. base::RunLoop run_loop;
  378. EXPECT_CALL(callback, Run(GoogleServiceAuthError::AuthErrorNone()))
  379. .WillOnce(base::test::RunClosure(run_loop.QuitClosure()));
  380. account_manager_facade->GetPersistentErrorForAccount(account.key,
  381. callback.Get());
  382. run_loop.Run();
  383. }
  384. TEST_F(AccountManagerFacadeImplTest,
  385. GetPersistentErrorMarshalsCredentialsRejectedByClient) {
  386. std::unique_ptr<AccountManagerFacadeImpl> account_manager_facade =
  387. CreateFacade();
  388. Account account = CreateTestGaiaAccount(kTestAccountEmail);
  389. GoogleServiceAuthError error =
  390. GoogleServiceAuthError::FromInvalidGaiaCredentialsReason(
  391. GoogleServiceAuthError::InvalidGaiaCredentialsReason::
  392. CREDENTIALS_REJECTED_BY_CLIENT);
  393. account_manager().SetPersistentErrorForAccount(account.key, error);
  394. MockOnceCallback<void(const GoogleServiceAuthError&)> callback;
  395. base::RunLoop run_loop;
  396. EXPECT_CALL(callback, Run(error))
  397. .WillOnce(base::test::RunClosure(run_loop.QuitClosure()));
  398. account_manager_facade->GetPersistentErrorForAccount(account.key,
  399. callback.Get());
  400. run_loop.Run();
  401. }
  402. TEST_F(AccountManagerFacadeImplTest, ShowAddAccountDialogCallsMojo) {
  403. std::unique_ptr<AccountManagerFacadeImpl> account_manager_facade =
  404. CreateFacade();
  405. account_manager().SetAccountAdditionResult(
  406. account_manager::AccountAdditionResult::FromStatus(
  407. account_manager::AccountAdditionResult::Status::kUnexpectedResponse));
  408. EXPECT_EQ(0, account_manager().show_add_account_dialog_calls());
  409. account_manager_facade->ShowAddAccountDialog(
  410. account_manager::AccountManagerFacade::AccountAdditionSource::
  411. kSettingsAddAccountButton);
  412. account_manager_facade->FlushMojoForTesting();
  413. EXPECT_EQ(1, account_manager().show_add_account_dialog_calls());
  414. }
  415. TEST_F(AccountManagerFacadeImplTest,
  416. ShowAddAccountDialogSetsCorrectOptionsForAdditionFromAsh) {
  417. std::unique_ptr<AccountManagerFacadeImpl> account_manager_facade =
  418. CreateFacade();
  419. account_manager().SetAccountAdditionResult(
  420. account_manager::AccountAdditionResult::FromStatus(
  421. account_manager::AccountAdditionResult::Status::kUnexpectedResponse));
  422. EXPECT_EQ(0, account_manager().show_add_account_dialog_calls());
  423. account_manager_facade->ShowAddAccountDialog(
  424. account_manager::AccountManagerFacade::AccountAdditionSource::
  425. kSettingsAddAccountButton);
  426. account_manager_facade->FlushMojoForTesting();
  427. EXPECT_EQ(1, account_manager().show_add_account_dialog_calls());
  428. EXPECT_TRUE(account_manager().show_add_account_dialog_options().has_value());
  429. EXPECT_TRUE(
  430. account_manager().show_add_account_dialog_options()->is_available_in_arc);
  431. EXPECT_FALSE(account_manager()
  432. .show_add_account_dialog_options()
  433. ->show_arc_availability_picker);
  434. }
  435. TEST_F(AccountManagerFacadeImplTest,
  436. ShowAddAccountDialogSetsCorrectOptionsForAdditionFromLacros) {
  437. std::unique_ptr<AccountManagerFacadeImpl> account_manager_facade =
  438. CreateFacade();
  439. account_manager().SetAccountAdditionResult(
  440. account_manager::AccountAdditionResult::FromStatus(
  441. account_manager::AccountAdditionResult::Status::kUnexpectedResponse));
  442. EXPECT_EQ(0, account_manager().show_add_account_dialog_calls());
  443. account_manager_facade->ShowAddAccountDialog(
  444. account_manager::AccountManagerFacade::AccountAdditionSource::
  445. kOgbAddAccount);
  446. account_manager_facade->FlushMojoForTesting();
  447. EXPECT_EQ(1, account_manager().show_add_account_dialog_calls());
  448. EXPECT_TRUE(account_manager().show_add_account_dialog_options().has_value());
  449. EXPECT_FALSE(
  450. account_manager().show_add_account_dialog_options()->is_available_in_arc);
  451. EXPECT_FALSE(account_manager()
  452. .show_add_account_dialog_options()
  453. ->show_arc_availability_picker);
  454. }
  455. TEST_F(AccountManagerFacadeImplTest,
  456. ShowAddAccountDialogSetsCorrectOptionsForAdditionFromArc) {
  457. std::unique_ptr<AccountManagerFacadeImpl> account_manager_facade =
  458. CreateFacade();
  459. account_manager().SetAccountAdditionResult(
  460. account_manager::AccountAdditionResult::FromStatus(
  461. account_manager::AccountAdditionResult::Status::kUnexpectedResponse));
  462. EXPECT_EQ(0, account_manager().show_add_account_dialog_calls());
  463. account_manager_facade->ShowAddAccountDialog(
  464. account_manager::AccountManagerFacade::AccountAdditionSource::kArc);
  465. account_manager_facade->FlushMojoForTesting();
  466. EXPECT_EQ(1, account_manager().show_add_account_dialog_calls());
  467. EXPECT_TRUE(account_manager().show_add_account_dialog_options().has_value());
  468. EXPECT_TRUE(
  469. account_manager().show_add_account_dialog_options()->is_available_in_arc);
  470. EXPECT_TRUE(account_manager()
  471. .show_add_account_dialog_options()
  472. ->show_arc_availability_picker);
  473. }
  474. TEST_F(AccountManagerFacadeImplTest, ShowAddAccountDialogUMA) {
  475. base::HistogramTester tester;
  476. std::unique_ptr<AccountManagerFacadeImpl> account_manager_facade =
  477. CreateFacade();
  478. auto result = account_manager::AccountAdditionResult::FromStatus(
  479. account_manager::AccountAdditionResult::Status::kAlreadyInProgress);
  480. account_manager().SetAccountAdditionResult(result);
  481. auto source = account_manager::AccountManagerFacade::AccountAdditionSource::
  482. kSettingsAddAccountButton;
  483. account_manager_facade->ShowAddAccountDialog(source);
  484. account_manager_facade->FlushMojoForTesting();
  485. // Check that UMA stats were sent.
  486. tester.ExpectUniqueSample(
  487. account_manager::AccountManagerFacade::kAccountAdditionSource,
  488. /*sample=*/source, /*expected_count=*/1);
  489. tester.ExpectUniqueSample(
  490. AccountManagerFacadeImpl::
  491. GetAccountAdditionResultStatusHistogramNameForTesting(),
  492. /*sample=*/result.status(), /*expected_count=*/1);
  493. }
  494. TEST_F(AccountManagerFacadeImplTest, ShowReauthAccountDialogCallsMojo) {
  495. std::unique_ptr<AccountManagerFacadeImpl> account_manager_facade =
  496. CreateFacade();
  497. EXPECT_EQ(0, account_manager().show_reauth_account_dialog_calls());
  498. account_manager_facade->ShowReauthAccountDialog(
  499. account_manager::AccountManagerFacade::AccountAdditionSource::
  500. kSettingsAddAccountButton,
  501. kTestAccountEmail, base::OnceClosure());
  502. account_manager_facade->FlushMojoForTesting();
  503. EXPECT_EQ(1, account_manager().show_reauth_account_dialog_calls());
  504. }
  505. TEST_F(AccountManagerFacadeImplTest, ShowReauthAccountDialogUMA) {
  506. base::HistogramTester tester;
  507. std::unique_ptr<AccountManagerFacadeImpl> account_manager_facade =
  508. CreateFacade();
  509. auto source = AccountManagerFacade::AccountAdditionSource::kContentAreaReauth;
  510. account_manager_facade->ShowReauthAccountDialog(source, kTestAccountEmail,
  511. base::OnceClosure());
  512. account_manager_facade->FlushMojoForTesting();
  513. // Check that UMA stats were sent.
  514. tester.ExpectUniqueSample(AccountManagerFacade::kAccountAdditionSource,
  515. /*sample=*/source, /*expected_count=*/1);
  516. }
  517. TEST_F(AccountManagerFacadeImplTest, ShowManageAccountsSettingsCallsMojo) {
  518. std::unique_ptr<AccountManagerFacadeImpl> account_manager_facade =
  519. CreateFacade();
  520. EXPECT_EQ(0, account_manager().show_manage_accounts_settings_calls());
  521. account_manager_facade->ShowManageAccountsSettings();
  522. account_manager_facade->FlushMojoForTesting();
  523. EXPECT_EQ(1, account_manager().show_manage_accounts_settings_calls());
  524. }
  525. TEST_F(AccountManagerFacadeImplTest,
  526. AccessTokenFetcherReturnsAnErrorForUninitializedRemote) {
  527. auto account_manager_facade = std::make_unique<AccountManagerFacadeImpl>(
  528. mojo::Remote<crosapi::mojom::AccountManager>(),
  529. /*remote_version=*/std::numeric_limits<uint32_t>::max(),
  530. /*account_manager_for_tests=*/nullptr);
  531. const Account account = CreateTestGaiaAccount(kTestAccountEmail);
  532. MockOAuthConsumer consumer;
  533. GoogleServiceAuthError error =
  534. GoogleServiceAuthError::FromServiceError("Mojo pipe disconnected");
  535. EXPECT_CALL(consumer, OnGetTokenFailure(Eq(error)));
  536. std::unique_ptr<OAuth2AccessTokenFetcher> access_token_fetcher =
  537. account_manager_facade->CreateAccessTokenFetcher(account.key, &consumer);
  538. access_token_fetcher->Start(kFakeClientId, kFakeClientSecret, /*scopes=*/{});
  539. base::RunLoop().RunUntilIdle();
  540. }
  541. TEST_F(AccountManagerFacadeImplTest,
  542. AccessTokenFetcherCanBeCreatedBeforeAccountManagerFacadeInitialization) {
  543. auto account_manager_facade = std::make_unique<AccountManagerFacadeImpl>(
  544. account_manager().CreateRemote(),
  545. /*remote_version=*/std::numeric_limits<uint32_t>::max(),
  546. /*account_manager_for_tests=*/nullptr);
  547. const Account account = CreateTestGaiaAccount(kTestAccountEmail);
  548. auto mock_access_token_fetcher = std::make_unique<MockAccessTokenFetcher>();
  549. EXPECT_CALL(*mock_access_token_fetcher.get(), Start(_, _))
  550. .WillOnce(WithArgs<1>(Invoke(&AccessTokenFetchSuccess)));
  551. account_manager().SetMockAccessTokenFetcher(
  552. std::move(mock_access_token_fetcher));
  553. MockOAuthConsumer consumer;
  554. std::unique_ptr<OAuth2AccessTokenFetcher> access_token_fetcher =
  555. account_manager_facade->CreateAccessTokenFetcher(account.key, &consumer);
  556. EXPECT_FALSE(account_manager_facade->IsInitialized());
  557. access_token_fetcher->Start(kFakeClientId, kFakeClientSecret, /*scopes=*/{});
  558. EXPECT_CALL(consumer,
  559. OnGetTokenSuccess(
  560. Field(&OAuth2AccessTokenConsumer::TokenResponse::access_token,
  561. Eq(kFakeAccessToken))));
  562. base::RunLoop().RunUntilIdle();
  563. EXPECT_TRUE(account_manager_facade->IsInitialized());
  564. }
  565. TEST_F(AccountManagerFacadeImplTest,
  566. AccessTokenFetcherCanHandleMojoRemoteDisconnection) {
  567. account_manager().SetIsInitialized(true);
  568. std::unique_ptr<AccountManagerFacadeImpl> account_manager_facade =
  569. CreateFacade();
  570. const Account account = CreateTestGaiaAccount(kTestAccountEmail);
  571. MockOAuthConsumer consumer;
  572. GoogleServiceAuthError error =
  573. GoogleServiceAuthError::FromServiceError("Mojo pipe disconnected");
  574. EXPECT_CALL(consumer, OnGetTokenFailure(Eq(error)));
  575. std::unique_ptr<OAuth2AccessTokenFetcher> access_token_fetcher =
  576. account_manager_facade->CreateAccessTokenFetcher(account.key, &consumer);
  577. access_token_fetcher->Start(kFakeClientId, kFakeClientSecret, /*scopes=*/{});
  578. account_manager().ClearReceivers();
  579. base::RunLoop().RunUntilIdle();
  580. }
  581. TEST_F(AccountManagerFacadeImplTest, AccessTokenFetchSucceeds) {
  582. account_manager().SetIsInitialized(true);
  583. std::unique_ptr<AccountManagerFacadeImpl> account_manager_facade =
  584. CreateFacade();
  585. const Account account = CreateTestGaiaAccount(kTestAccountEmail);
  586. auto mock_access_token_fetcher = std::make_unique<MockAccessTokenFetcher>();
  587. EXPECT_CALL(*mock_access_token_fetcher.get(), Start(_, _))
  588. .WillOnce(WithArgs<1>(Invoke(&AccessTokenFetchSuccess)));
  589. account_manager().SetMockAccessTokenFetcher(
  590. std::move(mock_access_token_fetcher));
  591. MockOAuthConsumer consumer;
  592. EXPECT_CALL(consumer,
  593. OnGetTokenSuccess(
  594. Field(&OAuth2AccessTokenConsumer::TokenResponse::access_token,
  595. Eq(kFakeAccessToken))));
  596. std::unique_ptr<OAuth2AccessTokenFetcher> access_token_fetcher =
  597. account_manager_facade->CreateAccessTokenFetcher(account.key, &consumer);
  598. access_token_fetcher->Start(kFakeClientId, kFakeClientSecret, /*scopes=*/{});
  599. base::RunLoop().RunUntilIdle();
  600. }
  601. TEST_F(AccountManagerFacadeImplTest, AccessTokenFetchErrorResponse) {
  602. account_manager().SetIsInitialized(true);
  603. std::unique_ptr<AccountManagerFacadeImpl> account_manager_facade =
  604. CreateFacade();
  605. const Account account = CreateTestGaiaAccount(kTestAccountEmail);
  606. auto mock_access_token_fetcher = std::make_unique<MockAccessTokenFetcher>();
  607. EXPECT_CALL(*mock_access_token_fetcher.get(), Start(_, _))
  608. .WillOnce(WithArgs<1>(Invoke(&AccessTokenFetchServiceError)));
  609. account_manager().SetMockAccessTokenFetcher(
  610. std::move(mock_access_token_fetcher));
  611. MockOAuthConsumer consumer;
  612. GoogleServiceAuthError error(GoogleServiceAuthError::SERVICE_ERROR);
  613. EXPECT_CALL(consumer, OnGetTokenFailure(Eq(error)));
  614. std::unique_ptr<OAuth2AccessTokenFetcher> access_token_fetcher =
  615. account_manager_facade->CreateAccessTokenFetcher(account.key, &consumer);
  616. access_token_fetcher->Start(kFakeClientId, kFakeClientSecret, /*scopes=*/{});
  617. base::RunLoop().RunUntilIdle();
  618. }
  619. TEST_F(AccountManagerFacadeImplTest,
  620. HistogramsForZeroAccountManagerRemoteDisconnections) {
  621. account_manager().SetIsInitialized(true);
  622. std::unique_ptr<AccountManagerFacadeImpl> account_manager_facade =
  623. CreateFacade();
  624. // Expect 0 disconnections in the default state.
  625. EXPECT_EQ(0, histogram_tester().GetTotalSum(
  626. kMojoDisconnectionsAccountManagerRemote));
  627. // Reset the facade so that histograms get logged.
  628. account_manager_facade->FlushMojoForTesting();
  629. account_manager_facade.reset();
  630. // Expect 1 log - at the end of `account_manager_facade` destruction.
  631. histogram_tester().ExpectTotalCount(kMojoDisconnectionsAccountManagerRemote,
  632. 1);
  633. // Expect 0 disconnections.
  634. EXPECT_EQ(0, histogram_tester().GetTotalSum(
  635. kMojoDisconnectionsAccountManagerRemote));
  636. }
  637. TEST_F(AccountManagerFacadeImplTest,
  638. HistogramsForAccountManagerRemoteDisconnection) {
  639. account_manager().SetIsInitialized(true);
  640. std::unique_ptr<AccountManagerFacadeImpl> account_manager_facade =
  641. CreateFacade();
  642. // Expect 0 disconnections in the default state.
  643. EXPECT_EQ(0, histogram_tester().GetTotalSum(
  644. kMojoDisconnectionsAccountManagerRemote));
  645. // Simulate a disconnection.
  646. account_manager().ClearReceivers();
  647. // And reset the facade so that histograms get logged.
  648. account_manager_facade->FlushMojoForTesting();
  649. account_manager_facade.reset();
  650. // Expect 1 log - at the end of `account_manager_facade` destruction.
  651. histogram_tester().ExpectTotalCount(kMojoDisconnectionsAccountManagerRemote,
  652. 1);
  653. // Expect 1 disconnection.
  654. EXPECT_EQ(1, histogram_tester().GetTotalSum(
  655. kMojoDisconnectionsAccountManagerRemote));
  656. }
  657. TEST_F(AccountManagerFacadeImplTest,
  658. HistogramsForZeroAccountManagerObserverReceiverDisconnections) {
  659. account_manager().SetIsInitialized(true);
  660. std::unique_ptr<AccountManagerFacadeImpl> account_manager_facade =
  661. CreateFacade();
  662. // Expect 0 disconnections in the default state.
  663. EXPECT_EQ(0, histogram_tester().GetTotalSum(
  664. kMojoDisconnectionsAccountManagerObserverReceiver));
  665. // Reset the facade so that histograms get logged.
  666. account_manager_facade->FlushMojoForTesting();
  667. account_manager_facade.reset();
  668. // Expect 1 log - at the end of `account_manager_facade` destruction.
  669. histogram_tester().ExpectTotalCount(
  670. kMojoDisconnectionsAccountManagerObserverReceiver, 1);
  671. // Expect 0 disconnections.
  672. EXPECT_EQ(0, histogram_tester().GetTotalSum(
  673. kMojoDisconnectionsAccountManagerObserverReceiver));
  674. }
  675. TEST_F(AccountManagerFacadeImplTest,
  676. HistogramsForAccountManagerObserverReceiverDisconnections) {
  677. account_manager().SetIsInitialized(true);
  678. std::unique_ptr<AccountManagerFacadeImpl> account_manager_facade =
  679. CreateFacade();
  680. // Expect 0 disconnections in the default state.
  681. EXPECT_EQ(0, histogram_tester().GetTotalSum(
  682. kMojoDisconnectionsAccountManagerObserverReceiver));
  683. // Simulate a disconnection.
  684. account_manager().ClearObservers();
  685. // And reset the facade so that histograms get logged.
  686. account_manager_facade->FlushMojoForTesting();
  687. account_manager_facade.reset();
  688. // Expect 1 log - at the end of `account_manager_facade` destruction.
  689. histogram_tester().ExpectTotalCount(
  690. kMojoDisconnectionsAccountManagerObserverReceiver, 1);
  691. // Expect 1 disconnection.
  692. EXPECT_EQ(1, histogram_tester().GetTotalSum(
  693. kMojoDisconnectionsAccountManagerObserverReceiver));
  694. }
  695. TEST_F(AccountManagerFacadeImplTest,
  696. HistogramsForZeroAccountManagerAccessTokenFetcherRemoteDisconnections) {
  697. account_manager().SetIsInitialized(true);
  698. std::unique_ptr<AccountManagerFacadeImpl> account_manager_facade =
  699. CreateFacade();
  700. const Account account = CreateTestGaiaAccount(kTestAccountEmail);
  701. auto mock_access_token_fetcher = std::make_unique<MockAccessTokenFetcher>();
  702. EXPECT_CALL(*mock_access_token_fetcher.get(), Start(_, _))
  703. .WillOnce(WithArgs<1>(Invoke(&AccessTokenFetchSuccess)));
  704. account_manager().SetMockAccessTokenFetcher(
  705. std::move(mock_access_token_fetcher));
  706. MockOAuthConsumer consumer;
  707. EXPECT_CALL(consumer,
  708. OnGetTokenSuccess(
  709. Field(&OAuth2AccessTokenConsumer::TokenResponse::access_token,
  710. Eq(kFakeAccessToken))));
  711. std::unique_ptr<OAuth2AccessTokenFetcher> access_token_fetcher =
  712. account_manager_facade->CreateAccessTokenFetcher(account.key, &consumer);
  713. // Expect 0 disconnections in the default state.
  714. EXPECT_EQ(0, histogram_tester().GetTotalSum(
  715. kMojoDisconnectionsAccountManagerAccessTokenFetcherRemote));
  716. access_token_fetcher->Start(kFakeClientId, kFakeClientSecret, /*scopes=*/{});
  717. // Flush all pending Mojo messages.
  718. base::RunLoop().RunUntilIdle();
  719. // Reset the fetcher so that histograms get logged.
  720. access_token_fetcher.reset();
  721. // Expect 1 log - at the end of `account_manager_facade` destruction.
  722. histogram_tester().ExpectTotalCount(
  723. kMojoDisconnectionsAccountManagerAccessTokenFetcherRemote, 1);
  724. // Expect 0 disconnections.
  725. EXPECT_EQ(0, histogram_tester().GetTotalSum(
  726. kMojoDisconnectionsAccountManagerAccessTokenFetcherRemote));
  727. }
  728. TEST_F(AccountManagerFacadeImplTest,
  729. HistogramsForAccountManagerAccessTokenFetcherRemoteDisconnections) {
  730. account_manager().SetIsInitialized(true);
  731. std::unique_ptr<AccountManagerFacadeImpl> account_manager_facade =
  732. CreateFacade();
  733. const Account account = CreateTestGaiaAccount(kTestAccountEmail);
  734. // Create a mock access token fetcher that closes its receiver end of the Mojo
  735. // pipe as soon as its `Start()` method is called with any parameters.
  736. auto mock_access_token_fetcher = std::make_unique<MockAccessTokenFetcher>();
  737. EXPECT_CALL(*mock_access_token_fetcher.get(), Start(_, _))
  738. .WillOnce(Invoke(mock_access_token_fetcher.get(),
  739. &MockAccessTokenFetcher::ResetReceiver));
  740. account_manager().SetMockAccessTokenFetcher(
  741. std::move(mock_access_token_fetcher));
  742. MockOAuthConsumer consumer;
  743. std::unique_ptr<OAuth2AccessTokenFetcher> access_token_fetcher =
  744. account_manager_facade->CreateAccessTokenFetcher(account.key, &consumer);
  745. // Expect 0 disconnections in the default state.
  746. EXPECT_EQ(0, histogram_tester().GetTotalSum(
  747. kMojoDisconnectionsAccountManagerAccessTokenFetcherRemote));
  748. // Calling `Start` will reset the Mojo connection from the receiver side. This
  749. // should notify the remote side, and result in a histogram log.
  750. access_token_fetcher->Start(kFakeClientId, kFakeClientSecret, /*scopes=*/{});
  751. // Flush all pending Mojo messages.
  752. base::RunLoop().RunUntilIdle();
  753. // Reset the fetcher so that histograms get logged.
  754. access_token_fetcher.reset();
  755. // Expect 1 log - at the end of `account_manager_facade` destruction.
  756. histogram_tester().ExpectTotalCount(
  757. kMojoDisconnectionsAccountManagerAccessTokenFetcherRemote, 1);
  758. // Expect 1 disconnection.
  759. EXPECT_EQ(1, histogram_tester().GetTotalSum(
  760. kMojoDisconnectionsAccountManagerAccessTokenFetcherRemote));
  761. }
  762. } // namespace account_manager