| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456 |
- // Copyright 2023 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
- import XCTest
- @testable import FirebaseAuth
- import FirebaseAuthInterop
- import FirebaseCore
- @available(iOS 13, tvOS 13, macOS 10.15, macCatalyst 13, watchOS 7, *)
- class AuthTests: RPCBaseTests {
- static let kAccessToken = "TEST_ACCESS_TOKEN"
- static let kNewAccessToken = "NEW_ACCESS_TOKEN"
- static let kFakeAPIKey = "FAKE_API_KEY"
- static let kFakeRecaptchaResponse = "RecaptchaResponse"
- static let kFakeRecaptchaVersion = "RecaptchaVersion"
- var auth: Auth!
- static var testNum = 0
- var authDispatcherCallback: (() -> Void)?
- override func setUp() {
- super.setUp()
- let options = FirebaseOptions(googleAppID: "0:0000000000000:ios:0000000000000000",
- gcmSenderID: "00000000000000000-00000000000-000000000")
- options.apiKey = AuthTests.kFakeAPIKey
- options.projectID = "myProjectID"
- let name = "test-AuthTests\(AuthTests.testNum)"
- AuthTests.testNum = AuthTests.testNum + 1
- FirebaseApp.configure(name: name, options: options)
- #if (os(macOS) && !FIREBASE_AUTH_TESTING_USE_MACOS_KEYCHAIN) || SWIFT_PACKAGE
- let keychainStorageProvider = FakeAuthKeychainStorage()
- #else
- let keychainStorageProvider = AuthKeychainStorageReal()
- #endif // (os(macOS) && !FIREBASE_AUTH_TESTING_USE_MACOS_KEYCHAIN) || SWIFT_PACKAGE
- auth = Auth(
- app: FirebaseApp.app(name: name)!,
- keychainStorageProvider: keychainStorageProvider
- )
- // Set authDispatcherCallback implementation in order to save the token refresh task for later
- // execution.
- AuthDispatcher.shared.dispatchAfterImplementation = { delay, queue, task in
- XCTAssertNotNil(task)
- XCTAssertGreaterThan(delay, 0)
- XCTAssertEqual(kAuthGlobalWorkQueue, queue)
- self.authDispatcherCallback = task
- }
- // Wait until Auth initialization completes
- waitForAuthGlobalWorkQueueDrain()
- }
- private func waitForAuthGlobalWorkQueueDrain() {
- let workerSemaphore = DispatchSemaphore(value: 0)
- kAuthGlobalWorkQueue.async {
- workerSemaphore.signal()
- }
- _ = workerSemaphore.wait(timeout: DispatchTime.distantFuture)
- }
- /** @fn testFetchSignInMethodsForEmailSuccess
- @brief Tests the flow of a successful @c fetchSignInMethodsForEmail:completion: call.
- */
- func testFetchSignInMethodsForEmailSuccess() throws {
- let allSignInMethods = ["emailLink", "facebook.com"]
- let expectation = self.expectation(description: #function)
- rpcIssuer.respondBlock = {
- let request = try XCTUnwrap(self.rpcIssuer.request as? CreateAuthURIRequest)
- XCTAssertEqual(request.identifier, self.kEmail)
- XCTAssertEqual(request.endpoint, "createAuthUri")
- XCTAssertEqual(request.apiKey, AuthTests.kFakeAPIKey)
- try self.rpcIssuer.respond(withJSON: ["signinMethods": allSignInMethods])
- }
- auth?.fetchSignInMethods(forEmail: kEmail) { signInMethods, error in
- // 4. After the response triggers the callback, verify the returned signInMethods.
- XCTAssertTrue(Thread.isMainThread)
- XCTAssertEqual(signInMethods, allSignInMethods)
- XCTAssertNil(error)
- expectation.fulfill()
- }
- waitForExpectations(timeout: 5)
- }
- /** @fn testFetchSignInMethodsForEmailFailure
- @brief Tests the flow of a failed @c fetchSignInMethodsForEmail:completion: call.
- */
- func testFetchSignInMethodsForEmailFailure() throws {
- let expectation = self.expectation(description: #function)
- rpcIssuer.respondBlock = {
- let message = "TOO_MANY_ATTEMPTS_TRY_LATER"
- try self.rpcIssuer.respond(serverErrorMessage: message)
- }
- auth?.fetchSignInMethods(forEmail: kEmail) { signInMethods, error in
- XCTAssertTrue(Thread.isMainThread)
- XCTAssertNil(signInMethods)
- let rpcError = (error as? NSError)!
- XCTAssertEqual(rpcError.code, AuthErrorCode.tooManyRequests.rawValue)
- expectation.fulfill()
- }
- waitForExpectations(timeout: 5)
- }
- #if os(iOS)
- /** @fn testPhoneAuthSuccess
- @brief Tests the flow of a successful @c signInWithCredential:completion for phone auth.
- */
- func testPhoneAuthSuccess() throws {
- let kVerificationID = "55432"
- let kVerificationCode = "12345678"
- let expectation = self.expectation(description: #function)
- setFakeGetAccountProvider()
- setFakeSecureTokenService()
- // 1. Setup respond block to test and fake send request.
- rpcIssuer.respondBlock = {
- // 2. Validate the created Request instance.
- let request = try XCTUnwrap(self.rpcIssuer.request as? VerifyPhoneNumberRequest)
- XCTAssertEqual(request.verificationCode, kVerificationCode)
- 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])
- }
- try auth?.signOut()
- let credential = PhoneAuthProvider.provider(auth: auth)
- .credential(withVerificationID: kVerificationID,
- verificationCode: kVerificationCode)
- auth?.signIn(with: credential) { authResult, error in
- // 4. After the response triggers the callback, verify the returned result.
- XCTAssertTrue(Thread.isMainThread)
- guard let user = authResult?.user,
- let additionalUserInfo = authResult?.additionalUserInfo else {
- XCTFail("authResult.user or additionalUserInfo is missing")
- return
- }
- XCTAssertEqual(user.refreshToken, self.kRefreshToken)
- XCTAssertFalse(user.isAnonymous)
- XCTAssertTrue(additionalUserInfo.isNewUser)
- XCTAssertNil(error)
- expectation.fulfill()
- }
- waitForExpectations(timeout: 5)
- assertUser(auth?.currentUser)
- }
- /** @fn testPhoneAuthMissingVerificationCode
- @brief Tests the flow of an unsuccessful @c signInWithCredential:completion for phone auth due
- to an empty verification code
- */
- func testPhoneAuthMissingVerificationCode() throws {
- let kVerificationID = "55432"
- let kVerificationCode = ""
- let expectation = self.expectation(description: #function)
- setFakeGetAccountProvider()
- setFakeSecureTokenService()
- try auth?.signOut()
- let credential = PhoneAuthProvider.provider(auth: auth)
- .credential(withVerificationID: kVerificationID,
- verificationCode: kVerificationCode)
- auth?.signIn(with: credential) { authResult, error in
- XCTAssertTrue(Thread.isMainThread)
- XCTAssertNil(authResult)
- XCTAssertEqual((error as? NSError)?.code, AuthErrorCode.missingVerificationCode.rawValue)
- expectation.fulfill()
- }
- waitForExpectations(timeout: 5)
- }
- /** @fn testPhoneAuthMissingVerificationID
- @brief Tests the flow of an unsuccessful @c signInWithCredential:completion for phone auth due
- to an empty verification ID.
- */
- func testPhoneAuthMissingVerificationID() throws {
- let kVerificationID = ""
- let kVerificationCode = "123"
- let expectation = self.expectation(description: #function)
- setFakeGetAccountProvider()
- setFakeSecureTokenService()
- try auth?.signOut()
- let credential = PhoneAuthProvider.provider(auth: auth)
- .credential(withVerificationID: kVerificationID,
- verificationCode: kVerificationCode)
- auth?.signIn(with: credential) { authResult, error in
- XCTAssertTrue(Thread.isMainThread)
- XCTAssertNil(authResult)
- XCTAssertEqual((error as? NSError)?.code, AuthErrorCode.missingVerificationID.rawValue)
- expectation.fulfill()
- }
- waitForExpectations(timeout: 5)
- }
- #endif
- /** @fn testSignInWithEmailLinkSuccess
- @brief Tests the flow of a successful @c signInWithEmail:link:completion: call.
- */
- func testSignInWithEmailLinkSuccess() throws {
- try signInWithEmailLinkSuccessWithLinkOrDeeplink(link: kFakeEmailSignInLink)
- }
- /** @fn testSignInWithEmailLinkSuccessDeeplink
- @brief Tests the flow of a successful @c signInWithEmail:link: call using a deep link.
- */
- func testSignInWithEmailLinkSuccessDeeplink() throws {
- try signInWithEmailLinkSuccessWithLinkOrDeeplink(link: kFakeEmailSignInDeeplink)
- }
- private func signInWithEmailLinkSuccessWithLinkOrDeeplink(link: String) throws {
- let fakeCode = "testoobcode"
- let expectation = self.expectation(description: #function)
- setFakeGetAccountProvider()
- setFakeSecureTokenService()
- // 1. Setup respond block to test and fake send request.
- rpcIssuer.respondBlock = {
- // 2. Validate the created Request instance.
- let request = try XCTUnwrap(self.rpcIssuer.request as? EmailLinkSignInRequest)
- XCTAssertEqual(request.email, self.kEmail)
- 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])
- }
- try auth?.signOut()
- auth?.signIn(withEmail: kEmail, link: link) { authResult, error in
- // 4. After the response triggers the callback, verify the returned result.
- XCTAssertTrue(Thread.isMainThread)
- guard let user = authResult?.user else {
- XCTFail("authResult.user is missing")
- return
- }
- XCTAssertEqual(user.refreshToken, self.kRefreshToken)
- XCTAssertFalse(user.isAnonymous)
- XCTAssertEqual(user.email, self.kEmail)
- XCTAssertNil(error)
- expectation.fulfill()
- }
- waitForExpectations(timeout: 5)
- assertUser(auth?.currentUser)
- }
- /** @fn testSignInWithEmailLinkFailure
- @brief Tests the flow of a failed @c signInWithEmail:link:completion: call.
- */
- func testSignInWithEmailLinkFailure() throws {
- let expectation = self.expectation(description: #function)
- // 1. Setup respond block to test and fake send request.
- rpcIssuer.respondBlock = {
- // 2. Send the response from the fake backend.
- try self.rpcIssuer.respond(serverErrorMessage: "INVALID_OOB_CODE")
- }
- try auth?.signOut()
- auth?.signIn(withEmail: kEmail, link: kFakeEmailSignInLink) { authResult, error in
- // 3. After the response triggers the callback, verify the returned result.
- XCTAssertTrue(Thread.isMainThread)
- XCTAssertNil(authResult)
- XCTAssertEqual((error as? NSError)?.code, AuthErrorCode.invalidActionCode.rawValue)
- expectation.fulfill()
- }
- waitForExpectations(timeout: 5)
- XCTAssertNil(auth?.currentUser)
- }
- #if os(iOS)
- /** @fn testSignInWithEmailPasswordWithRecaptchaSuccess
- @brief Tests the flow of a successful @c signInWithEmail:password:completion: call.
- */
- func testSignInWithEmailPasswordWithRecaptchaSuccess() throws {
- let kRefreshToken = "fakeRefreshToken"
- let expectation = self.expectation(description: #function)
- setFakeGetAccountProvider()
- setFakeSecureTokenService()
- // 1. Setup respond block to test and fake send request.
- rpcIssuer.respondBlock = {
- // 2. Validate the created Request instance.
- let request = try XCTUnwrap(self.rpcIssuer.request as? VerifyPasswordRequest)
- XCTAssertEqual(request.email, self.kEmail)
- XCTAssertEqual(request.password, self.kFakePassword)
- XCTAssertEqual(request.apiKey, AuthTests.kFakeAPIKey)
- XCTAssertTrue(request.returnSecureToken)
- request.injectRecaptchaFields(recaptchaResponse: AuthTests.kFakeRecaptchaResponse,
- 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])
- }
- try auth?.signOut()
- auth?.signIn(withEmail: kEmail, password: kFakePassword) { authResult, error in
- // 4. After the response triggers the callback, verify the returned result.
- XCTAssertTrue(Thread.isMainThread)
- guard let user = authResult?.user else {
- XCTFail("authResult.user is missing")
- return
- }
- XCTAssertEqual(user.refreshToken, kRefreshToken)
- XCTAssertFalse(user.isAnonymous)
- XCTAssertEqual(user.email, self.kEmail)
- guard let additionalUserInfo = authResult?.additionalUserInfo else {
- XCTFail("authResult.additionalUserInfo is missing")
- return
- }
- XCTAssertFalse(additionalUserInfo.isNewUser)
- XCTAssertEqual(additionalUserInfo.providerID, EmailAuthProvider.id)
- XCTAssertNil(error)
- expectation.fulfill()
- }
- waitForExpectations(timeout: 5)
- assertUser(auth?.currentUser)
- }
- /** @fn testSignInWithEmailPasswordWithRecaptchaFallbackSuccess
- @brief Tests the flow of a successful @c signInWithEmail:password:completion: call.
- */
- func testSignInWithEmailPasswordWithRecaptchaFallbackSuccess() throws {
- let kRefreshToken = "fakeRefreshToken"
- let expectation = self.expectation(description: #function)
- setFakeGetAccountProvider()
- setFakeSecureTokenService()
- let kTestRecaptchaKey = "projects/123/keys/456"
- rpcIssuer.recaptchaSiteKey = kTestRecaptchaKey
- // 1. Setup respond block to test and fake send request.
- rpcIssuer.respondBlock = {
- // 2. Validate the created Request instance.
- let request = try XCTUnwrap(self.rpcIssuer.request as? VerifyPasswordRequest)
- XCTAssertEqual(request.email, self.kEmail)
- XCTAssertEqual(request.password, self.kFakePassword)
- XCTAssertEqual(request.apiKey, AuthTests.kFakeAPIKey)
- XCTAssertTrue(request.returnSecureToken)
- request.injectRecaptchaFields(recaptchaResponse: AuthTests.kFakeRecaptchaResponse,
- recaptchaVersion: AuthTests.kFakeRecaptchaVersion)
- // 3. Send the response from the fake backend.
- try self.rpcIssuer.respond(serverErrorMessage: "MISSING_RECAPTCHA_TOKEN")
- }
- rpcIssuer.nextRespondBlock = {
- // 4. Validate again the created Request instance after the recaptcha retry.
- let request = try XCTUnwrap(self.rpcIssuer.request as? VerifyPasswordRequest)
- XCTAssertEqual(request.email, self.kEmail)
- XCTAssertEqual(request.password, self.kFakePassword)
- XCTAssertEqual(request.apiKey, AuthTests.kFakeAPIKey)
- XCTAssertTrue(request.returnSecureToken)
- 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])
- }
- try auth?.signOut()
- auth?.signIn(withEmail: kEmail, password: kFakePassword) { authResult, error in
- // 6. After the response triggers the callback, verify the returned result.
- XCTAssertTrue(Thread.isMainThread)
- XCTAssertNil(error)
- guard let user = authResult?.user else {
- XCTFail("authResult.user is missing")
- return
- }
- XCTAssertEqual(user.refreshToken, kRefreshToken)
- XCTAssertFalse(user.isAnonymous)
- XCTAssertEqual(user.email, self.kEmail)
- guard let additionalUserInfo = authResult?.additionalUserInfo else {
- XCTFail("authResult.additionalUserInfo is missing")
- return
- }
- XCTAssertFalse(additionalUserInfo.isNewUser)
- XCTAssertEqual(additionalUserInfo.providerID, EmailAuthProvider.id)
- expectation.fulfill()
- }
- waitForExpectations(timeout: 5)
- assertUser(auth?.currentUser)
- }
- #endif
- /** @fn testSignInAndRetrieveDataWithEmailPasswordSuccess
- @brief Tests the flow of a successful @c signInAndRetrieveDataWithEmail:password:completion:
- call. Superset of historical testSignInWithEmailPasswordSuccess.
- */
- func testSignInAndRetrieveDataWithEmailPasswordSuccess() throws {
- let kRefreshToken = "fakeRefreshToken"
- let expectation = self.expectation(description: #function)
- setFakeGetAccountProvider()
- setFakeSecureTokenService()
- // 1. Setup respond block to test and fake send request.
- rpcIssuer.respondBlock = {
- // 2. Validate the created Request instance.
- let request = try XCTUnwrap(self.rpcIssuer.request as? VerifyPasswordRequest)
- XCTAssertEqual(request.email, self.kEmail)
- XCTAssertEqual(request.password, self.kFakePassword)
- XCTAssertEqual(request.apiKey, AuthTests.kFakeAPIKey)
- 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])
- }
- try auth?.signOut()
- auth?.signIn(withEmail: kEmail, password: kFakePassword) { authResult, error in
- // 4. After the response triggers the callback, verify the returned result.
- XCTAssertTrue(Thread.isMainThread)
- guard let user = authResult?.user else {
- XCTFail("authResult.user is missing")
- return
- }
- XCTAssertEqual(user.refreshToken, kRefreshToken)
- XCTAssertFalse(user.isAnonymous)
- XCTAssertEqual(user.email, self.kEmail)
- guard let additionalUserInfo = authResult?.additionalUserInfo else {
- XCTFail("authResult.additionalUserInfo is missing")
- return
- }
- XCTAssertFalse(additionalUserInfo.isNewUser)
- XCTAssertEqual(additionalUserInfo.providerID, EmailAuthProvider.id)
- XCTAssertNil(error)
- expectation.fulfill()
- }
- waitForExpectations(timeout: 5)
- assertUser(auth?.currentUser)
- }
- /** @fn testSignInWithEmailPasswordFailure
- @brief Tests the flow of a failed @c signInWithEmail:password:completion: call.
- */
- func testSignInWithEmailPasswordFailure() throws {
- let expectation = self.expectation(description: #function)
- rpcIssuer.respondBlock = {
- // 2. Send the response from the fake backend.
- try self.rpcIssuer.respond(serverErrorMessage: "INVALID_PASSWORD")
- }
- try auth?.signOut()
- auth?.signIn(withEmail: kEmail, password: kFakePassword) { authResult, error in
- // 3. After the response triggers the callback, verify the returned result.
- XCTAssertTrue(Thread.isMainThread)
- XCTAssertNil(authResult)
- XCTAssertEqual((error as? NSError)?.code, AuthErrorCode.wrongPassword.rawValue)
- XCTAssertNotNil((error as? NSError)?.userInfo[NSLocalizedDescriptionKey])
- expectation.fulfill()
- }
- waitForExpectations(timeout: 5)
- XCTAssertNil(auth?.currentUser)
- }
- /** @fn testResetPasswordSuccess
- @brief Tests the flow of a successful @c confirmPasswordResetWithCode:newPassword:completion:
- call.
- */
- func testResetPasswordSuccess() throws {
- let expectation = self.expectation(description: #function)
- // 1. Setup respond block to test and fake send request.
- rpcIssuer.respondBlock = {
- // 2. Validate the created Request instance.
- let request = try XCTUnwrap(self.rpcIssuer.request as? ResetPasswordRequest)
- XCTAssertEqual(request.oobCode, self.kFakeOobCode)
- XCTAssertEqual(request.updatedPassword, self.kFakePassword)
- XCTAssertEqual(request.apiKey, AuthTests.kFakeAPIKey)
- // 3. Send the response from the fake backend.
- try self.rpcIssuer.respond(withJSON: [:])
- }
- try auth?.signOut()
- auth?
- .confirmPasswordReset(withCode: kFakeOobCode, newPassword: kFakePassword) { error in
- // 4. After the response triggers the callback, verify the returned result.
- XCTAssertTrue(Thread.isMainThread)
- XCTAssertNil(error)
- expectation.fulfill()
- }
- waitForExpectations(timeout: 5)
- }
- /** @fn testResetPasswordFailure
- @brief Tests the flow of a failed @c confirmPasswordResetWithCode:newPassword:completion:
- call.
- */
- func testResetPasswordFailure() throws {
- let expectation = self.expectation(description: #function)
- rpcIssuer.respondBlock = {
- // 2. Send the response from the fake backend.
- try self.rpcIssuer.respond(serverErrorMessage: "INVALID_OOB_CODE")
- }
- try auth?.signOut()
- auth?
- .confirmPasswordReset(withCode: kFakeOobCode, newPassword: kFakePassword) { error in
- // 3. After the response triggers the callback, verify the returned result.
- XCTAssertTrue(Thread.isMainThread)
- XCTAssertEqual((error as? NSError)?.code, AuthErrorCode.invalidActionCode.rawValue)
- XCTAssertNotNil((error as? NSError)?.userInfo[NSLocalizedDescriptionKey])
- expectation.fulfill()
- }
- waitForExpectations(timeout: 5)
- XCTAssertNil(auth?.currentUser)
- }
- /** @fn testCheckActionCodeSuccess
- @brief Tests the flow of a successful @c checkActionCode:completion call.
- */
- func testCheckActionCodeSuccess() throws {
- let kNewEmail = "newEmail@example.com"
- let verifyEmailRequestType = "VERIFY_EMAIL"
- let expectation = self.expectation(description: #function)
- // 1. Setup respond block to test and fake send request.
- rpcIssuer.respondBlock = {
- // 2. Validate the created Request instance.
- let request = try XCTUnwrap(self.rpcIssuer.request as? ResetPasswordRequest)
- XCTAssertEqual(request.oobCode, self.kFakeOobCode)
- 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])
- }
- try auth?.signOut()
- auth?.checkActionCode(kFakeOobCode) { info, error in
- // 4. After the response triggers the callback, verify the returned result.
- XCTAssertTrue(Thread.isMainThread)
- XCTAssertNil(error)
- XCTAssertEqual(info?.email, kNewEmail)
- XCTAssertEqual(info?.operation, ActionCodeOperation.verifyEmail)
- expectation.fulfill()
- }
- waitForExpectations(timeout: 5)
- }
- /** @fn testCheckActionCodeFailure
- @brief Tests the flow of a failed @c checkActionCode:completion call.
- */
- func testCheckActionCodeFailure() throws {
- let expectation = self.expectation(description: #function)
- // 1. Setup respond block to test and fake send request.
- rpcIssuer.respondBlock = {
- // 2. Send the response from the fake backend.
- try self.rpcIssuer.respond(serverErrorMessage: "EXPIRED_OOB_CODE")
- }
- try auth?.signOut()
- auth?.checkActionCode(kFakeOobCode) { info, error in
- // 3. After the response triggers the callback, verify the returned result.
- XCTAssertTrue(Thread.isMainThread)
- XCTAssertEqual((error as? NSError)?.code, AuthErrorCode.expiredActionCode.rawValue)
- XCTAssertNotNil((error as? NSError)?.userInfo[NSLocalizedDescriptionKey])
- expectation.fulfill()
- }
- waitForExpectations(timeout: 5)
- XCTAssertNil(auth?.currentUser)
- }
- /** @fn testApplyActionCodeSuccess
- @brief Tests the flow of a successful @c applyActionCode:completion call.
- */
- func testApplyActionCodeSuccess() throws {
- let expectation = self.expectation(description: #function)
- // 1. Setup respond block to test and fake send request.
- rpcIssuer.respondBlock = {
- // 2. Validate the created Request instance.
- let request = try XCTUnwrap(self.rpcIssuer.request as? SetAccountInfoRequest)
- XCTAssertEqual(request.apiKey, AuthTests.kFakeAPIKey)
- // 3. Send the response from the fake backend.
- try self.rpcIssuer.respond(withJSON: [:])
- }
- try auth?.signOut()
- auth?.applyActionCode(kFakeOobCode) { error in
- // 4. After the response triggers the callback, verify the returned result.
- XCTAssertTrue(Thread.isMainThread)
- XCTAssertNil(error)
- expectation.fulfill()
- }
- waitForExpectations(timeout: 5)
- }
- /** @fn testApplyActionCodeFailure
- @brief Tests the flow of a failed @c checkActionCode:completion call.
- */
- func testApplyActionCodeFailure() throws {
- let expectation = self.expectation(description: #function)
- // 1. Setup respond block to test and fake send request.
- rpcIssuer.respondBlock = {
- // 2. Send the response from the fake backend.
- try self.rpcIssuer.respond(serverErrorMessage: "INVALID_OOB_CODE")
- }
- try auth?.signOut()
- auth?.applyActionCode(kFakeOobCode) { error in
- // 3. After the response triggers the callback, verify the returned result.
- XCTAssertTrue(Thread.isMainThread)
- XCTAssertEqual((error as? NSError)?.code, AuthErrorCode.invalidActionCode.rawValue)
- XCTAssertNotNil((error as? NSError)?.userInfo[NSLocalizedDescriptionKey])
- expectation.fulfill()
- }
- waitForExpectations(timeout: 5)
- XCTAssertNil(auth?.currentUser)
- }
- /** @fn testVerifyPasswordResetCodeSuccess
- @brief Tests the flow of a successful @c verifyPasswordResetCode:completion call.
- */
- func testVerifyPasswordResetCodeSuccess() throws {
- let expectation = self.expectation(description: #function)
- // 1. Setup respond block to test and fake send request.
- rpcIssuer.respondBlock = {
- // 2. Validate the created Request instance.
- let request = try XCTUnwrap(self.rpcIssuer.request as? ResetPasswordRequest)
- XCTAssertEqual(request.apiKey, AuthTests.kFakeAPIKey)
- XCTAssertEqual(request.oobCode, self.kFakeOobCode)
- // 3. Send the response from the fake backend.
- try self.rpcIssuer.respond(withJSON: ["email": self.kEmail])
- }
- try auth?.signOut()
- auth?.verifyPasswordResetCode(kFakeOobCode) { email, error in
- // 4. After the response triggers the callback, verify the returned result.
- XCTAssertTrue(Thread.isMainThread)
- XCTAssertEqual(email, self.kEmail)
- XCTAssertNil(error)
- expectation.fulfill()
- }
- waitForExpectations(timeout: 5)
- }
- /** @fn testVerifyPasswordResetCodeFailure
- @brief Tests the flow of a failed @c verifyPasswordResetCode:completion call.
- */
- func testVerifyPasswordResetCodeFailure() throws {
- let expectation = self.expectation(description: #function)
- // 1. Setup respond block to test and fake send request.
- rpcIssuer.respondBlock = {
- // 2. Send the response from the fake backend.
- try self.rpcIssuer.respond(serverErrorMessage: "INVALID_OOB_CODE")
- }
- try auth?.signOut()
- auth?.verifyPasswordResetCode(kFakeOobCode) { email, error in
- // 3. After the response triggers the callback, verify the returned result.
- XCTAssertTrue(Thread.isMainThread)
- XCTAssertNil(email)
- XCTAssertEqual((error as? NSError)?.code, AuthErrorCode.invalidActionCode.rawValue)
- XCTAssertNotNil((error as? NSError)?.userInfo[NSLocalizedDescriptionKey])
- expectation.fulfill()
- }
- waitForExpectations(timeout: 5)
- XCTAssertNil(auth?.currentUser)
- }
- /** @fn testSignInWithEmailLinkCredentialSuccess
- @brief Tests the flow of a successfully @c signInWithCredential:completion: call with an
- email sign-in link credential using FIREmailAuthProvider.
- */
- func testSignInWithEmailLinkCredentialSuccess() throws {
- let expectation = self.expectation(description: #function)
- let fakeCode = "testoobcode"
- setFakeGetAccountProvider()
- setFakeSecureTokenService()
- // 1. Setup respond block to test and fake send request.
- rpcIssuer.respondBlock = {
- // 2. Validate the created Request instance.
- let request = try XCTUnwrap(self.rpcIssuer.request as? EmailLinkSignInRequest)
- XCTAssertEqual(request.apiKey, AuthTests.kFakeAPIKey)
- XCTAssertEqual(request.oobCode, fakeCode)
- 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])
- }
- try auth?.signOut()
- let emailCredential = EmailAuthProvider.credential(
- withEmail: kEmail,
- link: kFakeEmailSignInLink
- )
- auth?.signIn(with: emailCredential) { authResult, error in
- // 4. After the response triggers the callback, verify the returned result.
- XCTAssertTrue(Thread.isMainThread)
- guard let user = authResult?.user else {
- XCTFail("authResult.user or additionalUserInfo is missing")
- return
- }
- XCTAssertEqual(user.refreshToken, self.kRefreshToken)
- XCTAssertFalse(user.isAnonymous)
- XCTAssertEqual(user.email, self.kEmail)
- XCTAssertNil(error)
- expectation.fulfill()
- }
- waitForExpectations(timeout: 5)
- }
- /** @fn testSignInWithEmailLinkCredentialFailure
- @brief Tests the flow of a failed @c signInWithCredential:completion: call with an
- email-email sign-in link credential using FIREmailAuthProvider.
- */
- func testSignInWithEmailLinkCredentialFailure() throws {
- let expectation = self.expectation(description: #function)
- // 1. Setup respond block to test and fake send request.
- rpcIssuer.respondBlock = {
- // 2. Send the response from the fake backend.
- try self.rpcIssuer.respond(serverErrorMessage: "USER_DISABLED")
- }
- try auth?.signOut()
- let emailCredential = EmailAuthProvider.credential(
- withEmail: kEmail,
- link: kFakeEmailSignInLink
- )
- auth?.signIn(with: emailCredential) { authResult, error in
- // 3. After the response triggers the callback, verify the returned result.
- XCTAssertTrue(Thread.isMainThread)
- XCTAssertNil(authResult)
- XCTAssertEqual((error as? NSError)?.code, AuthErrorCode.userDisabled.rawValue)
- XCTAssertNotNil((error as? NSError)?.userInfo[NSLocalizedDescriptionKey])
- expectation.fulfill()
- }
- waitForExpectations(timeout: 5)
- XCTAssertNil(auth?.currentUser)
- }
- /** @fn testSignInWithEmailCredentialSuccess
- @brief Tests the flow of a successfully @c signInWithCredential:completion: call with an
- email-password credential.
- */
- func testSignInWithEmailCredentialSuccess() throws {
- let expectation = self.expectation(description: #function)
- setFakeGetAccountProvider()
- setFakeSecureTokenService()
- // 1. Setup respond block to test and fake send request.
- rpcIssuer.respondBlock = {
- // 2. Validate the created Request instance.
- let request = try XCTUnwrap(self.rpcIssuer.request as? VerifyPasswordRequest)
- XCTAssertEqual(request.apiKey, AuthTests.kFakeAPIKey)
- XCTAssertEqual(request.password, self.kFakePassword)
- 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])
- }
- try auth?.signOut()
- let emailCredential = EmailAuthProvider.credential(withEmail: kEmail, password: kFakePassword)
- auth?.signIn(with: emailCredential) { authResult, error in
- // 4. After the response triggers the callback, verify the returned result.
- XCTAssertTrue(Thread.isMainThread)
- guard let user = authResult?.user else {
- XCTFail("authResult.user or additionalUserInfo is missing")
- return
- }
- XCTAssertEqual(user.refreshToken, self.kRefreshToken)
- XCTAssertFalse(user.isAnonymous)
- XCTAssertEqual(user.email, self.kEmail)
- XCTAssertNil(error)
- expectation.fulfill()
- }
- waitForExpectations(timeout: 5)
- }
- /** @fn testSignInWithEmailCredentialFailure
- @brief Tests the flow of a failed @c signInWithCredential:completion: call with an
- email-password credential.
- */
- func testSignInWithEmailCredentialFailure() throws {
- let expectation = self.expectation(description: #function)
- // 1. Setup respond block to test and fake send request.
- rpcIssuer.respondBlock = {
- // 2. Send the response from the fake backend.
- try self.rpcIssuer.respond(serverErrorMessage: "USER_DISABLED")
- }
- try auth?.signOut()
- let emailCredential = EmailAuthProvider.credential(withEmail: kEmail, password: kFakePassword)
- auth?.signIn(with: emailCredential) { authResult, error in
- // 3. After the response triggers the callback, verify the returned result.
- XCTAssertTrue(Thread.isMainThread)
- XCTAssertNil(authResult)
- XCTAssertEqual((error as? NSError)?.code, AuthErrorCode.userDisabled.rawValue)
- XCTAssertNotNil((error as? NSError)?.userInfo[NSLocalizedDescriptionKey])
- expectation.fulfill()
- }
- waitForExpectations(timeout: 5)
- XCTAssertNil(auth?.currentUser)
- }
- /** @fn testSignInWithEmailCredentialEmptyPassword
- @brief Tests the flow of a failed @c signInWithCredential:completion: call with an
- email-password credential using an empty password. This error occurs on the client side,
- so there is no need to fake an RPC response.
- */
- func testSignInWithEmailCredentialEmptyPassword() throws {
- let expectation = self.expectation(description: #function)
- let emailCredential = EmailAuthProvider.credential(withEmail: kEmail, password: "")
- auth?.signIn(with: emailCredential) { authResult, error in
- XCTAssertTrue(Thread.isMainThread)
- XCTAssertNil(authResult)
- XCTAssertEqual((error as? NSError)?.code, AuthErrorCode.wrongPassword.rawValue)
- XCTAssertNotNil((error as? NSError)?.userInfo[NSLocalizedDescriptionKey])
- expectation.fulfill()
- }
- waitForExpectations(timeout: 5)
- }
- #if os(iOS)
- class FakeProvider: NSObject, FederatedAuthProvider {
- @available(iOS 13, tvOS 13, macOS 10.15, watchOS 8, *)
- func credential(with UIDelegate: FirebaseAuth.AuthUIDelegate?) async throws ->
- FirebaseAuth.AuthCredential {
- let credential = OAuthCredential(withProviderID: GoogleAuthProvider.id,
- sessionID: kOAuthSessionID,
- OAuthResponseURLString: kOAuthRequestURI)
- XCTAssertEqual(credential.OAuthResponseURLString, kOAuthRequestURI)
- XCTAssertEqual(credential.sessionID, kOAuthSessionID)
- return credential
- }
- }
- /** @fn testSignInWithProviderSuccess
- @brief Tests a successful @c signInWithProvider:UIDelegate:completion: call with an OAuth
- provider configured for Google.
- */
- func testSignInWithProviderSuccess() throws {
- let expectation = self.expectation(description: #function)
- setFakeGoogleGetAccountProvider()
- setFakeSecureTokenService()
- // 1. Setup respond block to test and fake send request.
- rpcIssuer.respondBlock = {
- // 2. Validate the created Request instance.
- let request = try XCTUnwrap(self.rpcIssuer.request as? VerifyAssertionRequest)
- XCTAssertEqual(request.apiKey, AuthTests.kFakeAPIKey)
- XCTAssertEqual(request.providerID, GoogleAuthProvider.id)
- 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])
- }
- try auth.signOut()
- auth.signIn(with: FakeProvider(), uiDelegate: nil) { authResult, error in
- // 4. After the response triggers the callback, verify the returned result.
- XCTAssertTrue(Thread.isMainThread)
- do {
- try self.assertUserGoogle(authResult?.user)
- } catch {
- XCTFail("\(error)")
- }
- XCTAssertNil(error)
- expectation.fulfill()
- }
- waitForExpectations(timeout: 5)
- try assertUserGoogle(auth.currentUser)
- }
- /** @fn testSignInWithProviderFailure
- @brief Tests a failed @c signInWithProvider:UIDelegate:completion: call with the error code
- FIRAuthErrorCodeWebSignInUserInteractionFailure.
- */
- func testSignInWithProviderFailure() throws {
- let expectation = self.expectation(description: #function)
- setFakeGoogleGetAccountProvider()
- setFakeSecureTokenService()
- // 1. Setup respond block to test and fake send request.
- rpcIssuer.respondBlock = {
- // 2. Validate the created Request instance.
- let request = try XCTUnwrap(self.rpcIssuer.request as? VerifyAssertionRequest)
- XCTAssertEqual(request.apiKey, AuthTests.kFakeAPIKey)
- XCTAssertEqual(request.providerID, GoogleAuthProvider.id)
- XCTAssertTrue(request.returnSecureToken)
- // 3. Send the response from the fake backend.
- try self.rpcIssuer.respond(serverErrorMessage: "USER_DISABLED")
- }
- try auth.signOut()
- auth.signIn(with: FakeProvider(), uiDelegate: nil) { authResult, error in
- // 4. After the response triggers the callback, verify the returned result.
- XCTAssertTrue(Thread.isMainThread)
- XCTAssertNil(authResult)
- XCTAssertEqual((error as? NSError)?.code, AuthErrorCode.userDisabled.rawValue)
- expectation.fulfill()
- }
- waitForExpectations(timeout: 5)
- }
- /** @fn testSignInWithGoogleAccountExistsError
- @brief Tests the flow of a failed @c signInWithCredential:completion: with a Google credential
- where the backend returns a needs @needConfirmation equal to true. An
- FIRAuthErrorCodeAccountExistsWithDifferentCredential error should be thrown.
- */
- func testSignInWithGoogleAccountExistsError() throws {
- let expectation = self.expectation(description: #function)
- setFakeGoogleGetAccountProvider()
- setFakeSecureTokenService()
- // 1. Setup respond block to test and fake send request.
- rpcIssuer.respondBlock = {
- // 2. Validate the created Request instance.
- let request = try XCTUnwrap(self.rpcIssuer.request as? VerifyAssertionRequest)
- XCTAssertEqual(request.apiKey, AuthTests.kFakeAPIKey)
- XCTAssertEqual(request.providerID, GoogleAuthProvider.id)
- XCTAssertEqual(request.providerIDToken, self.kGoogleIDToken)
- XCTAssertEqual(request.providerAccessToken, self.kGoogleAccessToken)
- 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])
- }
- try auth.signOut()
- let googleCredential = GoogleAuthProvider.credential(withIDToken: kGoogleIDToken,
- accessToken: kGoogleAccessToken)
- auth.signIn(with: googleCredential) { authResult, error in
- // 4. After the response triggers the callback, verify the returned result.
- XCTAssertTrue(Thread.isMainThread)
- XCTAssertNil(authResult)
- XCTAssertEqual((error as? NSError)?.code,
- AuthErrorCode.accountExistsWithDifferentCredential.rawValue)
- expectation.fulfill()
- }
- waitForExpectations(timeout: 5)
- }
- /** @fn testSignInWithOAuthCredentialSuccess
- @brief Tests the flow of a successful @c signInWithCredential:completion: call with a generic
- OAuth credential (In this case, configured for the Google IDP).
- */
- func testSignInWithOAuthCredentialSuccess() throws {
- let expectation = self.expectation(description: #function)
- setFakeGoogleGetAccountProvider()
- setFakeSecureTokenService()
- // 1. Setup respond block to test and fake send request.
- rpcIssuer.respondBlock = {
- // 2. Validate the created Request instance.
- let request = try XCTUnwrap(self.rpcIssuer.request as? VerifyAssertionRequest)
- XCTAssertEqual(request.apiKey, AuthTests.kFakeAPIKey)
- XCTAssertEqual(request.providerID, GoogleAuthProvider.id)
- XCTAssertEqual(request.requestURI, AuthTests.kOAuthRequestURI)
- XCTAssertEqual(request.sessionID, AuthTests.kOAuthSessionID)
- 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])
- }
- try auth.signOut()
- auth.signIn(with: FakeProvider(), uiDelegate: nil) { authResult, error in
- // 4. After the response triggers the callback, verify the returned result.
- do {
- try self.assertUserGoogle(authResult?.user)
- } catch {
- XCTFail("\(error)")
- }
- XCTAssertNil(error)
- expectation.fulfill()
- }
- waitForExpectations(timeout: 5)
- try assertUserGoogle(auth.currentUser)
- }
- #endif
- /** @fn testSignInWithCredentialSuccess
- @brief Tests the flow of a successful @c signInWithCredential:completion: call
- with a Google Sign-In credential.
- Note: also a superset of the former testSignInWithGoogleCredentialSuccess
- */
- func testSignInWithCredentialSuccess() throws {
- let expectation = self.expectation(description: #function)
- setFakeGoogleGetAccountProvider()
- setFakeSecureTokenService()
- // 1. Setup respond block to test and fake send request.
- rpcIssuer.respondBlock = {
- // 2. Validate the created Request instance.
- let request = try XCTUnwrap(self.rpcIssuer.request as? VerifyAssertionRequest)
- XCTAssertEqual(request.apiKey, AuthTests.kFakeAPIKey)
- XCTAssertEqual(request.providerID, GoogleAuthProvider.id)
- XCTAssertEqual(request.providerIDToken, self.kGoogleIDToken)
- XCTAssertEqual(request.providerAccessToken, self.kGoogleAccessToken)
- 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])
- }
- try auth.signOut()
- let googleCredential = GoogleAuthProvider.credential(withIDToken: kGoogleIDToken,
- accessToken: kGoogleAccessToken)
- auth.signIn(with: googleCredential) { authResult, error in
- // 4. After the response triggers the callback, verify the returned result.
- do {
- try self.assertUserGoogle(authResult?.user)
- guard let additionalUserInfo = authResult?.additionalUserInfo,
- let profile = additionalUserInfo.profile as? [String: String] else {
- XCTFail("authResult.additionalUserInfo is missing")
- return
- }
- XCTAssertEqual(profile, self.kGoogleProfile)
- XCTAssertEqual(additionalUserInfo.username, self.kGoogleDisplayName)
- XCTAssertEqual(additionalUserInfo.providerID, GoogleAuthProvider.id)
- } catch {
- XCTFail("\(error)")
- }
- XCTAssertNil(error)
- expectation.fulfill()
- }
- waitForExpectations(timeout: 5)
- try assertUserGoogle(auth.currentUser)
- }
- /** @fn testSignInWithGoogleCredentialFailure
- @brief Tests the flow of a failed @c signInWithCredential:completion: call with an
- Google Sign-In credential.
- */
- func testSignInWithGoogleCredentialFailure() throws {
- let expectation = self.expectation(description: #function)
- setFakeGoogleGetAccountProvider()
- setFakeSecureTokenService()
- // 1. Setup respond block to test and fake send request.
- rpcIssuer.respondBlock = {
- // 2. Validate the created Request instance.
- let request = try XCTUnwrap(self.rpcIssuer.request as? VerifyAssertionRequest)
- XCTAssertEqual(request.apiKey, AuthTests.kFakeAPIKey)
- XCTAssertEqual(request.providerID, GoogleAuthProvider.id)
- XCTAssertTrue(request.returnSecureToken)
- // 3. Send the response from the fake backend.
- try self.rpcIssuer.respond(serverErrorMessage: "EMAIL_EXISTS")
- }
- try auth.signOut()
- let googleCredential = GoogleAuthProvider.credential(withIDToken: kGoogleIDToken,
- accessToken: kGoogleAccessToken)
- auth.signIn(with: googleCredential) { authResult, error in
- // 4. After the response triggers the callback, verify the returned result.
- XCTAssertTrue(Thread.isMainThread)
- XCTAssertNil(authResult)
- XCTAssertEqual((error as? NSError)?.code, AuthErrorCode.emailAlreadyInUse.rawValue)
- XCTAssertEqual((error as? NSError)?.userInfo[NSLocalizedDescriptionKey] as? String,
- "The email address is already in use by another account.")
- expectation.fulfill()
- }
- waitForExpectations(timeout: 5)
- }
- /** @fn testSignInWithAppleCredentialFullNameInRequest
- @brief Tests the flow of a successful @c signInWithCredential:completion: call
- with an Apple Sign-In credential with a full name. This test differentiates from
- @c testSignInWithCredentialSuccess only in verifying the full name.
- */
- func testSignInWithAppleCredentialFullNameInRequest() throws {
- let expectation = self.expectation(description: #function)
- let kAppleIDToken = "APPLE_ID_TOKEN"
- let kFirst = "First"
- let kLast = "Last"
- var fullName = PersonNameComponents()
- fullName.givenName = kFirst
- fullName.familyName = kLast
- setFakeGoogleGetAccountProvider()
- setFakeSecureTokenService()
- // 1. Setup respond block to test and fake send request.
- rpcIssuer.respondBlock = {
- // 2. Validate the created Request instance.
- let request = try XCTUnwrap(self.rpcIssuer.request as? VerifyAssertionRequest)
- XCTAssertEqual(request.apiKey, AuthTests.kFakeAPIKey)
- XCTAssertEqual(request.providerID, AuthProviderID.apple.rawValue)
- XCTAssertEqual(request.providerIDToken, kAppleIDToken)
- XCTAssertEqual(request.fullName, fullName)
- 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])
- }
- try auth.signOut()
- let appleCredential = OAuthProvider.appleCredential(withIDToken: kAppleIDToken,
- rawNonce: nil,
- fullName: fullName)
- auth.signIn(with: appleCredential) { authResult, error in
- // 4. After the response triggers the callback, verify the returned result.
- do {
- try self.assertUserGoogle(authResult?.user)
- guard let additionalUserInfo = authResult?.additionalUserInfo,
- let profile = additionalUserInfo.profile as? [String: String] else {
- XCTFail("authResult.additionalUserInfo is missing")
- return
- }
- XCTAssertEqual(profile, self.kGoogleProfile)
- XCTAssertEqual(additionalUserInfo.username, self.kGoogleDisplayName)
- XCTAssertEqual(additionalUserInfo.providerID, AuthProviderID.apple.rawValue)
- } catch {
- XCTFail("\(error)")
- }
- XCTAssertNil(error)
- expectation.fulfill()
- }
- waitForExpectations(timeout: 5)
- XCTAssertNotNil(auth.currentUser)
- }
- /** @fn testSignInAnonymouslySuccess
- @brief Tests the flow of a successful @c signInAnonymouslyWithCompletion: call.
- */
- func testSignInAnonymouslySuccess() throws {
- let expectation = self.expectation(description: #function)
- setFakeSecureTokenService()
- setFakeGetAccountProviderAnonymous()
- // 1. Setup respond block to test and fake send request.
- rpcIssuer.respondBlock = {
- // 2. Validate the created Request instance.
- let request = try XCTUnwrap(self.rpcIssuer.request as? SignUpNewUserRequest)
- XCTAssertEqual(request.apiKey, AuthTests.kFakeAPIKey)
- XCTAssertNil(request.email)
- XCTAssertNil(request.password)
- 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])
- }
- try auth?.signOut()
- auth?.signInAnonymously { authResult, error in
- // 4. After the response triggers the callback, verify the returned result.
- XCTAssertNil(error)
- XCTAssertTrue(Thread.isMainThread)
- self.assertUserAnonymous(authResult?.user)
- guard let userInfo = authResult?.additionalUserInfo else {
- XCTFail("authResult.additionalUserInfo is missing")
- return
- }
- XCTAssertTrue(userInfo.isNewUser)
- XCTAssertNil(userInfo.username)
- XCTAssertNil(userInfo.profile)
- XCTAssertEqual(userInfo.providerID, "")
- expectation.fulfill()
- }
- waitForExpectations(timeout: 5)
- try assertUserAnonymous(XCTUnwrap(auth?.currentUser))
- }
- /** @fn testSignInAnonymouslyFailure
- @brief Tests the flow of a failed @c signInAnonymouslyWithCompletion: call.
- */
- func testSignInAnonymouslyFailure() throws {
- let expectation = self.expectation(description: #function)
- rpcIssuer.respondBlock = {
- try self.rpcIssuer.respond(serverErrorMessage: "OPERATION_NOT_ALLOWED")
- }
- try auth?.signOut()
- auth?.verifyPasswordResetCode(kFakeOobCode) { email, error in
- XCTAssertTrue(Thread.isMainThread)
- XCTAssertNil(email)
- XCTAssertEqual((error as? NSError)?.code, AuthErrorCode.operationNotAllowed.rawValue)
- XCTAssertNotNil((error as? NSError)?.userInfo[NSLocalizedDescriptionKey])
- expectation.fulfill()
- }
- waitForExpectations(timeout: 5)
- XCTAssertNil(auth?.currentUser)
- }
- /** @fn testSignInWithCustomTokenSuccess
- @brief Tests the flow of a successful @c signInWithCustomToken:completion: call.
- */
- func testSignInWithCustomTokenSuccess() throws {
- let expectation = self.expectation(description: #function)
- setFakeSecureTokenService()
- setFakeGetAccountProvider()
- // 1. Setup respond block to test and fake send request.
- rpcIssuer.respondBlock = {
- // 2. Validate the created Request instance.
- let request = try XCTUnwrap(self.rpcIssuer.request as? VerifyCustomTokenRequest)
- XCTAssertEqual(request.apiKey, AuthTests.kFakeAPIKey)
- XCTAssertEqual(request.token, self.kCustomToken)
- 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])
- }
- try auth?.signOut()
- auth?.signIn(withCustomToken: kCustomToken) { authResult, error in
- // 4. After the response triggers the callback, verify the returned result.
- XCTAssertTrue(Thread.isMainThread)
- self.assertUser(authResult?.user)
- guard let userInfo = authResult?.additionalUserInfo else {
- XCTFail("authResult.additionalUserInfo is missing")
- return
- }
- XCTAssertFalse(userInfo.isNewUser)
- XCTAssertNil(userInfo.username)
- XCTAssertNil(userInfo.profile)
- XCTAssertEqual(userInfo.providerID, "")
- XCTAssertNil(error)
- expectation.fulfill()
- }
- waitForExpectations(timeout: 5)
- assertUser(auth?.currentUser)
- }
- /** @fn testSignInWithCustomTokenFailure
- @brief Tests the flow of a failed @c signInWithCustomToken:completion: call.
- */
- func testSignInWithCustomTokenFailure() throws {
- let expectation = self.expectation(description: #function)
- rpcIssuer.respondBlock = {
- try self.rpcIssuer.respond(serverErrorMessage: "INVALID_CUSTOM_TOKEN")
- }
- try auth?.signOut()
- auth?.signIn(withCustomToken: kCustomToken) { authResult, error in
- XCTAssertTrue(Thread.isMainThread)
- XCTAssertNil(authResult?.user)
- XCTAssertEqual((error as? NSError)?.code, AuthErrorCode.invalidCustomToken.rawValue)
- XCTAssertNotNil((error as? NSError)?.userInfo[NSLocalizedDescriptionKey])
- expectation.fulfill()
- }
- waitForExpectations(timeout: 5)
- XCTAssertNil(auth?.currentUser)
- }
- #if os(iOS)
- /** @fn testCreateUserWithEmailPasswordWithRecaptchaVerificationSuccess
- @brief Tests the flow of a successful @c createUserWithEmail:password:completion: call.
- */
- func testCreateUserWithEmailPasswordWithRecaptchaVerificationSuccess() throws {
- let expectation = self.expectation(description: #function)
- let kTestRecaptchaKey = "projects/123/keys/456"
- rpcIssuer.recaptchaSiteKey = kTestRecaptchaKey
- setFakeSecureTokenService()
- setFakeGetAccountProvider()
- // 1. Setup respond block to test and fake send request.
- rpcIssuer.respondBlock = {
- // 2. Validate the created Request instance.
- let request = try XCTUnwrap(self.rpcIssuer.request as? SignUpNewUserRequest)
- XCTAssertEqual(request.apiKey, AuthTests.kFakeAPIKey)
- XCTAssertEqual(request.email, self.kEmail)
- XCTAssertEqual(request.password, self.kFakePassword)
- XCTAssertTrue(request.returnSecureToken)
- request.injectRecaptchaFields(recaptchaResponse: AuthTests.kFakeRecaptchaResponse,
- 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])
- }
- try auth?.signOut()
- auth?.createUser(withEmail: kEmail, password: kFakePassword) { authResult, error in
- // 4. After the response triggers the callback, verify the returned result.
- XCTAssertTrue(Thread.isMainThread)
- self.assertUser(authResult?.user)
- guard let userInfo = authResult?.additionalUserInfo else {
- XCTFail("authResult.additionalUserInfo is missing")
- return
- }
- XCTAssertTrue(userInfo.isNewUser)
- XCTAssertNil(userInfo.username)
- XCTAssertNil(userInfo.profile)
- XCTAssertEqual(userInfo.providerID, EmailAuthProvider.id)
- XCTAssertNil(error)
- expectation.fulfill()
- }
- waitForExpectations(timeout: 5)
- assertUser(auth?.currentUser)
- }
- /** @fn testCreateUserWithEmailPasswordWithRecaptchaVerificationFallbackSuccess
- @brief Tests the flow of a successful @c createUserWithEmail:password:completion: call.
- */
- func testCreateUserWithEmailPasswordWithRecaptchaVerificationFallbackSuccess() throws {
- let expectation = self.expectation(description: #function)
- let kTestRecaptchaKey = "projects/123/keys/456"
- rpcIssuer.recaptchaSiteKey = kTestRecaptchaKey
- setFakeSecureTokenService()
- setFakeGetAccountProvider()
- // 1. Setup respond block to test and fake send request.
- rpcIssuer.respondBlock = {
- // 2. Validate the created Request instance.
- let request = try XCTUnwrap(self.rpcIssuer.request as? SignUpNewUserRequest)
- XCTAssertEqual(request.apiKey, AuthTests.kFakeAPIKey)
- XCTAssertEqual(request.email, self.kEmail)
- XCTAssertEqual(request.password, self.kFakePassword)
- XCTAssertTrue(request.returnSecureToken)
- request.injectRecaptchaFields(recaptchaResponse: AuthTests.kFakeRecaptchaResponse,
- recaptchaVersion: AuthTests.kFakeRecaptchaVersion)
- // 3. Send the response from the fake backend.
- try self.rpcIssuer.respond(serverErrorMessage: "MISSING_RECAPTCHA_TOKEN")
- }
- rpcIssuer.nextRespondBlock = {
- // 4. Validate again the created Request instance after the recaptcha retry.
- let request = try XCTUnwrap(self.rpcIssuer.request as? SignUpNewUserRequest)
- XCTAssertEqual(request.email, self.kEmail)
- XCTAssertEqual(request.password, self.kFakePassword)
- XCTAssertEqual(request.apiKey, AuthTests.kFakeAPIKey)
- XCTAssertTrue(request.returnSecureToken)
- 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])
- }
- try auth?.signOut()
- auth?.createUser(withEmail: kEmail, password: kFakePassword) { authResult, error in
- // 4. After the response triggers the callback, verify the returned result.
- XCTAssertTrue(Thread.isMainThread)
- self.assertUser(authResult?.user)
- guard let userInfo = authResult?.additionalUserInfo else {
- XCTFail("authResult.additionalUserInfo is missing")
- return
- }
- XCTAssertTrue(userInfo.isNewUser)
- XCTAssertNil(userInfo.username)
- XCTAssertNil(userInfo.profile)
- XCTAssertEqual(userInfo.providerID, EmailAuthProvider.id)
- XCTAssertNil(error)
- expectation.fulfill()
- }
- waitForExpectations(timeout: 5)
- assertUser(auth?.currentUser)
- }
- #endif
- /** @fn testCreateUserWithEmailPasswordSuccess
- @brief Tests the flow of a successful @c createUserWithEmail:password:completion: call.
- */
- func testCreateUserWithEmailPasswordSuccess() throws {
- let expectation = self.expectation(description: #function)
- setFakeSecureTokenService()
- setFakeGetAccountProvider()
- // 1. Setup respond block to test and fake send request.
- rpcIssuer.respondBlock = {
- // 2. Validate the created Request instance.
- let request = try XCTUnwrap(self.rpcIssuer.request as? SignUpNewUserRequest)
- XCTAssertEqual(request.apiKey, AuthTests.kFakeAPIKey)
- XCTAssertEqual(request.email, self.kEmail)
- XCTAssertEqual(request.password, self.kFakePassword)
- 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])
- }
- try auth?.signOut()
- auth?.createUser(withEmail: kEmail, password: kFakePassword) { authResult, error in
- // 4. After the response triggers the callback, verify the returned result.
- XCTAssertTrue(Thread.isMainThread)
- self.assertUser(authResult?.user)
- guard let userInfo = authResult?.additionalUserInfo else {
- XCTFail("authResult.additionalUserInfo is missing")
- return
- }
- XCTAssertTrue(userInfo.isNewUser)
- XCTAssertNil(userInfo.username)
- XCTAssertNil(userInfo.profile)
- XCTAssertEqual(userInfo.providerID, EmailAuthProvider.id)
- XCTAssertNil(error)
- expectation.fulfill()
- }
- waitForExpectations(timeout: 5)
- assertUser(auth?.currentUser)
- }
- /** @fn testCreateUserWithEmailPasswordFailure
- @brief Tests the flow of a failed @c createUserWithEmail:password:completion: call.
- */
- func testCreateUserWithEmailPasswordFailure() throws {
- let expectation = self.expectation(description: #function)
- let reason = "The password must be 6 characters long or more."
- rpcIssuer.respondBlock = {
- try self.rpcIssuer.respond(serverErrorMessage: "WEAK_PASSWORD")
- }
- try auth?.signOut()
- auth?.createUser(withEmail: kEmail, password: kFakePassword) { authResult, error in
- XCTAssertTrue(Thread.isMainThread)
- XCTAssertNil(authResult?.user)
- XCTAssertEqual((error as? NSError)?.code, AuthErrorCode.weakPassword.rawValue)
- XCTAssertEqual((error as? NSError)?.userInfo[NSLocalizedDescriptionKey] as? String, reason)
- expectation.fulfill()
- }
- waitForExpectations(timeout: 5)
- XCTAssertNil(auth?.currentUser)
- }
- /** @fn testCreateUserEmptyPasswordFailure
- @brief Tests the flow of a failed @c createUserWithEmail:password:completion: call due to an
- empty password. This error occurs on the client side, so there is no need to fake an RPC
- response.
- */
- func testCreateUserEmptyPasswordFailure() throws {
- let expectation = self.expectation(description: #function)
- try auth?.signOut()
- auth?.createUser(withEmail: kEmail, password: "") { authResult, error in
- XCTAssertTrue(Thread.isMainThread)
- XCTAssertNil(authResult?.user)
- XCTAssertEqual((error as? NSError)?.code, AuthErrorCode.weakPassword.rawValue)
- expectation.fulfill()
- }
- waitForExpectations(timeout: 5)
- }
- /** @fn testCreateUserEmptyEmailFailure
- @brief Tests the flow of a failed @c createUserWithEmail:password:completion: call due to an
- empty email address. This error occurs on the client side, so there is no need to fake an
- RPC response.
- */
- func testCreateUserEmptyEmailFailure() throws {
- let expectation = self.expectation(description: #function)
- try auth?.signOut()
- auth?.createUser(withEmail: "", password: kFakePassword) { authResult, error in
- XCTAssertTrue(Thread.isMainThread)
- XCTAssertNil(authResult?.user)
- XCTAssertEqual((error as? NSError)?.code, AuthErrorCode.missingEmail.rawValue)
- expectation.fulfill()
- }
- waitForExpectations(timeout: 5)
- }
- #if os(iOS)
- /** @fn testSendPasswordResetEmailWithRecaptchaSuccess
- @brief Tests the flow of a successful @c sendPasswordResetWithEmail:completion: call.
- */
- func testSendPasswordResetEmailWithRecaptchaSuccess() throws {
- let expectation = self.expectation(description: #function)
- let kTestRecaptchaKey = "projects/123/keys/456"
- rpcIssuer.recaptchaSiteKey = kTestRecaptchaKey
- // 1. Setup respond block to test and fake send request.
- rpcIssuer.respondBlock = {
- // 2. Validate the created Request instance.
- let request = try XCTUnwrap(self.rpcIssuer.request as? GetOOBConfirmationCodeRequest)
- XCTAssertEqual(request.email, self.kEmail)
- XCTAssertEqual(request.apiKey, AuthTests.kFakeAPIKey)
- request.injectRecaptchaFields(recaptchaResponse: AuthTests.kFakeRecaptchaResponse,
- recaptchaVersion: AuthTests.kFakeRecaptchaVersion)
- // 3. Send the response from the fake backend.
- _ = try self.rpcIssuer.respond(withJSON: [:])
- }
- auth?.sendPasswordReset(withEmail: kEmail) { error in
- // 4. After the response triggers the callback, verify success.
- XCTAssertTrue(Thread.isMainThread)
- XCTAssertNil(error)
- expectation.fulfill()
- }
- waitForExpectations(timeout: 5)
- }
- /** @fn testSendPasswordResetEmailWithRecaptchaFallbackSuccess
- @brief Tests the flow of a successful @c sendPasswordResetWithEmail:completion: call.
- */
- func testSendPasswordResetEmailWithRecaptchaFallbackSuccess() throws {
- let expectation = self.expectation(description: #function)
- let kTestRecaptchaKey = "projects/123/keys/456"
- rpcIssuer.recaptchaSiteKey = kTestRecaptchaKey
- // 1. Setup respond block to test and fake send request.
- rpcIssuer.respondBlock = {
- // 2. Validate the created Request instance.
- let request = try XCTUnwrap(self.rpcIssuer.request as? GetOOBConfirmationCodeRequest)
- XCTAssertEqual(request.email, self.kEmail)
- XCTAssertEqual(request.apiKey, AuthTests.kFakeAPIKey)
- request.injectRecaptchaFields(recaptchaResponse: AuthTests.kFakeRecaptchaResponse,
- recaptchaVersion: AuthTests.kFakeRecaptchaVersion)
- // 3. Send the response from the fake backend.
- try self.rpcIssuer.respond(serverErrorMessage: "MISSING_RECAPTCHA_TOKEN")
- }
- rpcIssuer.nextRespondBlock = {
- // 4. Validate again the created Request instance after the recaptcha retry.
- let request = try XCTUnwrap(self.rpcIssuer.request as? GetOOBConfirmationCodeRequest)
- XCTAssertEqual(request.email, self.kEmail)
- XCTAssertEqual(request.apiKey, AuthTests.kFakeAPIKey)
- 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])
- }
- auth?.sendPasswordReset(withEmail: kEmail) { error in
- // 4. After the response triggers the callback, verify success.
- XCTAssertTrue(Thread.isMainThread)
- XCTAssertNil(error)
- expectation.fulfill()
- }
- waitForExpectations(timeout: 5)
- }
- #endif
- /** @fn testSendPasswordResetEmailSuccess
- @brief Tests the flow of a successful @c sendPasswordReset call.
- */
- func testSendPasswordResetEmailSuccess() throws {
- let expectation = self.expectation(description: #function)
- // 1. Setup respond block to test and fake send request.
- rpcIssuer.respondBlock = {
- // 2. Validate the created Request instance.
- let request = try XCTUnwrap(self.rpcIssuer.request as? GetOOBConfirmationCodeRequest)
- XCTAssertEqual(request.email, self.kEmail)
- XCTAssertEqual(request.apiKey, AuthTests.kFakeAPIKey)
- // 3. Send the response from the fake backend.
- _ = try self.rpcIssuer.respond(withJSON: [:])
- }
- auth?.sendPasswordReset(withEmail: kEmail) { error in
- // 4. After the response triggers the callback, verify success.
- XCTAssertTrue(Thread.isMainThread)
- XCTAssertNil(error)
- expectation.fulfill()
- }
- waitForExpectations(timeout: 5)
- }
- /** @fn testSendPasswordResetEmailFailure
- @brief Tests the flow of a failed @c sendPasswordReset call.
- */
- func testSendPasswordResetEmailFailure() throws {
- let expectation = self.expectation(description: #function)
- rpcIssuer.respondBlock = {
- try self.rpcIssuer.respond(underlyingErrorMessage: "ipRefererBlocked")
- }
- auth?.sendPasswordReset(withEmail: kEmail) { error in
- XCTAssertTrue(Thread.isMainThread)
- let rpcError = (error as? NSError)!
- XCTAssertEqual(rpcError.code, AuthErrorCode.appNotAuthorized.rawValue)
- XCTAssertNotNil(rpcError.userInfo[NSLocalizedDescriptionKey])
- expectation.fulfill()
- }
- waitForExpectations(timeout: 5)
- }
- #if os(iOS)
- /** @fn testSendSignInLinkToEmailWithRecaptchaSuccess
- @brief Tests the flow of a successful @c sendSignInLinkToEmail:actionCodeSettings: call.
- */
- func testSendSignInLinkToEmailWithRecaptchaSuccess() throws {
- let expectation = self.expectation(description: #function)
- let kTestRecaptchaKey = "projects/123/keys/456"
- rpcIssuer.recaptchaSiteKey = kTestRecaptchaKey
- // 1. Setup respond block to test and fake send request.
- rpcIssuer.respondBlock = {
- // 2. Validate the created Request instance.
- let request = try XCTUnwrap(self.rpcIssuer.request as? GetOOBConfirmationCodeRequest)
- XCTAssertEqual(request.email, self.kEmail)
- XCTAssertEqual(request.apiKey, AuthTests.kFakeAPIKey)
- XCTAssertEqual(request.continueURL, self.kContinueURL)
- XCTAssertTrue(request.handleCodeInApp)
- request.injectRecaptchaFields(recaptchaResponse: AuthTests.kFakeRecaptchaResponse,
- recaptchaVersion: AuthTests.kFakeRecaptchaVersion)
- // 3. Send the response from the fake backend.
- _ = try self.rpcIssuer.respond(withJSON: [:])
- }
- auth?.sendSignInLink(toEmail: kEmail,
- actionCodeSettings: fakeActionCodeSettings()) { error in
- // 4. After the response triggers the callback, verify success.
- XCTAssertTrue(Thread.isMainThread)
- XCTAssertNil(error)
- expectation.fulfill()
- }
- waitForExpectations(timeout: 5)
- }
- /** @fn testSendSignInLinkToEmailWithRecaptchaFallbackSuccess
- @brief Tests the flow of a successful @c sendSignInLinkToEmail:actionCodeSettings: call.
- */
- func testSendSignInLinkToEmailWithRecaptchaFallbackSuccess() throws {
- let expectation = self.expectation(description: #function)
- let kTestRecaptchaKey = "projects/123/keys/456"
- rpcIssuer.recaptchaSiteKey = kTestRecaptchaKey
- // 1. Setup respond block to test and fake send request.
- rpcIssuer.respondBlock = {
- // 2. Validate the created Request instance.
- let request = try XCTUnwrap(self.rpcIssuer.request as? GetOOBConfirmationCodeRequest)
- XCTAssertEqual(request.email, self.kEmail)
- XCTAssertEqual(request.apiKey, AuthTests.kFakeAPIKey)
- XCTAssertEqual(request.continueURL, self.kContinueURL)
- XCTAssertTrue(request.handleCodeInApp)
- request.injectRecaptchaFields(recaptchaResponse: AuthTests.kFakeRecaptchaResponse,
- recaptchaVersion: AuthTests.kFakeRecaptchaVersion)
- // 3. Send the response from the fake backend.
- _ = try self.rpcIssuer.respond(withJSON: [:])
- }
- rpcIssuer.nextRespondBlock = {
- // 4. Validate again the created Request instance after the recaptcha retry.
- let request = try XCTUnwrap(self.rpcIssuer.request as? GetOOBConfirmationCodeRequest)
- XCTAssertEqual(request.email, self.kEmail)
- XCTAssertEqual(request.apiKey, AuthTests.kFakeAPIKey)
- 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])
- }
- auth?.sendSignInLink(toEmail: kEmail,
- actionCodeSettings: fakeActionCodeSettings()) { error in
- // 4. After the response triggers the callback, verify success.
- XCTAssertTrue(Thread.isMainThread)
- XCTAssertNil(error)
- expectation.fulfill()
- }
- waitForExpectations(timeout: 5)
- }
- #endif
- /** @fn testSendSignInLinkToEmailSuccess
- @brief Tests the flow of a successful @c sendSignInLinkToEmail call.
- */
- func testSendSignInLinkToEmailSuccess() throws {
- let expectation = self.expectation(description: #function)
- // 1. Setup respond block to test and fake send request.
- rpcIssuer.respondBlock = {
- // 2. Validate the created Request instance.
- let request = try XCTUnwrap(self.rpcIssuer.request as? GetOOBConfirmationCodeRequest)
- XCTAssertEqual(request.email, self.kEmail)
- XCTAssertEqual(request.apiKey, AuthTests.kFakeAPIKey)
- XCTAssertEqual(request.continueURL, self.kContinueURL)
- XCTAssertTrue(request.handleCodeInApp)
- // 3. Send the response from the fake backend.
- _ = try self.rpcIssuer.respond(withJSON: [:])
- }
- auth?.sendSignInLink(toEmail: kEmail,
- actionCodeSettings: fakeActionCodeSettings()) { error in
- // 4. After the response triggers the callback, verify success.
- XCTAssertTrue(Thread.isMainThread)
- XCTAssertNil(error)
- expectation.fulfill()
- }
- waitForExpectations(timeout: 5)
- }
- /** @fn testSendSignInLinkToEmailFailure
- @brief Tests the flow of a failed @c sendSignInLink call.
- */
- func testSendSignInLinkToEmailFailure() throws {
- let expectation = self.expectation(description: #function)
- rpcIssuer.respondBlock = {
- try self.rpcIssuer.respond(underlyingErrorMessage: "ipRefererBlocked")
- }
- auth?.sendSignInLink(toEmail: kEmail,
- actionCodeSettings: fakeActionCodeSettings()) { error in
- XCTAssertTrue(Thread.isMainThread)
- let rpcError = error as? NSError
- XCTAssertEqual(rpcError?.code, AuthErrorCode.appNotAuthorized.rawValue)
- XCTAssertNotNil(rpcError?.userInfo[NSLocalizedDescriptionKey])
- expectation.fulfill()
- }
- waitForExpectations(timeout: 5)
- }
- /** @fn testUpdateCurrentUserFailure
- @brief Tests the flow of a failed @c updateCurrentUser:completion:
- call.
- */
- func testUpdateCurrentUserFailure() throws {
- try waitForSignInWithAccessToken()
- let expectation = self.expectation(description: #function)
- let kTestAPIKey2 = "fakeAPIKey2"
- let auth = try XCTUnwrap(auth)
- let user2 = auth.currentUser
- user2?.requestConfiguration = AuthRequestConfiguration(apiKey: kTestAPIKey2,
- appID: kTestFirebaseAppID)
- rpcIssuer.respondBlock = {
- try self.rpcIssuer.respond(underlyingErrorMessage: "keyInvalid")
- }
- // Clear fake so we can inject error
- rpcIssuer.fakeGetAccountProviderJSON = nil
- auth.updateCurrentUser(user2) { error in
- XCTAssertEqual((error as? NSError)?.code, AuthErrorCode.invalidAPIKey.rawValue)
- expectation.fulfill()
- }
- waitForExpectations(timeout: 5)
- }
- /** @fn testUpdateCurrentUserFailureNetworkError
- @brief Tests the flow of a failed @c updateCurrentUser:completion:
- call with a network error.
- */
- func testUpdateCurrentUserFailureNetworkError() throws {
- try waitForSignInWithAccessToken()
- let expectation = self.expectation(description: #function)
- let kTestAPIKey2 = "fakeAPIKey2"
- let auth = try XCTUnwrap(auth)
- let user2 = auth.currentUser
- user2?.requestConfiguration = AuthRequestConfiguration(apiKey: kTestAPIKey2,
- appID: kTestFirebaseAppID)
- rpcIssuer.respondBlock = {
- let kFakeErrorDomain = "fakeDomain"
- let kFakeErrorCode = -1
- let responseError = NSError(domain: kFakeErrorDomain, code: kFakeErrorCode)
- try self.rpcIssuer.respond(withData: nil, error: responseError)
- }
- // Clear fake so we can inject error
- rpcIssuer.fakeGetAccountProviderJSON = nil
- auth.updateCurrentUser(user2) { error in
- XCTAssertEqual((error as? NSError)?.code, AuthErrorCode.networkError.rawValue)
- expectation.fulfill()
- }
- waitForExpectations(timeout: 5)
- }
- /** @fn testUpdateCurrentUserFailureNullUser
- @brief Tests the flow of a failed @c updateCurrentUser:completion:
- call with FIRAuthErrorCodeNullUser.
- */
- func testUpdateCurrentUserFailureNullUser() throws {
- try waitForSignInWithAccessToken()
- let expectation = self.expectation(description: #function)
- auth.updateCurrentUser(nil) { error in
- XCTAssertEqual((error as? NSError)?.code, AuthErrorCode.nullUser.rawValue)
- expectation.fulfill()
- }
- waitForExpectations(timeout: 5)
- }
- /** @fn testUpdateCurrentUserFailureTenantIDMismatch
- @brief Tests the flow of a failed @c updateCurrentUser:completion:
- call with FIRAuthErrorCodeTenantIDMismatch.
- */
- func testUpdateCurrentUserFailureTenantIDMismatch() throws {
- // User without tenant id
- try waitForSignInWithAccessToken()
- let auth = try XCTUnwrap(auth)
- let user1 = auth.currentUser
- try auth.signOut()
- // User with tenant id "tenant-id"
- auth.tenantID = "tenant-id-1"
- let kTestAccessToken2 = "fakeAccessToken2"
- try waitForSignInWithAccessToken(fakeAccessToken: kTestAccessToken2)
- let user2 = auth.currentUser
- try auth.signOut()
- auth.tenantID = "tenant-id-2"
- let expectation = self.expectation(description: #function)
- auth.updateCurrentUser(user1) { error in
- XCTAssertEqual((error as? NSError)?.code, AuthErrorCode.tenantIDMismatch.rawValue)
- expectation.fulfill()
- }
- try auth.signOut()
- auth.tenantID = "tenant-id-2"
- let expectation2 = self.expectation(description: "tenant-id-test2")
- auth.updateCurrentUser(user2) { error in
- XCTAssertEqual((error as? NSError)?.code, AuthErrorCode.tenantIDMismatch.rawValue)
- expectation2.fulfill()
- }
- try auth.signOut()
- auth.tenantID = nil
- let expectation3 = self.expectation(description: "tenant-id-test3")
- auth.updateCurrentUser(user2) { error in
- XCTAssertEqual((error as? NSError)?.code, AuthErrorCode.tenantIDMismatch.rawValue)
- expectation3.fulfill()
- }
- waitForExpectations(timeout: 5)
- }
- /** @fn testUpdateCurrentUserSuccess
- @brief Tests the flow of a successful @c updateCurrentUser:completion:
- call with a network error.
- */
- func testUpdateCurrentUserSuccess() throws {
- // Sign in with the first user.
- try waitForSignInWithAccessToken()
- let auth = try XCTUnwrap(auth)
- let user1 = auth.currentUser
- let kTestAPIKey = "fakeAPIKey"
- user1?.requestConfiguration = AuthRequestConfiguration(apiKey: kTestAPIKey,
- appID: kTestFirebaseAppID)
- try auth.signOut()
- let kTestAccessToken2 = "fakeAccessToken2"
- try waitForSignInWithAccessToken(fakeAccessToken: kTestAccessToken2)
- let user2 = auth.currentUser
- let expectation = self.expectation(description: #function)
- // Current user should now be user2.
- XCTAssertEqual(auth.currentUser, user2)
- auth.updateCurrentUser(user1) { error in
- XCTAssertNil(error)
- // Current user should now be user1.
- XCTAssertEqual(auth.currentUser, user1)
- XCTAssertNotEqual(auth.currentUser, user2)
- expectation.fulfill()
- }
- waitForExpectations(timeout: 5)
- }
- /** @fn testRevokeTokenSuccess
- @brief Tests the flow of a successful @c revokeToken:completion.
- */
- func testRevokeTokenSuccess() throws {
- try waitForSignInWithAccessToken()
- let expectation = self.expectation(description: #function)
- let code = "code"
- rpcIssuer.respondBlock = {
- let request = try XCTUnwrap(self.rpcIssuer.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 self.rpcIssuer.respond(withJSON: [:])
- }
- auth?.revokeToken(withAuthorizationCode: code) { error in
- // Verify callback success.
- XCTAssertNil(error)
- expectation.fulfill()
- }
- waitForExpectations(timeout: 5)
- }
- /** @fn testRevokeTokenMissingCallback
- @brief Tests the flow of @c revokeToken:completion with a nil callback.
- */
- func testRevokeTokenMissingCallback() throws {
- try waitForSignInWithAccessToken()
- let code = "code"
- let issuer = rpcIssuer
- 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: [:])
- }
- auth?.revokeToken(withAuthorizationCode: code)
- }
- /** @fn testSignOut
- @brief Tests the @c signOut: method.
- */
- func testSignOut() throws {
- try waitForSignInWithAccessToken()
- // Verify signing out succeeds and clears the current user.
- let auth = try XCTUnwrap(auth)
- try auth.signOut()
- XCTAssertNil(auth.currentUser)
- }
- /** @fn testIsSignInWithEmailLink
- @brief Tests the @c isSignInWithEmailLink: method.
- */
- func testIsSignInWithEmailLink() throws {
- let auth = try XCTUnwrap(auth)
- let kBadSignInEmailLink = "http://www.facebook.com"
- XCTAssertTrue(auth.isSignIn(withEmailLink: kFakeEmailSignInLink))
- XCTAssertTrue(auth.isSignIn(withEmailLink: kFakeEmailSignInDeeplink))
- XCTAssertFalse(auth.isSignIn(withEmailLink: kBadSignInEmailLink))
- XCTAssertFalse(auth.isSignIn(withEmailLink: ""))
- }
- /** @fn testAuthStateChanges
- @brief Tests @c addAuthStateDidChangeListener: and @c removeAuthStateDidChangeListener: methods.
- */
- func testAuthStateChanges() throws {
- // Set up listener.
- let auth = try XCTUnwrap(auth)
- var shouldHaveUser = false
- var expectation: XCTestExpectation?
- let listener = { listenerAuth, user in
- XCTAssertTrue(Thread.isMainThread)
- XCTAssertEqual(auth, listenerAuth)
- XCTAssertEqual(user, auth.currentUser)
- if shouldHaveUser {
- XCTAssertNotNil(user)
- } else {
- XCTAssertNil(user)
- }
- // `expectation` being nil means the listener is not expected to be fired at this moment.
- XCTAssertNotNil(expectation)
- expectation?.fulfill()
- }
- try auth.signOut()
- // Listener should fire immediately when attached.
- expectation = self.expectation(description: "initial")
- shouldHaveUser = false
- let handle = auth.addStateDidChangeListener(listener)
- waitForExpectations(timeout: 5)
- expectation = nil
- // Listener should fire for signing in.
- expectation = self
- .expectation(description: "sign-in") // waited on in waitForSignInWithAccessToken
- shouldHaveUser = true
- try waitForSignInWithAccessToken()
- // Listener should not fire for signing in again.
- expectation = nil
- shouldHaveUser = true
- try waitForSignInWithAccessToken()
- // Listener should fire for signing out.
- expectation = self.expectation(description: "sign-out")
- shouldHaveUser = false
- try auth.signOut()
- waitForExpectations(timeout: 5)
- // Listener should no longer fire once detached.
- expectation = nil
- auth.removeStateDidChangeListener(handle)
- try waitForSignInWithAccessToken()
- }
- /** @fn testIDTokenChanges
- @brief Tests @c addIDTokenDidChangeListener: and @c removeIDTokenDidChangeListener: methods.
- */
- func testIDTokenChanges() throws {
- // Set up listener.
- let auth = try XCTUnwrap(auth)
- var shouldHaveUser = false
- var expectation: XCTestExpectation?
- var fulfilled = false
- let listener = { listenerAuth, user in
- XCTAssertTrue(Thread.isMainThread)
- XCTAssertEqual(auth, listenerAuth)
- XCTAssertEqual(user, auth.currentUser)
- if shouldHaveUser {
- XCTAssertNotNil(user)
- } else {
- XCTAssertNil(user)
- }
- // `expectation` being nil means the listener is not expected to be fired at this moment.
- XCTAssertNotNil(expectation)
- if !fulfilled {
- fulfilled = true
- expectation?.fulfill()
- }
- }
- try auth.signOut()
- // Listener should fire immediately when attached.
- expectation = self.expectation(description: "initial")
- shouldHaveUser = false
- let handle = auth.addIDTokenDidChangeListener(listener)
- waitForExpectations(timeout: 5)
- expectation = nil
- // Listener should fire for signing in. Expectation is waited on in
- // waitForSignInWithAccessToken.
- fulfilled = false
- expectation = self.expectation(description: "sign-in")
- shouldHaveUser = true
- try waitForSignInWithAccessToken()
- // Listener should not fire for signing in again.
- expectation = nil
- shouldHaveUser = true
- try waitForSignInWithAccessToken()
- // Listener should fire for signing in again as the same user with another access token.
- fulfilled = false
- expectation = self.expectation(description: "sign-in")
- shouldHaveUser = true
- try waitForSignInWithAccessToken(fakeAccessToken: AuthTests.kNewAccessToken)
- // Listener should fire for signing out.
- fulfilled = false
- expectation = self.expectation(description: "sign-out")
- shouldHaveUser = false
- try auth.signOut()
- waitForExpectations(timeout: 5)
- // Listener should no longer fire once detached.
- expectation = nil
- auth.removeStateDidChangeListener(handle)
- try waitForSignInWithAccessToken()
- }
- /** @fn testUseEmulator
- @brief Tests the @c useEmulatorWithHost:port: method.
- */
- func testUseEmulator() throws {
- auth.useEmulator(withHost: "host", port: 12345)
- XCTAssertEqual("host:12345", auth.requestConfiguration.emulatorHostAndPort)
- #if os(iOS)
- let settings = try XCTUnwrap(auth.settings)
- XCTAssertTrue(settings.isAppVerificationDisabledForTesting)
- #endif
- }
- /** @fn testUseEmulatorNeverCalled
- @brief Tests that the emulatorHostAndPort stored in @c FIRAuthRequestConfiguration is nil if the
- @c useEmulatorWithHost:port: is not called.
- */
- func testUseEmulatorNeverCalled() throws {
- XCTAssertNil(auth.requestConfiguration.emulatorHostAndPort)
- #if os(iOS)
- let settings = try XCTUnwrap(auth.settings)
- XCTAssertFalse(settings.isAppVerificationDisabledForTesting)
- #endif
- }
- /** @fn testUseEmulatorIPv6Address
- @brief Tests the @c useEmulatorWithHost:port: method with an IPv6 host address.
- */
- func testUseEmulatorIPv6Address() throws {
- auth.useEmulator(withHost: "::1", port: 12345)
- XCTAssertEqual("[::1]:12345", auth.requestConfiguration.emulatorHostAndPort)
- #if os(iOS)
- let settings = try XCTUnwrap(auth.settings)
- XCTAssertTrue(settings.isAppVerificationDisabledForTesting)
- #endif
- }
- // MARK: Automatic Token Refresh Tests.
- /** @fn testAutomaticTokenRefresh
- @brief Tests a successful flow to automatically refresh tokens for a signed in user.
- */
- func testAutomaticTokenRefresh() throws {
- try auth.signOut()
- // Enable auto refresh
- enableAutoTokenRefresh()
- // Sign in a user.
- try waitForSignInWithAccessToken()
- setFakeSecureTokenService(fakeAccessToken: AuthTests.kNewAccessToken)
- // Verify that the current user's access token is the "old" access token before automatic token
- // refresh.
- XCTAssertEqual(AuthTests.kAccessToken, auth.currentUser?.rawAccessToken())
- // Execute saved token refresh task.
- let expectation = self.expectation(description: #function)
- kAuthGlobalWorkQueue.async {
- XCTAssertNotNil(self.authDispatcherCallback)
- self.authDispatcherCallback?()
- expectation.fulfill()
- }
- waitForExpectations(timeout: 5)
- waitForAuthGlobalWorkQueueDrain()
- // Verify that current user's access token is the "new" access token provided in the mock secure
- // token response during automatic token refresh.
- RPCBaseTests.waitSleep()
- XCTAssertEqual(AuthTests.kNewAccessToken, auth.currentUser?.rawAccessToken())
- }
- /** @fn testAutomaticTokenRefreshInvalidTokenFailure
- @brief Tests an unsuccessful flow to auto refresh tokens with an "invalid token" error.
- This error should cause the user to be signed out.
- */
- func testAutomaticTokenRefreshInvalidTokenFailure() throws {
- try auth.signOut()
- // Enable auto refresh
- enableAutoTokenRefresh()
- // Sign in a user.
- try waitForSignInWithAccessToken()
- // Set up expectation for secureToken RPC made by a failed attempt to refresh tokens.
- rpcIssuer.secureTokenErrorString = "INVALID_ID_TOKEN"
- // Verify that the current user's access token is the "old" access token before automatic token
- // refresh.
- XCTAssertEqual(AuthTests.kAccessToken, auth.currentUser?.rawAccessToken())
- // Execute saved token refresh task.
- let expectation = self.expectation(description: #function)
- kAuthGlobalWorkQueue.async {
- XCTAssertNotNil(self.authDispatcherCallback)
- self.authDispatcherCallback?()
- expectation.fulfill()
- }
- waitForExpectations(timeout: 5)
- waitForAuthGlobalWorkQueueDrain()
- // Verify that the user is nil after failed attempt to refresh tokens caused signed out.
- RPCBaseTests.waitSleep()
- XCTAssertNil(auth.currentUser)
- }
- /** @fn testAutomaticTokenRefreshRetry
- @brief Tests that a retry is attempted for a automatic token refresh task (which is not due to
- invalid tokens). The initial attempt to refresh the access token fails, but the second
- attempt is successful.
- */
- func testAutomaticTokenRefreshRetry() throws {
- try auth.signOut()
- // Enable auto refresh
- enableAutoTokenRefresh()
- // Sign in a user.
- try waitForSignInWithAccessToken()
- // Set up expectation for secureToken RPC made by a failed attempt to refresh tokens.
- rpcIssuer.secureTokenNetworkError = NSError(domain: "ERROR", code: -1)
- // Execute saved token refresh task.
- let expectation = self.expectation(description: #function)
- kAuthGlobalWorkQueue.async {
- XCTAssertNotNil(self.authDispatcherCallback)
- self.authDispatcherCallback?()
- self.authDispatcherCallback = nil
- expectation.fulfill()
- }
- waitForExpectations(timeout: 5)
- waitForAuthGlobalWorkQueueDrain()
- rpcIssuer.secureTokenNetworkError = nil
- setFakeSecureTokenService(fakeAccessToken: AuthTests.kNewAccessToken)
- // The old access token should still be the current user's access token and not the new access
- // token (kNewAccessToken).
- XCTAssertEqual(AuthTests.kAccessToken, auth.currentUser?.rawAccessToken())
- // Execute saved token refresh task.
- let expectation2 = self.expectation(description: "dispatchAfterExpectation")
- kAuthGlobalWorkQueue.async {
- RPCBaseTests.waitSleep()
- XCTAssertNotNil(self.authDispatcherCallback)
- self.authDispatcherCallback?()
- expectation2.fulfill()
- }
- waitForExpectations(timeout: 5)
- waitForAuthGlobalWorkQueueDrain()
- // Time for callback to run.
- RPCBaseTests.waitSleep()
- // Verify that current user's access token is the "new" access token provided in the mock secure
- // token response during automatic token refresh.
- XCTAssertEqual(AuthTests.kNewAccessToken, auth.currentUser?.rawAccessToken())
- }
- #if os(iOS)
- /** @fn testAutoRefreshAppForegroundedNotification
- @brief Tests that app foreground notification triggers the scheduling of an automatic token
- refresh task.
- */
- func testAutoRefreshAppForegroundedNotification() throws {
- try auth.signOut()
- // Enable auto refresh
- enableAutoTokenRefresh()
- // Sign in a user.
- try waitForSignInWithAccessToken()
- // Post "UIApplicationDidBecomeActiveNotification" to trigger scheduling token refresh task.
- NotificationCenter.default.post(name: UIApplication.didBecomeActiveNotification, object: nil)
- setFakeSecureTokenService(fakeAccessToken: AuthTests.kNewAccessToken)
- // Verify that the current user's access token is the "old" access token before automatic
- // token refresh.
- XCTAssertEqual(AuthTests.kAccessToken, auth.currentUser?.rawAccessToken())
- // Execute saved token refresh task.
- let expectation = self.expectation(description: #function)
- kAuthGlobalWorkQueue.async {
- XCTAssertNotNil(self.authDispatcherCallback)
- self.authDispatcherCallback?()
- expectation.fulfill()
- }
- waitForExpectations(timeout: 5)
- waitForAuthGlobalWorkQueueDrain()
- // Time for callback to run.
- RPCBaseTests.waitSleep()
- // Verify that current user's access token is the "new" access token provided in the mock
- // secure token response during automatic token refresh.
- XCTAssertEqual(AuthTests.kNewAccessToken, auth.currentUser?.rawAccessToken())
- }
- #endif
- // MARK: Application Delegate tests.
- #if os(iOS)
- func testAppDidRegisterForRemoteNotifications_APNSTokenUpdated() {
- class FakeAuthTokenManager: AuthAPNSTokenManager {
- override var token: AuthAPNSToken? {
- get {
- return tokenStore
- }
- set(setToken) {
- tokenStore = setToken
- }
- }
- }
- let apnsToken = Data()
- auth.tokenManager = FakeAuthTokenManager(withApplication: UIApplication.shared)
- auth.application(UIApplication.shared,
- didRegisterForRemoteNotificationsWithDeviceToken: apnsToken)
- XCTAssertEqual(auth.tokenManager.token?.data, apnsToken)
- XCTAssertEqual(auth.tokenManager.token?.type, .unknown)
- }
- func testAppDidFailToRegisterForRemoteNotifications_TokenManagerCancels() {
- class FakeAuthTokenManager: AuthAPNSTokenManager {
- var cancelled = false
- override func cancel(withError error: Error) {
- cancelled = true
- }
- }
- let error = NSError(domain: "AuthTests", code: -1)
- let fakeTokenManager = FakeAuthTokenManager(withApplication: UIApplication.shared)
- auth.tokenManager = fakeTokenManager
- XCTAssertFalse(fakeTokenManager.cancelled)
- auth.application(UIApplication.shared,
- didFailToRegisterForRemoteNotificationsWithError: error)
- XCTAssertTrue(fakeTokenManager.cancelled)
- }
- func testAppDidReceiveRemoteNotificationWithCompletion_NotificationManagerHandleCanNotification() {
- class FakeNotificationManager: AuthNotificationManager {
- var canHandled = false
- override func canHandle(notification: [AnyHashable: Any]) -> Bool {
- canHandled = true
- return true
- }
- }
- let notification = ["test": ""]
- let fakeKeychain = AuthKeychainServices(
- service: "AuthTests",
- storage: FakeAuthKeychainStorage()
- )
- let appCredentialManager = AuthAppCredentialManager(withKeychain: fakeKeychain)
- let fakeNotificationManager = FakeNotificationManager(withApplication: UIApplication.shared,
- appCredentialManager: appCredentialManager)
- auth.notificationManager = fakeNotificationManager
- XCTAssertFalse(fakeNotificationManager.canHandled)
- auth.application(UIApplication.shared,
- didReceiveRemoteNotification: notification) { _ in
- }
- XCTAssertTrue(fakeNotificationManager.canHandled)
- }
- func testAppOpenURL_AuthPresenterCanHandleURL() throws {
- class FakeURLPresenter: AuthURLPresenter {
- var canHandled = false
- override func canHandle(url: URL) -> Bool {
- canHandled = true
- return true
- }
- }
- let url = try XCTUnwrap(URL(string: "https://localhost"))
- let fakeURLPresenter = FakeURLPresenter()
- auth.authURLPresenter = fakeURLPresenter
- XCTAssertFalse(fakeURLPresenter.canHandled)
- XCTAssertTrue(auth.application(UIApplication.shared, open: url, options: [:]))
- XCTAssertTrue(fakeURLPresenter.canHandled)
- }
- #endif // os(iOS)
- // MARK: Interoperability Tests
- func testComponentsRegistered() throws {
- // Verify that the components are registered properly. Check the count, because any time a new
- // component is added it should be added to the test suite as well.
- XCTAssertEqual(AuthComponent.componentsToRegister().count, 1)
- // TODO: Can/should we do something like?
- // XCTAssert(component.protocol == @protocol(FIRAuthInterop));
- }
- // MARK: Helper Functions
- private func enableAutoTokenRefresh() {
- let expectation = self.expectation(description: #function)
- auth.getToken(forcingRefresh: false) { token, error in
- expectation.fulfill()
- }
- waitForExpectations(timeout: 5)
- }
- private func waitForSignInWithAccessToken(fakeAccessToken: String = kAccessToken) throws {
- let kRefreshToken = "fakeRefreshToken"
- let expectation = self.expectation(description: #function)
- setFakeGetAccountProvider()
- setFakeSecureTokenService()
- // 1. Set up respondBlock to test request and send it to generate a fake response.
- rpcIssuer.respondBlock = {
- // 2. Validate the created Request instance.
- let request = try XCTUnwrap(self.rpcIssuer.request as? VerifyPasswordRequest)
- XCTAssertEqual(request.email, self.kEmail)
- XCTAssertEqual(request.password, self.kFakePassword)
- XCTAssertEqual(request.apiKey, AuthTests.kFakeAPIKey)
- 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])
- }
- auth?.signIn(withEmail: kEmail, password: kFakePassword) { authResult, error in
- // 4. After the response triggers the callback, verify the returned result.
- XCTAssertTrue(Thread.isMainThread)
- guard let user = authResult?.user else {
- XCTFail("authResult.user is missing")
- return
- }
- XCTAssertEqual(user.refreshToken, kRefreshToken)
- XCTAssertFalse(user.isAnonymous)
- XCTAssertEqual(user.email, self.kEmail)
- guard let additionalUserInfo = authResult?.additionalUserInfo else {
- XCTFail("authResult.additionalUserInfo is missing")
- return
- }
- XCTAssertFalse(additionalUserInfo.isNewUser)
- XCTAssertEqual(additionalUserInfo.providerID, EmailAuthProvider.id)
- XCTAssertNil(error)
- expectation.fulfill()
- }
- waitForExpectations(timeout: 5)
- assertUser(auth?.currentUser)
- }
- private func assertUser(_ user: User?) {
- guard let user = user else {
- XCTFail("authResult.additionalUserInfo is missing")
- return
- }
- XCTAssertEqual(user.uid, kLocalID)
- XCTAssertEqual(user.displayName, kDisplayName)
- XCTAssertEqual(user.email, kEmail)
- XCTAssertFalse(user.isAnonymous)
- XCTAssertEqual(user.providerData.count, 1)
- }
- private func assertUserAnonymous(_ user: User?) {
- guard let user = user else {
- XCTFail("authResult.additionalUserInfo is missing")
- return
- }
- XCTAssertEqual(user.uid, kLocalID)
- XCTAssertNil(user.email)
- XCTAssertNil(user.displayName)
- XCTAssertTrue(user.isAnonymous)
- XCTAssertEqual(user.providerData.count, 0)
- }
- }
|