From acc4bbf505659934ced4214715d9fd7c65fab8bf Mon Sep 17 00:00:00 2001 From: Paul Beusterien Date: Mon, 9 Dec 2024 13:03:12 -0800 Subject: [PATCH] Auth Unit Test Fixes (#14223) --- .../AuthProvider/PhoneAuthProvider.swift | 2 +- .../SystemService/AuthAPNSTokenManager.swift | 2 +- .../AuthAppCredentialManager.swift | 2 +- .../AuthNotificationManager.swift | 2 +- .../Tests/Unit/AuthBackendTests.swift | 18 +- FirebaseAuth/Tests/Unit/AuthTests.swift | 250 +++++++++--------- .../Tests/Unit/CreateAuthURITests.swift | 16 +- .../Tests/Unit/DeleteAccountTests.swift | 6 +- .../Tests/Unit/EmailLinkSignInTests.swift | 29 +- .../Unit/Fakes/FakeBackendRPCIssuer.swift | 98 +++---- .../Tests/Unit/GetAccountInfoTests.swift | 5 +- .../Unit/GetOOBConfirmationCodeTests.swift | 10 +- .../Tests/Unit/GetProjectConfigTests.swift | 8 +- .../Tests/Unit/OAuthProviderTests.swift | 20 +- .../Tests/Unit/PhoneAuthProviderTests.swift | 71 ++--- FirebaseAuth/Tests/Unit/RPCBaseTests.swift | 8 +- .../Tests/Unit/ResetPasswordTests.swift | 4 +- .../Tests/Unit/RevokeTokenTests.swift | 2 +- .../Unit/SendVerificationCodeTests.swift | 2 +- .../Tests/Unit/SetAccountInfoTests.swift | 2 +- .../Unit/SignInWithGameCenterTests.swift | 2 +- .../Tests/Unit/SignUpNewUserTests.swift | 2 +- FirebaseAuth/Tests/Unit/UserTests.swift | 183 ++++++------- .../Tests/Unit/VerifyAssertionTests.swift | 4 +- .../Tests/Unit/VerifyClientTests.swift | 2 +- .../Tests/Unit/VerifyCustomTokenTests.swift | 2 +- .../Tests/Unit/VerifyPasswordTests.swift | 2 +- .../Tests/Unit/VerifyPhoneNumberTests.swift | 4 +- 28 files changed, 378 insertions(+), 380 deletions(-) diff --git a/FirebaseAuth/Sources/Swift/AuthProvider/PhoneAuthProvider.swift b/FirebaseAuth/Sources/Swift/AuthProvider/PhoneAuthProvider.swift index b50636615cc..8c7a6982fd4 100644 --- a/FirebaseAuth/Sources/Swift/AuthProvider/PhoneAuthProvider.swift +++ b/FirebaseAuth/Sources/Swift/AuthProvider/PhoneAuthProvider.swift @@ -525,7 +525,7 @@ import Foundation ) } - return try await withCheckedThrowingContinuation { continuation in + return try await withUnsafeThrowingContinuation { continuation in self.auth.authURLPresenter.present(url, uiDelegate: uiDelegate, callbackMatcher: callbackMatcher) { callbackURL, error in diff --git a/FirebaseAuth/Sources/Swift/SystemService/AuthAPNSTokenManager.swift b/FirebaseAuth/Sources/Swift/SystemService/AuthAPNSTokenManager.swift index ff677b8771b..479918165e9 100644 --- a/FirebaseAuth/Sources/Swift/SystemService/AuthAPNSTokenManager.swift +++ b/FirebaseAuth/Sources/Swift/SystemService/AuthAPNSTokenManager.swift @@ -74,7 +74,7 @@ } func getToken() async throws -> AuthAPNSToken { - return try await withCheckedThrowingContinuation { continuation in + return try await withUnsafeThrowingContinuation { continuation in self.getTokenInternal { result in switch result { case let .success(token): diff --git a/FirebaseAuth/Sources/Swift/SystemService/AuthAppCredentialManager.swift b/FirebaseAuth/Sources/Swift/SystemService/AuthAppCredentialManager.swift index 0c83875a8d1..a513dd1cbb0 100644 --- a/FirebaseAuth/Sources/Swift/SystemService/AuthAppCredentialManager.swift +++ b/FirebaseAuth/Sources/Swift/SystemService/AuthAppCredentialManager.swift @@ -65,7 +65,7 @@ func didStartVerification(withReceipt receipt: String, timeout: TimeInterval) async -> AuthAppCredential { - return await withCheckedContinuation { continuation in + return await withUnsafeContinuation { continuation in self.didStartVerificationInternal(withReceipt: receipt, timeout: timeout) { credential in continuation.resume(returning: credential) } diff --git a/FirebaseAuth/Sources/Swift/SystemService/AuthNotificationManager.swift b/FirebaseAuth/Sources/Swift/SystemService/AuthNotificationManager.swift index 2cfd76ca2de..296ab5d4b28 100644 --- a/FirebaseAuth/Sources/Swift/SystemService/AuthNotificationManager.swift +++ b/FirebaseAuth/Sources/Swift/SystemService/AuthNotificationManager.swift @@ -114,7 +114,7 @@ } func checkNotificationForwarding() async -> Bool { - return await withCheckedContinuation { continuation in + return await withUnsafeContinuation { continuation in checkNotificationForwardingInternal { value in continuation.resume(returning: value) } diff --git a/FirebaseAuth/Tests/Unit/AuthBackendTests.swift b/FirebaseAuth/Tests/Unit/AuthBackendTests.swift index 6056bbae362..748a5ba1982 100644 --- a/FirebaseAuth/Tests/Unit/AuthBackendTests.swift +++ b/FirebaseAuth/Tests/Unit/AuthBackendTests.swift @@ -90,7 +90,7 @@ class AuthBackendTests: RPCBaseTests { let request = FakeRequest(withRequestBody: [:]) rpcIssuer.respondBlock = { let responseError = NSError(domain: self.kFakeErrorDomain, code: self.kFakeErrorCode) - try self.rpcIssuer.respond(withData: nil, error: responseError) + return (nil, responseError) } do { let _ = try await authBackend.call(with: request) @@ -122,7 +122,7 @@ class AuthBackendTests: RPCBaseTests { let request = FakeRequest(withRequestBody: [:]) rpcIssuer.respondBlock = { let responseError = NSError(domain: self.kFakeErrorDomain, code: self.kFakeErrorCode) - try self.rpcIssuer.respond(withData: data, error: responseError) + return (data, error: responseError) } do { let _ = try await authBackend.call(with: request) @@ -159,7 +159,7 @@ class AuthBackendTests: RPCBaseTests { let data = "Some non-JSON value.".data(using: .utf8) let request = FakeRequest(withRequestBody: [:]) rpcIssuer.respondBlock = { - try self.rpcIssuer.respond(withData: data, error: nil) + (data, nil) } do { let _ = try await authBackend.call(with: request) @@ -201,7 +201,7 @@ class AuthBackendTests: RPCBaseTests { let responseError = NSError(domain: kFakeErrorDomain, code: kFakeErrorCode) let request = FakeRequest(withRequestBody: [:]) rpcIssuer.respondBlock = { - try self.rpcIssuer.respond(withData: data, error: responseError) + (data, responseError) } do { let _ = try await authBackend.call(with: request) @@ -243,7 +243,7 @@ class AuthBackendTests: RPCBaseTests { let data = "[]".data(using: .utf8) let request = FakeRequest(withRequestBody: [:]) rpcIssuer.respondBlock = { - try self.rpcIssuer.respond(withData: data, error: nil) + (data, nil) } do { let _ = try await authBackend.call(with: request) @@ -277,8 +277,8 @@ class AuthBackendTests: RPCBaseTests { let request = FakeRequest(withRequestBody: [:]) rpcIssuer.respondBlock = { let responseError = NSError(domain: self.kFakeErrorDomain, code: self.kFakeErrorCode) - try self.rpcIssuer.respond(serverErrorMessage: kErrorMessageCaptchaRequired, - error: responseError) + return try self.rpcIssuer.respond(serverErrorMessage: kErrorMessageCaptchaRequired, + error: responseError) } do { let _ = try await authBackend.call(with: request) @@ -317,7 +317,7 @@ class AuthBackendTests: RPCBaseTests { let request = FakeRequest(withRequestBody: [:]) rpcIssuer.respondBlock = { let responseError = NSError(domain: self.kFakeErrorDomain, code: self.kFakeErrorCode) - try self.rpcIssuer.respond( + return try self.rpcIssuer.respond( serverErrorMessage: kErrorMessageCaptchaCheckFailed, error: responseError ) @@ -427,7 +427,7 @@ class AuthBackendTests: RPCBaseTests { let request = FakeRequest(withRequestBody: [:]) let responseError = NSError(domain: kFakeErrorDomain, code: kFakeErrorCode) rpcIssuer.respondBlock = { - let _ = try self.rpcIssuer.respond(withJSON: [:], error: responseError) + try self.rpcIssuer.respond(withJSON: [:], error: responseError) } do { let _ = try await authBackend.call(with: request) diff --git a/FirebaseAuth/Tests/Unit/AuthTests.swift b/FirebaseAuth/Tests/Unit/AuthTests.swift index 9bf57b39dd3..fe7be777cc9 100644 --- a/FirebaseAuth/Tests/Unit/AuthTests.swift +++ b/FirebaseAuth/Tests/Unit/AuthTests.swift @@ -84,7 +84,7 @@ class AuthTests: RPCBaseTests { XCTAssertEqual(request.endpoint, "createAuthUri") XCTAssertEqual(request.apiKey, AuthTests.kFakeAPIKey) - try self.rpcIssuer.respond(withJSON: ["signinMethods": allSignInMethods]) + return try self.rpcIssuer.respond(withJSON: ["signinMethods": allSignInMethods]) } auth?.fetchSignInMethods(forEmail: kEmail) { signInMethods, error in @@ -106,7 +106,7 @@ class AuthTests: RPCBaseTests { rpcIssuer.respondBlock = { let message = "TOO_MANY_ATTEMPTS_TRY_LATER" - try self.rpcIssuer.respond(serverErrorMessage: message) + return try self.rpcIssuer.respond(serverErrorMessage: message) } auth?.fetchSignInMethods(forEmail: kEmail) { signInMethods, error in XCTAssertTrue(Thread.isMainThread) @@ -137,9 +137,9 @@ class AuthTests: RPCBaseTests { XCTAssertEqual(request.verificationID, kVerificationID) // 3. Send the response from the fake backend. - try self.rpcIssuer.respond(withJSON: ["idToken": AuthTests.kAccessToken, - "isNewUser": true, - "refreshToken": self.kRefreshToken]) + return try self.rpcIssuer.respond(withJSON: ["idToken": AuthTests.kAccessToken, + "isNewUser": true, + "refreshToken": self.kRefreshToken]) } try auth?.signOut() @@ -241,10 +241,10 @@ class AuthTests: RPCBaseTests { XCTAssertEqual(request.oobCode, fakeCode) XCTAssertEqual(request.apiKey, AuthTests.kFakeAPIKey) - try self.rpcIssuer.respond(withJSON: ["idToken": AuthTests.kAccessToken, - "email": self.kEmail, - "isNewUser": true, - "refreshToken": self.kRefreshToken]) + return try self.rpcIssuer.respond(withJSON: ["idToken": AuthTests.kAccessToken, + "email": self.kEmail, + "isNewUser": true, + "refreshToken": self.kRefreshToken]) } try auth?.signOut() auth?.signIn(withEmail: kEmail, link: link) { authResult, error in @@ -309,10 +309,10 @@ class AuthTests: RPCBaseTests { recaptchaVersion: AuthTests.kFakeRecaptchaVersion) // 3. Send the response from the fake backend. - try self.rpcIssuer.respond(withJSON: ["idToken": AuthTests.kAccessToken, - "email": self.kEmail, - "isNewUser": true, - "refreshToken": kRefreshToken]) + return try self.rpcIssuer.respond(withJSON: ["idToken": AuthTests.kAccessToken, + "email": self.kEmail, + "isNewUser": true, + "refreshToken": kRefreshToken]) } try auth?.signOut() @@ -362,7 +362,7 @@ class AuthTests: RPCBaseTests { recaptchaVersion: AuthTests.kFakeRecaptchaVersion) // 3. Send the response from the fake backend. - try self.rpcIssuer.respond(serverErrorMessage: "MISSING_RECAPTCHA_TOKEN") + return try self.rpcIssuer.respond(serverErrorMessage: "MISSING_RECAPTCHA_TOKEN") } rpcIssuer.nextRespondBlock = { // 4. Validate again the created Request instance after the recaptcha retry. @@ -374,10 +374,10 @@ class AuthTests: RPCBaseTests { request.injectRecaptchaFields(recaptchaResponse: AuthTests.kFakeRecaptchaResponse, recaptchaVersion: AuthTests.kFakeRecaptchaVersion) // 5. Send the response from the fake backend. - try self.rpcIssuer.respond(withJSON: ["idToken": AuthTests.kAccessToken, - "email": self.kEmail, - "isNewUser": true, - "refreshToken": kRefreshToken]) + return try self.rpcIssuer.respond(withJSON: ["idToken": AuthTests.kAccessToken, + "email": self.kEmail, + "isNewUser": true, + "refreshToken": kRefreshToken]) } try auth?.signOut() @@ -425,10 +425,10 @@ class AuthTests: RPCBaseTests { XCTAssertTrue(request.returnSecureToken) // 3. Send the response from the fake backend. - try self.rpcIssuer.respond(withJSON: ["idToken": AuthTests.kAccessToken, - "email": self.kEmail, - "isNewUser": true, - "refreshToken": kRefreshToken]) + return try self.rpcIssuer.respond(withJSON: ["idToken": AuthTests.kAccessToken, + "email": self.kEmail, + "isNewUser": true, + "refreshToken": kRefreshToken]) } try auth?.signOut() @@ -495,7 +495,7 @@ class AuthTests: RPCBaseTests { XCTAssertEqual(request.apiKey, AuthTests.kFakeAPIKey) // 3. Send the response from the fake backend. - try self.rpcIssuer.respond(withJSON: [:]) + return try self.rpcIssuer.respond(withJSON: [:]) } try auth?.signOut() auth? @@ -549,9 +549,9 @@ class AuthTests: RPCBaseTests { XCTAssertEqual(request.apiKey, AuthTests.kFakeAPIKey) // 3. Send the response from the fake backend. - try self.rpcIssuer.respond(withJSON: ["email": self.kEmail, - "requestType": verifyEmailRequestType, - "newEmail": kNewEmail]) + return try self.rpcIssuer.respond(withJSON: ["email": self.kEmail, + "requestType": verifyEmailRequestType, + "newEmail": kNewEmail]) } try auth?.signOut() auth?.checkActionCode(kFakeOobCode) { info, error in @@ -601,7 +601,7 @@ class AuthTests: RPCBaseTests { XCTAssertEqual(request.apiKey, AuthTests.kFakeAPIKey) // 3. Send the response from the fake backend. - try self.rpcIssuer.respond(withJSON: [:]) + return try self.rpcIssuer.respond(withJSON: [:]) } try auth?.signOut() auth?.applyActionCode(kFakeOobCode) { error in @@ -650,7 +650,7 @@ class AuthTests: RPCBaseTests { XCTAssertEqual(request.oobCode, self.kFakeOobCode) // 3. Send the response from the fake backend. - try self.rpcIssuer.respond(withJSON: ["email": self.kEmail]) + return try self.rpcIssuer.respond(withJSON: ["email": self.kEmail]) } try auth?.signOut() auth?.verifyPasswordResetCode(kFakeOobCode) { email, error in @@ -706,9 +706,9 @@ class AuthTests: RPCBaseTests { XCTAssertEqual(request.email, self.kEmail) // 3. Send the response from the fake backend. - try self.rpcIssuer.respond(withJSON: ["idToken": AuthTests.kAccessToken, - "isNewUser": true, - "refreshToken": self.kRefreshToken]) + return try self.rpcIssuer.respond(withJSON: ["idToken": AuthTests.kAccessToken, + "isNewUser": true, + "refreshToken": self.kRefreshToken]) } try auth?.signOut() let emailCredential = EmailAuthProvider.credential( @@ -778,9 +778,9 @@ class AuthTests: RPCBaseTests { XCTAssertEqual(request.email, self.kEmail) // 3. Send the response from the fake backend. - try self.rpcIssuer.respond(withJSON: ["idToken": AuthTests.kAccessToken, - "isNewUser": true, - "refreshToken": self.kRefreshToken]) + return try self.rpcIssuer.respond(withJSON: ["idToken": AuthTests.kAccessToken, + "isNewUser": true, + "refreshToken": self.kRefreshToken]) } try auth?.signOut() let emailCredential = EmailAuthProvider.credential(withEmail: kEmail, password: kFakePassword) @@ -876,14 +876,14 @@ class AuthTests: RPCBaseTests { XCTAssertTrue(request.returnSecureToken) // 3. Send the response from the fake backend. - try self.rpcIssuer.respond(withJSON: ["idToken": RPCBaseTests.kFakeAccessToken, - "refreshToken": self.kRefreshToken, - "federatedId": self.kGoogleID, - "providerId": GoogleAuthProvider.id, - "localId": self.kLocalID, - "displayName": self.kDisplayName, - "rawUserInfo": self.kGoogleProfile, - "username": self.kUserName]) + return try self.rpcIssuer.respond(withJSON: ["idToken": RPCBaseTests.kFakeAccessToken, + "refreshToken": self.kRefreshToken, + "federatedId": self.kGoogleID, + "providerId": GoogleAuthProvider.id, + "localId": self.kLocalID, + "displayName": self.kDisplayName, + "rawUserInfo": self.kGoogleProfile, + "username": self.kUserName]) } try auth.signOut() auth.signIn(with: FakeProvider(), uiDelegate: nil) { authResult, error in @@ -919,7 +919,7 @@ class AuthTests: RPCBaseTests { XCTAssertTrue(request.returnSecureToken) // 3. Send the response from the fake backend. - try self.rpcIssuer.respond(serverErrorMessage: "USER_DISABLED") + return try self.rpcIssuer.respond(serverErrorMessage: "USER_DISABLED") } try auth.signOut() auth.signIn(with: FakeProvider(), uiDelegate: nil) { authResult, error in @@ -953,15 +953,15 @@ class AuthTests: RPCBaseTests { XCTAssertTrue(request.returnSecureToken) // 3. Send the response from the fake backend. - try self.rpcIssuer.respond(withJSON: ["idToken": RPCBaseTests.kFakeAccessToken, - "refreshToken": self.kRefreshToken, - "federatedId": self.kGoogleID, - "providerId": GoogleAuthProvider.id, - "localId": self.kLocalID, - "displayName": self.kGoogleDisplayName, - "rawUserInfo": self.kGoogleProfile, - "username": self.kUserName, - "needConfirmation": true]) + return try self.rpcIssuer.respond(withJSON: ["idToken": RPCBaseTests.kFakeAccessToken, + "refreshToken": self.kRefreshToken, + "federatedId": self.kGoogleID, + "providerId": GoogleAuthProvider.id, + "localId": self.kLocalID, + "displayName": self.kGoogleDisplayName, + "rawUserInfo": self.kGoogleProfile, + "username": self.kUserName, + "needConfirmation": true]) } try auth.signOut() let googleCredential = GoogleAuthProvider.credential(withIDToken: kGoogleIDToken, @@ -997,14 +997,14 @@ class AuthTests: RPCBaseTests { XCTAssertTrue(request.returnSecureToken) // 3. Send the response from the fake backend. - try self.rpcIssuer.respond(withJSON: ["idToken": RPCBaseTests.kFakeAccessToken, - "refreshToken": self.kRefreshToken, - "federatedId": self.kGoogleID, - "providerId": GoogleAuthProvider.id, - "localId": self.kLocalID, - "displayName": self.kGoogleDisplayName, - "rawUserInfo": self.kGoogleProfile, - "username": self.kUserName]) + return try self.rpcIssuer.respond(withJSON: ["idToken": RPCBaseTests.kFakeAccessToken, + "refreshToken": self.kRefreshToken, + "federatedId": self.kGoogleID, + "providerId": GoogleAuthProvider.id, + "localId": self.kLocalID, + "displayName": self.kGoogleDisplayName, + "rawUserInfo": self.kGoogleProfile, + "username": self.kUserName]) } try auth.signOut() auth.signIn(with: FakeProvider(), uiDelegate: nil) { authResult, error in @@ -1043,14 +1043,14 @@ class AuthTests: RPCBaseTests { XCTAssertTrue(request.returnSecureToken) // 3. Send the response from the fake backend. - try self.rpcIssuer.respond(withJSON: ["idToken": RPCBaseTests.kFakeAccessToken, - "refreshToken": self.kRefreshToken, - "federatedId": self.kGoogleID, - "providerId": GoogleAuthProvider.id, - "localId": self.kLocalID, - "displayName": self.kGoogleDisplayName, - "rawUserInfo": self.kGoogleProfile, - "username": self.kGoogleDisplayName]) + return try self.rpcIssuer.respond(withJSON: ["idToken": RPCBaseTests.kFakeAccessToken, + "refreshToken": self.kRefreshToken, + "federatedId": self.kGoogleID, + "providerId": GoogleAuthProvider.id, + "localId": self.kLocalID, + "displayName": self.kGoogleDisplayName, + "rawUserInfo": self.kGoogleProfile, + "username": self.kGoogleDisplayName]) } try auth.signOut() let googleCredential = GoogleAuthProvider.credential(withIDToken: kGoogleIDToken, @@ -1095,7 +1095,7 @@ class AuthTests: RPCBaseTests { XCTAssertTrue(request.returnSecureToken) // 3. Send the response from the fake backend. - try self.rpcIssuer.respond(serverErrorMessage: "EMAIL_EXISTS") + return try self.rpcIssuer.respond(serverErrorMessage: "EMAIL_EXISTS") } try auth.signOut() let googleCredential = GoogleAuthProvider.credential(withIDToken: kGoogleIDToken, @@ -1139,16 +1139,16 @@ class AuthTests: RPCBaseTests { XCTAssertTrue(request.returnSecureToken) // 3. Send the response from the fake backend. - try self.rpcIssuer.respond(withJSON: ["idToken": RPCBaseTests.kFakeAccessToken, - "refreshToken": self.kRefreshToken, - "federatedId": self.kGoogleID, - "providerId": AuthProviderID.apple.rawValue, - "localId": self.kLocalID, - "displayName": self.kGoogleDisplayName, - "rawUserInfo": self.kGoogleProfile, - "firstName": kFirst, - "lastName": kLast, - "username": self.kGoogleDisplayName]) + return try self.rpcIssuer.respond(withJSON: ["idToken": RPCBaseTests.kFakeAccessToken, + "refreshToken": self.kRefreshToken, + "federatedId": self.kGoogleID, + "providerId": AuthProviderID.apple.rawValue, + "localId": self.kLocalID, + "displayName": self.kGoogleDisplayName, + "rawUserInfo": self.kGoogleProfile, + "firstName": kFirst, + "lastName": kLast, + "username": self.kGoogleDisplayName]) } try auth.signOut() let appleCredential = OAuthProvider.appleCredential(withIDToken: kAppleIDToken, @@ -1194,10 +1194,10 @@ class AuthTests: RPCBaseTests { XCTAssertTrue(request.returnSecureToken) // 3. Send the response from the fake backend. - try self.rpcIssuer.respond(withJSON: ["idToken": AuthTests.kAccessToken, - "email": self.kEmail, - "isNewUser": true, - "refreshToken": self.kRefreshToken]) + return try self.rpcIssuer.respond(withJSON: ["idToken": AuthTests.kAccessToken, + "email": self.kEmail, + "isNewUser": true, + "refreshToken": self.kRefreshToken]) } try auth?.signOut() auth?.signInAnonymously { authResult, error in @@ -1257,10 +1257,10 @@ class AuthTests: RPCBaseTests { XCTAssertTrue(request.returnSecureToken) // 3. Send the response from the fake backend. - try self.rpcIssuer.respond(withJSON: ["idToken": AuthTests.kAccessToken, - "email": self.kEmail, - "isNewUser": false, - "refreshToken": self.kRefreshToken]) + return try self.rpcIssuer.respond(withJSON: ["idToken": AuthTests.kAccessToken, + "email": self.kEmail, + "isNewUser": false, + "refreshToken": self.kRefreshToken]) } try auth?.signOut() auth?.signIn(withCustomToken: kCustomToken) { authResult, error in @@ -1327,10 +1327,10 @@ class AuthTests: RPCBaseTests { recaptchaVersion: AuthTests.kFakeRecaptchaVersion) // 3. Send the response from the fake backend. - try self.rpcIssuer.respond(withJSON: ["idToken": AuthTests.kAccessToken, - "email": self.kEmail, - "isNewUser": true, - "refreshToken": self.kRefreshToken]) + return try self.rpcIssuer.respond(withJSON: ["idToken": AuthTests.kAccessToken, + "email": self.kEmail, + "isNewUser": true, + "refreshToken": self.kRefreshToken]) } try auth?.signOut() auth?.createUser(withEmail: kEmail, password: kFakePassword) { authResult, error in @@ -1375,7 +1375,7 @@ class AuthTests: RPCBaseTests { recaptchaVersion: AuthTests.kFakeRecaptchaVersion) // 3. Send the response from the fake backend. - try self.rpcIssuer.respond(serverErrorMessage: "MISSING_RECAPTCHA_TOKEN") + return try self.rpcIssuer.respond(serverErrorMessage: "MISSING_RECAPTCHA_TOKEN") } rpcIssuer.nextRespondBlock = { // 4. Validate again the created Request instance after the recaptcha retry. @@ -1387,10 +1387,10 @@ class AuthTests: RPCBaseTests { request.injectRecaptchaFields(recaptchaResponse: AuthTests.kFakeRecaptchaResponse, recaptchaVersion: AuthTests.kFakeRecaptchaVersion) // 5. Send the response from the fake backend. - try self.rpcIssuer.respond(withJSON: ["idToken": AuthTests.kAccessToken, - "email": self.kEmail, - "isNewUser": true, - "refreshToken": self.kRefreshToken]) + return try self.rpcIssuer.respond(withJSON: ["idToken": AuthTests.kAccessToken, + "email": self.kEmail, + "isNewUser": true, + "refreshToken": self.kRefreshToken]) } try auth?.signOut() @@ -1432,10 +1432,10 @@ class AuthTests: RPCBaseTests { XCTAssertTrue(request.returnSecureToken) // 3. Send the response from the fake backend. - try self.rpcIssuer.respond(withJSON: ["idToken": AuthTests.kAccessToken, - "email": self.kEmail, - "isNewUser": true, - "refreshToken": self.kRefreshToken]) + return try self.rpcIssuer.respond(withJSON: ["idToken": AuthTests.kAccessToken, + "email": self.kEmail, + "isNewUser": true, + "refreshToken": self.kRefreshToken]) } try auth?.signOut() auth?.createUser(withEmail: kEmail, password: kFakePassword) { authResult, error in @@ -1532,7 +1532,7 @@ class AuthTests: RPCBaseTests { recaptchaVersion: AuthTests.kFakeRecaptchaVersion) // 3. Send the response from the fake backend. - _ = try self.rpcIssuer.respond(withJSON: [:]) + return try self.rpcIssuer.respond(withJSON: [:]) } auth?.sendPasswordReset(withEmail: kEmail) { error in // 4. After the response triggers the callback, verify success. @@ -1561,7 +1561,7 @@ class AuthTests: RPCBaseTests { recaptchaVersion: AuthTests.kFakeRecaptchaVersion) // 3. Send the response from the fake backend. - try self.rpcIssuer.respond(serverErrorMessage: "MISSING_RECAPTCHA_TOKEN") + return try self.rpcIssuer.respond(serverErrorMessage: "MISSING_RECAPTCHA_TOKEN") } rpcIssuer.nextRespondBlock = { // 4. Validate again the created Request instance after the recaptcha retry. @@ -1571,10 +1571,10 @@ class AuthTests: RPCBaseTests { request.injectRecaptchaFields(recaptchaResponse: AuthTests.kFakeRecaptchaResponse, recaptchaVersion: AuthTests.kFakeRecaptchaVersion) // 5. Send the response from the fake backend. - try self.rpcIssuer.respond(withJSON: ["idToken": AuthTests.kAccessToken, - "email": self.kEmail, - "isNewUser": true, - "refreshToken": self.kRefreshToken]) + return try self.rpcIssuer.respond(withJSON: ["idToken": AuthTests.kAccessToken, + "email": self.kEmail, + "isNewUser": true, + "refreshToken": self.kRefreshToken]) } auth?.sendPasswordReset(withEmail: kEmail) { error in @@ -1601,7 +1601,7 @@ class AuthTests: RPCBaseTests { XCTAssertEqual(request.apiKey, AuthTests.kFakeAPIKey) // 3. Send the response from the fake backend. - _ = try self.rpcIssuer.respond(withJSON: [:]) + return try self.rpcIssuer.respond(withJSON: [:]) } auth?.sendPasswordReset(withEmail: kEmail) { error in // 4. After the response triggers the callback, verify success. @@ -1651,7 +1651,7 @@ class AuthTests: RPCBaseTests { recaptchaVersion: AuthTests.kFakeRecaptchaVersion) // 3. Send the response from the fake backend. - _ = try self.rpcIssuer.respond(withJSON: [:]) + return try self.rpcIssuer.respond(withJSON: [:]) } auth?.sendSignInLink(toEmail: kEmail, actionCodeSettings: fakeActionCodeSettings()) { error in @@ -1683,7 +1683,7 @@ class AuthTests: RPCBaseTests { recaptchaVersion: AuthTests.kFakeRecaptchaVersion) // 3. Send the response from the fake backend. - _ = try self.rpcIssuer.respond(withJSON: [:]) + return try self.rpcIssuer.respond(withJSON: [:]) } rpcIssuer.nextRespondBlock = { // 4. Validate again the created Request instance after the recaptcha retry. @@ -1693,10 +1693,10 @@ class AuthTests: RPCBaseTests { request.injectRecaptchaFields(recaptchaResponse: AuthTests.kFakeRecaptchaResponse, recaptchaVersion: AuthTests.kFakeRecaptchaVersion) // 5. Send the response from the fake backend. - try self.rpcIssuer.respond(withJSON: ["idToken": AuthTests.kAccessToken, - "email": self.kEmail, - "isNewUser": true, - "refreshToken": self.kRefreshToken]) + return try self.rpcIssuer.respond(withJSON: ["idToken": AuthTests.kAccessToken, + "email": self.kEmail, + "isNewUser": true, + "refreshToken": self.kRefreshToken]) } auth?.sendSignInLink(toEmail: kEmail, @@ -1726,7 +1726,7 @@ class AuthTests: RPCBaseTests { XCTAssertTrue(request.handleCodeInApp) // 3. Send the response from the fake backend. - _ = try self.rpcIssuer.respond(withJSON: [:]) + return try self.rpcIssuer.respond(withJSON: [:]) } auth?.sendSignInLink(toEmail: kEmail, actionCodeSettings: fakeActionCodeSettings()) { error in @@ -1797,7 +1797,7 @@ class AuthTests: RPCBaseTests { let kFakeErrorDomain = "fakeDomain" let kFakeErrorCode = -1 let responseError = NSError(domain: kFakeErrorDomain, code: kFakeErrorCode) - try self.rpcIssuer.respond(withData: nil, error: responseError) + return (nil, responseError) } // Clear fake so we can inject error rpcIssuer.fakeGetAccountProviderJSON = nil @@ -1916,7 +1916,7 @@ class AuthTests: RPCBaseTests { XCTAssertEqual(request.tokenType, .authorizationCode) // Send the response from the fake backend. - _ = try self.rpcIssuer.respond(withJSON: [:]) + return try self.rpcIssuer.respond(withJSON: [:]) } auth?.revokeToken(withAuthorizationCode: code) { error in // Verify callback success. @@ -1932,17 +1932,17 @@ class AuthTests: RPCBaseTests { func testRevokeTokenMissingCallback() throws { try waitForSignInWithAccessToken() let code = "code" - let issuer = rpcIssuer + let issuer = try XCTUnwrap(rpcIssuer) - issuer?.respondBlock = { - let request = try XCTUnwrap(issuer?.request as? RevokeTokenRequest) + issuer.respondBlock = { + let request = try XCTUnwrap(issuer.request as? RevokeTokenRequest) XCTAssertEqual(request.apiKey, AuthTests.kFakeAPIKey) XCTAssertEqual(request.providerID, AuthProviderID.apple.rawValue) XCTAssertEqual(request.token, code) XCTAssertEqual(request.tokenType, .authorizationCode) // Send the response from the fake backend. - _ = try issuer?.respond(withJSON: [:]) + return try issuer.respond(withJSON: [:]) } auth?.revokeToken(withAuthorizationCode: code) } @@ -2402,11 +2402,11 @@ class AuthTests: RPCBaseTests { XCTAssertTrue(request.returnSecureToken) // 3. Send the response from the fake backend. - try self.rpcIssuer.respond(withJSON: ["idToken": fakeAccessToken, - "email": self.kEmail, - "isNewUser": true, - "expiresIn": "3600", - "refreshToken": kRefreshToken]) + return try self.rpcIssuer.respond(withJSON: ["idToken": fakeAccessToken, + "email": self.kEmail, + "isNewUser": true, + "expiresIn": "3600", + "refreshToken": kRefreshToken]) } auth?.signIn(withEmail: kEmail, password: kFakePassword) { authResult, error in // 4. After the response triggers the callback, verify the returned result. diff --git a/FirebaseAuth/Tests/Unit/CreateAuthURITests.swift b/FirebaseAuth/Tests/Unit/CreateAuthURITests.swift index 334091d21fd..fde2b4d155c 100644 --- a/FirebaseAuth/Tests/Unit/CreateAuthURITests.swift +++ b/FirebaseAuth/Tests/Unit/CreateAuthURITests.swift @@ -71,9 +71,10 @@ class CreateAuthURITests: RPCBaseTests { func testSuccessfulCreateAuthURIResponse() async throws { let kAuthUriKey = "authUri" let kTestAuthUri = "AuthURI" + let rpcIssuer = try XCTUnwrap(self.rpcIssuer) - rpcIssuer?.respondBlock = { - try self.rpcIssuer?.respond(withJSON: [kAuthUriKey: kTestAuthUri]) + rpcIssuer.respondBlock = { + try self.rpcIssuer.respond(withJSON: [kAuthUriKey: kTestAuthUri]) } let rpcResponse = try await authBackend.call(with: makeAuthURIRequest()) XCTAssertEqual(rpcResponse.authURI, kTestAuthUri) @@ -83,17 +84,18 @@ class CreateAuthURITests: RPCBaseTests { let kTestExpectedKind = "identitytoolkit#CreateAuthUriResponse" let kTestProviderID1 = "google.com" let kTestProviderID2 = "facebook.com" + let rpcIssuer = try XCTUnwrap(self.rpcIssuer) - rpcIssuer?.respondBlock = { - try self.rpcIssuer? + rpcIssuer.respondBlock = { + try self.rpcIssuer .respond(withJSON: ["kind": kTestExpectedKind, "allProviders": [kTestProviderID1, kTestProviderID2]]) } let rpcResponse = try await authBackend.call(with: makeAuthURIRequest()) - XCTAssertEqual(rpcIssuer?.requestURL?.absoluteString, kExpectedAPIURL) - XCTAssertEqual(rpcIssuer?.decodedRequest?["identifier"] as? String, kTestIdentifier) - XCTAssertEqual(rpcIssuer?.decodedRequest?["continueUri"] as? String, kTestContinueURI) + XCTAssertEqual(rpcIssuer.requestURL?.absoluteString, kExpectedAPIURL) + XCTAssertEqual(rpcIssuer.decodedRequest?["identifier"] as? String, kTestIdentifier) + XCTAssertEqual(rpcIssuer.decodedRequest?["continueUri"] as? String, kTestContinueURI) XCTAssertEqual(rpcResponse.allProviders?.count, 2) XCTAssertEqual(rpcResponse.allProviders?.first, kTestProviderID1) diff --git a/FirebaseAuth/Tests/Unit/DeleteAccountTests.swift b/FirebaseAuth/Tests/Unit/DeleteAccountTests.swift index a968a02e3e8..5dabf73662b 100644 --- a/FirebaseAuth/Tests/Unit/DeleteAccountTests.swift +++ b/FirebaseAuth/Tests/Unit/DeleteAccountTests.swift @@ -61,8 +61,10 @@ class DeleteAccountTests: RPCBaseTests { @brief This test checks for a successful response */ func testSuccessfulDeleteAccountResponse() async throws { - rpcIssuer?.respondBlock = { - try self.rpcIssuer?.respond(withJSON: [:]) + let rpcIssuer = try XCTUnwrap(self.rpcIssuer) + + rpcIssuer.respondBlock = { + try self.rpcIssuer.respond(withJSON: [:]) } let rpcResponse = try await authBackend.call(with: makeDeleteAccountRequest()) XCTAssertNotNil(rpcResponse) diff --git a/FirebaseAuth/Tests/Unit/EmailLinkSignInTests.swift b/FirebaseAuth/Tests/Unit/EmailLinkSignInTests.swift index ce4b2dd57d5..49e9e7dabb9 100644 --- a/FirebaseAuth/Tests/Unit/EmailLinkSignInTests.swift +++ b/FirebaseAuth/Tests/Unit/EmailLinkSignInTests.swift @@ -54,16 +54,18 @@ class EmailLinkSignInTests: RPCBaseTests { @brief Tests the email link sign-in request with mandatory parameters. */ func testEmailLinkRequest() async throws { - rpcIssuer?.respondBlock = { + let rpcIssuer = try XCTUnwrap(self.rpcIssuer) + + rpcIssuer.respondBlock = { XCTAssertEqual(self.rpcIssuer?.requestURL?.absoluteString, self.kExpectedAPIURL) guard let requestDictionary = self.rpcIssuer?.decodedRequest as? [AnyHashable: String] else { XCTFail("decodedRequest is not a dictionary") - return + return (nil, nil) } XCTAssertEqual(requestDictionary[self.kEmailKey], self.kTestEmail) XCTAssertEqual(requestDictionary[self.kOOBCodeKey], self.kTestOOBCode) XCTAssertNil(requestDictionary[self.kIDTokenKey]) - try self.rpcIssuer?.respond(withJSON: [:]) // unblock the await + return try self.rpcIssuer.respond(withJSON: [:]) // unblock the await } let _ = try await authBackend.call(with: makeEmailLinkSignInRequest()) } @@ -75,17 +77,18 @@ class EmailLinkSignInTests: RPCBaseTests { let kTestIDToken = "testIDToken" let request = makeEmailLinkSignInRequest() request.idToken = kTestIDToken + let rpcIssuer = try XCTUnwrap(self.rpcIssuer) - rpcIssuer?.respondBlock = { + rpcIssuer.respondBlock = { XCTAssertEqual(self.rpcIssuer?.requestURL?.absoluteString, self.kExpectedAPIURL) guard let requestDictionary = self.rpcIssuer?.decodedRequest as? [AnyHashable: String] else { XCTFail("decodedRequest is not a dictionary") - return + return (nil, nil) } XCTAssertEqual(requestDictionary[self.kEmailKey], self.kTestEmail) XCTAssertEqual(requestDictionary[self.kOOBCodeKey], self.kTestOOBCode) XCTAssertEqual(requestDictionary[self.kIDTokenKey], kTestIDToken) - try self.rpcIssuer?.respond(withJSON: [:]) // unblock the await + return try self.rpcIssuer.respond(withJSON: [:]) // unblock the await } let _ = try await authBackend.call(with: request) } @@ -108,12 +111,14 @@ class EmailLinkSignInTests: RPCBaseTests { let kTestTokenExpirationTimeInterval: Double = 55 * 60 let kTestRefreshToken = "testRefreshToken" - rpcIssuer?.respondBlock = { - try self.rpcIssuer?.respond(withJSON: ["idToken": kTestIDTokenResponse, - "email": kTestEmailResponse, - "isNewUser": true, - "expiresIn": "\(kTestTokenExpirationTimeInterval)", - "refreshToken": kTestRefreshToken]) + let rpcIssuer = try XCTUnwrap(self.rpcIssuer) + + rpcIssuer.respondBlock = { + try self.rpcIssuer.respond(withJSON: ["idToken": kTestIDTokenResponse, + "email": kTestEmailResponse, + "isNewUser": true, + "expiresIn": "\(kTestTokenExpirationTimeInterval)", + "refreshToken": kTestRefreshToken]) } let response = try await authBackend.call(with: makeEmailLinkSignInRequest()) diff --git a/FirebaseAuth/Tests/Unit/Fakes/FakeBackendRPCIssuer.swift b/FirebaseAuth/Tests/Unit/Fakes/FakeBackendRPCIssuer.swift index ceca635dacf..ec931c0c859 100644 --- a/FirebaseAuth/Tests/Unit/Fakes/FakeBackendRPCIssuer.swift +++ b/FirebaseAuth/Tests/Unit/Fakes/FakeBackendRPCIssuer.swift @@ -61,14 +61,14 @@ final class FakeBackendRPCIssuer: AuthBackendRPCIssuerProtocol, @unchecked Senda /** @var verifyRequester @brief Optional function to run tests on the request. */ - var verifyRequester: ((SendVerificationCodeRequest) -> Void)? - var verifyClientRequester: ((VerifyClientRequest) -> Void)? - var projectConfigRequester: ((GetProjectConfigRequest) -> Void)? - var verifyPasswordRequester: ((VerifyPasswordRequest) -> Void)? + var verifyRequester: ((SendVerificationCodeRequest) -> (Data?, Error?))? + var verifyClientRequester: ((VerifyClientRequest) -> (Data?, Error?))? + var projectConfigRequester: ((GetProjectConfigRequest) -> (Data?, Error?))? + var verifyPasswordRequester: ((VerifyPasswordRequest) -> (Data?, Error?))? var verifyPhoneNumberRequester: ((VerifyPhoneNumberRequest) -> Void)? - var respondBlock: (() throws -> Void)? - var nextRespondBlock: (() throws -> Void)? + var respondBlock: (() throws -> (Data?, Error?))? + var nextRespondBlock: (() throws -> (Data?, Error?))? var fakeGetAccountProviderJSON: [[String: AnyHashable]]? var fakeSecureTokenServiceJSON: [String: AnyHashable]? @@ -80,35 +80,23 @@ final class FakeBackendRPCIssuer: AuthBackendRPCIssuerProtocol, @unchecked Senda func asyncCallToURL(with request: T, body: Data?, contentType: String) async -> (Data?, Error?) where T: FirebaseAuth.AuthRPCRequest { - return await withCheckedContinuation { continuation in - self.asyncCallToURL(with: request, body: body, contentType: contentType) { data, error in - continuation.resume(returning: (data, error)) - } - } - } - - func asyncCallToURL(with request: T, - body: Data?, - contentType: String, - completionHandler: @escaping ((Data?, Error?) -> Void)) { self.contentType = contentType - handler = completionHandler self.request = request requestURL = request.requestURL() // TODO: See if we can use the above generics to avoid all this. if let verifyRequester, let verifyRequest = request as? SendVerificationCodeRequest { - verifyRequester(verifyRequest) + return verifyRequester(verifyRequest) } else if let verifyClientRequester, let verifyClientRequest = request as? VerifyClientRequest { - verifyClientRequester(verifyClientRequest) + return verifyClientRequester(verifyClientRequest) } else if let projectConfigRequester, let projectConfigRequest = request as? GetProjectConfigRequest { - projectConfigRequester(projectConfigRequest) + return projectConfigRequester(projectConfigRequest) } else if let verifyPasswordRequester, let verifyPasswordRequest = request as? VerifyPasswordRequest { - verifyPasswordRequester(verifyPasswordRequest) + return verifyPasswordRequester(verifyPasswordRequest) } else if let verifyPhoneNumberRequester, let verifyPhoneNumberRequest = request as? VerifyPhoneNumberRequest { verifyPhoneNumberRequester(verifyPhoneNumberRequest) @@ -116,10 +104,10 @@ final class FakeBackendRPCIssuer: AuthBackendRPCIssuerProtocol, @unchecked Senda if let _ = request as? GetAccountInfoRequest, let json = fakeGetAccountProviderJSON { - guard let _ = try? respond(withJSON: ["users": json]) else { + guard let (data, error) = try? respond(withJSON: ["users": json]) else { fatalError("fakeGetAccountProviderJSON respond failed") } - return + return (data, error) } else if let _ = request as? GetRecaptchaConfigRequest { if rceMode != "OFF" { // Check if reCAPTCHA is enabled let recaptchaKey = recaptchaSiteKey // iOS key from your config @@ -127,40 +115,38 @@ final class FakeBackendRPCIssuer: AuthBackendRPCIssuerProtocol, @unchecked Senda ["provider": "EMAIL_PASSWORD_PROVIDER", "enforcementState": rceMode], ["provider": "PHONE_PROVIDER", "enforcementState": rceMode], ] - guard let _ = try? respond(withJSON: [ + guard let (data, error) = try? respond(withJSON: [ "recaptchaKey": recaptchaKey, "recaptchaEnforcementState": enforcementState, ]) else { fatalError("GetRecaptchaConfigRequest respond failed") } + return (data, error) } else { // reCAPTCHA OFF let enforcementState = [ ["provider": "EMAIL_PASSWORD_PROVIDER", "enforcementState": "OFF"], ["provider": "PHONE_PROVIDER", "enforcementState": "OFF"], ] - guard let _ = try? respond(withJSON: [ + guard let (data, error) = try? respond(withJSON: [ "recaptchaEnforcementState": enforcementState, ]) else { fatalError("GetRecaptchaConfigRequest respond failed") } + return (data, error) } - return } else if let _ = request as? SecureTokenRequest { if let secureTokenNetworkError { - guard let _ = try? respond(withData: nil, - error: secureTokenNetworkError) else { - fatalError("Failed to generate secureTokenNetworkError") - } + return (nil, secureTokenNetworkError) } else if let secureTokenErrorString { - guard let _ = try? respond(serverErrorMessage: secureTokenErrorString) else { + guard let (data, error) = try? respond(serverErrorMessage: secureTokenErrorString) else { fatalError("Failed to generate secureTokenErrorString") } - return + return (data, error) } else if let json = fakeSecureTokenServiceJSON { - guard let _ = try? respond(withJSON: json) else { + guard let (data, error) = try? respond(withJSON: json) else { fatalError("fakeGetAccountProviderJSON respond failed") } - return + return (data, error) } } if let body = body { @@ -180,26 +166,28 @@ final class FakeBackendRPCIssuer: AuthBackendRPCIssuerProtocol, @unchecked Senda } if let respondBlock { do { - try respondBlock() + let (data, error) = try respondBlock() + self.respondBlock = nextRespondBlock + nextRespondBlock = nil + return (data, error) } catch { - XCTFail("Unexpected exception in respondBlock") + return (nil, error) } - self.respondBlock = nextRespondBlock - nextRespondBlock = nil } + fatalError("Should never get here") } - func respond(serverErrorMessage errorMessage: String) throws { + func respond(serverErrorMessage errorMessage: String) throws -> (Data, Error?) { let error = NSError(domain: NSCocoaErrorDomain, code: 0) - try respond(serverErrorMessage: errorMessage, error: error) + return try respond(serverErrorMessage: errorMessage, error: error) } - func respond(serverErrorMessage errorMessage: String, error: NSError) throws { - _ = try respond(withJSON: ["error": ["message": errorMessage]], error: error) + func respond(serverErrorMessage errorMessage: String, error: NSError) throws -> (Data, Error?) { + return try respond(withJSON: ["error": ["message": errorMessage]], error: error) } - @discardableResult func respond(underlyingErrorMessage errorMessage: String, - message: String = "See the reason") throws -> Data { + func respond(underlyingErrorMessage errorMessage: String, + message: String = "See the reason") throws -> (Data, Error?) { let error = NSError(domain: NSCocoaErrorDomain, code: 0) return try respond( withJSON: ["error": ["message": message, @@ -208,21 +196,9 @@ final class FakeBackendRPCIssuer: AuthBackendRPCIssuerProtocol, @unchecked Senda ) } - @discardableResult func respond(withJSON json: [String: Any], - error: NSError? = nil) throws -> Data { - let data = try JSONSerialization.data(withJSONObject: json, - options: JSONSerialization.WritingOptions.prettyPrinted) - try respond(withData: data, error: error) - return data - } - - func respond(withData data: Data?, error: NSError?) throws { - let handler = try XCTUnwrap(handler, "There is no pending RPC request.") - XCTAssertTrue( - (data != nil) || (error != nil), - "At least one of: data or error should be been non-nil." - ) - self.handler = nil - handler(data, error) + func respond(withJSON json: [String: Any], error: NSError? = nil) throws -> (Data, Error?) { + return try (JSONSerialization.data(withJSONObject: json, + options: JSONSerialization.WritingOptions.prettyPrinted), + error) } } diff --git a/FirebaseAuth/Tests/Unit/GetAccountInfoTests.swift b/FirebaseAuth/Tests/Unit/GetAccountInfoTests.swift index dff1e74936e..ec5eba4e2d0 100644 --- a/FirebaseAuth/Tests/Unit/GetAccountInfoTests.swift +++ b/FirebaseAuth/Tests/Unit/GetAccountInfoTests.swift @@ -96,9 +96,10 @@ class GetAccountInfoTests: RPCBaseTests { kEmailVerifiedKey: true, kPasswordHashKey: kTestPasswordHash, ] as [String: Any]] + let rpcIssuer = try XCTUnwrap(self.rpcIssuer) - rpcIssuer?.respondBlock = { - try self.rpcIssuer?.respond(withJSON: ["users": usersIn]) + rpcIssuer.respondBlock = { + try self.rpcIssuer.respond(withJSON: ["users": usersIn]) } let rpcResponse = try await authBackend.call(with: makeGetAccountInfoRequest()) diff --git a/FirebaseAuth/Tests/Unit/GetOOBConfirmationCodeTests.swift b/FirebaseAuth/Tests/Unit/GetOOBConfirmationCodeTests.swift index 631bab3a723..a504f022e49 100644 --- a/FirebaseAuth/Tests/Unit/GetOOBConfirmationCodeTests.swift +++ b/FirebaseAuth/Tests/Unit/GetOOBConfirmationCodeTests.swift @@ -191,13 +191,14 @@ class GetOOBConfirmationCodeTests: RPCBaseTests { it succeeds, and we get the OOB Code decoded correctly. */ func testSuccessfulOOBResponse() async throws { + let rpcIssuer = try XCTUnwrap(self.rpcIssuer) for request in [ getPasswordResetRequest, getSignInWithEmailRequest, getEmailVerificationRequest, ] { - rpcIssuer?.respondBlock = { - try self.rpcIssuer?.respond(withJSON: [self.kOOBCodeKey: self.kTestOOBCode]) + rpcIssuer.respondBlock = { + try self.rpcIssuer.respond(withJSON: [self.kOOBCodeKey: self.kTestOOBCode]) } let response = try await authBackend.call(with: request()) XCTAssertEqual(response.OOBCode, kTestOOBCode) @@ -209,13 +210,14 @@ class GetOOBConfirmationCodeTests: RPCBaseTests { response value. It should still succeed. */ func testSuccessfulOOBResponseWithoutOOBCode() async throws { + let rpcIssuer = try XCTUnwrap(self.rpcIssuer) for request in [ getPasswordResetRequest, getSignInWithEmailRequest, getEmailVerificationRequest, ] { - rpcIssuer?.respondBlock = { - try self.rpcIssuer?.respond(withJSON: [:]) + rpcIssuer.respondBlock = { + try self.rpcIssuer.respond(withJSON: [:]) } let response = try await authBackend.call(with: request()) XCTAssertNil(response.OOBCode) diff --git a/FirebaseAuth/Tests/Unit/GetProjectConfigTests.swift b/FirebaseAuth/Tests/Unit/GetProjectConfigTests.swift index 6dbe4c644c6..a49e7709fa0 100644 --- a/FirebaseAuth/Tests/Unit/GetProjectConfigTests.swift +++ b/FirebaseAuth/Tests/Unit/GetProjectConfigTests.swift @@ -55,10 +55,10 @@ class GetProjectConfigTests: RPCBaseTests { let kTestProjectID = "21141651616" let kTestDomain1 = "localhost" let kTestDomain2 = "example.firebaseapp.com" - - rpcIssuer?.respondBlock = { - try self.rpcIssuer?.respond(withJSON: ["projectId": kTestProjectID, - "authorizedDomains": [kTestDomain1, kTestDomain2]]) + let rpcIssuer = try XCTUnwrap(self.rpcIssuer) + rpcIssuer.respondBlock = { + try self.rpcIssuer.respond(withJSON: ["projectId": kTestProjectID, + "authorizedDomains": [kTestDomain1, kTestDomain2]]) } let rpcResponse = try await authBackend.call(with: makeGetProjectConfigRequest()) XCTAssertEqual(rpcResponse.projectID, kTestProjectID) diff --git a/FirebaseAuth/Tests/Unit/OAuthProviderTests.swift b/FirebaseAuth/Tests/Unit/OAuthProviderTests.swift index a5a330babf7..d4b2b47d6f2 100644 --- a/FirebaseAuth/Tests/Unit/OAuthProviderTests.swift +++ b/FirebaseAuth/Tests/Unit/OAuthProviderTests.swift @@ -301,22 +301,20 @@ import FirebaseCore // 1. Setup fakes and parameters for getCredential. if !OAuthProviderTests.testEmulator { let projectConfigExpectation = self.expectation(description: "projectConfiguration") - rpcIssuer?.projectConfigRequester = { request in + rpcIssuer.projectConfigRequester = { request in // 3. Validate the created Request instance. XCTAssertEqual(request.apiKey, OAuthProviderTests.kFakeAPIKey) XCTAssertEqual(request.endpoint, "getProjectConfig") // 4. Fulfill the expectation. projectConfigExpectation.fulfill() - kAuthGlobalWorkQueue.async { - do { - // 5. Send the response from the fake backend. - try self.rpcIssuer? - .respond(withJSON: ["authorizedDomains": [ - OAuthProviderTests.kFakeAuthorizedWebDomain, - OAuthProviderTests.kFakeAuthorizedDomain]]) - } catch { - XCTFail("Failure sending response: \(error)") - } + do { + // 5. Send the response from the fake backend. + return try self.rpcIssuer.respond(withJSON: ["authorizedDomains": [ + OAuthProviderTests.kFakeAuthorizedWebDomain, + OAuthProviderTests.kFakeAuthorizedDomain]]) + } catch { + XCTFail("Failure sending response: \(error)") + return (nil, nil) } } } diff --git a/FirebaseAuth/Tests/Unit/PhoneAuthProviderTests.swift b/FirebaseAuth/Tests/Unit/PhoneAuthProviderTests.swift index fd7291f6820..94880a3d856 100644 --- a/FirebaseAuth/Tests/Unit/PhoneAuthProviderTests.swift +++ b/FirebaseAuth/Tests/Unit/PhoneAuthProviderTests.swift @@ -110,17 +110,18 @@ AuthRecaptchaVerifier.setShared(mockVerifier, auth: auth) rpcIssuer.rceMode = "ENFORCE" let requestExpectation = expectation(description: "verifyRequester") - rpcIssuer?.verifyRequester = { request in + rpcIssuer.verifyRequester = { request in XCTAssertEqual(request.phoneNumber, self.kTestPhoneNumber) XCTAssertEqual(request.captchaResponse, self.kCaptchaResponse) XCTAssertEqual(request.recaptchaVersion, "RECAPTCHA_ENTERPRISE") XCTAssertEqual(request.codeIdentity, CodeIdentity.empty) requestExpectation.fulfill() do { - try self.rpcIssuer? + return try self.rpcIssuer .respond(withJSON: [self.kVerificationIDKey: self.kTestVerificationID]) } catch { XCTFail("Failure sending response: \(error)") + return (nil, nil) } } do { @@ -157,13 +158,12 @@ XCTAssertEqual(request.codeIdentity, CodeIdentity.empty) requestExpectation.fulfill() do { - try self.rpcIssuer? - .respond( - serverErrorMessage: "INVALID_RECAPTCHA_TOKEN", - error: AuthErrorUtils.invalidRecaptchaTokenError() as NSError - ) + return try self.rpcIssuer + .respond(serverErrorMessage: "INVALID_RECAPTCHA_TOKEN", + error: AuthErrorUtils.invalidRecaptchaTokenError() as NSError) } catch { XCTFail("Failure sending response: \(error)") + return (nil, nil) } } do { @@ -218,17 +218,18 @@ AuthRecaptchaVerifier.setShared(mockVerifier, auth: auth) rpcIssuer.rceMode = "AUDIT" let requestExpectation = expectation(description: "verifyRequester") - rpcIssuer?.verifyRequester = { request in + rpcIssuer.verifyRequester = { request in XCTAssertEqual(request.phoneNumber, self.kTestPhoneNumber) XCTAssertEqual(request.captchaResponse, self.kCaptchaResponse) XCTAssertEqual(request.recaptchaVersion, "RECAPTCHA_ENTERPRISE") XCTAssertEqual(request.codeIdentity, CodeIdentity.empty) requestExpectation.fulfill() do { - try self.rpcIssuer? + return try self.rpcIssuer .respond(withJSON: [self.kVerificationIDKey: self.kTestVerificationID]) } catch { XCTFail("Failure sending response: \(error)") + return (nil, nil) } } do { @@ -263,13 +264,14 @@ XCTAssertEqual(request.codeIdentity, CodeIdentity.empty) requestExpectation.fulfill() do { - try self.rpcIssuer? + return try self.rpcIssuer .respond( serverErrorMessage: "INVALID_RECAPTCHA_TOKEN", error: AuthErrorUtils.invalidRecaptchaTokenError() as NSError ) } catch { XCTFail("Failure sending response: \(error)") + return (nil, nil) } } do { @@ -573,12 +575,13 @@ verifyClientRequestExpectation.fulfill() do { // Response for the underlying VerifyClientRequest RPC call. - try self.rpcIssuer?.respond(withJSON: [ + return try self.rpcIssuer.respond(withJSON: [ "receipt": self.kTestReceipt, "suggestedTimeout": self.kTestTimeout, ]) } catch { XCTFail("Failure sending response: \(error)") + return (nil, nil) } } @@ -598,15 +601,18 @@ do { if visited == false || goodRetry == false { // First Response for the underlying SendVerificationCode RPC call. - try self.rpcIssuer?.respond(serverErrorMessage: "INVALID_APP_CREDENTIAL") + let (data, error) = try self.rpcIssuer + .respond(serverErrorMessage: "INVALID_APP_CREDENTIAL") visited = true + return (data, error) } else { // Second Response for the underlying SendVerificationCode RPC call. - try self.rpcIssuer? + return try self.rpcIssuer .respond(withJSON: [self.kVerificationIDKey: self.kTestVerificationID]) } } catch { XCTFail("Failure sending response: \(error)") + return (nil, nil) } } @@ -662,29 +668,29 @@ verifyClientRequestExpectation.fulfill() do { // Response for the underlying VerifyClientRequest RPC call. - try self.rpcIssuer?.respond(withJSON: [ + return try self.rpcIssuer.respond(withJSON: [ "receipt": self.kTestReceipt, "suggestedTimeout": self.kTestTimeout, ]) } catch { XCTFail("Failure sending response: \(error)") + return (nil, nil) } } if reCAPTCHAfallback { let projectConfigExpectation = self.expectation(description: "projectConfiguration") - rpcIssuer?.projectConfigRequester = { request in + rpcIssuer.projectConfigRequester = { request in XCTAssertEqual(request.apiKey, PhoneAuthProviderTests.kFakeAPIKey) projectConfigExpectation.fulfill() - kAuthGlobalWorkQueue.async { - do { - // Response for the underlying VerifyClientRequest RPC call. - try self.rpcIssuer?.respond( - withJSON: ["projectId": "kFakeProjectID", - "authorizedDomains": [PhoneAuthProviderTests.kFakeAuthorizedDomain]] - ) - } catch { - XCTFail("Failure sending response: \(error)") - } + do { + // Response for the underlying VerifyClientRequest RPC call. + return try self.rpcIssuer.respond( + withJSON: ["projectId": "kFakeProjectID", + "authorizedDomains": [PhoneAuthProviderTests.kFakeAuthorizedDomain]] + ) + } catch { + XCTFail("Failure sending response: \(error)") + return (nil, nil) } } } @@ -711,10 +717,11 @@ verifyRequesterExpectation.fulfill() do { // Response for the underlying SendVerificationCode RPC call. - try self.rpcIssuer? + return try self.rpcIssuer .respond(withJSON: [self.kVerificationIDKey: self.kTestVerificationID]) } catch { XCTFail("Failure sending response: \(error)") + return (nil, nil) } } @@ -771,17 +778,18 @@ // 1. Intercept, handle, and test the projectConfiguration RPC calls. let projectConfigExpectation = expectation(description: "projectConfiguration") expectations.append(projectConfigExpectation) - rpcIssuer?.projectConfigRequester = { request in + rpcIssuer.projectConfigRequester = { request in XCTAssertEqual(request.apiKey, PhoneAuthProviderTests.kFakeAPIKey) projectConfigExpectation.fulfill() do { // Response for the underlying VerifyClientRequest RPC call. - try self.rpcIssuer?.respond( + return try self.rpcIssuer.respond( withJSON: ["projectId": "kFakeProjectID", "authorizedDomains": [PhoneAuthProviderTests.kFakeAuthorizedDomain]] ) } catch { XCTFail("Failure sending response: \(error)") + return (nil, nil) } } } @@ -802,7 +810,7 @@ if errorURLString == nil, presenterError == nil { let requestExpectation = expectation(description: "verifyRequester") expectations.append(requestExpectation) - rpcIssuer?.verifyRequester = { request in + rpcIssuer.verifyRequester = { request in XCTAssertEqual(request.phoneNumber, self.kTestPhoneNumber) switch request.codeIdentity { case let .credential(credential): @@ -819,13 +827,14 @@ do { // Response for the underlying SendVerificationCode RPC call. if let errorString { - try self.rpcIssuer?.respond(serverErrorMessage: errorString) + return try self.rpcIssuer.respond(serverErrorMessage: errorString) } else { - try self.rpcIssuer? + return try self.rpcIssuer .respond(withJSON: [self.kVerificationIDKey: self.kTestVerificationID]) } } catch { XCTFail("Failure sending response: \(error)") + return (nil, nil) } } } diff --git a/FirebaseAuth/Tests/Unit/RPCBaseTests.swift b/FirebaseAuth/Tests/Unit/RPCBaseTests.swift index 8ff45d7d073..f3ba6cb6cfb 100644 --- a/FirebaseAuth/Tests/Unit/RPCBaseTests.swift +++ b/FirebaseAuth/Tests/Unit/RPCBaseTests.swift @@ -99,7 +99,7 @@ class RPCBaseTests: XCTestCase { XCTFail("decodedRequest is not a dictionary") } // Dummy response to unblock await. - let _ = try self.rpcIssuer?.respond(withJSON: [:]) + return try self.rpcIssuer.respond(withJSON: [:]) } let _ = try await authBackend.call(with: request) } @@ -117,11 +117,11 @@ class RPCBaseTests: XCTestCase { checkLocalizedDescription: String? = nil) async throws { rpcIssuer.respondBlock = { if let json = json { - _ = try self.rpcIssuer.respond(withJSON: json) + return try self.rpcIssuer.respond(withJSON: json) } else if let reason = reason { - _ = try self.rpcIssuer.respond(underlyingErrorMessage: reason, message: message) + return try self.rpcIssuer.respond(underlyingErrorMessage: reason, message: message) } else { - _ = try self.rpcIssuer.respond(serverErrorMessage: message) + return try self.rpcIssuer.respond(serverErrorMessage: message) } } do { diff --git a/FirebaseAuth/Tests/Unit/ResetPasswordTests.swift b/FirebaseAuth/Tests/Unit/ResetPasswordTests.swift index a3220f3ee41..bb28a9cfa1d 100644 --- a/FirebaseAuth/Tests/Unit/ResetPasswordTests.swift +++ b/FirebaseAuth/Tests/Unit/ResetPasswordTests.swift @@ -79,8 +79,8 @@ class ResetPasswordTests: RPCBaseTests { let kExpectedResetPasswordRequestType = "PASSWORD_RESET" rpcIssuer.respondBlock = { - try self.rpcIssuer?.respond(withJSON: ["email": kTestEmail, - "requestType": kExpectedResetPasswordRequestType]) + try self.rpcIssuer.respond(withJSON: ["email": kTestEmail, + "requestType": kExpectedResetPasswordRequestType]) } let rpcResponse = try await authBackend.call(with: makeResetPasswordRequest()) diff --git a/FirebaseAuth/Tests/Unit/RevokeTokenTests.swift b/FirebaseAuth/Tests/Unit/RevokeTokenTests.swift index f55f42514d7..8fab2237e43 100644 --- a/FirebaseAuth/Tests/Unit/RevokeTokenTests.swift +++ b/FirebaseAuth/Tests/Unit/RevokeTokenTests.swift @@ -51,7 +51,7 @@ class RevokeTokenTests: RPCBaseTests { */ func testSuccessfulRevokeTokenResponse() async throws { rpcIssuer.respondBlock = { - try self.rpcIssuer?.respond(withJSON: [:]) + try self.rpcIssuer.respond(withJSON: [:]) } let rpcResponse = try await authBackend.call(with: makeRevokeTokenRequest()) XCTAssertNotNil(rpcResponse) diff --git a/FirebaseAuth/Tests/Unit/SendVerificationCodeTests.swift b/FirebaseAuth/Tests/Unit/SendVerificationCodeTests.swift index d6b4b42bc14..e92bdf40f2b 100644 --- a/FirebaseAuth/Tests/Unit/SendVerificationCodeTests.swift +++ b/FirebaseAuth/Tests/Unit/SendVerificationCodeTests.swift @@ -111,7 +111,7 @@ class SendVerificationCodeTests: RPCBaseTests { let kFakeVerificationID = "testVerificationID" rpcIssuer.respondBlock = { - try self.rpcIssuer?.respond(withJSON: [kVerificationIDKey: kFakeVerificationID]) + try self.rpcIssuer.respond(withJSON: [kVerificationIDKey: kFakeVerificationID]) } let rpcResponse = try await authBackend.call(with: makeSendVerificationCodeRequest(CodeIdentity.recaptcha(kTestReCAPTCHAToken))) diff --git a/FirebaseAuth/Tests/Unit/SetAccountInfoTests.swift b/FirebaseAuth/Tests/Unit/SetAccountInfoTests.swift index 037116982de..b3ccb3e8ad1 100644 --- a/FirebaseAuth/Tests/Unit/SetAccountInfoTests.swift +++ b/FirebaseAuth/Tests/Unit/SetAccountInfoTests.swift @@ -206,7 +206,7 @@ class SetAccountInfoTests: RPCBaseTests { let kTestRefreshToken = "REFRESH_TOKEN" rpcIssuer.respondBlock = { - try self.rpcIssuer?.respond(withJSON: + try self.rpcIssuer.respond(withJSON: [kProviderUserInfoKey: [[kPhotoUrlKey: kTestPhotoURL]], kIDTokenKey: kTestIDToken, kExpiresInKey: kTestExpiresIn, diff --git a/FirebaseAuth/Tests/Unit/SignInWithGameCenterTests.swift b/FirebaseAuth/Tests/Unit/SignInWithGameCenterTests.swift index 515cbd13e87..989e436c575 100644 --- a/FirebaseAuth/Tests/Unit/SignInWithGameCenterTests.swift +++ b/FirebaseAuth/Tests/Unit/SignInWithGameCenterTests.swift @@ -87,7 +87,7 @@ class SignInWithGameCenterTests: RPCBaseTests { XCTAssertEqual(requestDictionary[kDisplayNameKey], kDisplayName) rpcIssuer.respondBlock = { - try self.rpcIssuer?.respond(withJSON: [ + try self.rpcIssuer.respond(withJSON: [ "idToken": self.kIDToken, "refreshToken": kRefreshToken, "localId": kLocalID, diff --git a/FirebaseAuth/Tests/Unit/SignUpNewUserTests.swift b/FirebaseAuth/Tests/Unit/SignUpNewUserTests.swift index a75f6263a79..01c76eaf190 100644 --- a/FirebaseAuth/Tests/Unit/SignUpNewUserTests.swift +++ b/FirebaseAuth/Tests/Unit/SignUpNewUserTests.swift @@ -76,7 +76,7 @@ class SignUpNewUserTests: RPCBaseTests { let kRefreshTokenKey = "refreshToken" rpcIssuer?.respondBlock = { - try self.rpcIssuer?.respond(withJSON: [ + try self.rpcIssuer.respond(withJSON: [ kIDTokenKey: kTestIDToken, kExpiresInKey: kTestExpiresIn, kRefreshTokenKey: kTestRefreshToken, diff --git a/FirebaseAuth/Tests/Unit/UserTests.swift b/FirebaseAuth/Tests/Unit/UserTests.swift index d1f305f7116..ba11eb2ee47 100644 --- a/FirebaseAuth/Tests/Unit/UserTests.swift +++ b/FirebaseAuth/Tests/Unit/UserTests.swift @@ -411,7 +411,7 @@ class UserTests: RPCBaseTests { signInWithEmailPasswordReturnFakeUser { user in do { self.rpcIssuer.respondBlock = { - try self.rpcIssuer?.respond(serverErrorMessage: "INVALID_EMAIL") + try self.rpcIssuer.respond(serverErrorMessage: "INVALID_EMAIL") } user.updateEmail(to: self.kNewEmail) { rawError in XCTAssertTrue(Thread.isMainThread) @@ -437,7 +437,7 @@ class UserTests: RPCBaseTests { signInWithEmailPasswordReturnFakeUser { user in do { self.rpcIssuer.respondBlock = { - try self.rpcIssuer?.respond(serverErrorMessage: "INVALID_ID_TOKEN") + try self.rpcIssuer.respond(serverErrorMessage: "INVALID_ID_TOKEN") } user.updateEmail(to: self.kNewEmail) { rawError in XCTAssertTrue(Thread.isMainThread) @@ -466,8 +466,8 @@ class UserTests: RPCBaseTests { signInWithEmailPasswordReturnFakeUser { user in do { self.rpcIssuer.respondBlock = { - try self.rpcIssuer?.respond(withJSON: ["idToken": RPCBaseTests.kFakeAccessToken, - "refreshToken": self.kRefreshToken]) + try self.rpcIssuer.respond(withJSON: ["idToken": RPCBaseTests.kFakeAccessToken, + "refreshToken": self.kRefreshToken]) } self.expectVerifyPhoneNumberRequest() self.rpcIssuer?.fakeGetAccountProviderJSON = [[ @@ -500,7 +500,7 @@ class UserTests: RPCBaseTests { signInWithEmailPasswordReturnFakeUser { user in do { self.rpcIssuer.respondBlock = { - try self.rpcIssuer?.respond(serverErrorMessage: "INVALID_PHONE_NUMBER") + try self.rpcIssuer.respond(serverErrorMessage: "INVALID_PHONE_NUMBER") } self.expectVerifyPhoneNumberRequest() @@ -532,7 +532,7 @@ class UserTests: RPCBaseTests { signInWithEmailPasswordReturnFakeUser { user in do { self.rpcIssuer.respondBlock = { - try self.rpcIssuer?.respond(serverErrorMessage: "TOKEN_EXPIRED") + try self.rpcIssuer.respond(serverErrorMessage: "TOKEN_EXPIRED") } self.expectVerifyPhoneNumberRequest() @@ -575,7 +575,7 @@ class UserTests: RPCBaseTests { signInWithEmailPasswordReturnFakeUser { user in do { self.rpcIssuer.respondBlock = { - try self.rpcIssuer?.respond(serverErrorMessage: "CREDENTIAL_TOO_OLD_LOGIN_AGAIN") + try self.rpcIssuer.respond(serverErrorMessage: "CREDENTIAL_TOO_OLD_LOGIN_AGAIN") } user.updatePassword(to: self.kNewPassword) { rawError in XCTAssertTrue(Thread.isMainThread) @@ -601,7 +601,7 @@ class UserTests: RPCBaseTests { signInWithEmailPasswordReturnFakeUser { user in do { self.rpcIssuer.respondBlock = { - try self.rpcIssuer?.respond(serverErrorMessage: "WEAK_PASSWORD") + try self.rpcIssuer.respond(serverErrorMessage: "WEAK_PASSWORD") } user.updatePassword(to: self.kNewPassword) { rawError in XCTAssertTrue(Thread.isMainThread) @@ -628,7 +628,7 @@ class UserTests: RPCBaseTests { signInWithEmailPasswordReturnFakeUser { user in do { self.rpcIssuer.respondBlock = { - try self.rpcIssuer?.respond(serverErrorMessage: "USER_DISABLED") + try self.rpcIssuer.respond(serverErrorMessage: "USER_DISABLED") } user.updatePassword(to: self.kNewPassword) { rawError in XCTAssertTrue(Thread.isMainThread) @@ -654,8 +654,8 @@ class UserTests: RPCBaseTests { signInWithEmailPasswordReturnFakeUser { user in do { self.rpcIssuer.respondBlock = { - try self.rpcIssuer?.respond(withJSON: ["idToken": RPCBaseTests.kFakeAccessToken, - "refreshToken": self.kRefreshToken]) + try self.rpcIssuer.respond(withJSON: ["idToken": RPCBaseTests.kFakeAccessToken, + "refreshToken": self.kRefreshToken]) } let profileChange = user.createProfileChangeRequest() profileChange.photoURL = URL(string: self.kTestPhotoURL) @@ -681,7 +681,7 @@ class UserTests: RPCBaseTests { signInWithEmailPasswordReturnFakeUser { user in do { self.rpcIssuer.respondBlock = { - try self.rpcIssuer?.respond(serverErrorMessage: "TOO_MANY_ATTEMPTS_TRY_LATER") + try self.rpcIssuer.respond(serverErrorMessage: "TOO_MANY_ATTEMPTS_TRY_LATER") } let profileChange = user.createProfileChangeRequest() profileChange.displayName = self.kNewDisplayName @@ -710,7 +710,7 @@ class UserTests: RPCBaseTests { signInWithEmailPasswordReturnFakeUser { user in do { self.rpcIssuer.respondBlock = { - try self.rpcIssuer?.respond(serverErrorMessage: "USER_NOT_FOUND") + try self.rpcIssuer.respond(serverErrorMessage: "USER_NOT_FOUND") } let profileChange = user.createProfileChangeRequest() profileChange.displayName = self.kNewDisplayName @@ -816,7 +816,7 @@ class UserTests: RPCBaseTests { signInWithEmailPasswordReturnFakeUser { user in do { self.rpcIssuer.respondBlock = { - try self.rpcIssuer?.respond(serverErrorMessage: "QUOTA_EXCEEDED") + try self.rpcIssuer.respond(serverErrorMessage: "QUOTA_EXCEEDED") } // Clear fake so we can inject error self.rpcIssuer?.fakeGetAccountProviderJSON = nil @@ -843,7 +843,7 @@ class UserTests: RPCBaseTests { signInWithEmailPasswordReturnFakeUser { user in do { self.rpcIssuer.respondBlock = { - try self.rpcIssuer?.respond(serverErrorMessage: "TOKEN_EXPIRED") + try self.rpcIssuer.respond(serverErrorMessage: "TOKEN_EXPIRED") } // Clear fake so we can inject error self.rpcIssuer?.fakeGetAccountProviderJSON = nil @@ -870,8 +870,8 @@ class UserTests: RPCBaseTests { signInWithEmailPasswordReturnFakeUser { user in do { self.rpcIssuer.respondBlock = { - try self.rpcIssuer?.respond(withJSON: ["idToken": RPCBaseTests.kFakeAccessToken, - "refreshToken": self.kRefreshToken]) + try self.rpcIssuer.respond(withJSON: ["idToken": RPCBaseTests.kFakeAccessToken, + "refreshToken": self.kRefreshToken]) } let emailCredential = EmailAuthProvider.credential(withEmail: self.kEmail, password: self.kFakePassword) @@ -899,14 +899,14 @@ class UserTests: RPCBaseTests { signInWithGoogleCredential { user in do { self.rpcIssuer.respondBlock = { - try self.rpcIssuer?.respond(withJSON: ["idToken": RPCBaseTests.kFakeAccessToken, - "refreshToken": self.kRefreshToken, - "federatedId": self.kGoogleID, - "providerId": GoogleAuthProvider.id, - "localId": self.kLocalID, - "displayName": self.kGoogleDisplayName, - "rawUserInfo": self.kGoogleProfile, - "username": self.kUserName]) + try self.rpcIssuer.respond(withJSON: ["idToken": RPCBaseTests.kFakeAccessToken, + "refreshToken": self.kRefreshToken, + "federatedId": self.kGoogleID, + "providerId": GoogleAuthProvider.id, + "localId": self.kLocalID, + "displayName": self.kGoogleDisplayName, + "rawUserInfo": self.kGoogleProfile, + "username": self.kUserName]) } let googleCredential = GoogleAuthProvider.credential(withIDToken: self.kGoogleIDToken, accessToken: self.kGoogleAccessToken) @@ -950,8 +950,8 @@ class UserTests: RPCBaseTests { signInWithEmailPasswordReturnFakeUser { user in do { self.rpcIssuer.respondBlock = { - try self.rpcIssuer?.respond(withJSON: ["idToken": RPCBaseTests.kFakeAccessToken, - "refreshToken": self.kRefreshToken]) + try self.rpcIssuer.respond(withJSON: ["idToken": RPCBaseTests.kFakeAccessToken, + "refreshToken": self.kRefreshToken]) } self.setFakeGetAccountProvider(withLocalID: "A different Local ID") let emailCredential = EmailAuthProvider.credential(withEmail: self.kEmail, @@ -981,7 +981,7 @@ class UserTests: RPCBaseTests { signInWithEmailPasswordReturnFakeUser { user in do { self.rpcIssuer.respondBlock = { - try self.rpcIssuer?.respond(serverErrorMessage: "USER_NOT_FOUND") + try self.rpcIssuer.respond(serverErrorMessage: "USER_NOT_FOUND") } let googleCredential = GoogleAuthProvider.credential(withIDToken: self.kGoogleIDToken, accessToken: self.kGoogleAccessToken) @@ -1012,14 +1012,14 @@ class UserTests: RPCBaseTests { do { self.setFakeGoogleGetAccountProvider() self.rpcIssuer.respondBlock = { - try self.rpcIssuer?.respond(withJSON: ["idToken": RPCBaseTests.kFakeAccessToken, - "refreshToken": self.kRefreshToken, - "federatedId": self.kGoogleID, - "providerId": GoogleAuthProvider.id, - "localId": self.kLocalID, - "displayName": self.kGoogleDisplayName, - "rawUserInfo": self.kGoogleProfile, - "username": self.kUserName]) + try self.rpcIssuer.respond(withJSON: ["idToken": RPCBaseTests.kFakeAccessToken, + "refreshToken": self.kRefreshToken, + "federatedId": self.kGoogleID, + "providerId": GoogleAuthProvider.id, + "localId": self.kLocalID, + "displayName": self.kGoogleDisplayName, + "rawUserInfo": self.kGoogleProfile, + "username": self.kUserName]) } let googleCredential = GoogleAuthProvider.credential(withIDToken: self.kGoogleIDToken, accessToken: self.kGoogleAccessToken) @@ -1062,7 +1062,7 @@ class UserTests: RPCBaseTests { do { self.setFakeGetAccountProvider() self.rpcIssuer.respondBlock = { - try self.rpcIssuer?.respond(serverErrorMessage: "CREDENTIAL_TOO_OLD_LOGIN_AGAIN") + try self.rpcIssuer.respond(serverErrorMessage: "CREDENTIAL_TOO_OLD_LOGIN_AGAIN") } let googleCredential = GoogleAuthProvider.credential(withIDToken: self.kGoogleIDToken, accessToken: self.kGoogleAccessToken) @@ -1125,7 +1125,7 @@ class UserTests: RPCBaseTests { do { self.setFakeGetAccountProvider() self.rpcIssuer.respondBlock = { - try self.rpcIssuer?.respond(serverErrorMessage: "USER_DISABLED") + try self.rpcIssuer.respond(serverErrorMessage: "USER_DISABLED") } let googleCredential = GoogleAuthProvider.credential(withIDToken: self.kGoogleIDToken, accessToken: self.kGoogleAccessToken) @@ -1160,9 +1160,12 @@ class UserTests: RPCBaseTests { XCTAssertEqual(request?.email, self.kEmail) XCTAssertEqual(request?.password, self.kFakePassword) XCTAssertNil(request?.displayName) - try self.rpcIssuer?.respond(withJSON: ["idToken": RPCBaseTests.kFakeAccessToken, - "refreshToken": self.kRefreshToken]) + let (data, error) = try self.rpcIssuer.respond(withJSON: [ + "idToken": RPCBaseTests.kFakeAccessToken, + "refreshToken": self.kRefreshToken, + ]) self.setFakeGetAccountProvider(withProviderID: EmailAuthProvider.id) + return (data, error) } let emailCredential = EmailAuthProvider.credential(withEmail: self.kEmail, password: self.kFakePassword) @@ -1200,9 +1203,12 @@ class UserTests: RPCBaseTests { XCTAssertNotNil(request) XCTAssertEqual(request?.email, self.kEmail) XCTAssertEqual(request?.password, self.kFakePassword) - try self.rpcIssuer?.respond(withJSON: ["idToken": RPCBaseTests.kFakeAccessToken, - "refreshToken": self.kRefreshToken]) + let (data, error) = try self.rpcIssuer.respond(withJSON: [ + "idToken": RPCBaseTests.kFakeAccessToken, + "refreshToken": self.kRefreshToken, + ]) self.setFakeGetAccountProvider(withProviderID: EmailAuthProvider.id) + return (data, error) } let emailCredential = EmailAuthProvider.credential(withEmail: self.kEmail, password: self.kFakePassword) @@ -1242,7 +1248,7 @@ class UserTests: RPCBaseTests { XCTAssertNotNil(request) XCTAssertEqual(request?.email, self.kEmail) XCTAssertEqual(request?.password, self.kFakePassword) - try self.rpcIssuer?.respond(serverErrorMessage: "TOO_MANY_ATTEMPTS_TRY_LATER") + return try self.rpcIssuer.respond(serverErrorMessage: "TOO_MANY_ATTEMPTS_TRY_LATER") } let emailCredential = EmailAuthProvider.credential(withEmail: self.kEmail, password: self.kFakePassword) @@ -1272,7 +1278,7 @@ class UserTests: RPCBaseTests { do { self.rpcIssuer.respondBlock = { XCTAssertNotNil(self.rpcIssuer?.request as? SignUpNewUserRequest) - try self.rpcIssuer?.respond(serverErrorMessage: "TOKEN_EXPIRED") + return try self.rpcIssuer.respond(serverErrorMessage: "TOKEN_EXPIRED") } let emailCredential = EmailAuthProvider.credential(withEmail: self.kEmail, password: self.kFakePassword) @@ -1292,16 +1298,12 @@ class UserTests: RPCBaseTests { #if os(iOS) private class FakeOAuthProvider: OAuthProvider { - override func getCredentialWith(_ UIDelegate: AuthUIDelegate?, - completion: ((AuthCredential?, Error?) -> Void)? = nil) { - if let completion { - let credential = OAuthCredential( - withProviderID: GoogleAuthProvider.id, - sessionID: UserTests.kOAuthSessionID, - OAuthResponseURLString: UserTests.kOAuthRequestURI - ) - completion(credential, nil) - } + override func credential(with uiDelegate: AuthUIDelegate?) async throws -> AuthCredential { + return OAuthCredential( + withProviderID: GoogleAuthProvider.id, + sessionID: UserTests.kOAuthSessionID, + OAuthResponseURLString: UserTests.kOAuthRequestURI + ) } } @@ -1318,7 +1320,7 @@ class UserTests: RPCBaseTests { do { self.setFakeGetAccountProvider() self.rpcIssuer.respondBlock = { - try self.rpcIssuer?.respond(serverErrorMessage: "TOKEN_EXPIRED") + try self.rpcIssuer.respond(serverErrorMessage: "TOKEN_EXPIRED") } user.link(with: FakeOAuthProvider(providerID: "foo", auth: auth), uiDelegate: nil) { linkAuthResult, rawError in @@ -1347,7 +1349,7 @@ class UserTests: RPCBaseTests { do { self.setFakeGetAccountProvider() self.rpcIssuer.respondBlock = { - try self.rpcIssuer?.respond(serverErrorMessage: "TOKEN_EXPIRED") + try self.rpcIssuer.respond(serverErrorMessage: "TOKEN_EXPIRED") } user.reauthenticate(with: FakeOAuthProvider(providerID: "foo", auth: auth), uiDelegate: nil) { linkAuthResult, rawError in @@ -1377,8 +1379,8 @@ class UserTests: RPCBaseTests { do { self.setFakeGetAccountProvider(withProviderID: PhoneAuthProvider.id) self.rpcIssuer.respondBlock = { - try self.rpcIssuer?.respond(withJSON: ["idToken": RPCBaseTests.kFakeAccessToken, - "refreshToken": self.kRefreshToken]) + try self.rpcIssuer.respond(withJSON: ["idToken": RPCBaseTests.kFakeAccessToken, + "refreshToken": self.kRefreshToken]) } let credential = PhoneAuthProvider.provider(auth: auth).credential( withVerificationID: self.kVerificationID, @@ -1422,8 +1424,8 @@ class UserTests: RPCBaseTests { do { self.setFakeGetAccountProvider(withProviderID: PhoneAuthProvider.id) self.rpcIssuer.respondBlock = { - try self.rpcIssuer?.respond(withJSON: ["idToken": RPCBaseTests.kFakeAccessToken, - "refreshToken": self.kRefreshToken]) + try self.rpcIssuer.respond(withJSON: ["idToken": RPCBaseTests.kFakeAccessToken, + "refreshToken": self.kRefreshToken]) } let credential = PhoneAuthProvider.provider(auth: auth).credential( withVerificationID: self.kVerificationID, @@ -1460,8 +1462,8 @@ class UserTests: RPCBaseTests { XCTAssertNil(request.providers) XCTAssertNil(request.deleteAttributes) XCTAssertEqual(try XCTUnwrap(request.deleteProviders?.first), PhoneAuthProvider.id) - try self.rpcIssuer?.respond(withJSON: ["idToken": RPCBaseTests.kFakeAccessToken, - "refreshToken": self.kRefreshToken]) + return try self.rpcIssuer.respond(withJSON: ["idToken": RPCBaseTests.kFakeAccessToken, + "refreshToken": self.kRefreshToken]) } user.unlink(fromProvider: PhoneAuthProvider.id) { user, error in XCTAssertNil(error) @@ -1518,10 +1520,10 @@ class UserTests: RPCBaseTests { do { self.setFakeGetAccountProvider(withProviderID: PhoneAuthProvider.id) self.rpcIssuer.respondBlock = { - try self.rpcIssuer?.respond(withJSON: ["idToken": RPCBaseTests.kFakeAccessToken, - "refreshToken": self.kRefreshToken, - "phoneNumber": self.kTestPhoneNumber, - "temporaryProof": "Fake Temporary Proof"]) + try self.rpcIssuer.respond(withJSON: ["idToken": RPCBaseTests.kFakeAccessToken, + "refreshToken": self.kRefreshToken, + "phoneNumber": self.kTestPhoneNumber, + "temporaryProof": "Fake Temporary Proof"]) } let credential = PhoneAuthProvider.provider(auth: auth).credential( withVerificationID: self.kVerificationID, @@ -1627,9 +1629,9 @@ class UserTests: RPCBaseTests { XCTAssertNil(request.deleteAttributes) XCTAssertNil(request.deleteProviders) - try self.rpcIssuer?.respond(withJSON: ["idToken": RPCBaseTests.kFakeAccessToken, - "email": self.kNewEmail, - "refreshToken": self.kRefreshToken]) + return try self.rpcIssuer.respond(withJSON: ["idToken": RPCBaseTests.kFakeAccessToken, + "email": self.kNewEmail, + "refreshToken": self.kRefreshToken]) } if changeEmail { user.updateEmail(to: kNewEmail) { error in @@ -1664,11 +1666,12 @@ class UserTests: RPCBaseTests { XCTAssertTrue(request.returnSecureToken) do { // 3. Send the response from the fake backend. - try self.rpcIssuer?.respond(withJSON: ["idToken": fakeAccessToken, - "isNewUser": true, - "refreshToken": kRefreshToken]) + return try self.rpcIssuer.respond(withJSON: ["idToken": fakeAccessToken, + "isNewUser": true, + "refreshToken": kRefreshToken]) } catch { XCTFail("Failure sending response: \(error)") + return (nil, nil) } } // 1. After setting up fakes, sign out and sign in. @@ -1711,13 +1714,13 @@ class UserTests: RPCBaseTests { ) // 3. Send the response from the fake backend. - try self.rpcIssuer?.respond(withJSON: ["idToken": RPCBaseTests.kFakeAccessToken, - "providerId": GoogleAuthProvider.id, - "refreshToken": self.kRefreshToken, - "localId": self.kLocalID, - "displayName": self.kDisplayName, - "rawUserInfo": self.kGoogleProfile, - "username": self.kUserName]) + return try self.rpcIssuer.respond(withJSON: ["idToken": RPCBaseTests.kFakeAccessToken, + "providerId": GoogleAuthProvider.id, + "refreshToken": self.kRefreshToken, + "localId": self.kLocalID, + "displayName": self.kDisplayName, + "rawUserInfo": self.kGoogleProfile, + "username": self.kUserName]) } do { @@ -1777,14 +1780,14 @@ class UserTests: RPCBaseTests { XCTAssertTrue(request.returnSecureToken) // 3. Send the response from the fake backend. - try self.rpcIssuer?.respond(withJSON: ["idToken": RPCBaseTests.kFakeAccessToken, - "refreshToken": self.kRefreshToken, - "federatedId": self.kFacebookID, - "providerId": FacebookAuthProvider.id, - "localId": self.kLocalID, - "displayName": self.kDisplayName, - "rawUserInfo": self.kGoogleProfile, - "username": self.kUserName]) + return try self.rpcIssuer.respond(withJSON: ["idToken": RPCBaseTests.kFakeAccessToken, + "refreshToken": self.kRefreshToken, + "federatedId": self.kFacebookID, + "providerId": FacebookAuthProvider.id, + "localId": self.kLocalID, + "displayName": self.kDisplayName, + "rawUserInfo": self.kGoogleProfile, + "username": self.kUserName]) } do { @@ -1837,9 +1840,9 @@ class UserTests: RPCBaseTests { XCTAssertNil(request.idToken) // Send the response from the fake backend. - try self.rpcIssuer?.respond(withJSON: ["idToken": RPCBaseTests.kFakeAccessToken, - "isNewUser": true, - "refreshToken": kRefreshToken]) + return try self.rpcIssuer.respond(withJSON: ["idToken": RPCBaseTests.kFakeAccessToken, + "isNewUser": true, + "refreshToken": kRefreshToken]) } do { diff --git a/FirebaseAuth/Tests/Unit/VerifyAssertionTests.swift b/FirebaseAuth/Tests/Unit/VerifyAssertionTests.swift index 2fb630a62ce..c8b58bcd60a 100644 --- a/FirebaseAuth/Tests/Unit/VerifyAssertionTests.swift +++ b/FirebaseAuth/Tests/Unit/VerifyAssertionTests.swift @@ -168,7 +168,7 @@ class VerifyAssertionTests: RPCBaseTests { */ func testSuccessfulVerifyAssertionResponse() async throws { rpcIssuer?.respondBlock = { - try self.rpcIssuer?.respond(withJSON: [ + try self.rpcIssuer.respond(withJSON: [ self.kProviderIDKey: self.kTestProviderID, self.kIDTokenKey: self.kTestIDToken, self.kExpiresInKey: self.kTestExpiresIn, @@ -199,7 +199,7 @@ class VerifyAssertionTests: RPCBaseTests { */ func testSuccessfulVerifyAssertionResponseWithTextData() async throws { rpcIssuer?.respondBlock = { - try self.rpcIssuer?.respond(withJSON: [ + try self.rpcIssuer.respond(withJSON: [ self.kProviderIDKey: self.kTestProviderID, self.kIDTokenKey: self.kTestIDToken, self.kExpiresInKey: self.kTestExpiresIn, diff --git a/FirebaseAuth/Tests/Unit/VerifyClientTests.swift b/FirebaseAuth/Tests/Unit/VerifyClientTests.swift index 528cb357c88..e501069633c 100644 --- a/FirebaseAuth/Tests/Unit/VerifyClientTests.swift +++ b/FirebaseAuth/Tests/Unit/VerifyClientTests.swift @@ -66,7 +66,7 @@ class VerifyClientTests: RPCBaseTests { let kFakeSuggestedTimeout = "1234" rpcIssuer?.respondBlock = { - try self.rpcIssuer?.respond(withJSON: [ + try self.rpcIssuer.respond(withJSON: [ kReceiptKey: kFakeReceipt, kSuggestedTimeOutKey: kFakeSuggestedTimeout, ]) diff --git a/FirebaseAuth/Tests/Unit/VerifyCustomTokenTests.swift b/FirebaseAuth/Tests/Unit/VerifyCustomTokenTests.swift index 8e3e052a4b2..a40e00a51b5 100644 --- a/FirebaseAuth/Tests/Unit/VerifyCustomTokenTests.swift +++ b/FirebaseAuth/Tests/Unit/VerifyCustomTokenTests.swift @@ -100,7 +100,7 @@ class VerifyCustomTokenTests: RPCBaseTests { let kIsNewUserKey = "isNewUser" rpcIssuer.respondBlock = { - try self.rpcIssuer?.respond(withJSON: [ + try self.rpcIssuer.respond(withJSON: [ kIDTokenKey: kTestIDToken, kExpiresInKey: kTestExpiresIn, kRefreshTokenKey: kTestRefreshToken, diff --git a/FirebaseAuth/Tests/Unit/VerifyPasswordTests.swift b/FirebaseAuth/Tests/Unit/VerifyPasswordTests.swift index 06821bf74c2..9f93d86daac 100644 --- a/FirebaseAuth/Tests/Unit/VerifyPasswordTests.swift +++ b/FirebaseAuth/Tests/Unit/VerifyPasswordTests.swift @@ -161,7 +161,7 @@ class VerifyPasswordTests: RPCBaseTests { let kTestPhotoUrl = "www.example.com" rpcIssuer?.respondBlock = { - try self.rpcIssuer?.respond(withJSON: [ + try self.rpcIssuer.respond(withJSON: [ kLocalIDKey: kTestLocalID, kEmailKey: kTestEmail, kDisplayNameKey: kTestDisplayName, diff --git a/FirebaseAuth/Tests/Unit/VerifyPhoneNumberTests.swift b/FirebaseAuth/Tests/Unit/VerifyPhoneNumberTests.swift index 50fb9cf67e5..10831736a50 100644 --- a/FirebaseAuth/Tests/Unit/VerifyPhoneNumberTests.swift +++ b/FirebaseAuth/Tests/Unit/VerifyPhoneNumberTests.swift @@ -108,7 +108,7 @@ import XCTest let kTestRefreshToken = "REFRESH_TOKEN" rpcIssuer.respondBlock = { - try self.rpcIssuer?.respond(withJSON: [ + try self.rpcIssuer.respond(withJSON: [ "idToken": kTestIDToken, "refreshToken": kTestRefreshToken, "localId": kTestLocalID, @@ -129,7 +129,7 @@ import XCTest */ func testSuccessfulVerifyPhoneNumberResponseWithTemporaryProof() async throws { rpcIssuer.respondBlock = { - try self.rpcIssuer?.respond(withJSON: [ + try self.rpcIssuer.respond(withJSON: [ "temporaryProof": self.kTemporaryProof, "phoneNumber": self.kPhoneNumber, ])