summaryrefslogtreecommitdiffstats
path: root/chrome/browser/signin/signin_tracker_unittest.cc
blob: 324c17797f2c0828148bb17818b1d15d6cd570ba (plain)
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
// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chrome/browser/signin/signin_tracker.h"

#include "base/bind.h"
#include "base/bind_helpers.h"
#include "base/compiler_specific.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/signin/fake_auth_status_provider.h"
#include "chrome/browser/signin/fake_signin_manager.h"
#include "chrome/browser/signin/signin_manager.h"
#include "chrome/browser/signin/signin_manager_factory.h"
#include "chrome/browser/signin/token_service.h"
#include "chrome/browser/signin/token_service_factory.h"
#include "chrome/browser/sync/profile_sync_service_factory.h"
#include "chrome/browser/sync/profile_sync_service_mock.h"
#include "chrome/common/chrome_notification_types.h"
#include "content/public/browser/notification_service.h"
#include "google_apis/gaia/gaia_constants.h"
#include "google_apis/gaia/google_service_auth_error.h"

#include "testing/gmock/include/gmock/gmock.h"
#include "testing/gtest/include/gtest/gtest.h"

using ::testing::_;
using ::testing::AnyNumber;
using ::testing::Mock;
using ::testing::Return;
using ::testing::ReturnRef;

namespace {

class MockTokenService : public TokenService {
 public:
  MockTokenService() { }
  virtual ~MockTokenService() { }

  MOCK_CONST_METHOD1(HasTokenForService, bool(const char*));
};

ProfileKeyedService* BuildMockTokenService(content::BrowserContext* profile) {
  return new MockTokenService;
}

class MockObserver : public SigninTracker::Observer {
 public:
  MockObserver() {}
  ~MockObserver() {}

  MOCK_METHOD0(GaiaCredentialsValid, void(void));
  MOCK_METHOD1(SigninFailed, void(const GoogleServiceAuthError&));
  MOCK_METHOD0(SigninSuccess, void(void));
};

}  // namespace

class SigninTrackerTest : public testing::Test {
 public:
  SigninTrackerTest() {}
  virtual void SetUp() OVERRIDE {
    profile_.reset(new TestingProfile());
    mock_token_service_ = static_cast<MockTokenService*>(
        TokenServiceFactory::GetInstance()->SetTestingFactoryAndUse(
            profile_.get(), BuildMockTokenService));
    mock_pss_ = static_cast<ProfileSyncServiceMock*>(
        ProfileSyncServiceFactory::GetInstance()->SetTestingFactoryAndUse(
            profile_.get(),
            ProfileSyncServiceMock::BuildMockProfileSyncService));
    mock_pss_->Initialize();

    mock_signin_manager_ = static_cast<FakeSigninManagerBase*>(
        SigninManagerFactory::GetInstance()->SetTestingFactoryAndUse(
            profile_.get(), FakeSigninManagerBase::Build));
    mock_signin_manager_->Initialize(profile_.get(), NULL);
    // Make gmock not spam the output with information about these uninteresting
    // calls.
    EXPECT_CALL(*mock_pss_, AddObserver(_)).Times(AnyNumber());
    EXPECT_CALL(*mock_pss_, RemoveObserver(_)).Times(AnyNumber());
    tracker_.reset(new SigninTracker(profile_.get(), &observer_));
  }
  virtual void TearDown() OVERRIDE {
    tracker_.reset();
    profile_.reset();
  }
  scoped_ptr<SigninTracker> tracker_;
  scoped_ptr<TestingProfile> profile_;
  ProfileSyncServiceMock* mock_pss_;
  FakeSigninManagerBase* mock_signin_manager_;
  MockTokenService* mock_token_service_;
  MockObserver observer_;
};

TEST_F(SigninTrackerTest, GaiaSignInFailed) {
  // SIGNIN_FAILED notification should result in a SigninFailed callback.
  GoogleServiceAuthError error(
      GoogleServiceAuthError::INVALID_GAIA_CREDENTIALS);
  EXPECT_CALL(observer_, SigninFailed(error));
  content::NotificationService::current()->Notify(
      chrome::NOTIFICATION_GOOGLE_SIGNIN_FAILED,
      content::Source<Profile>(profile_.get()),
      content::Details<const GoogleServiceAuthError>(&error));
}

TEST_F(SigninTrackerTest, GaiaSignInSucceeded) {
  // SIGNIN_SUCCEEDED notification should lead us to get a GaiCredentialsValid()
  // callback.
  EXPECT_CALL(observer_, GaiaCredentialsValid());
  EXPECT_CALL(*mock_pss_, IsSyncEnabledAndLoggedIn())
      .WillRepeatedly(Return(false));
  EXPECT_CALL(*mock_token_service_, HasTokenForService(_))
      .WillRepeatedly(Return(false));
  GoogleServiceSigninSuccessDetails details("username@gmail.com", "password");
  content::NotificationService::current()->Notify(
      chrome::NOTIFICATION_GOOGLE_SIGNIN_SUCCESSFUL,
      content::Source<Profile>(profile_.get()),
      content::Details<const GoogleServiceSigninSuccessDetails>(&details));
}

static void ExpectSignedInSyncService(ProfileSyncServiceMock* sync_service,
                                      MockTokenService* token_service,
                                      const GoogleServiceAuthError& error) {
  if (token_service) {
    EXPECT_CALL(*token_service, HasTokenForService(_))
        .WillRepeatedly(Return(true));
  }
  EXPECT_CALL(*sync_service, IsSyncEnabledAndLoggedIn()).WillRepeatedly(
      Return(true));
  EXPECT_CALL(*sync_service, IsSyncTokenAvailable()).WillRepeatedly(
      Return(true));
  EXPECT_CALL(*sync_service, waiting_for_auth()).WillRepeatedly(Return(false));
  EXPECT_CALL(*sync_service, GetAuthError()).WillRepeatedly(ReturnRef(error));
  EXPECT_CALL(*sync_service, HasUnrecoverableError()).WillRepeatedly(
      Return(false));
  EXPECT_CALL(*sync_service, sync_initialized()).WillRepeatedly(Return(true));

}

TEST_F(SigninTrackerTest, GaiaSigninWhenServicesAlreadyRunning) {
  // SIGNIN_SUCCEEDED notification should result in a SigninSuccess() callback
  // if we're already signed in.
  EXPECT_CALL(observer_, GaiaCredentialsValid());
  EXPECT_CALL(observer_, SigninSuccess());
  GoogleServiceAuthError error(GoogleServiceAuthError::NONE);
  ExpectSignedInSyncService(mock_pss_, mock_token_service_, error);
  mock_signin_manager_->SetAuthenticatedUsername("username@gmail.com");
  GoogleServiceSigninSuccessDetails details("username@gmail.com", "password");
  content::NotificationService::current()->Notify(
      chrome::NOTIFICATION_GOOGLE_SIGNIN_SUCCESSFUL,
      content::Source<Profile>(profile_.get()),
      content::Details<const GoogleServiceSigninSuccessDetails>(&details));
}

TEST_F(SigninTrackerTest, NoGaiaSigninWhenOAuthTokensNotAvailable) {
  // SIGNIN_SUCCESSFUL notification should not result in a SigninSuccess()
  // callback if our oauth token hasn't been fetched.
  EXPECT_CALL(observer_, GaiaCredentialsValid());
  GoogleServiceAuthError error(GoogleServiceAuthError::NONE);
  ExpectSignedInSyncService(mock_pss_, NULL, error);
  EXPECT_CALL(*mock_token_service_,
              HasTokenForService(GaiaConstants::kSyncService))
      .WillRepeatedly(Return(true));
  EXPECT_CALL(*mock_token_service_,
              HasTokenForService(GaiaConstants::kGaiaOAuth2LoginRefreshToken))
      .WillRepeatedly(Return(false));
  GoogleServiceSigninSuccessDetails details("username@gmail.com", "password");
  content::NotificationService::current()->Notify(
      chrome::NOTIFICATION_GOOGLE_SIGNIN_SUCCESSFUL,
      content::Source<Profile>(profile_.get()),
      content::Details<const GoogleServiceSigninSuccessDetails>(&details));
}

TEST_F(SigninTrackerTest, GaiaSigninAfterOAuthTokenBecomesAvailable) {
  // SIGNIN_SUCCESSFUL notification should not result in a SigninSuccess()
  // callback until after our oauth token hasn't been fetched.
  EXPECT_CALL(observer_, GaiaCredentialsValid());
  GoogleServiceAuthError none(GoogleServiceAuthError::NONE);
  ExpectSignedInSyncService(mock_pss_, NULL, none);
  EXPECT_CALL(*mock_token_service_,
              HasTokenForService(GaiaConstants::kSyncService))
      .WillRepeatedly(Return(true));
  EXPECT_CALL(*mock_token_service_,
              HasTokenForService(GaiaConstants::kGaiaOAuth2LoginRefreshToken))
      .WillRepeatedly(Return(false));
  mock_signin_manager_->SetAuthenticatedUsername("username@gmail.com");
  GoogleServiceSigninSuccessDetails details("username@gmail.com", "password");
  content::NotificationService::current()->Notify(
      chrome::NOTIFICATION_GOOGLE_SIGNIN_SUCCESSFUL,
      content::Source<Profile>(profile_.get()),
      content::Details<const GoogleServiceSigninSuccessDetails>(&details));
  Mock::VerifyAndClearExpectations(mock_pss_);
  Mock::VerifyAndClearExpectations(mock_token_service_);
  EXPECT_CALL(observer_, SigninSuccess());
  ExpectSignedInSyncService(mock_pss_, mock_token_service_, none);
  TokenService::TokenAvailableDetails available(
      GaiaConstants::kGaiaOAuth2LoginRefreshToken, "foo_token");
  content::NotificationService::current()->Notify(
      chrome::NOTIFICATION_TOKEN_AVAILABLE,
      content::Source<TokenService>(mock_token_service_),
      content::Details<const TokenService::TokenAvailableDetails>(&available));
}

TEST_F(SigninTrackerTest, SigninFailedWhenTokenFetchFails) {
  // TOKEN_REQUEST_FAILED notification should result in SigninFailed() callback.
  EXPECT_CALL(observer_, GaiaCredentialsValid());
  GoogleServiceAuthError none(GoogleServiceAuthError::NONE);
  ExpectSignedInSyncService(mock_pss_, NULL, none);
  EXPECT_CALL(*mock_token_service_,
              HasTokenForService(GaiaConstants::kSyncService))
      .WillRepeatedly(Return(true));
  EXPECT_CALL(*mock_token_service_,
              HasTokenForService(GaiaConstants::kGaiaOAuth2LoginRefreshToken))
      .WillRepeatedly(Return(false));
  GoogleServiceSigninSuccessDetails details("username@gmail.com", "password");
  content::NotificationService::current()->Notify(
      chrome::NOTIFICATION_GOOGLE_SIGNIN_SUCCESSFUL,
      content::Source<Profile>(profile_.get()),
      content::Details<const GoogleServiceSigninSuccessDetails>(&details));

  GoogleServiceAuthError error(
      GoogleServiceAuthError::INVALID_GAIA_CREDENTIALS);
  EXPECT_CALL(observer_, SigninFailed(error));
  TokenService::TokenRequestFailedDetails failed(
      GaiaConstants::kGaiaOAuth2LoginRefreshToken, error);
  content::NotificationService::current()->Notify(
      chrome::NOTIFICATION_TOKEN_REQUEST_FAILED,
      content::Source<TokenService>(mock_token_service_),
      content::Details<const TokenService::TokenRequestFailedDetails>(&failed));
}

TEST_F(SigninTrackerTest, NoGaiaSigninWhenServicesNotRunning) {
  // SIGNIN_SUCCEEDED notification should not result in a SigninSuccess()
  // callback if we're not already signed in.
  EXPECT_CALL(observer_, GaiaCredentialsValid());
  EXPECT_CALL(*mock_token_service_, HasTokenForService(_))
      .WillRepeatedly(Return(true));
  EXPECT_CALL(*mock_pss_, IsSyncEnabledAndLoggedIn()).WillRepeatedly(
      Return(false));
  EXPECT_CALL(*mock_pss_, IsSyncTokenAvailable()).WillRepeatedly(
      Return(false));
  GoogleServiceSigninSuccessDetails details("username@gmail.com", "password");
  content::NotificationService::current()->Notify(
      chrome::NOTIFICATION_GOOGLE_SIGNIN_SUCCESSFUL,
      content::Source<Profile>(profile_.get()),
      content::Details<const GoogleServiceSigninSuccessDetails>(&details));
}

TEST_F(SigninTrackerTest, GaiaSigninAfterSyncStarts) {
  // Make sure that we don't get a SigninSuccess() callback until after the
  // sync service reports that it's signed in.
  EXPECT_CALL(observer_, GaiaCredentialsValid());
  EXPECT_CALL(*mock_pss_, IsSyncEnabledAndLoggedIn()).WillOnce(
      Return(false));
  EXPECT_CALL(*mock_token_service_, HasTokenForService(_))
      .WillRepeatedly(Return(true));
  mock_signin_manager_->SetAuthenticatedUsername("username@gmail.com");
  GoogleServiceSigninSuccessDetails details("username@gmail.com", "password");
  content::NotificationService::current()->Notify(
      chrome::NOTIFICATION_GOOGLE_SIGNIN_SUCCESSFUL,
      content::Source<Profile>(profile_.get()),
      content::Details<const GoogleServiceSigninSuccessDetails>(&details));
  Mock::VerifyAndClearExpectations(mock_pss_);
  // Mimic the sync engine getting credentials.
  EXPECT_CALL(observer_, SigninSuccess());
  GoogleServiceAuthError error(GoogleServiceAuthError::NONE);
  ExpectSignedInSyncService(mock_pss_, mock_token_service_, error);
  tracker_->OnStateChanged();
}

TEST_F(SigninTrackerTest, SyncSigninError) {
  // Make sure that we get a SigninFailed() callback if sync gets an error after
  // initializaiton.
  EXPECT_CALL(observer_, GaiaCredentialsValid());
  EXPECT_CALL(*mock_pss_, IsSyncEnabledAndLoggedIn()).WillRepeatedly(
      Return(false));
  EXPECT_CALL(*mock_pss_, IsSyncTokenAvailable()).WillRepeatedly(
      Return(false));
  EXPECT_CALL(*mock_token_service_, HasTokenForService(_))
      .WillRepeatedly(Return(true));
  mock_signin_manager_->SetAuthenticatedUsername("username@gmail.com");
  GoogleServiceSigninSuccessDetails details("username@gmail.com", "password");
  content::NotificationService::current()->Notify(
      chrome::NOTIFICATION_GOOGLE_SIGNIN_SUCCESSFUL,
      content::Source<Profile>(profile_.get()),
      content::Details<const GoogleServiceSigninSuccessDetails>(&details));

  // Still waiting for auth, so sync state changes should be ignored.
  EXPECT_CALL(*mock_pss_, waiting_for_auth()).WillOnce(Return(true));
  tracker_->OnStateChanged();
  // Now mimic an auth error - this should cause us to fail (not waiting for
  // auth, but still have no credentials).
  GoogleServiceAuthError error(
      GoogleServiceAuthError::INVALID_GAIA_CREDENTIALS);
  FakeAuthStatusProvider provider(mock_signin_manager_->signin_global_error());
  provider.SetAuthError(error);
  EXPECT_CALL(*mock_pss_, waiting_for_auth()).WillRepeatedly(Return(false));
  EXPECT_CALL(observer_, SigninFailed(error));
  tracker_->OnStateChanged();
}

// Test cases for initial state = SERVICES_INITIALIZING.
TEST_F(SigninTrackerTest, SigninSuccess) {
  // Reset the |tracker_| and restart with initial state parameter for its
  // constructor later.
  tracker_.reset();
  GoogleServiceAuthError error(GoogleServiceAuthError::NONE);
  ExpectSignedInSyncService(mock_pss_, mock_token_service_, error);
  mock_signin_manager_->SetAuthenticatedUsername("username@gmail.com");

  // Finally SigninSuccess() is expected to be called when everything is ready.
  EXPECT_CALL(observer_, SigninSuccess());
  tracker_.reset(new SigninTracker(profile_.get(), &observer_,
                                   SigninTracker::SERVICES_INITIALIZING));
}

TEST_F(SigninTrackerTest, SigninFailedSyncTokenUnavailable) {
  tracker_.reset();
  EXPECT_CALL(*mock_token_service_, HasTokenForService(_))
      .WillRepeatedly(Return(true));
  mock_signin_manager_->SetAuthenticatedUsername("username@gmail.com");
  GoogleServiceAuthError error(GoogleServiceAuthError::NONE);
  EXPECT_CALL(*mock_pss_, IsSyncEnabledAndLoggedIn()).WillRepeatedly(
      Return(true));
  // Inject Token unavailable error.
  EXPECT_CALL(*mock_pss_, IsSyncTokenAvailable()).WillRepeatedly(
      Return(false));
  EXPECT_CALL(*mock_pss_, waiting_for_auth()).WillRepeatedly(Return(false));
  EXPECT_CALL(*mock_pss_, GetAuthError()).WillRepeatedly(ReturnRef(error));
  EXPECT_CALL(*mock_pss_, HasUnrecoverableError()).WillRepeatedly(
      Return(false));
  EXPECT_CALL(*mock_pss_, sync_initialized()).WillRepeatedly(Return(true));
  // Any error should result in SigninFailed() being called.
  EXPECT_CALL(observer_, SigninFailed(error));
  tracker_.reset(new SigninTracker(profile_.get(), &observer_,
                                   SigninTracker::SERVICES_INITIALIZING));
}

TEST_F(SigninTrackerTest, SigninFailedGoogleServiceAuthError) {
  tracker_.reset();
  EXPECT_CALL(*mock_token_service_, HasTokenForService(_))
      .WillRepeatedly(Return(true));
  mock_signin_manager_->SetAuthenticatedUsername("username@gmail.com");
  // Inject authentication error.
  GoogleServiceAuthError error(GoogleServiceAuthError::SERVICE_UNAVAILABLE);
  FakeAuthStatusProvider provider(mock_signin_manager_->signin_global_error());
  provider.SetAuthError(error);
  EXPECT_CALL(*mock_pss_, IsSyncEnabledAndLoggedIn()).WillRepeatedly(
      Return(true));
  EXPECT_CALL(*mock_pss_, IsSyncTokenAvailable()).WillRepeatedly(
      Return(true));
  EXPECT_CALL(*mock_pss_, waiting_for_auth()).WillRepeatedly(Return(false));
  EXPECT_CALL(*mock_pss_, GetAuthError()).WillRepeatedly(ReturnRef(error));
  EXPECT_CALL(*mock_pss_, HasUnrecoverableError()).WillRepeatedly(
      Return(false));
  EXPECT_CALL(*mock_pss_, sync_initialized()).WillRepeatedly(Return(true));
  // Any error should result in SigninFailed() being called.
  EXPECT_CALL(observer_, SigninFailed(error));
  tracker_.reset(new SigninTracker(profile_.get(), &observer_,
                                   SigninTracker::SERVICES_INITIALIZING));
}

TEST_F(SigninTrackerTest, SigninFailedWhenInitializing) {
  tracker_.reset();
  // SigninFailed() should be called.
  GoogleServiceAuthError error(GoogleServiceAuthError::REQUEST_CANCELED);
  EXPECT_CALL(observer_, SigninFailed(error));
  tracker_.reset(new SigninTracker(profile_.get(), &observer_,
                                   SigninTracker::SERVICES_INITIALIZING));
  tracker_->OnStateChanged();
}