Ver código fonte

Merge branch 'pin-GIDDataFetcher' into pin-GIDProfileDataFetcher

pinlu 3 anos atrás
pai
commit
4a67268d11

+ 14 - 13
GoogleSignIn/Tests/Unit/GIDFakeFetcher.h → GoogleSignIn/Sources/GIDDataFetcher/API/GIDDataFetcher.h

@@ -1,5 +1,5 @@
 /*
- * Copyright 2021 Google LLC
+ * Copyright 2022 Google LLC
  *
  * Licensed under the Apache License, Version 2.0 (the "License");
  * you may not use this file except in compliance with the License.
@@ -14,20 +14,21 @@
  * limitations under the License.
  */
 
-#ifdef SWIFT_PACKAGE
-@import GTMSessionFetcherCore;
-#else
-#import <GTMSessionFetcher/GTMSessionFetcher.h>
-#endif
+#import <Foundation/Foundation.h>
 
-// A fake |GTMHTTPFetcher| for testing.
-@interface GIDFakeFetcher : GTMSessionFetcher
+NS_ASSUME_NONNULL_BEGIN
 
-// The URL of the fetching request.
-- (NSURL *)requestURL;
+@protocol GIDDataFetcher <NSObject>
 
-// Emulates server returning with data and/or error.
-- (void)didFinishWithData:(NSData *)data error:(NSError *)error;
+/// Fetches the data from an URL.
+///
+/// @param URL The endpoint to fetch data.
+/// @param comment The comment for logging purpose.
+/// @param completion The block that is called on completion asynchronously.
+- (void)fetchURL:(NSURL *)URL
+     withComment:(NSString *)comment
+      completion:(void (^)(NSData *_Nullable, NSError *_Nullable))completion;
 
-- (instancetype)initWithRequest:(NSURLRequest *)request;
 @end
+
+NS_ASSUME_NONNULL_END

+ 37 - 0
GoogleSignIn/Sources/GIDDataFetcher/Implementations/Fakes/GIDFakeDataFetcher.h

@@ -0,0 +1,37 @@
+/*
+ * Copyright 2022 Google LLC
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#import <Foundation/Foundation.h>
+
+#import "GoogleSignIn/Sources/GIDDataFetcher/API/GIDDataFetcher.h"
+
+NS_ASSUME_NONNULL_BEGIN
+
+typedef void(^GIDDataFetcherFakeResponse)(NSData *_Nullable data, NSError *_Nullable error);
+
+typedef void (^GIDDataFetcherTestBlock)(GIDDataFetcherFakeResponse response);
+
+@interface GIDFakeDataFetcher : NSObject <GIDDataFetcher>
+
+/// Set the test block which provides the response value.
+- (void)setTestBlock:(GIDDataFetcherTestBlock)block;
+
+/// The saved url when `fetchURL:withComment:completion:` is invoked.
+- (nullable NSURL *)requestURL;
+
+@end
+
+NS_ASSUME_NONNULL_END

+ 23 - 0
GoogleSignIn/Sources/GIDDataFetcher/Implementations/Fakes/GIDFakeDataFetcher.m

@@ -0,0 +1,23 @@
+#import "GoogleSignIn/Sources/GIDDataFetcher/Implementations/Fakes/GIDFakeDataFetcher.h"
+
+@interface GIDFakeDataFetcher ()
+
+@property(nonatomic) GIDDataFetcherTestBlock testBlock;
+
+@property(nonatomic) NSURL *requestURL;
+
+@end
+
+@implementation GIDFakeDataFetcher
+
+- (void)fetchURL:(NSURL *)URL
+     withComment:(NSString *)comment
+      completion:(void (^)(NSData *_Nullable, NSError *_Nullable))completion {
+  self.requestURL = URL;
+  NSAssert(self.testBlock != nil, @"Set the test block before invoking this method.");
+  self.testBlock(^(NSData *_Nullable data, NSError *_Nullable error){
+    completion(data,error);
+  });
+}
+
+@end

+ 7 - 10
GoogleSignIn/Tests/Unit/GIDFakeFetcherService.h → GoogleSignIn/Sources/GIDDataFetcher/Implementations/GIDDataFetcher.h

@@ -1,5 +1,5 @@
 /*
- * Copyright 2021 Google LLC
+ * Copyright 2022 Google LLC
  *
  * Licensed under the Apache License, Version 2.0 (the "License");
  * you may not use this file except in compliance with the License.
@@ -14,16 +14,13 @@
  * limitations under the License.
  */
 
-#ifdef SWIFT_PACKAGE
-@import GTMSessionFetcherCore;
-#else
-#import <GTMSessionFetcher/GTMSessionFetcher.h>
-#endif
+#import <Foundation/Foundation.h>
 
-// A fake |GTMHTTPFetcherService| for testing.
-@interface GIDFakeFetcherService : NSObject<GTMSessionFetcherServiceProtocol>
+#import "GoogleSignIn/Sources/GIDDataFetcher/API/GIDDataFetcher.h"
 
-// Returns the list of |GPPFakeFetcher| objects that have been created.
-- (NSArray *)fetchers;
+NS_ASSUME_NONNULL_BEGIN
 
+@interface GIDDataFetcher : NSObject<GIDDataFetcher>
 @end
+
+NS_ASSUME_NONNULL_END

+ 29 - 0
GoogleSignIn/Sources/GIDDataFetcher/Implementations/GIDDataFetcher.m

@@ -0,0 +1,29 @@
+#import "GoogleSignIn/Sources/GIDDataFetcher/Implementations/GIDDataFetcher.h"
+
+#ifdef SWIFT_PACKAGE
+@import GTMAppAuth;
+#else
+#import <GTMAppAuth/GTMAppAuth.h>
+#endif
+
+NS_ASSUME_NONNULL_BEGIN
+
+// Maximum retry interval in seconds for the fetcher.
+static const NSTimeInterval kFetcherMaxRetryInterval = 15.0;
+
+@implementation GIDDataFetcher
+
+- (void)fetchURL:(NSURL *)URL
+     withComment:(NSString *)comment
+      completion:(void (^)(NSData *_Nullable, NSError *_Nullable))completion {
+  NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:URL];
+  GTMSessionFetcher *fetcher = [GTMSessionFetcher fetcherWithRequest:request];
+  fetcher.retryEnabled = YES;
+  fetcher.maxRetryInterval = kFetcherMaxRetryInterval;
+  fetcher.comment = comment;
+  [fetcher beginFetchWithCompletionHandler:completion];
+}
+
+@end
+
+NS_ASSUME_NONNULL_END

+ 16 - 71
GoogleSignIn/Sources/GIDSignIn.m

@@ -21,6 +21,8 @@
 #import "GoogleSignIn/Sources/Public/GoogleSignIn/GIDProfileData.h"
 #import "GoogleSignIn/Sources/Public/GoogleSignIn/GIDSignInResult.h"
 
+#import "GoogleSignIn/Sources/GIDDataFetcher/API/GIDDataFetcher.h"
+#import "GoogleSignIn/Sources/GIDDataFetcher/Implementations/GIDDataFetcher.h"
 #import "GoogleSignIn/Sources/GIDEMMSupport.h"
 #import "GoogleSignIn/Sources/GIDKeychainHandler/API/GIDKeychainHandler.h"
 #import "GoogleSignIn/Sources/GIDKeychainHandler/Implementations/GIDKeychainHandler.h"
@@ -123,9 +125,6 @@ static NSString *const kUserCanceledError = @"The user canceled the sign-in flow
 // User preference key to detect fresh install of the app.
 static NSString *const kAppHasRunBeforeKey = @"GID_AppHasRunBefore";
 
-// Maximum retry interval in seconds for the fetcher.
-static const NSTimeInterval kFetcherMaxRetryInterval = 15.0;
-
 // The delay before the new sign-in flow can be presented after the existing one is cancelled.
 static const NSTimeInterval kPresentationDelayAfterCancel = 1.0;
 
@@ -174,6 +173,9 @@ static NSString *const kConfigOpenIDRealmKey = @"GIDOpenIDRealm";
   id<GIDKeychainHandler> _keychainHandler;
   
   id<GIDProfileDataFetcher> _profileDataFetcher;
+  
+  // The class to fetches data from an url end point.
+  id<GIDDataFetcher> _dataFetcher;
 }
 
 #pragma mark - Public methods
@@ -425,10 +427,9 @@ static NSString *const kConfigOpenIDRealmKey = @"GIDOpenIDRealm";
                      kEnvironmentLoggingParameter,
                      GIDEnvironment()];
   NSURL *revokeURL = [NSURL URLWithString:revokeURLString];
-  [self startFetchURL:revokeURL
-              fromAuthState:authState
-                withComment:@"GIDSignIn: revoke tokens"
-      withCompletionHandler:^(NSData *data, NSError *error) {
+  [_dataFetcher fetchURL:revokeURL
+             withComment:@"GIDSignIn: revoke tokens"
+              completion:^(NSData *data, NSError *error) {
     // Revoking an already revoked token seems always successful, which helps us here.
     if (!error) {
       [self signOut];
@@ -455,11 +456,14 @@ static NSString *const kConfigOpenIDRealmKey = @"GIDOpenIDRealm";
 #pragma mark - Private methods
 
 - (id)initPrivate {
-  GIDKeychainHandler *keychainHandler = [[GIDKeychainHandler alloc] init];
-  return [self initWithKeychainHandler:keychainHandler];
+  id<GIDKeychainHandler> keychainHandler = [[GIDKeychainHandler alloc] init];
+  id<GIDDataFetcher> dataFetcher = [[GIDDataFetcher alloc] init];
+  return [self initWithKeychainHandler:keychainHandler
+                           dataFetcher:dataFetcher];
 }
 
-- (instancetype)initWithKeychainHandler:(id<GIDKeychainHandler>)keychainHandler {
+- (instancetype)initWithKeychainHandler:(id<GIDKeychainHandler>)keychainHandler
+                            dataFetcher:(id<GIDDataFetcher>)dataFetcher{
   self = [super init];
   if (self) {
     // Get the bundle of the current executable.
@@ -497,6 +501,8 @@ static NSString *const kConfigOpenIDRealmKey = @"GIDOpenIDRealm";
     _keychainHandler = keychainHandler;
     
     _profileDataFetcher = [[GIDProfileDataFetcher alloc] init];
+
+    _dataFetcher = dataFetcher;
   }
   return self;
 }
@@ -827,47 +833,6 @@ static NSString *const kConfigOpenIDRealmKey = @"GIDOpenIDRealm";
       }
       [handlerAuthFlow next];
     }];
-    
-    
-//    OIDIDToken *idToken =
-//        [[OIDIDToken alloc] initWithIDTokenString: authState.lastTokenResponse.idToken];
-//    // If the profile data are present in the ID token, use them.
-//    if (idToken) {
-//      handlerAuthFlow.profileData = [self profileDataWithIDToken:idToken];
-//    }
-//
-//    // If we can't retrieve profile data from the ID token, make a userInfo request to fetch them.
-//    if (!handlerAuthFlow.profileData) {
-//      [handlerAuthFlow wait];
-//      NSURL *infoURL = [NSURL URLWithString:
-//          [NSString stringWithFormat:kUserInfoURLTemplate,
-//              [GIDSignInPreferences googleUserInfoServer],
-//              authState.lastTokenResponse.accessToken]];
-//      [self startFetchURL:infoURL
-//                  fromAuthState:authState
-//                    withComment:@"GIDSignIn: fetch basic profile info"
-//          withCompletionHandler:^(NSData *data, NSError *error) {
-//        if (data && !error) {
-//          NSError *jsonDeserializationError;
-//          NSDictionary<NSString *, NSString *> *profileDict =
-//              [NSJSONSerialization JSONObjectWithData:data
-//                                              options:NSJSONReadingMutableContainers
-//                                                error:&jsonDeserializationError];
-//          if (profileDict) {
-//            handlerAuthFlow.profileData = [[GIDProfileData alloc]
-//                initWithEmail:idToken.claims[kBasicProfileEmailKey]
-//                          name:profileDict[kBasicProfileNameKey]
-//                    givenName:profileDict[kBasicProfileGivenNameKey]
-//                    familyName:profileDict[kBasicProfileFamilyNameKey]
-//                      imageURL:[NSURL URLWithString:profileDict[kBasicProfilePictureKey]]];
-//          }
-//        }
-//        if (error) {
-//          handlerAuthFlow.error = error;
-//        }
-//        [handlerAuthFlow next];
-//      }];
-//    }
   }];
 }
 
@@ -896,26 +861,6 @@ static NSString *const kConfigOpenIDRealmKey = @"GIDOpenIDRealm";
   }];
 }
 
-- (void)startFetchURL:(NSURL *)URL
-            fromAuthState:(OIDAuthState *)authState
-              withComment:(NSString *)comment
-    withCompletionHandler:(void (^)(NSData *, NSError *))handler {
-  NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:URL];
-  GTMSessionFetcher *fetcher;
-  GTMAppAuthFetcherAuthorization *authorization =
-      [[GTMAppAuthFetcherAuthorization alloc] initWithAuthState:authState];
-  id<GTMSessionFetcherServiceProtocol> fetcherService = authorization.fetcherService;
-  if (fetcherService) {
-    fetcher = [fetcherService fetcherWithRequest:request];
-  } else {
-    fetcher = [GTMSessionFetcher fetcherWithRequest:request];
-  }
-  fetcher.retryEnabled = YES;
-  fetcher.maxRetryInterval = kFetcherMaxRetryInterval;
-  fetcher.comment = comment;
-  [fetcher beginFetchWithCompletionHandler:handler];
-}
-
 // Parse incoming URL from the Google Device Policy app.
 - (BOOL)handleDevicePolicyAppURL:(NSURL *)url {
   OIDURLQueryComponent *queryComponent = [[OIDURLQueryComponent alloc] initWithURL:url];

+ 2 - 0
GoogleSignIn/Sources/GIDSignIn_Private.h

@@ -29,6 +29,7 @@ NS_ASSUME_NONNULL_BEGIN
 @class GIDGoogleUser;
 @class GIDSignInInternalOptions;
 
+@protocol GIDDataFetcher;
 @protocol GIDKeychainHandler;
 
 /// Represents a completion block that takes a `GIDSignInResult` on success or an error if the
@@ -50,6 +51,7 @@ typedef void (^GIDDisconnectCompletion)(NSError *_Nullable error);
 
 /// The designated initializer.
 - (instancetype)initWithKeychainHandler:(id<GIDKeychainHandler>)keychainHandler
+                            dataFetcher:(id<GIDDataFetcher>)dataFetcher
     NS_DESIGNATED_INITIALIZER;
 
 /// Authenticates with extra options.

+ 95 - 0
GoogleSignIn/Tests/Unit/GIDDataFetcherTest.m

@@ -0,0 +1,95 @@
+// Copyright 2022 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+//      http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#import "GoogleSignIn/Sources/GIDDataFetcher/Implementations/GIDDataFetcher.h"
+
+#import <XCTest/XCTest.h>
+
+#ifdef SWIFT_PACKAGE
+@import GTMAppAuth;
+#else
+#import <GTMAppAuth/GTMAppAuth.h>
+#endif
+
+static NSString *const kTestURL = @"https://testURL.com";
+static NSString *const kErrorDomain = @"ERROR_DOMAIN";
+static NSInteger const kErrorCode = 400;
+
+@interface GIDDataFetcherTest : XCTestCase {
+  GIDDataFetcher *_dataFetcher;
+}
+
+@end
+
+@implementation GIDDataFetcherTest
+
+- (void)setUp {
+  [super setUp];
+  _dataFetcher = [[GIDDataFetcher alloc] init];
+}
+
+- (void)testFetchData_success {
+  NSURL *url = [NSURL URLWithString:kTestURL];
+  XCTestExpectation *expectation =
+      [self expectationWithDescription:@"Callback called with no error"];
+  
+  
+  GTMSessionFetcherTestBlock block =
+      ^(GTMSessionFetcher *fetcherToTest, GTMSessionFetcherTestResponse testResponse) {
+        NSData *data = [[NSData alloc] init];
+        testResponse(nil, data, nil);
+      };
+  [GTMSessionFetcher setGlobalTestBlock:block];
+  
+  [_dataFetcher fetchURL:url
+             withComment:@"Test data fetcher."
+              completion:^(NSData *data, NSError *error) {
+    XCTAssertNil(error);
+    [expectation fulfill];
+  }];
+
+  [self waitForExpectationsWithTimeout:1 handler:nil];
+}
+
+- (void)testFetchData_error {
+  NSURL *url = [NSURL URLWithString:kTestURL];
+  XCTestExpectation *expectation =
+      [self expectationWithDescription:@"Callback called with an error"];
+  
+  GTMSessionFetcherTestBlock block =
+      ^(GTMSessionFetcher *fetcherToTest, GTMSessionFetcherTestResponse testResponse) {
+        NSData *data = [[NSData alloc] init];
+        NSError *error = [self error];
+        testResponse(nil, data, error);
+      };
+  [GTMSessionFetcher setGlobalTestBlock:block];
+  
+  
+  [_dataFetcher fetchURL:url
+             withComment:@"Test data fetcher."
+              completion:^(NSData *data, NSError *error) {
+    XCTAssertNotNil(error);
+    XCTAssertEqual(error.code, kErrorCode);
+    [expectation fulfill];
+  }];
+  [self waitForExpectationsWithTimeout:1 handler:nil];
+}
+
+#pragma mark - Helpers
+
+- (NSError *)error {
+  return [NSError errorWithDomain:kErrorDomain code:kErrorCode userInfo:nil];
+}
+
+@end

+ 0 - 54
GoogleSignIn/Tests/Unit/GIDFakeFetcher.m

@@ -1,54 +0,0 @@
-// Copyright 2021 Google LLC
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-//      http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-#import "GoogleSignIn/Tests/Unit/GIDFakeFetcher.h"
-
-typedef void (^FetchCompletionHandler)(NSData *, NSError *);
-
-@implementation GIDFakeFetcher {
-  FetchCompletionHandler _handler;
-  NSURL *_requestURL;
-}
-
-- (instancetype)initWithRequest:(NSURLRequest *)request {
-  self = [super initWithRequest:request configuration:nil];
-  if (self) {
-    _requestURL = [[request URL] copy];
-  }
-  return self;
-}
-
-
-- (void)beginFetchWithDelegate:(id)delegate didFinishSelector:(SEL)finishedSEL {
-  [NSException raise:@"NotImplementedException" format:@"Implement this method if it is used"];
-}
-
-- (void)beginFetchWithCompletionHandler:(FetchCompletionHandler)handler {
-  if (_handler) {
-    [NSException raise:NSInvalidArgumentException format:@"Attempted start fetch again"];
-  }
-  _handler = [handler copy];
-}
-
-- (NSURL *)requestURL {
-  return _requestURL;
-}
-
-- (void)didFinishWithData:(NSData *)data error:(NSError *)error {
-  FetchCompletionHandler handler = _handler;
-  _handler = nil;
-  handler(data, error);
-}
-
-@end

+ 0 - 78
GoogleSignIn/Tests/Unit/GIDFakeFetcherService.m

@@ -1,78 +0,0 @@
-// Copyright 2021 Google LLC
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-//      http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-#import "GoogleSignIn/Tests/Unit/GIDFakeFetcherService.h"
-
-#import "GoogleSignIn/Tests/Unit/GIDFakeFetcher.h"
-
-@implementation GIDFakeFetcherService {
-  NSMutableArray *_fetchers;
-}
-
-@synthesize delegateQueue;
-@synthesize callbackQueue;
-@synthesize reuseSession;
-
-- (instancetype)init {
-  self = [super init];
-  if (self) {
-    _fetchers = [[NSMutableArray alloc] init];
-  }
-  return self;
-}
-
-- (BOOL)fetcherShouldBeginFetching:(GTMSessionFetcher *)fetcher {
-  return YES;
-}
-
-- (void)fetcherDidCreateSession:(GTMSessionFetcher *)fetcher {
-}
-
-- (void)fetcherDidBeginFetching:(GTMSessionFetcher *)fetcher {
-}
-
-- (void)fetcherDidStop:(GTMSessionFetcher *)fetcher {
-}
-
-- (BOOL)isDelayingFetcher:(GTMSessionFetcher *)fetcher {
-  return NO;
-}
-
-- (GTMSessionFetcher *)fetcherWithRequest:(NSURLRequest *)request {
-  GIDFakeFetcher *fetcher = [[GIDFakeFetcher alloc] initWithRequest:request];
-  [_fetchers addObject:fetcher];
-  return fetcher;
-}
-
-- (NSURLSession *)session {
-  return nil;
-}
-
-- (NSURLSession *)sessionForFetcherCreation {
-  return nil;
-}
-
-- (id<NSURLSessionDelegate>)sessionDelegate {
-  return nil;
-}
-
-- (NSArray *)fetchers {
-  return _fetchers;
-}
-
-- (NSDate *)stoppedAllFetchersDate {
-  return nil;
-}
-
-@end

+ 92 - 115
GoogleSignIn/Tests/Unit/GIDSignInTest.m

@@ -31,13 +31,13 @@
 #import "GoogleSignIn/Sources/GIDSignIn_Private.h"
 #import "GoogleSignIn/Sources/GIDSignInPreferences.h"
 #import "GoogleSignIn/Sources/GIDKeychainHandler/Implementations/Fakes/GIDFakeKeychainHandler.h"
+#import "GoogleSignIn/Sources/GIDDataFetcher/Implementations/Fakes/GIDFakeDataFetcher.h"
+#import "GoogleSignIn/Sources/GIDDataFetcher/Implementations/GIDDataFetcher.h"
 
 #if TARGET_OS_IOS && !TARGET_OS_MACCATALYST
 #import "GoogleSignIn/Sources/GIDEMMErrorHandler.h"
 #endif // TARGET_OS_IOS && !TARGET_OS_MACCATALYST
 
-#import "GoogleSignIn/Tests/Unit/GIDFakeFetcher.h"
-#import "GoogleSignIn/Tests/Unit/GIDFakeFetcherService.h"
 #import "GoogleSignIn/Tests/Unit/GIDFakeMainBundle.h"
 #import "GoogleSignIn/Tests/Unit/OIDAuthorizationResponse+Testing.h"
 #import "GoogleSignIn/Tests/Unit/OIDTokenResponse+Testing.h"
@@ -194,8 +194,12 @@ static NSString *const kNewScope = @"newScope";
   // Mock |GTMAppAuthFetcherAuthorization|.
   id _authorization;
   
+  // Fake for |GIDKeychainHandler|.
   GIDFakeKeychainHandler *_keychainHandler;
 
+  // Fake for |GIDDataFetcher|.
+  GIDFakeDataFetcher *_dataFetcher;
+  
 #if TARGET_OS_IOS || TARGET_OS_MACCATALYST
   // Mock |UIViewController|.
   id _presentingViewController;
@@ -216,9 +220,6 @@ static NSString *const kNewScope = @"newScope";
   // Whether callback block has been called.
   BOOL _completionCalled;
 
-  // Fake fetcher service to emulate network requests.
-  GIDFakeFetcherService *_fetcherService;
-
   // Fake [NSBundle mainBundle];
   GIDFakeMainBundle *_fakeMainBundle;
 
@@ -298,7 +299,6 @@ static NSString *const kNewScope = @"newScope";
                  callback:COPY_TO_ARG_BLOCK(self->_savedTokenCallback)]);
 
   // Fakes
-  _fetcherService = [[GIDFakeFetcherService alloc] init];
   _fakeMainBundle = [[GIDFakeMainBundle alloc] init];
   [_fakeMainBundle startFakingWithClientID:kClientId];
   [_fakeMainBundle fakeAllSchemesSupported];
@@ -308,7 +308,11 @@ static NSString *const kNewScope = @"newScope";
                                           forKey:kAppHasRunBeforeKey];
 
   _keychainHandler = [[GIDFakeKeychainHandler alloc] init];
-  _signIn = [[GIDSignIn alloc] initWithKeychainHandler:_keychainHandler];
+  
+  _dataFetcher = [[GIDFakeDataFetcher alloc] init];
+  
+  _signIn = [[GIDSignIn alloc] initWithKeychainHandler:_keychainHandler
+                                           dataFetcher:_dataFetcher]; 
   _hint = nil;
 
   __weak GIDSignInTest *weakSelf = self;
@@ -739,135 +743,140 @@ static NSString *const kNewScope = @"newScope";
 #pragma mark - Tests - disconnectWithCallback:
 
 // Verifies disconnect calls callback with no errors if access token is present.
-- (void)testDisconnect_accessToken {
+- (void)testDisconnect_accessTokenIsPresent {
   [_keychainHandler saveAuthState:_authState];
-  [[[_authState expect] andReturn:_tokenResponse] lastTokenResponse];
-  [[[_tokenResponse expect] andReturn:kAccessToken] accessToken];
-  [[[_authorization expect] andReturn:_fetcherService] fetcherService];
+  OCMStub([_authState lastTokenResponse]).andReturn(_tokenResponse);
+  OCMStub([_tokenResponse accessToken]).andReturn(kAccessToken);
+  
+  GIDDataFetcherTestBlock testBlock =
+      ^(GIDDataFetcherFakeResponse response) {
+        NSData *data = [[NSData alloc] init];
+        response(data, nil);
+     };
+  [_dataFetcher setTestBlock:testBlock];
+  
   XCTestExpectation *expectation =
       [self expectationWithDescription:@"Callback called with nil error"];
   [_signIn disconnectWithCompletion:^(NSError * _Nullable error) {
-    if (error == nil) {
-      [expectation fulfill];
-    }
+    XCTAssertNil(error);
+    NSURL *url = [self->_dataFetcher requestURL];
+    [self verifyURL:url withToken:kAccessToken];
+    [expectation fulfill];
   }];
-  [self verifyAndRevokeToken:kAccessToken hasCallback:YES];
-  [_authorization verify];
-  [_authState verify];
-  [_tokenResponse verify];
+  [self waitForExpectationsWithTimeout:1 handler:nil];
   XCTAssertNil([_keychainHandler loadAuthState]);
 }
 
 // Verifies disconnect if access token is present.
-- (void)testDisconnectNoCallback_accessToken {
+- (void)testDisconnectNoCallback_accessTokenIsPresent {
   [_keychainHandler saveAuthState:_authState];
-  [[[_authState expect] andReturn:_tokenResponse] lastTokenResponse];
-  [[[_tokenResponse expect] andReturn:kAccessToken] accessToken];
-  [[[_authorization expect] andReturn:_fetcherService] fetcherService];
+  OCMStub([_authState lastTokenResponse]).andReturn(_tokenResponse);
+  OCMStub([_tokenResponse accessToken]).andReturn(kAccessToken);
+  
+  GIDDataFetcherTestBlock testBlock =
+      ^(GIDDataFetcherFakeResponse response) {
+        NSData *data = [[NSData alloc] init];
+        response(data, nil);
+     };
+  [_dataFetcher setTestBlock:testBlock];
+  
   [_signIn disconnectWithCompletion:nil];
-  [self verifyAndRevokeToken:kAccessToken hasCallback:NO];
-  [_authorization verify];
-  [_authState verify];
-  [_tokenResponse verify];
+  NSURL *url = [_dataFetcher requestURL];
+  [self verifyURL:url withToken:kAccessToken];
   XCTAssertNil([_keychainHandler loadAuthState]);
 }
 
-// Verifies disconnect calls callback with no errors if refresh token is present.
-- (void)testDisconnect_refreshToken {
+//// Verifies disconnect calls callback with no errors if refresh token is present.
+- (void)testDisconnect_refreshTokenIsPresent {
   [_keychainHandler saveAuthState:_authState];
-  [[[_authState expect] andReturn:_tokenResponse] lastTokenResponse];
-  [[[_tokenResponse expect] andReturn:nil] accessToken];
-  [[[_authState expect] andReturn:_tokenResponse] lastTokenResponse];
-  [[[_tokenResponse expect] andReturn:kRefreshToken] refreshToken];
-  [[[_authorization expect] andReturn:_fetcherService] fetcherService];
+  OCMStub([_authState lastTokenResponse]).andReturn(_tokenResponse);
+  OCMStub([_tokenResponse accessToken]).andReturn(nil);
+  OCMStub([_tokenResponse refreshToken]).andReturn(kRefreshToken);
+  
+  GIDDataFetcherTestBlock testBlock =
+      ^(GIDDataFetcherFakeResponse response) {
+        NSData *data = [[NSData alloc] init];
+        response(data, nil);
+     };
+  [_dataFetcher setTestBlock:testBlock];
+  
   XCTestExpectation *expectation =
       [self expectationWithDescription:@"Callback called with nil error"];
   [_signIn disconnectWithCompletion:^(NSError * _Nullable error) {
-    if (error == nil) {
-      [expectation fulfill];
-    }
+    XCTAssertNil(error);
+    NSURL *url = [self->_dataFetcher requestURL];
+    [self verifyURL:url withToken:kRefreshToken];
+    [expectation fulfill];
   }];
-  [self verifyAndRevokeToken:kRefreshToken hasCallback:YES];
-  [_authorization verify];
-  [_authState verify];
+  [self waitForExpectationsWithTimeout:1 handler:nil];
   XCTAssertNil([_keychainHandler loadAuthState]);
 }
 
 // Verifies disconnect errors are passed along to the callback.
 - (void)testDisconnect_errors {
   [_keychainHandler saveAuthState:_authState];
-  [[[_authState expect] andReturn:_tokenResponse] lastTokenResponse];
-  [[[_tokenResponse expect] andReturn:kAccessToken] accessToken];
-  [[[_authorization expect] andReturn:_fetcherService] fetcherService];
+  OCMStub([_authState lastTokenResponse]).andReturn(_tokenResponse);
+  OCMStub([_tokenResponse accessToken]).andReturn(kAccessToken);
+  GIDDataFetcherTestBlock testBlock =
+      ^(GIDDataFetcherFakeResponse response) {
+        NSError *error = [self error];
+        response(nil, error);
+     };
+  [_dataFetcher setTestBlock:testBlock];
+  
   XCTestExpectation *expectation =
       [self expectationWithDescription:@"Callback called with an error"];
   [_signIn disconnectWithCompletion:^(NSError * _Nullable error) {
-    if (error != nil) {
-      [expectation fulfill];
-    }
+    XCTAssertNotNil(error);
+    [expectation fulfill];
   }];
-  XCTAssertTrue([self isFetcherStarted], @"should start fetching");
-  // Emulate result back from server.
-  NSError *error = [self error];
-  [self didFetch:nil error:error];
   [self waitForExpectationsWithTimeout:1 handler:nil];
-  [_authorization verify];
-  [_authState verify];
-  [_tokenResponse verify];
   XCTAssertNotNil([_keychainHandler loadAuthState]);
 }
 
 // Verifies disconnect with errors
 - (void)testDisconnectNoCallback_errors {
   [_keychainHandler saveAuthState:_authState];
-  [[[_authState expect] andReturn:_tokenResponse] lastTokenResponse];
-  [[[_tokenResponse expect] andReturn:kAccessToken] accessToken];
-  [[[_authorization expect] andReturn:_fetcherService] fetcherService];
+  OCMStub([_authState lastTokenResponse]).andReturn(_tokenResponse);
+  OCMStub([_tokenResponse accessToken]).andReturn(kAccessToken);
+  GIDDataFetcherTestBlock testBlock =
+      ^(GIDDataFetcherFakeResponse response) {
+        NSError *error = [self error];
+        response(nil, error);
+     };
+  [_dataFetcher setTestBlock:testBlock];
+  
   [_signIn disconnectWithCompletion:nil];
-  XCTAssertTrue([self isFetcherStarted], @"should start fetching");
-  // Emulate result back from server.
-  NSError *error = [self error];
-  [self didFetch:nil error:error];
-  [_authorization verify];
-  [_authState verify];
-  [_tokenResponse verify];
   XCTAssertNotNil([_keychainHandler loadAuthState]);
 }
 
 // Verifies disconnect calls callback with no errors and clears keychain if no tokens are present.
 - (void)testDisconnect_noTokens {
   [_keychainHandler saveAuthState:_authState];
-  [[[_authState expect] andReturn:_tokenResponse] lastTokenResponse];
-  [[[_tokenResponse expect] andReturn:nil] accessToken];
-  [[[_authState expect] andReturn:_tokenResponse] lastTokenResponse];
-  [[[_tokenResponse expect] andReturn:nil] refreshToken];
+  OCMStub([_authState lastTokenResponse]).andReturn(_tokenResponse);
+  OCMStub([_tokenResponse accessToken]).andReturn(nil);
+  OCMStub([_tokenResponse refreshToken]).andReturn(nil);
   XCTestExpectation *expectation =
       [self expectationWithDescription:@"Callback called with nil error"];
   [_signIn disconnectWithCompletion:^(NSError * _Nullable error) {
-    if (error == nil) {
-      [expectation fulfill];
-    }
+    XCTAssertNil(error);
+    // Since _dataFetcher is not invoked so there is no request url saved.
+    XCTAssertNil([self->_dataFetcher requestURL]);
+    [expectation fulfill];
   }];
   [self waitForExpectationsWithTimeout:1 handler:nil];
-  XCTAssertFalse([self isFetcherStarted], @"should not fetch");
-  [_authorization verify];
-  [_authState verify];
-  [_tokenResponse verify];
   XCTAssertNil([_keychainHandler loadAuthState]);
 }
 
 // Verifies disconnect clears keychain if no tokens are present.
 - (void)testDisconnectNoCallback_noTokens {
   [_keychainHandler saveAuthState:_authState];
-  [[[_authState expect] andReturn:_tokenResponse] lastTokenResponse];
-  [[[_tokenResponse expect] andReturn:nil] accessToken];
-  [[[_authState expect] andReturn:_tokenResponse] lastTokenResponse];
-  [[[_tokenResponse expect] andReturn:nil] refreshToken];
+  OCMStub([_authState lastTokenResponse]).andReturn(_tokenResponse);
+  OCMStub([_tokenResponse accessToken]).andReturn(nil);
+  OCMStub([_tokenResponse refreshToken]).andReturn(nil);
   [_signIn disconnectWithCompletion:nil];
-  XCTAssertFalse([self isFetcherStarted], @"should not fetch");
-  [_authorization verify];
-  [_authState verify];
-  [_tokenResponse verify];
+  // Since _dataFetcher is not invoked so there is no request url saved.
+  XCTAssertNil([_dataFetcher requestURL]);
   XCTAssertNil([_keychainHandler loadAuthState]);
 }
 
@@ -1085,39 +1094,12 @@ static NSString *const kNewScope = @"newScope";
 
 #pragma mark - Helpers
 
-// Whether or not a fetcher has been started.
-- (BOOL)isFetcherStarted {
-  NSUInteger count = _fetcherService.fetchers.count;
-  XCTAssertTrue(count <= 1, @"Only one fetcher is supported");
-  return !!count;
-}
-
-// Gets the URL being fetched.
-- (NSURL *)fetchedURL {
-  return [_fetcherService.fetchers[0] requestURL];
-}
-
-// Emulates server returning the data as in JSON.
-- (void)didFetch:(id)dataObject error:(NSError *)error {
-  NSData *data = nil;
-  if (dataObject) {
-    NSError *jsonError = nil;
-    data = [NSJSONSerialization dataWithJSONObject:dataObject
-                                           options:0
-                                             error:&jsonError];
-    XCTAssertNil(jsonError, @"must provide valid data");
-  }
-  [_fetcherService.fetchers[0] didFinishWithData:data error:error];
-}
-
 - (NSError *)error {
   return [NSError errorWithDomain:kErrorDomain code:kErrorCode userInfo:nil];
 }
 
-// Verifies a fetcher has started for revoking token and emulates a server response.
-- (void)verifyAndRevokeToken:(NSString *)token hasCallback:(BOOL)hasCallback {
-  XCTAssertTrue([self isFetcherStarted], @"should start fetching");
-  NSURL *url = [self fetchedURL];
+// Verifies the url to fetch the data.
+- (void)verifyURL:(NSURL *)url withToken:(NSString *)token {
   XCTAssertEqualObjects([url scheme], @"https", @"scheme must match");
   XCTAssertEqualObjects([url host], @"accounts.google.com", @"host must match");
   XCTAssertEqualObjects([url path], @"/o/oauth2/revoke", @"path must match");
@@ -1129,11 +1111,6 @@ static NSString *const kNewScope = @"newScope";
                         @"SDK version logging parameter should match");
   XCTAssertEqualObjects([params valueForKey:kEnvironmentLoggingParameter], GIDEnvironment(),
                         @"Environment logging parameter should match");
-  // Emulate result back from server.
-  [self didFetch:nil error:nil];
-  if (hasCallback) {
-    [self waitForExpectationsWithTimeout:1 handler:nil];
-  }
 }
 
 - (void)OAuthLoginWithAddScopesFlow:(BOOL)addScopesFlow