Ver Fonte

Add GIDDataFetcher protocol and implementation (#273)

pinlu há 3 anos atrás
pai
commit
918748401c

+ 41 - 0
GoogleSignIn/Sources/GIDHTTPFetcher/API/GIDHTTPFetcher.h

@@ -0,0 +1,41 @@
+/*
+ * 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>
+
+@protocol GTMFetcherAuthorizationProtocol;
+
+NS_ASSUME_NONNULL_BEGIN
+
+@protocol GIDHTTPFetcher <NSObject>
+
+/// Fetches the data from an URL request.
+///
+/// @param urlRequest The url request to fetch data.
+/// @param authorizer The object to add authorization to the request.
+/// @param comment The comment for logging purpose.
+/// @param completion The block that is called on completion asynchronously.
+- (void)fetchURLRequest:(NSURLRequest *)urlRequest
+#pragma clang diagnostic push
+#pragma clang diagnostic ignored "-Wdeprecated-declarations"
+         withAuthorizer:(id<GTMFetcherAuthorizationProtocol>)authorizer
+#pragma clang diagnostic pop
+            withComment:(NSString *)comment
+             completion:(void (^)(NSData *_Nullable, NSError *_Nullable))completion;
+
+@end
+
+NS_ASSUME_NONNULL_END

+ 46 - 0
GoogleSignIn/Sources/GIDHTTPFetcher/Implementations/Fakes/GIDFakeHTTPFetcher.h

@@ -0,0 +1,46 @@
+/*
+ * 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/GIDHTTPFetcher/API/GIDHTTPFetcher.h"
+
+NS_ASSUME_NONNULL_BEGIN
+
+/// The block which provides the response for the method
+/// fetchURLRequest:withAuthorizer:withComment:completion:`.
+///
+/// @param data The NSData returned if succeed,
+/// @param error The error returned if failed.
+typedef void(^GIDHTTPFetcherFakeResponseProviderBlock)(NSData *_Nullable data,
+                                                      NSError *_Nullable error);
+
+/// The block to set up data based on the input request for the method
+/// fetchURLRequest:withAuthorizer:withComment:completion:`.
+///
+/// @param request The request from input.
+/// @param responseProvider The block which provides the response.
+typedef void (^GIDHTTPFetcherTestBlock)(NSURLRequest *request,
+                                        GIDHTTPFetcherFakeResponseProviderBlock responseProvider);
+
+@interface GIDFakeHTTPFetcher : NSObject <GIDHTTPFetcher>
+
+/// Set the test block which provides the response value.
+- (void)setTestBlock:(GIDHTTPFetcherTestBlock)block;
+
+@end
+
+NS_ASSUME_NONNULL_END

+ 23 - 0
GoogleSignIn/Sources/GIDHTTPFetcher/Implementations/Fakes/GIDFakeHTTPFetcher.m

@@ -0,0 +1,23 @@
+#import "GoogleSignIn/Sources/GIDHTTPFetcher/Implementations/Fakes/GIDFakeHTTPFetcher.h"
+
+@interface GIDFakeHTTPFetcher ()
+
+@property(nonatomic) GIDHTTPFetcherTestBlock testBlock;
+
+@end
+
+@implementation GIDFakeHTTPFetcher
+
+- (void)fetchURLRequest:(NSURLRequest *)urlRequest
+#pragma clang diagnostic ignored "-Wdeprecated-declarations"
+         withAuthorizer:(id<GTMFetcherAuthorizationProtocol>)authorizer
+#pragma clang diagnostic pop
+            withComment:(NSString *)comment
+             completion:(void (^)(NSData *_Nullable, NSError *_Nullable))completion {
+  NSAssert(self.testBlock != nil, @"Set the test block before invoking this method.");
+  self.testBlock(urlRequest, ^(NSData *_Nullable data, NSError *_Nullable error) {
+    completion(data, error);
+  });
+}
+
+@end

+ 7 - 10
GoogleSignIn/Tests/Unit/GIDFakeFetcherService.h → GoogleSignIn/Sources/GIDHTTPFetcher/Implementations/GIDHTTPFetcher.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/GIDHTTPFetcher/API/GIDHTTPFetcher.h"
 
-// Returns the list of |GPPFakeFetcher| objects that have been created.
-- (NSArray *)fetchers;
+NS_ASSUME_NONNULL_BEGIN
 
+@interface GIDHTTPFetcher : NSObject<GIDHTTPFetcher>
 @end
+
+NS_ASSUME_NONNULL_END

+ 32 - 0
GoogleSignIn/Sources/GIDHTTPFetcher/Implementations/GIDHTTPFetcher.m

@@ -0,0 +1,32 @@
+#import "GoogleSignIn/Sources/GIDHTTPFetcher/Implementations/GIDHTTPFetcher.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 GIDHTTPFetcher
+
+- (void)fetchURLRequest:(NSURLRequest *)urlRequest
+#pragma clang diagnostic ignored "-Wdeprecated-declarations"
+         withAuthorizer:(id<GTMFetcherAuthorizationProtocol>)authorizer
+#pragma clang diagnostic pop
+            withComment:(NSString *)comment
+             completion:(void (^)(NSData *_Nullable, NSError *_Nullable))completion {
+  GTMSessionFetcher *fetcher = [GTMSessionFetcher fetcherWithRequest:urlRequest];
+  fetcher.authorizer = authorizer;
+  fetcher.retryEnabled = YES;
+  fetcher.maxRetryInterval = kFetcherMaxRetryInterval;
+  fetcher.comment = comment;
+  [fetcher beginFetchWithCompletionHandler:completion];
+}
+
+@end
+
+NS_ASSUME_NONNULL_END

+ 38 - 42
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/GIDHTTPFetcher/API/GIDHTTPFetcher.h"
+#import "GoogleSignIn/Sources/GIDHTTPFetcher/Implementations/GIDHTTPFetcher.h"
 #import "GoogleSignIn/Sources/GIDEMMSupport.h"
 #import "GoogleSignIn/Sources/GIDKeychainHandler/API/GIDKeychainHandler.h"
 #import "GoogleSignIn/Sources/GIDKeychainHandler/Implementations/GIDKeychainHandler.h"
@@ -79,10 +81,10 @@ static NSString *const kAuthorizationURLTemplate = @"https://%@/o/oauth2/v2/auth
 static NSString *const kTokenURLTemplate = @"https://%@/token";
 
 // The URL template for the URL to get user info.
-static NSString *const kUserInfoURLTemplate = @"https://%@/oauth2/v3/userinfo?access_token=%@";
+static NSString *const kUserInfoURLTemplate = @"https://%@/oauth2/v3/userinfo";
 
 // The URL template for the URL to revoke the token.
-static NSString *const kRevokeTokenURLTemplate = @"https://%@/o/oauth2/revoke?token=%@";
+static NSString *const kRevokeTokenURLTemplate = @"https://%@/o/oauth2/revoke";
 
 // Expected path in the URL scheme to be handled.
 static NSString *const kBrowserCallbackPath = @"/oauth2callback";
@@ -121,9 +123,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;
 
@@ -170,6 +169,9 @@ static NSString *const kConfigOpenIDRealmKey = @"GIDOpenIDRealm";
   BOOL _restarting;
   
   id<GIDKeychainHandler> _keychainHandler;
+  
+  // The class to fetches data from a url end point.
+  id<GIDHTTPFetcher> _httpFetcher;
 }
 
 #pragma mark - Public methods
@@ -412,19 +414,26 @@ static NSString *const kConfigOpenIDRealmKey = @"GIDOpenIDRealm";
     return;
   }
   NSString *revokeURLString = [NSString stringWithFormat:kRevokeTokenURLTemplate,
-      [GIDSignInPreferences googleAuthorizationServer], token];
+      [GIDSignInPreferences googleAuthorizationServer]];
   // Append logging parameter
-  revokeURLString = [NSString stringWithFormat:@"%@&%@=%@&%@=%@",
+  revokeURLString = [NSString stringWithFormat:@"%@?%@=%@&%@=%@",
                      revokeURLString,
                      kSDKVersionLoggingParameter,
                      GIDVersion(),
                      kEnvironmentLoggingParameter,
                      GIDEnvironment()];
   NSURL *revokeURL = [NSURL URLWithString:revokeURLString];
-  [self startFetchURL:revokeURL
-              fromAuthState:authState
-                withComment:@"GIDSignIn: revoke tokens"
-      withCompletionHandler:^(NSData *data, NSError *error) {
+  NSMutableURLRequest *revokeRequest = [NSMutableURLRequest requestWithURL:revokeURL];
+  [revokeRequest setHTTPMethod:@"POST"];
+  NSString *postString = [NSString stringWithFormat:@"token=%@", token];
+  [revokeRequest setHTTPBody:[postString dataUsingEncoding:NSUTF8StringEncoding]];
+  GTMAppAuthFetcherAuthorization *authorization =
+      [[GTMAppAuthFetcherAuthorization alloc] initWithAuthState:authState];
+  
+  [_httpFetcher fetchURLRequest:revokeRequest
+                 withAuthorizer:authorization
+                    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];
@@ -451,11 +460,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<GIDHTTPFetcher> httpFetcher = [[GIDHTTPFetcher alloc] init];
+  return [self initWithKeychainHandler:keychainHandler
+                           httpFetcher:httpFetcher];
 }
 
-- (instancetype)initWithKeychainHandler:(id<GIDKeychainHandler>)keychainHandler {
+- (instancetype)initWithKeychainHandler:(id<GIDKeychainHandler>)keychainHandler
+                            httpFetcher:(id<GIDHTTPFetcher>)httpFetcher{
   self = [super init];
   if (self) {
     // Get the bundle of the current executable.
@@ -491,6 +503,7 @@ static NSString *const kConfigOpenIDRealmKey = @"GIDOpenIDRealm";
 #endif // TARGET_OS_IOS && !TARGET_OS_MACCATALYST
     
     _keychainHandler = keychainHandler;
+    _httpFetcher = httpFetcher;
   }
   return self;
 }
@@ -817,14 +830,17 @@ static NSString *const kConfigOpenIDRealmKey = @"GIDOpenIDRealm";
     // 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) {
+      NSString *infoString = [NSString stringWithFormat:kUserInfoURLTemplate,
+                                 [GIDSignInPreferences googleUserInfoServer]];
+      NSURL *infoURL = [NSURL URLWithString:infoString];
+      NSMutableURLRequest *infoRequest = [NSMutableURLRequest requestWithURL:infoURL];
+      GTMAppAuthFetcherAuthorization *authorization =
+          [[GTMAppAuthFetcherAuthorization alloc] initWithAuthState:authState];
+
+      [self->_httpFetcher fetchURLRequest:infoRequest
+                           withAuthorizer:authorization
+                              withComment:@"GIDSignIn: fetch basic profile info"
+                               completion:^(NSData *data, NSError *error) {
         if (data && !error) {
           NSError *jsonDeserializationError;
           NSDictionary<NSString *, NSString *> *profileDict =
@@ -874,26 +890,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 GIDHTTPFetcher;
 @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
+                            httpFetcher:(id<GIDHTTPFetcher>)HTTPFetcher
     NS_DESIGNATED_INITIALIZER;
 
 /// Authenticates with extra options.

+ 0 - 33
GoogleSignIn/Tests/Unit/GIDFakeFetcher.h

@@ -1,33 +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.
- */
-
-#ifdef SWIFT_PACKAGE
-@import GTMSessionFetcherCore;
-#else
-#import <GTMSessionFetcher/GTMSessionFetcher.h>
-#endif
-
-// A fake |GTMHTTPFetcher| for testing.
-@interface GIDFakeFetcher : GTMSessionFetcher
-
-// The URL of the fetching request.
-- (NSURL *)requestURL;
-
-// Emulates server returning with data and/or error.
-- (void)didFinishWithData:(NSData *)data error:(NSError *)error;
-
-- (instancetype)initWithRequest:(NSURLRequest *)request;
-@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

+ 104 - 0
GoogleSignIn/Tests/Unit/GIDHTTPFetcherTest.m

@@ -0,0 +1,104 @@
+// 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/GIDHTTPFetcher/Implementations/GIDHTTPFetcher.h"
+
+#import "GoogleSignIn/Tests/Unit/OIDAuthState+Testing.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 GIDHTTPFetcherTest : XCTestCase {
+  GIDHTTPFetcher *_httpFetcher;
+}
+
+@end
+
+@implementation GIDHTTPFetcherTest
+
+- (void)setUp {
+  [super setUp];
+  _httpFetcher = [[GIDHTTPFetcher alloc] init];
+}
+
+- (void)testFetchData_success {
+  NSURL *url = [NSURL URLWithString:kTestURL];
+  NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
+  OIDAuthState *authState = [OIDAuthState testInstance];
+  GTMAppAuthFetcherAuthorization *authorization =
+      [[GTMAppAuthFetcherAuthorization alloc] initWithAuthState:authState];
+  GTMSessionFetcherTestBlock block =
+      ^(GTMSessionFetcher *fetcherToTest, GTMSessionFetcherTestResponse testResponse) {
+        NSData *data = [[NSData alloc] init];
+        testResponse(nil, data, nil);
+      };
+  [GTMSessionFetcher setGlobalTestBlock:block];
+  
+  XCTestExpectation *expectation =
+      [self expectationWithDescription:@"Callback called with no error"];
+  
+  [_httpFetcher fetchURLRequest:request
+                 withAuthorizer:authorization
+                    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];
+  NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
+  OIDAuthState *authState = [OIDAuthState testInstance];
+  GTMAppAuthFetcherAuthorization *authorization =
+      [[GTMAppAuthFetcherAuthorization alloc] initWithAuthState:authState];
+  GTMSessionFetcherTestBlock block =
+      ^(GTMSessionFetcher *fetcherToTest, GTMSessionFetcherTestResponse testResponse) {
+        NSData *data = [[NSData alloc] init];
+        NSError *error = [self error];
+        testResponse(nil, data, error);
+      };
+  [GTMSessionFetcher setGlobalTestBlock:block];
+  
+  XCTestExpectation *expectation =
+      [self expectationWithDescription:@"Callback called with an error"];
+  
+  [_httpFetcher fetchURLRequest:request
+                 withAuthorizer:authorization
+                    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

+ 125 - 119
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/GIDHTTPFetcher/Implementations/Fakes/GIDFakeHTTPFetcher.h"
+#import "GoogleSignIn/Sources/GIDHTTPFetcher/Implementations/GIDHTTPFetcher.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 |GIDHTTPFetcher|.
+  GIDFakeHTTPFetcher *_httpFetcher;
+  
 #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];
+  
+  _httpFetcher = [[GIDFakeHTTPFetcher alloc] init];
+  
+  _signIn = [[GIDSignIn alloc] initWithKeychainHandler:_keychainHandler
+                                           httpFetcher:_httpFetcher];
   _hint = nil;
 
   __weak GIDSignInTest *weakSelf = self;
@@ -739,135 +743,166 @@ 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];
-  XCTestExpectation *expectation =
+  OCMStub([_authState lastTokenResponse]).andReturn(_tokenResponse);
+  OCMStub([_tokenResponse accessToken]).andReturn(kAccessToken);
+  
+  XCTestExpectation *fetcherExpectation =
+      [self expectationWithDescription:@"testBlock is invoked."];
+  GIDHTTPFetcherTestBlock testBlock =
+      ^(NSURLRequest *request, GIDHTTPFetcherFakeResponseProviderBlock responseProvider) {
+        [self verifyRevokeRequest:request withToken:kAccessToken];
+        NSData *data = [[NSData alloc] init];
+        responseProvider(data, nil);
+        [fetcherExpectation fulfill];
+      };
+  [_httpFetcher setTestBlock:testBlock];
+  
+  XCTestExpectation *completionExpectation =
       [self expectationWithDescription:@"Callback called with nil error"];
   [_signIn disconnectWithCompletion:^(NSError * _Nullable error) {
-    if (error == nil) {
-      [expectation fulfill];
-    }
+    XCTAssertNil(error);
+    [completionExpectation 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);
+  
+  XCTestExpectation *fetcherExpectation =
+      [self expectationWithDescription:@"testBlock is invoked."];
+  GIDHTTPFetcherTestBlock testBlock =
+      ^(NSURLRequest *request, GIDHTTPFetcherFakeResponseProviderBlock responseProvider) {
+        [self verifyRevokeRequest:request withToken:kAccessToken];
+        NSData *data = [[NSData alloc] init];
+        responseProvider(data, nil);
+        [fetcherExpectation fulfill];
+      };
+  [_httpFetcher setTestBlock:testBlock];
+  
   [_signIn disconnectWithCompletion:nil];
-  [self verifyAndRevokeToken:kAccessToken hasCallback:NO];
-  [_authorization verify];
-  [_authState verify];
-  [_tokenResponse verify];
+  [self waitForExpectationsWithTimeout:1 handler:nil];
   XCTAssertNil([_keychainHandler loadAuthState]);
 }
 
 // Verifies disconnect calls callback with no errors if refresh token is present.
-- (void)testDisconnect_refreshToken {
+- (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];
-  XCTestExpectation *expectation =
+  OCMStub([_authState lastTokenResponse]).andReturn(_tokenResponse);
+  OCMStub([_tokenResponse accessToken]).andReturn(nil);
+  OCMStub([_tokenResponse refreshToken]).andReturn(kRefreshToken);
+  
+  XCTestExpectation *fetcherExpectation =
+      [self expectationWithDescription:@"testBlock is invoked."];
+  GIDHTTPFetcherTestBlock testBlock =
+      ^(NSURLRequest *request, GIDHTTPFetcherFakeResponseProviderBlock responseProvider) {
+        [self verifyRevokeRequest:request withToken:kRefreshToken];
+        NSData *data = [[NSData alloc] init];
+        responseProvider(data, nil);
+        [fetcherExpectation fulfill];
+      };
+  [_httpFetcher setTestBlock:testBlock];
+  
+  XCTestExpectation *completionExpectation =
       [self expectationWithDescription:@"Callback called with nil error"];
   [_signIn disconnectWithCompletion:^(NSError * _Nullable error) {
-    if (error == nil) {
-      [expectation fulfill];
-    }
+    XCTAssertNil(error);
+    [completionExpectation 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];
-  XCTestExpectation *expectation =
+  OCMStub([_authState lastTokenResponse]).andReturn(_tokenResponse);
+  OCMStub([_tokenResponse accessToken]).andReturn(kAccessToken);
+  
+  XCTestExpectation *fetcherExpectation =
+      [self expectationWithDescription:@"testBlock is invoked."];
+  GIDHTTPFetcherTestBlock testBlock =
+      ^(NSURLRequest *request, GIDHTTPFetcherFakeResponseProviderBlock responseProvider) {
+        [self verifyRevokeRequest:request withToken:kAccessToken];
+        NSError *error = [self error];
+        responseProvider(nil, error);
+        [fetcherExpectation fulfill];
+      };
+  [_httpFetcher setTestBlock:testBlock];
+  
+  XCTestExpectation *completionExpectation =
       [self expectationWithDescription:@"Callback called with an error"];
   [_signIn disconnectWithCompletion:^(NSError * _Nullable error) {
-    if (error != nil) {
-      [expectation fulfill];
-    }
+    XCTAssertNotNil(error);
+    [completionExpectation 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);
+  
+  XCTestExpectation *fetcherExpectation =
+      [self expectationWithDescription:@"testBlock is invoked."];
+  GIDHTTPFetcherTestBlock testBlock =
+      ^(NSURLRequest *request, GIDHTTPFetcherFakeResponseProviderBlock responseProvider) {
+        [self verifyRevokeRequest:request withToken:kAccessToken];
+        NSError *error = [self error];
+        responseProvider(nil, error);
+        [fetcherExpectation fulfill];
+      };
+  [_httpFetcher 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];
+  [self waitForExpectationsWithTimeout:1 handler:nil];
   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);
+  GIDHTTPFetcherTestBlock testBlock =
+      ^(NSURLRequest *request, GIDHTTPFetcherFakeResponseProviderBlock responseProvider) {
+        XCTFail(@"_httpFetcher should not be invoked.");
+      };
+  [_httpFetcher setTestBlock:testBlock];
+  
   XCTestExpectation *expectation =
       [self expectationWithDescription:@"Callback called with nil error"];
   [_signIn disconnectWithCompletion:^(NSError * _Nullable error) {
-    if (error == nil) {
-      [expectation fulfill];
-    }
+    XCTAssertNil(error);
+    [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);
+  GIDHTTPFetcherTestBlock testBlock =
+      ^(NSURLRequest *request, GIDHTTPFetcherFakeResponseProviderBlock responseProvider) {
+        XCTFail(@"_httpFetcher should not be invoked.");
+      };
+  [_httpFetcher setTestBlock:testBlock];
+  
   [_signIn disconnectWithCompletion:nil];
-  XCTAssertFalse([self isFetcherStarted], @"should not fetch");
-  [_authorization verify];
-  [_authState verify];
-  [_tokenResponse verify];
   XCTAssertNil([_keychainHandler loadAuthState]);
 }
 
@@ -1085,55 +1120,26 @@ 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];
+- (void)verifyRevokeRequest:(NSURLRequest *)request withToken:(NSString *)token {
+  NSURL *url = request.URL;
   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");
   OIDURLQueryComponent *queryComponent = [[OIDURLQueryComponent alloc] initWithURL:url];
   NSDictionary<NSString *, NSObject<NSCopying> *> *params = queryComponent.dictionaryValue;
-  XCTAssertEqualObjects([params valueForKey:@"token"], token,
-                        @"token parameter should match");
   XCTAssertEqualObjects([params valueForKey:kSDKVersionLoggingParameter], GIDVersion(),
                         @"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];
-  }
+
+  NSData *body = request.HTTPBody;
+  NSString* bodyString = [[NSString alloc] initWithData:body encoding:NSUTF8StringEncoding];
+  NSArray<NSString *> *strings = [bodyString componentsSeparatedByString:@"="];
+  XCTAssertEqualObjects(strings[1], token);
 }
 
 - (void)OAuthLoginWithAddScopesFlow:(BOOL)addScopesFlow