| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326 |
- /*
- * Copyright 2017 Google
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
- #import <Foundation/Foundation.h>
- #import <OCMock/OCMock.h>
- #import <XCTest/XCTest.h>
- #import <GoogleUtilities/GULAppDelegateSwizzler.h>
- #import "FirebaseAuth/Interop/FIRAuthInterop.h"
- #import "FirebaseAuth/Sources/Public/FirebaseAuth/FIRActionCodeSettings.h"
- #import "FirebaseAuth/Sources/Public/FirebaseAuth/FIRAdditionalUserInfo.h"
- #import "FirebaseAuth/Sources/Public/FirebaseAuth/FIRAuthSettings.h"
- #import "FirebaseAuth/Sources/Public/FirebaseAuth/FIREmailAuthProvider.h"
- #import "FirebaseAuth/Sources/Public/FirebaseAuth/FIRFacebookAuthProvider.h"
- #import "FirebaseAuth/Sources/Public/FirebaseAuth/FIRGoogleAuthProvider.h"
- #import "FirebaseAuth/Sources/Public/FirebaseAuth/FIROAuthProvider.h"
- #import "FirebaseCore/Extension/FirebaseCoreInternal.h"
- #import "FirebaseAuth/Sources/Auth/FIRAuthDispatcher.h"
- #import "FirebaseAuth/Sources/Auth/FIRAuthGlobalWorkQueue.h"
- #import "FirebaseAuth/Sources/Auth/FIRAuthOperationType.h"
- #import "FirebaseAuth/Sources/Auth/FIRAuth_Internal.h"
- #import "FirebaseAuth/Sources/AuthProvider/OAuth/FIROAuthCredential_Internal.h"
- #import "FirebaseAuth/Sources/Backend/FIRAuthBackend.h"
- #import "FirebaseAuth/Sources/Backend/RPC/FIRCreateAuthURIRequest.h"
- #import "FirebaseAuth/Sources/Backend/RPC/FIRCreateAuthURIResponse.h"
- #import "FirebaseAuth/Sources/Backend/RPC/FIREmailLinkSignInRequest.h"
- #import "FirebaseAuth/Sources/Backend/RPC/FIREmailLinkSignInResponse.h"
- #import "FirebaseAuth/Sources/Backend/RPC/FIRGetAccountInfoRequest.h"
- #import "FirebaseAuth/Sources/Backend/RPC/FIRGetAccountInfoResponse.h"
- #import "FirebaseAuth/Sources/Backend/RPC/FIRGetOOBConfirmationCodeRequest.h"
- #import "FirebaseAuth/Sources/Backend/RPC/FIRGetOOBConfirmationCodeResponse.h"
- #import "FirebaseAuth/Sources/Backend/RPC/FIRResetPasswordRequest.h"
- #import "FirebaseAuth/Sources/Backend/RPC/FIRResetPasswordResponse.h"
- #import "FirebaseAuth/Sources/Backend/RPC/FIRRevokeTokenRequest.h"
- #import "FirebaseAuth/Sources/Backend/RPC/FIRRevokeTokenResponse.h"
- #import "FirebaseAuth/Sources/Backend/RPC/FIRSecureTokenRequest.h"
- #import "FirebaseAuth/Sources/Backend/RPC/FIRSecureTokenResponse.h"
- #import "FirebaseAuth/Sources/Backend/RPC/FIRSetAccountInfoRequest.h"
- #import "FirebaseAuth/Sources/Backend/RPC/FIRSetAccountInfoResponse.h"
- #import "FirebaseAuth/Sources/Backend/RPC/FIRSignUpNewUserRequest.h"
- #import "FirebaseAuth/Sources/Backend/RPC/FIRSignUpNewUserResponse.h"
- #import "FirebaseAuth/Sources/Backend/RPC/FIRVerifyAssertionRequest.h"
- #import "FirebaseAuth/Sources/Backend/RPC/FIRVerifyAssertionResponse.h"
- #import "FirebaseAuth/Sources/Backend/RPC/FIRVerifyCustomTokenRequest.h"
- #import "FirebaseAuth/Sources/Backend/RPC/FIRVerifyCustomTokenResponse.h"
- #import "FirebaseAuth/Sources/Backend/RPC/FIRVerifyPasswordRequest.h"
- #import "FirebaseAuth/Sources/Backend/RPC/FIRVerifyPasswordResponse.h"
- #import "FirebaseAuth/Sources/Backend/RPC/FIRVerifyPhoneNumberRequest.h"
- #import "FirebaseAuth/Sources/Backend/RPC/FIRVerifyPhoneNumberResponse.h"
- #import "FirebaseAuth/Sources/User/FIRUser_Internal.h"
- #import "FirebaseAuth/Sources/Utilities/FIRAuthErrorUtils.h"
- #import "FirebaseAuth/Sources/Utilities/FIRAuthRecaptchaVerifier.h"
- #import "FirebaseAuth/Tests/Unit/FIRApp+FIRAuthUnitTests.h"
- #import "FirebaseAuth/Tests/Unit/OCMStubRecorder+FIRAuthUnitTests.h"
- #if TARGET_OS_IOS
- #import "FirebaseAuth/Sources/Public/FirebaseAuth/FIRAuthUIDelegate.h"
- #import "FirebaseAuth/Sources/Public/FirebaseAuth/FIRPhoneAuthCredential.h"
- #import "FirebaseAuth/Sources/Public/FirebaseAuth/FIRPhoneAuthProvider.h"
- #import "FirebaseAuth/Sources/SystemService/FIRAuthAPNSToken.h"
- #import "FirebaseAuth/Sources/SystemService/FIRAuthAPNSTokenManager.h"
- #import "FirebaseAuth/Sources/SystemService/FIRAuthNotificationManager.h"
- #import "FirebaseAuth/Sources/Utilities/FIRAuthURLPresenter.h"
- #endif // TARGET_OS_IOS
- /** @var kAPIKey
- @brief The fake API key.
- */
- static NSString *const kAPIKey = @"FAKE_API_KEY";
- /** @var kFirebaseAppID
- @brief The fake Firebase app ID.
- */
- static NSString *const kFirebaseAppID = @"FAKE_APP_ID";
- /** @var kAccessToken
- @brief The fake access token.
- */
- static NSString *const kAccessToken = @"ACCESS_TOKEN";
- /** @var kNewAccessToken
- @brief Another fake access token used to simulate token refreshed via automatic token refresh.
- */
- NSString *kNewAccessToken = @"NewAccessToken";
- /** @var kAccessTokenValidInterval
- @brief The time to live for the fake access token.
- */
- static const NSTimeInterval kAccessTokenTimeToLive = 60 * 60;
- /** @var kTestTokenExpirationTimeInterval
- @brief The fake time interval that it takes a token to expire.
- */
- static const NSTimeInterval kTestTokenExpirationTimeInterval = 55 * 60;
- /** @var kRefreshToken
- @brief The fake refresh token.
- */
- static NSString *const kRefreshToken = @"REFRESH_TOKEN";
- /** @var kEmail
- @brief The fake user email.
- */
- static NSString *const kEmail = @"user@company.com";
- /** @var kFakePassword
- @brief The fake user password.
- */
- static NSString *const kFakePassword = @"!@#$%^";
- /** @var kPasswordHash
- @brief The fake user password hash.
- */
- static NSString *const kPasswordHash = @"UkVEQUNURUQ=";
- /** @var kLocalID
- @brief The fake local user ID.
- */
- static NSString *const kLocalID = @"LOCAL_ID";
- /** @var kDisplayName
- @brief The fake user display name.
- */
- static NSString *const kDisplayName = @"User Doe";
- /** @var kFakeGivenName
- @brief The fake user given name.
- */
- static NSString *const kFakeGivenName = @"Firstname";
- /** @var kFakeFamilyName
- @brief The fake user family name.
- */
- static NSString *const kFakeFamilyName = @"Lastname";
- /** @var kGoogleUD
- @brief The fake user ID under Google Sign-In.
- */
- static NSString *const kGoogleID = @"GOOGLE_ID";
- /** @var kGoogleEmail
- @brief The fake user email under Google Sign-In.
- */
- static NSString *const kGoogleEmail = @"user@gmail.com";
- /** @var kGoogleDisplayName
- @brief The fake user display name under Google Sign-In.
- */
- static NSString *const kGoogleDisplayName = @"Google Doe";
- /** @var kGoogleAccessToken
- @brief The fake access token from Google Sign-In.
- */
- static NSString *const kGoogleAccessToken = @"GOOGLE_ACCESS_TOKEN";
- /** @var kGoogleIDToken
- @brief The fake ID token from Google Sign-In.
- */
- static NSString *const kGoogleIDToken = @"GOOGLE_ID_TOKEN";
- /** @var kAppleAuthProviderID
- @brief The provider ID for Apple Sign-In.
- */
- static NSString *const kAppleAuthProviderID = @"apple.com";
- /** @var kAppleIDToken
- @brief The fake ID token from Apple Sign-In.
- */
- static NSString *const kAppleIDToken = @"APPLE_ID_TOKEN";
- /** @var kCustomToken
- @brief The fake custom token to sign in.
- */
- static NSString *const kCustomToken = @"CUSTOM_TOKEN";
- /** @var kVerificationCode
- @brief Fake verification code used for testing.
- */
- static NSString *const kVerificationCode = @"12345678";
- /** @var kVerificationID
- @brief Fake verification ID for testing.
- */
- static NSString *const kVerificationID = @"55432";
- /** @var kOAuthRequestURI
- @brief Fake OAuthRequest URI for testing.
- */
- static NSString *const kOAuthRequestURI = @"requestURI";
- /** @var kOAuthSessionID
- @brief Fake session ID for testing.
- */
- static NSString *const kOAuthSessionID = @"sessionID";
- /** @var kFakeWebSignInUserInteractionFailureReason
- @brief Fake reason for FIRAuthErrorCodeWebSignInUserInteractionFailure error while testing.
- */
- static NSString *const kFakeWebSignInUserInteractionFailureReason = @"fake_reason";
- /** @var kContinueURL
- @brief Fake string value of continue url.
- */
- static NSString *const kContinueURL = @"continueURL";
- /** @var kCanHandleCodeInAppKey
- @brief The key for the request parameter indicating whether the action code can be handled in
- the app or not.
- */
- static NSString *const kCanHandleCodeInAppKey = @"canHandleCodeInApp";
- /** @var kFIREmailLinkAuthSignInMethod
- @brief Fake email link sign-in method for testing.
- */
- static NSString *const kFIREmailLinkAuthSignInMethod = @"emailLink";
- /** @var kFIRFacebookAuthSignInMethod
- @brief Fake Facebook sign-in method for testing.
- */
- static NSString *const kFIRFacebookAuthSignInMethod = @"facebook.com";
- /** @var kBadSignInEmailLink
- @brief Bad sign-in link to test email link sign-in
- */
- static NSString *const kBadSignInEmailLink = @"http://www.facebook.com";
- /** @var kFakeEmailSignInDeeplink
- @brief Fake email sign-in link
- */
- static NSString *const kFakeEmailSignInDeeplink =
- @"https://example.domain.com/?apiKey=testAPIKey&oobCode=testoobcode&mode=signIn";
- /** @var kFakeEmailSignInlink
- @brief Fake email sign-in link
- */
- static NSString *const kFakeEmailSignInlink =
- @"https://test.app.goo.gl/?link=https://test.firebase"
- "app.com/__/auth/"
- "action?apiKey%3DtestAPIKey%26mode%3DsignIn%26oobCode%3Dtestoobcode%26continueU"
- "rl%3Dhttps://test.apps.com&ibi=com.test.com&ifl=https://test.firebaseapp.com/__/auth/"
- "action?ap"
- "iKey%3DtestAPIKey%26mode%3DsignIn%26oobCode%3Dtestoobcode%26continueUrl%3Dhttps://"
- "test.apps.co"
- "m";
- /** @var kExpectationTimeout
- @brief The maximum time waiting for expectations to fulfill.
- */
- static const NSTimeInterval kExpectationTimeout = 2;
- /** @var kWaitInterval
- @brief The time waiting for background tasks to finish before continue when necessary.
- */
- static const NSTimeInterval kWaitInterval = .5;
- /** @var kFakeRecaptchaResponse
- @brief The fake recaptcha response.
- */
- static NSString *const kFakeRecaptchaResponse = @"RecaptchaResponse";
- /** @var kFakeRecaptchaVersion
- @brief The fake recaptcha version.
- */
- static NSString *const kFakeRecaptchaVersion = @"RecaptchaVersion";
- #if TARGET_OS_IOS
- /** @class FIRAuthAppDelegate
- @brief Application delegate implementation to test the app delegate proxying
- */
- @interface FIRAuthAppDelegate : NSObject <UIApplicationDelegate>
- @end
- @implementation FIRAuthAppDelegate
- - (void)application:(UIApplication *)application
- didReceiveRemoteNotification:(NSDictionary *)userInfo
- fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler {
- }
- - (BOOL)application:(UIApplication *)app
- openURL:(NSURL *)url
- options:(NSDictionary<UIApplicationOpenURLOptionsKey, id> *)options {
- return NO;
- }
- @end
- #endif // TARGET_OS_IOS
- @interface GULAppDelegateSwizzler (FIRMessagingRemoteNotificationsProxyTest)
- + (void)resetProxyOriginalDelegateOnceToken;
- @end
- /** Category for FIRAuth to expose FIRComponentRegistrant conformance. */
- @interface FIRAuth () <FIRLibrary>
- @end
- /** @class FIRAuthTests
- @brief Tests for @c FIRAuth.
- */
- @interface FIRAuthTests : XCTestCase
- #if TARGET_OS_IOS
- /// A partial mock of `[FIRAuth auth].tokenManager`
- @property(nonatomic, strong) id mockTokenManager;
- /// A partial mock of `[FIRAuth auth].notificationManager`
- @property(nonatomic, strong) id mockNotificationManager;
- /// A partial mock of `[FIRAuth auth].authURLPresenter`
- @property(nonatomic, strong) id mockAuthURLPresenter;
- /// An application delegate instance returned by `self.mockApplication.delegate`
- @property(nonatomic, strong) FIRAuthAppDelegate *fakeApplicationDelegate;
- #endif // TARGET_OS_IOS
- @end
- @implementation FIRAuthTests {
- /** @var _mockBackend
- @brief The mock @c FIRAuthBackendImplementation .
- */
- id _mockBackend;
- /** @var _FIRAuthDispatcherCallback
- @brief Used to save a task from FIRAuthDispatcher to be executed later.
- */
- __block void (^_Nonnull _FIRAuthDispatcherCallback)(void);
- }
- /** @fn googleProfile
- @brief The fake user profile under additional user data in @c FIRVerifyAssertionResponse.
- */
- + (NSDictionary *)googleProfile {
- static NSDictionary *kGoogleProfile = nil;
- static dispatch_once_t onceToken;
- dispatch_once(&onceToken, ^{
- kGoogleProfile = @{
- @"iss" : @"https://accounts.google.com\\",
- @"email" : kGoogleEmail,
- @"given_name" : @"User",
- @"family_name" : @"Doe"
- };
- });
- return kGoogleProfile;
- }
- - (void)setUp {
- [super setUp];
- #if TARGET_OS_IOS
- // Make sure the `self.fakeApplicationDelegate` will be swizzled on FIRAuth init.
- [GULAppDelegateSwizzler resetProxyOriginalDelegateOnceToken];
- self.fakeApplicationDelegate = [[FIRAuthAppDelegate alloc] init];
- [[GULAppDelegateSwizzler sharedApplication]
- setDelegate:(id<UIApplicationDelegate>)self.fakeApplicationDelegate];
- #endif // TARGET_OS_IOS
- _mockBackend = OCMProtocolMock(@protocol(FIRAuthBackendImplementation));
- [FIRAuthBackend setBackendImplementation:_mockBackend];
- [FIRApp resetAppForAuthUnitTests];
- // Set FIRAuthDispatcher implementation in order to save the token refresh task for later
- // execution.
- [[FIRAuthDispatcher sharedInstance]
- setDispatchAfterImplementation:^(NSTimeInterval delay, dispatch_queue_t _Nonnull queue,
- void (^task)(void)) {
- XCTAssertNotNil(task);
- XCTAssert(delay > 0);
- XCTAssertEqualObjects(FIRAuthGlobalWorkQueue(), queue);
- self->_FIRAuthDispatcherCallback = task;
- }];
- #if TARGET_OS_IOS
- // Wait until FIRAuth initialization completes
- [self waitForAuthGlobalWorkQueueDrain];
- self.mockTokenManager = OCMPartialMock([FIRAuth auth].tokenManager);
- self.mockNotificationManager = OCMPartialMock([FIRAuth auth].notificationManager);
- self.mockAuthURLPresenter = OCMPartialMock([FIRAuth auth].authURLPresenter);
- #endif // TARGET_OS_IOS
- }
- - (void)tearDown {
- [FIRAuthBackend setDefaultBackendImplementationWithRPCIssuer:nil];
- [[FIRAuthDispatcher sharedInstance] setDispatchAfterImplementation:nil];
- #if TARGET_OS_IOS
- [self.mockAuthURLPresenter stopMocking];
- self.mockAuthURLPresenter = nil;
- [self.mockNotificationManager stopMocking];
- self.mockNotificationManager = nil;
- [self.mockTokenManager stopMocking];
- self.mockTokenManager = nil;
- self.fakeApplicationDelegate = nil;
- #endif // TARGET_OS_IOS
- [super tearDown];
- }
- #pragma mark - Server API Tests
- /** @fn testFetchSignInMethodsForEmailSuccess
- @brief Tests the flow of a successful @c fetchSignInMethodsForEmail:completion: call.
- */
- - (void)testFetchSignInMethodsForEmailSuccess {
- NSArray<NSString *> *allSignInMethods =
- @[ kFIREmailLinkAuthSignInMethod, kFIRFacebookAuthSignInMethod ];
- OCMExpect([_mockBackend createAuthURI:[OCMArg any] callback:[OCMArg any]])
- .andCallBlock2(
- ^(FIRCreateAuthURIRequest *_Nullable request, FIRCreateAuthURIResponseCallback callback) {
- XCTAssertEqualObjects(request.identifier, kEmail);
- XCTAssertNotNil(request.endpoint);
- XCTAssertEqualObjects(request.APIKey, kAPIKey);
- dispatch_async(FIRAuthGlobalWorkQueue(), ^() {
- id mockCreateAuthURIResponse = OCMClassMock([FIRCreateAuthURIResponse class]);
- OCMStub([mockCreateAuthURIResponse signinMethods]).andReturn(allSignInMethods);
- callback(mockCreateAuthURIResponse, nil);
- });
- });
- XCTestExpectation *expectation = [self expectationWithDescription:@"callback"];
- [[FIRAuth auth] fetchSignInMethodsForEmail:kEmail
- completion:^(NSArray<NSString *> *_Nullable signInMethods,
- NSError *_Nullable error) {
- XCTAssertTrue([NSThread isMainThread]);
- XCTAssertEqualObjects(signInMethods, allSignInMethods);
- XCTAssertTrue([allSignInMethods isKindOfClass:[NSArray class]]);
- XCTAssertNil(error);
- [expectation fulfill];
- }];
- [self waitForExpectationsWithTimeout:kExpectationTimeout handler:nil];
- OCMVerifyAll(_mockBackend);
- }
- /** @fn testFetchSignInMethodsForEmailFailure
- @brief Tests the flow of a failed @c fetchSignInMethodsForEmail:completion: call.
- */
- - (void)testFetchSignInMethodsForEmailFailure {
- OCMExpect([_mockBackend createAuthURI:[OCMArg any] callback:[OCMArg any]])
- .andDispatchError2([FIRAuthErrorUtils tooManyRequestsErrorWithMessage:nil]);
- XCTestExpectation *expectation = [self expectationWithDescription:@"callback"];
- [[FIRAuth auth] fetchSignInMethodsForEmail:kEmail
- completion:^(NSArray<NSString *> *_Nullable signInMethods,
- NSError *_Nullable error) {
- XCTAssertTrue([NSThread isMainThread]);
- XCTAssertNil(signInMethods);
- XCTAssertEqual(error.code, FIRAuthErrorCodeTooManyRequests);
- XCTAssertNotNil(error.userInfo[NSLocalizedDescriptionKey]);
- [expectation fulfill];
- }];
- [self waitForExpectationsWithTimeout:kExpectationTimeout handler:nil];
- OCMVerifyAll(_mockBackend);
- }
- #if TARGET_OS_IOS
- /** @fn testPhoneAuthSuccess
- @brief Tests the flow of a successful @c signInWithCredential:completion for phone auth.
- */
- - (void)testPhoneAuthSuccess {
- OCMExpect([_mockBackend verifyPhoneNumber:[OCMArg any] callback:[OCMArg any]])
- .andCallBlock2(^(FIRVerifyPhoneNumberRequest *_Nullable request,
- FIRVerifyPhoneNumberResponseCallback callback) {
- XCTAssertEqualObjects(request.verificationCode, kVerificationCode);
- XCTAssertEqualObjects(request.verificationID, kVerificationID);
- XCTAssertEqual(request.operation, FIRAuthOperationTypeSignUpOrSignIn);
- dispatch_async(FIRAuthGlobalWorkQueue(), ^() {
- id mockVerifyPhoneResponse = OCMClassMock([FIRVerifyPhoneNumberResponse class]);
- [self stubTokensWithMockResponse:mockVerifyPhoneResponse];
- // Stub isNewUser flag in the response.
- OCMStub([mockVerifyPhoneResponse isNewUser]).andReturn(YES);
- callback(mockVerifyPhoneResponse, nil);
- });
- });
- [self expectGetAccountInfo];
- XCTestExpectation *expectation = [self expectationWithDescription:@"callback"];
- [[FIRAuth auth] signOut:NULL];
- FIRAuthCredential *credential =
- [[FIRPhoneAuthProvider provider] credentialWithVerificationID:kVerificationID
- verificationCode:kVerificationCode];
- [[FIRAuth auth] signInWithCredential:credential
- completion:^(FIRAuthDataResult *_Nullable authDataResult,
- NSError *_Nullable error) {
- XCTAssertTrue([NSThread isMainThread]);
- [self assertUser:authDataResult.user];
- XCTAssertTrue(authDataResult.additionalUserInfo.isNewUser);
- XCTAssertNil(error);
- [expectation fulfill];
- }];
- [self waitForExpectationsWithTimeout:kExpectationTimeout handler:nil];
- [self assertUser:[FIRAuth auth].currentUser];
- OCMVerifyAll(_mockBackend);
- }
- /** @fn testPhoneAuthMissingVerificationCode
- @brief Tests the flow of an unsuccessful @c signInWithCredential:completion for phone auth due
- to an empty verification code
- */
- - (void)testPhoneAuthMissingVerificationCode {
- XCTestExpectation *expectation = [self expectationWithDescription:@"callback"];
- [[FIRAuth auth] signOut:NULL];
- FIRAuthCredential *credential =
- [[FIRPhoneAuthProvider provider] credentialWithVerificationID:kVerificationID
- verificationCode:@""];
- [[FIRAuth auth]
- signInWithCredential:credential
- completion:^(FIRAuthDataResult *_Nullable result, NSError *_Nullable error) {
- XCTAssertTrue([NSThread isMainThread]);
- XCTAssertNil(result);
- XCTAssertEqual(error.code, FIRAuthErrorCodeMissingVerificationCode);
- [expectation fulfill];
- }];
- [self waitForExpectationsWithTimeout:kExpectationTimeout handler:nil];
- }
- /** @fn testPhoneAuthMissingVerificationID
- @brief Tests the flow of an unsuccessful @c signInWithCredential:completion for phone auth due
- to an empty verification ID.
- */
- - (void)testPhoneAuthMissingVerificationID {
- XCTestExpectation *expectation = [self expectationWithDescription:@"callback"];
- [[FIRAuth auth] signOut:NULL];
- FIRAuthCredential *credential =
- [[FIRPhoneAuthProvider provider] credentialWithVerificationID:@""
- verificationCode:kVerificationCode];
- [[FIRAuth auth]
- signInWithCredential:credential
- completion:^(FIRAuthDataResult *_Nullable result, NSError *_Nullable error) {
- XCTAssertTrue([NSThread isMainThread]);
- XCTAssertNil(result);
- XCTAssertEqual(error.code, FIRAuthErrorCodeMissingVerificationID);
- [expectation fulfill];
- }];
- [self waitForExpectationsWithTimeout:kExpectationTimeout handler:nil];
- }
- #endif
- /** @fn testSignInWithEmailLinkSuccess
- @brief Tests the flow of a successful @c signInWithEmail:link:completion: call.
- */
- - (void)testSignInWithEmailLinkSuccess {
- NSString *fakeCode = @"testoobcode";
- OCMExpect([_mockBackend emailLinkSignin:[OCMArg any] callback:[OCMArg any]])
- .andCallBlock2(^(FIREmailLinkSignInRequest *_Nullable request,
- FIREmailLinkSigninResponseCallback callback) {
- XCTAssertEqualObjects(request.email, kEmail);
- XCTAssertEqualObjects(request.oobCode, fakeCode);
- dispatch_async(FIRAuthGlobalWorkQueue(), ^() {
- id mockEmailLinkSignInResponse = OCMClassMock([FIREmailLinkSignInResponse class]);
- [self stubTokensWithMockResponse:mockEmailLinkSignInResponse];
- callback(mockEmailLinkSignInResponse, nil);
- OCMStub([mockEmailLinkSignInResponse refreshToken]).andReturn(kRefreshToken);
- });
- });
- [self expectGetAccountInfo];
- XCTestExpectation *expectation = [self expectationWithDescription:@"callback"];
- [[FIRAuth auth] signOut:NULL];
- [[FIRAuth auth]
- signInWithEmail:kEmail
- link:kFakeEmailSignInlink
- completion:^(FIRAuthDataResult *_Nullable authResult, NSError *_Nullable error) {
- XCTAssertTrue([NSThread isMainThread]);
- XCTAssertNotNil(authResult.user);
- XCTAssertEqualObjects(authResult.user.refreshToken, kRefreshToken);
- XCTAssertFalse(authResult.user.anonymous);
- XCTAssertEqualObjects(authResult.user.email, kEmail);
- XCTAssertNil(error);
- [expectation fulfill];
- }];
- [self waitForExpectationsWithTimeout:kExpectationTimeout handler:nil];
- [self assertUser:[FIRAuth auth].currentUser];
- OCMVerifyAll(_mockBackend);
- }
- /** @fn testSignInWithEmailLinkSuccessDeeplink
- @brief Tests the flow of a successful @c signInWithEmail:link:completion: call using a deep
- link.
- */
- - (void)testSignInWithEmailLinkSuccessDeeplink {
- NSString *fakeCode = @"testoobcode";
- OCMExpect([_mockBackend emailLinkSignin:[OCMArg any] callback:[OCMArg any]])
- .andCallBlock2(^(FIREmailLinkSignInRequest *_Nullable request,
- FIREmailLinkSigninResponseCallback callback) {
- XCTAssertEqualObjects(request.email, kEmail);
- XCTAssertEqualObjects(request.oobCode, fakeCode);
- dispatch_async(FIRAuthGlobalWorkQueue(), ^() {
- id mockEmailLinkSignInResponse = OCMClassMock([FIREmailLinkSignInResponse class]);
- [self stubTokensWithMockResponse:mockEmailLinkSignInResponse];
- callback(mockEmailLinkSignInResponse, nil);
- OCMStub([mockEmailLinkSignInResponse refreshToken]).andReturn(kRefreshToken);
- });
- });
- [self expectGetAccountInfo];
- XCTestExpectation *expectation = [self expectationWithDescription:@"callback"];
- [[FIRAuth auth] signOut:NULL];
- [[FIRAuth auth]
- signInWithEmail:kEmail
- link:kFakeEmailSignInDeeplink
- completion:^(FIRAuthDataResult *_Nullable authResult, NSError *_Nullable error) {
- XCTAssertTrue([NSThread isMainThread]);
- XCTAssertNotNil(authResult.user);
- XCTAssertEqualObjects(authResult.user.refreshToken, kRefreshToken);
- XCTAssertFalse(authResult.user.anonymous);
- XCTAssertEqualObjects(authResult.user.email, kEmail);
- XCTAssertNil(error);
- [expectation fulfill];
- }];
- [self waitForExpectationsWithTimeout:kExpectationTimeout handler:nil];
- [self assertUser:[FIRAuth auth].currentUser];
- OCMVerifyAll(_mockBackend);
- }
- /** @fn testSignInWithEmailLinkFailure
- @brief Tests the flow of a failed @c signInWithEmail:link:completion: call.
- */
- - (void)testSignInWithEmailLinkFailure {
- OCMExpect([_mockBackend emailLinkSignin:[OCMArg any] callback:[OCMArg any]])
- ._andDispatchError2([FIRAuthErrorUtils invalidActionCodeErrorWithMessage:nil]);
- XCTestExpectation *expectation = [self expectationWithDescription:@"callback"];
- [[FIRAuth auth] signOut:NULL];
- [[FIRAuth auth]
- signInWithEmail:kEmail
- link:kFakeEmailSignInlink
- completion:^(FIRAuthDataResult *_Nullable authResult, NSError *_Nullable error) {
- XCTAssertTrue([NSThread isMainThread]);
- XCTAssertEqual(error.code, FIRAuthErrorCodeInvalidActionCode);
- [expectation fulfill];
- }];
- [self waitForExpectationsWithTimeout:kExpectationTimeout handler:nil];
- OCMVerifyAll(_mockBackend);
- }
- #if TARGET_OS_IOS && !TARGET_OS_MACCATALYST
- /** @fn testSignInWithEmailPasswordWithRecaptchaSuccess
- @brief Tests the flow of a successful @c signInWithEmail:password:completion: call.
- */
- - (void)testSignInWithEmailPasswordWithRecaptchaSuccess {
- id mockVerifier = OCMClassMock([FIRAuthRecaptchaVerifier class]);
- OCMStub([mockVerifier sharedRecaptchaVerifier:[FIRAuth auth]]).andReturn(mockVerifier);
- OCMExpect([mockVerifier enablementStatusForProvider:FIRAuthRecaptchaProviderPassword])
- .andReturn(YES);
- FIRVerifyPasswordRequest *constRequestWithRecaptchaToken =
- [[FIRVerifyPasswordRequest alloc] initWithEmail:kEmail
- password:kFakePassword
- requestConfiguration:[FIRAuth auth].requestConfiguration];
- [constRequestWithRecaptchaToken injectRecaptchaFields:kFakeRecaptchaResponse
- recaptchaVersion:kFakeRecaptchaVersion];
- OCMStub([mockVerifier
- injectRecaptchaFields:[OCMArg any]
- provider:FIRAuthRecaptchaProviderPassword
- action:FIRAuthRecaptchaActionSignInWithPassword
- completion:([OCMArg invokeBlockWithArgs:constRequestWithRecaptchaToken, nil])]);
- OCMExpect([_mockBackend verifyPassword:[OCMArg any] callback:[OCMArg any]])
- .andCallBlock2(^(FIRVerifyPasswordRequest *_Nullable request,
- FIRVerifyPasswordResponseCallback callback) {
- XCTAssertEqualObjects(request.APIKey, kAPIKey);
- XCTAssertEqualObjects(request.email, kEmail);
- XCTAssertEqualObjects(request.password, kFakePassword);
- XCTAssertTrue(request.returnSecureToken);
- dispatch_async(FIRAuthGlobalWorkQueue(), ^() {
- id mockVerifyPasswordResponse = OCMClassMock([FIRVerifyPasswordResponse class]);
- [self stubTokensWithMockResponse:mockVerifyPasswordResponse];
- callback(mockVerifyPasswordResponse, nil);
- });
- });
- [self expectGetAccountInfo];
- XCTestExpectation *expectation = [self expectationWithDescription:@"callback"];
- [[FIRAuth auth] signOut:NULL];
- [[FIRAuth auth] signInWithEmail:kEmail
- password:kFakePassword
- completion:^(FIRAuthDataResult *_Nullable result, NSError *_Nullable error) {
- XCTAssertTrue([NSThread isMainThread]);
- [self assertUser:result.user];
- XCTAssertNil(error);
- [expectation fulfill];
- }];
- [self waitForExpectationsWithTimeout:kExpectationTimeout handler:nil];
- [self assertUser:[FIRAuth auth].currentUser];
- }
- /** @fn testSignInWithEmailPasswordWithRecaptchaFallbackSuccess
- @brief Tests the flow of a successful @c signInWithEmail:password:completion: call.
- */
- - (void)testSignInWithEmailPasswordWithRecaptchaFallbackSuccess {
- id mockVerifier = OCMClassMock([FIRAuthRecaptchaVerifier class]);
- OCMStub([mockVerifier sharedRecaptchaVerifier:[FIRAuth auth]]).andReturn(mockVerifier);
- OCMExpect([mockVerifier enablementStatusForProvider:FIRAuthRecaptchaProviderPassword])
- .andReturn(NO);
- FIRVerifyPasswordRequest *constRequestWithRecaptchaToken =
- [[FIRVerifyPasswordRequest alloc] initWithEmail:kEmail
- password:kFakePassword
- requestConfiguration:[FIRAuth auth].requestConfiguration];
- [constRequestWithRecaptchaToken injectRecaptchaFields:kFakeRecaptchaResponse
- recaptchaVersion:kFakeRecaptchaVersion];
- OCMStub([mockVerifier
- injectRecaptchaFields:[OCMArg any]
- provider:FIRAuthRecaptchaProviderPassword
- action:FIRAuthRecaptchaActionSignInWithPassword
- completion:([OCMArg invokeBlockWithArgs:constRequestWithRecaptchaToken, nil])]);
- OCMExpect([_mockBackend verifyPassword:[OCMArg any] callback:[OCMArg any]])
- .andCallBlock2(^(FIRVerifyPasswordRequest *_Nullable request,
- FIRVerifyPasswordResponseCallback callback) {
- XCTAssertEqualObjects(request.APIKey, kAPIKey);
- XCTAssertEqualObjects(request.email, kEmail);
- XCTAssertEqualObjects(request.password, kFakePassword);
- XCTAssertTrue(request.returnSecureToken);
- NSError *underlyingError =
- [[NSError alloc] initWithDomain:FIRAuthErrorDomain
- code:FIRAuthErrorCodeInternalError
- userInfo:@{
- FIRAuthErrorUserInfoDeserializedResponseKey :
- @{@"message" : @"MISSING_RECAPTCHA_TOKEN"}
- }];
- NSError *error = [[NSError alloc] initWithDomain:FIRAuthErrorDomain
- code:FIRAuthErrorCodeInternalError
- userInfo:@{NSUnderlyingErrorKey : underlyingError}];
- dispatch_async(FIRAuthGlobalWorkQueue(), ^() {
- callback(nil, error);
- });
- });
- OCMExpect([_mockBackend verifyPassword:[OCMArg any] callback:[OCMArg any]])
- .andCallBlock2(^(FIRVerifyPasswordRequest *_Nullable request,
- FIRVerifyPasswordResponseCallback callback) {
- XCTAssertEqualObjects(request.APIKey, kAPIKey);
- XCTAssertEqualObjects(request.email, kEmail);
- XCTAssertEqualObjects(request.password, kFakePassword);
- XCTAssertTrue(request.returnSecureToken);
- dispatch_async(FIRAuthGlobalWorkQueue(), ^() {
- id mockVerifyPasswordResponse = OCMClassMock([FIRVerifyPasswordResponse class]);
- [self stubTokensWithMockResponse:mockVerifyPasswordResponse];
- callback(mockVerifyPasswordResponse, nil);
- });
- });
- [self expectGetAccountInfo];
- XCTestExpectation *expectation = [self expectationWithDescription:@"callback"];
- [[FIRAuth auth] signOut:NULL];
- [[FIRAuth auth] signInWithEmail:kEmail
- password:kFakePassword
- completion:^(FIRAuthDataResult *_Nullable result, NSError *_Nullable error) {
- XCTAssertTrue([NSThread isMainThread]);
- [self assertUser:result.user];
- XCTAssertNil(error);
- [expectation fulfill];
- }];
- [self waitForExpectationsWithTimeout:kExpectationTimeout handler:nil];
- [self assertUser:[FIRAuth auth].currentUser];
- }
- #endif
- /** @fn testSignInWithEmailPasswordSuccess
- @brief Tests the flow of a successful @c signInWithEmail:password:completion: call.
- */
- - (void)testSignInWithEmailPasswordSuccess {
- OCMExpect([_mockBackend verifyPassword:[OCMArg any] callback:[OCMArg any]])
- .andCallBlock2(^(FIRVerifyPasswordRequest *_Nullable request,
- FIRVerifyPasswordResponseCallback callback) {
- XCTAssertEqualObjects(request.APIKey, kAPIKey);
- XCTAssertEqualObjects(request.email, kEmail);
- XCTAssertEqualObjects(request.password, kFakePassword);
- XCTAssertTrue(request.returnSecureToken);
- dispatch_async(FIRAuthGlobalWorkQueue(), ^() {
- id mockVerifyPasswordResponse = OCMClassMock([FIRVerifyPasswordResponse class]);
- [self stubTokensWithMockResponse:mockVerifyPasswordResponse];
- callback(mockVerifyPasswordResponse, nil);
- });
- });
- [self expectGetAccountInfo];
- XCTestExpectation *expectation = [self expectationWithDescription:@"callback"];
- [[FIRAuth auth] signOut:NULL];
- [[FIRAuth auth] signInWithEmail:kEmail
- password:kFakePassword
- completion:^(FIRAuthDataResult *_Nullable result, NSError *_Nullable error) {
- XCTAssertTrue([NSThread isMainThread]);
- [self assertUser:result.user];
- XCTAssertNil(error);
- [expectation fulfill];
- }];
- [self waitForExpectationsWithTimeout:kExpectationTimeout handler:nil];
- [self assertUser:[FIRAuth auth].currentUser];
- OCMVerifyAll(_mockBackend);
- }
- /** @fn testSignInWithEmailPasswordFailure
- @brief Tests the flow of a failed @c signInWithEmail:password:completion: call.
- */
- - (void)testSignInWithEmailPasswordFailure {
- OCMExpect([_mockBackend verifyPassword:[OCMArg any] callback:[OCMArg any]])
- .andDispatchError2([FIRAuthErrorUtils wrongPasswordErrorWithMessage:nil]);
- XCTestExpectation *expectation = [self expectationWithDescription:@"callback"];
- [[FIRAuth auth] signOut:NULL];
- [[FIRAuth auth] signInWithEmail:kEmail
- password:kFakePassword
- completion:^(FIRAuthDataResult *_Nullable result, NSError *_Nullable error) {
- XCTAssertTrue([NSThread isMainThread]);
- XCTAssertNil(result.user);
- XCTAssertEqual(error.code, FIRAuthErrorCodeWrongPassword);
- XCTAssertNotNil(error.userInfo[NSLocalizedDescriptionKey]);
- [expectation fulfill];
- }];
- [self waitForExpectationsWithTimeout:kExpectationTimeout handler:nil];
- XCTAssertNil([FIRAuth auth].currentUser);
- OCMVerifyAll(_mockBackend);
- }
- /** @fn testSignInAndRetrieveDataWithEmailPasswordSuccess
- @brief Tests the flow of a successful @c signInAndRetrieveDataWithEmail:password:completion:
- call.
- */
- - (void)testSignInAndRetrieveDataWithEmailPasswordSuccess {
- OCMExpect([_mockBackend verifyPassword:[OCMArg any] callback:[OCMArg any]])
- .andCallBlock2(^(FIRVerifyPasswordRequest *_Nullable request,
- FIRVerifyPasswordResponseCallback callback) {
- XCTAssertEqualObjects(request.APIKey, kAPIKey);
- XCTAssertEqualObjects(request.email, kEmail);
- XCTAssertEqualObjects(request.password, kFakePassword);
- XCTAssertTrue(request.returnSecureToken);
- dispatch_async(FIRAuthGlobalWorkQueue(), ^() {
- id mockVerifyPasswordResponse = OCMClassMock([FIRVerifyPasswordResponse class]);
- [self stubTokensWithMockResponse:mockVerifyPasswordResponse];
- callback(mockVerifyPasswordResponse, nil);
- });
- });
- [self expectGetAccountInfo];
- XCTestExpectation *expectation = [self expectationWithDescription:@"callback"];
- [[FIRAuth auth] signOut:NULL];
- [[FIRAuth auth]
- signInWithEmail:kEmail
- password:kFakePassword
- completion:^(FIRAuthDataResult *_Nullable result, NSError *_Nullable error) {
- XCTAssertTrue([NSThread isMainThread]);
- [self assertUser:result.user];
- XCTAssertFalse(result.additionalUserInfo.isNewUser);
- XCTAssertEqualObjects(result.additionalUserInfo.providerID, FIREmailAuthProviderID);
- XCTAssertNil(error);
- [expectation fulfill];
- }];
- [self waitForExpectationsWithTimeout:kExpectationTimeout handler:nil];
- [self assertUser:[FIRAuth auth].currentUser];
- OCMVerifyAll(_mockBackend);
- }
- /** @fn testSignInAndRetrieveDataWithEmailPasswordFailure
- @brief Tests the flow of a failed @c signInAndRetrieveDataWithEmail:password:completion: call.
- */
- - (void)testSignInAndRetrieveDataWithEmailPasswordFailure {
- OCMExpect([_mockBackend verifyPassword:[OCMArg any] callback:[OCMArg any]])
- .andDispatchError2([FIRAuthErrorUtils wrongPasswordErrorWithMessage:nil]);
- XCTestExpectation *expectation = [self expectationWithDescription:@"callback"];
- [[FIRAuth auth] signOut:NULL];
- [[FIRAuth auth] signInWithEmail:kEmail
- password:kFakePassword
- completion:^(FIRAuthDataResult *_Nullable result, NSError *_Nullable error) {
- XCTAssertTrue([NSThread isMainThread]);
- XCTAssertNil(result);
- XCTAssertEqual(error.code, FIRAuthErrorCodeWrongPassword);
- XCTAssertNotNil(error.userInfo[NSLocalizedDescriptionKey]);
- [expectation fulfill];
- }];
- [self waitForExpectationsWithTimeout:kExpectationTimeout handler:nil];
- XCTAssertNil([FIRAuth auth].currentUser);
- OCMVerifyAll(_mockBackend);
- }
- /** @fn testResetPasswordSuccess
- @brief Tests the flow of a successful @c confirmPasswordResetWithCode:newPassword:completion:
- call.
- */
- - (void)testResetPasswordSuccess {
- NSString *fakeEmail = @"fakeEmail";
- NSString *fakeCode = @"fakeCode";
- NSString *fakeNewPassword = @"fakeNewPassword";
- OCMExpect([_mockBackend resetPassword:[OCMArg any] callback:[OCMArg any]])
- .andCallBlock2(
- ^(FIRResetPasswordRequest *_Nullable request, FIRResetPasswordCallback callback) {
- XCTAssertEqualObjects(request.APIKey, kAPIKey);
- XCTAssertEqualObjects(request.oobCode, fakeCode);
- XCTAssertEqualObjects(request.updatedPassword, fakeNewPassword);
- dispatch_async(FIRAuthGlobalWorkQueue(), ^() {
- id mockResetPasswordResponse = OCMClassMock([FIRResetPasswordResponse class]);
- OCMStub([mockResetPasswordResponse email]).andReturn(fakeEmail);
- callback(mockResetPasswordResponse, nil);
- });
- });
- XCTestExpectation *expectation = [self expectationWithDescription:@"callback"];
- [[FIRAuth auth] signOut:NULL];
- [[FIRAuth auth] confirmPasswordResetWithCode:fakeCode
- newPassword:fakeNewPassword
- completion:^(NSError *_Nullable error) {
- XCTAssertTrue([NSThread isMainThread]);
- XCTAssertNil(error);
- [expectation fulfill];
- }];
- [self waitForExpectationsWithTimeout:kExpectationTimeout handler:nil];
- OCMVerifyAll(_mockBackend);
- }
- /** @fn testResetPasswordFailure
- @brief Tests the flow of a failed @c confirmPasswordResetWithCode:newPassword:completion:
- call.
- */
- - (void)testResetPasswordFailure {
- NSString *fakeCode = @"fakeCode";
- NSString *fakeNewPassword = @"fakeNewPassword";
- OCMExpect([_mockBackend resetPassword:[OCMArg any] callback:[OCMArg any]])
- ._andDispatchError2([FIRAuthErrorUtils invalidActionCodeErrorWithMessage:nil]);
- XCTestExpectation *expectation = [self expectationWithDescription:@"callback"];
- [[FIRAuth auth] signOut:NULL];
- [[FIRAuth auth] confirmPasswordResetWithCode:fakeCode
- newPassword:fakeNewPassword
- completion:^(NSError *_Nullable error) {
- XCTAssertTrue([NSThread isMainThread]);
- XCTAssertEqual(error.code, FIRAuthErrorCodeInvalidActionCode);
- [expectation fulfill];
- }];
- [self waitForExpectationsWithTimeout:kExpectationTimeout handler:nil];
- OCMVerifyAll(_mockBackend);
- }
- /** @fn testCheckActionCodeSuccess
- @brief Tests the flow of a successful @c checkActionCode:completion call.
- */
- - (void)testCheckActionCodeSuccess {
- NSString *verifyEmailRequestType = @"VERIFY_EMAIL";
- NSString *fakeEmail = @"fakeEmail";
- NSString *fakeNewEmail = @"fakeNewEmail";
- NSString *fakeCode = @"fakeCode";
- OCMExpect([_mockBackend resetPassword:[OCMArg any] callback:[OCMArg any]])
- .andCallBlock2(
- ^(FIRResetPasswordRequest *_Nullable request, FIRResetPasswordCallback callback) {
- XCTAssertEqualObjects(request.APIKey, kAPIKey);
- XCTAssertEqualObjects(request.oobCode, fakeCode);
- dispatch_async(FIRAuthGlobalWorkQueue(), ^() {
- id mockResetPasswordResponse = OCMClassMock([FIRResetPasswordResponse class]);
- OCMStub([mockResetPasswordResponse email]).andReturn(fakeEmail);
- OCMStub([mockResetPasswordResponse verifiedEmail]).andReturn(fakeNewEmail);
- OCMStubRecorder *stub =
- OCMStub([(FIRResetPasswordResponse *)mockResetPasswordResponse requestType]);
- stub.andReturn(verifyEmailRequestType);
- callback(mockResetPasswordResponse, nil);
- });
- });
- XCTestExpectation *expectation = [self expectationWithDescription:@"callback"];
- [[FIRAuth auth] checkActionCode:fakeCode
- completion:^(FIRActionCodeInfo *_Nullable info, NSError *_Nullable error) {
- XCTAssertTrue([NSThread isMainThread]);
- XCTAssertNil(error);
- XCTAssertEqual(info.operation, FIRActionCodeOperationVerifyEmail);
- XCTAssert([fakeNewEmail isEqualToString:info.email]);
- [expectation fulfill];
- }];
- [self waitForExpectationsWithTimeout:kExpectationTimeout handler:nil];
- OCMVerifyAll(_mockBackend);
- }
- /** @fn testCheckActionCodeFailure
- @brief Tests the flow of a failed @c checkActionCode:completion call.
- */
- - (void)testCheckActionCodeFailure {
- NSString *fakeCode = @"fakeCode";
- OCMExpect([_mockBackend resetPassword:[OCMArg any] callback:[OCMArg any]])
- ._andDispatchError2([FIRAuthErrorUtils expiredActionCodeErrorWithMessage:nil]);
- XCTestExpectation *expectation = [self expectationWithDescription:@"callback"];
- [[FIRAuth auth] signOut:NULL];
- [[FIRAuth auth] checkActionCode:fakeCode
- completion:^(FIRActionCodeInfo *_Nullable info, NSError *_Nullable error) {
- XCTAssertTrue([NSThread isMainThread]);
- XCTAssertNotNil(error);
- XCTAssertEqual(error.code, FIRAuthErrorCodeExpiredActionCode);
- [expectation fulfill];
- }];
- [self waitForExpectationsWithTimeout:kExpectationTimeout handler:nil];
- OCMVerifyAll(_mockBackend);
- }
- /** @fn testApplyActionCodeSuccess
- @brief Tests the flow of a successful @c applyActionCode:completion call.
- */
- - (void)testApplyActionCodeSuccess {
- NSString *fakeCode = @"fakeCode";
- OCMExpect([_mockBackend setAccountInfo:[OCMArg any] callback:[OCMArg any]])
- .andCallBlock2(^(FIRSetAccountInfoRequest *_Nullable request,
- FIRSetAccountInfoResponseCallback callback) {
- XCTAssertEqualObjects(request.APIKey, kAPIKey);
- XCTAssertEqualObjects(request.OOBCode, fakeCode);
- dispatch_async(FIRAuthGlobalWorkQueue(), ^() {
- id mockSetAccountInfoResponse = OCMClassMock([FIRSetAccountInfoResponse class]);
- callback(mockSetAccountInfoResponse, nil);
- });
- });
- XCTestExpectation *expectation = [self expectationWithDescription:@"callback"];
- [[FIRAuth auth] applyActionCode:fakeCode
- completion:^(NSError *_Nullable error) {
- XCTAssertTrue([NSThread isMainThread]);
- XCTAssertNil(error);
- [expectation fulfill];
- }];
- [self waitForExpectationsWithTimeout:kExpectationTimeout handler:nil];
- OCMVerifyAll(_mockBackend);
- }
- /** @fn testApplyActionCodeFailure
- @brief Tests the flow of a failed @c checkActionCode:completion call.
- */
- - (void)testApplyActionCodeFailure {
- NSString *fakeCode = @"fakeCode";
- OCMExpect([_mockBackend setAccountInfo:[OCMArg any] callback:[OCMArg any]])
- ._andDispatchError2([FIRAuthErrorUtils invalidActionCodeErrorWithMessage:nil]);
- XCTestExpectation *expectation = [self expectationWithDescription:@"callback"];
- [[FIRAuth auth] signOut:NULL];
- [[FIRAuth auth] applyActionCode:fakeCode
- completion:^(NSError *_Nullable error) {
- XCTAssertTrue([NSThread isMainThread]);
- XCTAssertNotNil(error);
- XCTAssertEqual(error.code, FIRAuthErrorCodeInvalidActionCode);
- [expectation fulfill];
- }];
- [self waitForExpectationsWithTimeout:kExpectationTimeout handler:nil];
- OCMVerifyAll(_mockBackend);
- }
- /** @fn testVerifyPasswordResetCodeSuccess
- @brief Tests the flow of a successful @c verifyPasswordResetCode:completion call.
- */
- - (void)testVerifyPasswordResetCodeSuccess {
- NSString *passwordResetRequestType = @"PASSWORD_RESET";
- NSString *fakeEmail = @"fakeEmail";
- NSString *fakeCode = @"fakeCode";
- OCMExpect([_mockBackend resetPassword:[OCMArg any] callback:[OCMArg any]])
- .andCallBlock2(
- ^(FIRResetPasswordRequest *_Nullable request, FIRResetPasswordCallback callback) {
- XCTAssertEqualObjects(request.APIKey, kAPIKey);
- XCTAssertEqualObjects(request.oobCode, fakeCode);
- dispatch_async(FIRAuthGlobalWorkQueue(), ^() {
- id mockResetPasswordResponse = OCMClassMock([FIRResetPasswordResponse class]);
- OCMStub([mockResetPasswordResponse email]).andReturn(fakeEmail);
- OCMStubRecorder *stub =
- OCMStub([(FIRResetPasswordResponse *)mockResetPasswordResponse requestType]);
- stub.andReturn(passwordResetRequestType);
- callback(mockResetPasswordResponse, nil);
- });
- });
- XCTestExpectation *expectation = [self expectationWithDescription:@"callback"];
- [[FIRAuth auth] verifyPasswordResetCode:fakeCode
- completion:^(NSString *_Nullable email, NSError *_Nullable error) {
- XCTAssertTrue([NSThread isMainThread]);
- XCTAssertNil(error);
- XCTAssertEqual(email, fakeEmail);
- [expectation fulfill];
- }];
- [self waitForExpectationsWithTimeout:kExpectationTimeout handler:nil];
- OCMVerifyAll(_mockBackend);
- }
- /** @fn testVerifyPasswordResetCodeFailure
- @brief Tests the flow of a failed @c verifyPasswordResetCode:completion call.
- */
- - (void)testVeridyPasswordResetCodeFailure {
- NSString *fakeCode = @"fakeCode";
- OCMExpect([_mockBackend resetPassword:[OCMArg any] callback:[OCMArg any]])
- ._andDispatchError2([FIRAuthErrorUtils invalidActionCodeErrorWithMessage:nil]);
- XCTestExpectation *expectation = [self expectationWithDescription:@"callback"];
- [[FIRAuth auth] signOut:NULL];
- [[FIRAuth auth] verifyPasswordResetCode:fakeCode
- completion:^(NSString *_Nullable email, NSError *_Nullable error) {
- XCTAssertTrue([NSThread isMainThread]);
- XCTAssertNotNil(error);
- XCTAssertEqual(error.code, FIRAuthErrorCodeInvalidActionCode);
- [expectation fulfill];
- }];
- [self waitForExpectationsWithTimeout:kExpectationTimeout handler:nil];
- OCMVerifyAll(_mockBackend);
- }
- /** @fn testSignInWithEmailLinkCredentialSuccess
- @brief Tests the flow of a successfully @c signInWithCredential:completion: call with an
- email sign-in link credential using FIREmailAuthProvider.
- */
- - (void)testSignInWithEmailLinkCredentialSuccess {
- NSString *fakeCode = @"testoobcode";
- OCMExpect([_mockBackend emailLinkSignin:[OCMArg any] callback:[OCMArg any]])
- .andCallBlock2(^(FIREmailLinkSignInRequest *_Nullable request,
- FIREmailLinkSigninResponseCallback callback) {
- XCTAssertEqualObjects(request.email, kEmail);
- XCTAssertEqualObjects(request.oobCode, fakeCode);
- dispatch_async(FIRAuthGlobalWorkQueue(), ^() {
- id mockEmailLinkSigninResponse = OCMClassMock([FIREmailLinkSignInResponse class]);
- [self stubTokensWithMockResponse:mockEmailLinkSigninResponse];
- callback(mockEmailLinkSigninResponse, nil);
- });
- });
- [self expectGetAccountInfo];
- XCTestExpectation *expectation = [self expectationWithDescription:@"callback"];
- [[FIRAuth auth] signOut:NULL];
- FIRAuthCredential *emailCredential =
- [FIREmailAuthProvider credentialWithEmail:kEmail link:kFakeEmailSignInlink];
- [[FIRAuth auth]
- signInWithCredential:emailCredential
- completion:^(FIRAuthDataResult *_Nullable authResult, NSError *_Nullable error) {
- XCTAssertTrue([NSThread isMainThread]);
- XCTAssertNotNil(authResult.user);
- XCTAssertEqualObjects(authResult.user.refreshToken, kRefreshToken);
- XCTAssertFalse(authResult.user.anonymous);
- XCTAssertEqualObjects(authResult.user.email, kEmail);
- XCTAssertNil(error);
- [expectation fulfill];
- }];
- [self waitForExpectationsWithTimeout:kExpectationTimeout handler:nil];
- [self assertUser:[FIRAuth auth].currentUser];
- OCMVerifyAll(_mockBackend);
- }
- /** @fn testSignInWithEmailLinkCredentialFailure
- @brief Tests the flow of a failed @c signInWithCredential:completion: call with an
- email-email sign-in link credential using FIREmailAuthProvider.
- */
- - (void)testSignInWithEmailLinkCredentialFailure {
- OCMExpect([_mockBackend emailLinkSignin:[OCMArg any] callback:[OCMArg any]])
- .andDispatchError2([FIRAuthErrorUtils userDisabledErrorWithMessage:nil]);
- XCTestExpectation *expectation = [self expectationWithDescription:@"callback"];
- [[FIRAuth auth] signOut:NULL];
- FIRAuthCredential *emailCredential =
- [FIREmailAuthProvider credentialWithEmail:kEmail link:kFakeEmailSignInlink];
- [[FIRAuth auth]
- signInWithCredential:emailCredential
- completion:^(FIRAuthDataResult *_Nullable result, NSError *_Nullable error) {
- XCTAssertTrue([NSThread isMainThread]);
- XCTAssertNil(result);
- XCTAssertEqual(error.code, FIRAuthErrorCodeUserDisabled);
- XCTAssertNotNil(error.userInfo[NSLocalizedDescriptionKey]);
- [expectation fulfill];
- }];
- [self waitForExpectationsWithTimeout:kExpectationTimeout handler:nil];
- XCTAssertNil([FIRAuth auth].currentUser);
- OCMVerifyAll(_mockBackend);
- }
- /** @fn testSignInWithEmailCredentialSuccess
- @brief Tests the flow of a successfully @c signInWithCredential:completion: call with an
- email-password credential.
- */
- - (void)testSignInWithEmailCredentialSuccess {
- OCMExpect([_mockBackend verifyPassword:[OCMArg any] callback:[OCMArg any]])
- .andCallBlock2(^(FIRVerifyPasswordRequest *_Nullable request,
- FIRVerifyPasswordResponseCallback callback) {
- XCTAssertEqualObjects(request.APIKey, kAPIKey);
- XCTAssertEqualObjects(request.email, kEmail);
- XCTAssertEqualObjects(request.password, kFakePassword);
- XCTAssertTrue(request.returnSecureToken);
- dispatch_async(FIRAuthGlobalWorkQueue(), ^() {
- id mockVerifyPasswordResponse = OCMClassMock([FIRVerifyPasswordResponse class]);
- [self stubTokensWithMockResponse:mockVerifyPasswordResponse];
- callback(mockVerifyPasswordResponse, nil);
- });
- });
- [self expectGetAccountInfo];
- XCTestExpectation *expectation = [self expectationWithDescription:@"callback"];
- [[FIRAuth auth] signOut:NULL];
- FIRAuthCredential *emailCredential = [FIREmailAuthProvider credentialWithEmail:kEmail
- password:kFakePassword];
- [[FIRAuth auth]
- signInWithCredential:emailCredential
- completion:^(FIRAuthDataResult *_Nullable result, NSError *_Nullable error) {
- XCTAssertTrue([NSThread isMainThread]);
- [self assertUser:result.user];
- XCTAssertNil(error);
- [expectation fulfill];
- }];
- [self waitForExpectationsWithTimeout:kExpectationTimeout handler:nil];
- [self assertUser:[FIRAuth auth].currentUser];
- OCMVerifyAll(_mockBackend);
- }
- /** @fn testSignInWithEmailCredentialFailure
- @brief Tests the flow of a failed @c signInWithCredential:completion: call with an
- email-password credential.
- */
- - (void)testSignInWithEmailCredentialFailure {
- OCMExpect([_mockBackend verifyPassword:[OCMArg any] callback:[OCMArg any]])
- .andDispatchError2([FIRAuthErrorUtils userDisabledErrorWithMessage:nil]);
- XCTestExpectation *expectation = [self expectationWithDescription:@"callback"];
- [[FIRAuth auth] signOut:NULL];
- FIRAuthCredential *emailCredential = [FIREmailAuthProvider credentialWithEmail:kEmail
- password:kFakePassword];
- [[FIRAuth auth]
- signInWithCredential:emailCredential
- completion:^(FIRAuthDataResult *_Nullable result, NSError *_Nullable error) {
- XCTAssertTrue([NSThread isMainThread]);
- XCTAssertNil(result);
- XCTAssertEqual(error.code, FIRAuthErrorCodeUserDisabled);
- XCTAssertNotNil(error.userInfo[NSLocalizedDescriptionKey]);
- [expectation fulfill];
- }];
- [self waitForExpectationsWithTimeout:kExpectationTimeout handler:nil];
- XCTAssertNil([FIRAuth auth].currentUser);
- OCMVerifyAll(_mockBackend);
- }
- /** @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.
- */
- - (void)testSignInWithEmailCredentialEmptyPassword {
- NSString *emptyString = @"";
- XCTestExpectation *expectation = [self expectationWithDescription:@"callback"];
- [[FIRAuth auth] signOut:NULL];
- FIRAuthCredential *emailCredential = [FIREmailAuthProvider credentialWithEmail:kEmail
- password:emptyString];
- [[FIRAuth auth]
- signInWithCredential:emailCredential
- completion:^(FIRAuthDataResult *_Nullable result, NSError *_Nullable error) {
- XCTAssertTrue([NSThread isMainThread]);
- XCTAssertEqual(error.code, FIRAuthErrorCodeWrongPassword);
- [expectation fulfill];
- }];
- [self waitForExpectationsWithTimeout:kExpectationTimeout handler:nil];
- }
- #if TARGET_OS_IOS
- /** @fn testSignInWithProviderSuccess
- @brief Tests a successful @c signInWithProvider:UIDelegate:completion: call with an OAuth
- provider configured for Google.
- */
- - (void)testSignInWithProviderSuccess {
- OCMExpect([_mockBackend verifyAssertion:[OCMArg any] callback:[OCMArg any]])
- .andCallBlock2(^(FIRVerifyAssertionRequest *_Nullable request,
- FIRVerifyAssertionResponseCallback callback) {
- XCTAssertEqualObjects(request.APIKey, kAPIKey);
- XCTAssertEqualObjects(request.providerID, FIRGoogleAuthProviderID);
- XCTAssertTrue(request.returnSecureToken);
- dispatch_async(FIRAuthGlobalWorkQueue(), ^() {
- id mockVerifyAssertionResponse = OCMClassMock([FIRVerifyAssertionResponse class]);
- OCMStub([mockVerifyAssertionResponse federatedID]).andReturn(kGoogleID);
- OCMStub([mockVerifyAssertionResponse providerID]).andReturn(FIRGoogleAuthProviderID);
- OCMStub([mockVerifyAssertionResponse localID]).andReturn(kLocalID);
- OCMStub([mockVerifyAssertionResponse displayName]).andReturn(kGoogleDisplayName);
- [self stubTokensWithMockResponse:mockVerifyAssertionResponse];
- callback(mockVerifyAssertionResponse, nil);
- });
- });
- [self expectGetAccountInfoGoogle];
- XCTestExpectation *expectation = [self expectationWithDescription:@"callback"];
- [[FIRAuth auth] signOut:NULL];
- id mockProvider = OCMClassMock([FIROAuthProvider class]);
- OCMExpect([mockProvider getCredentialWithUIDelegate:[OCMArg any] completion:[OCMArg any]])
- .andCallBlock2(^(id<FIRAuthUIDelegate> delegate, FIRAuthCredentialCallback callback) {
- dispatch_async(FIRAuthGlobalWorkQueue(), ^() {
- FIROAuthCredential *credential =
- [[FIROAuthCredential alloc] initWithProviderID:FIRGoogleAuthProviderID
- sessionID:kOAuthSessionID
- OAuthResponseURLString:kOAuthRequestURI];
- callback(credential, nil);
- });
- });
- [[FIRAuth auth]
- signInWithProvider:mockProvider
- UIDelegate:nil
- completion:^(FIRAuthDataResult *_Nullable authResult, NSError *_Nullable error) {
- XCTAssertTrue([NSThread isMainThread]);
- [self assertUserGoogle:authResult.user];
- XCTAssertNil(error);
- [expectation fulfill];
- }];
- [self waitForExpectationsWithTimeout:kExpectationTimeout handler:nil];
- OCMVerifyAll(_mockBackend);
- }
- /** @fn testSignInWithProviderFailure
- @brief Tests a failed @c signInWithProvider:UIDelegate:completion: call with the error code
- FIRAuthErrorCodeWebSignInUserInteractionFailure.
- */
- - (void)testSignInWithProviderFailure {
- OCMExpect([_mockBackend verifyAssertion:[OCMArg any] callback:[OCMArg any]])
- .andDispatchError2([FIRAuthErrorUtils
- webSignInUserInteractionFailureWithReason:kFakeWebSignInUserInteractionFailureReason]);
- [[FIRAuth auth] signOut:NULL];
- id mockProvider = OCMClassMock([FIROAuthProvider class]);
- OCMExpect([mockProvider getCredentialWithUIDelegate:[OCMArg any] completion:[OCMArg any]])
- .andCallBlock2(^(id<FIRAuthUIDelegate> delegate, FIRAuthCredentialCallback callback) {
- dispatch_async(FIRAuthGlobalWorkQueue(), ^() {
- FIROAuthCredential *credential =
- [[FIROAuthCredential alloc] initWithProviderID:FIRGoogleAuthProviderID
- sessionID:kOAuthSessionID
- OAuthResponseURLString:kOAuthRequestURI];
- callback(credential, nil);
- });
- });
- XCTestExpectation *expectation = [self expectationWithDescription:@"callback"];
- [[FIRAuth auth]
- signInWithProvider:mockProvider
- UIDelegate:nil
- completion:^(FIRAuthDataResult *_Nullable authResult, NSError *_Nullable error) {
- XCTAssertTrue([NSThread isMainThread]);
- XCTAssertNil(authResult);
- XCTAssertEqual(error.code, FIRAuthErrorCodeWebSignInUserInteractionFailure);
- XCTAssertEqualObjects(error.userInfo[NSLocalizedFailureReasonErrorKey],
- kFakeWebSignInUserInteractionFailureReason);
- [expectation fulfill];
- }];
- [self waitForExpectationsWithTimeout:kExpectationTimeout handler:nil];
- OCMVerifyAll(_mockBackend);
- }
- /** @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.
- */
- - (void)testSignInWithGoogleAccountExistsError {
- OCMExpect([_mockBackend verifyAssertion:[OCMArg any] callback:[OCMArg any]])
- .andCallBlock2(^(FIRVerifyAssertionRequest *_Nullable request,
- FIRVerifyAssertionResponseCallback callback) {
- XCTAssertEqualObjects(request.APIKey, kAPIKey);
- XCTAssertEqualObjects(request.providerID, FIRGoogleAuthProviderID);
- XCTAssertEqualObjects(request.providerIDToken, kGoogleIDToken);
- XCTAssertEqualObjects(request.providerAccessToken, kGoogleAccessToken);
- XCTAssertTrue(request.returnSecureToken);
- dispatch_async(FIRAuthGlobalWorkQueue(), ^() {
- id mockVerifyAssertionResponse = OCMClassMock([FIRVerifyAssertionResponse class]);
- OCMStub([mockVerifyAssertionResponse needConfirmation]).andReturn(YES);
- OCMStub([mockVerifyAssertionResponse email]).andReturn(kEmail);
- [self stubTokensWithMockResponse:mockVerifyAssertionResponse];
- callback(mockVerifyAssertionResponse, nil);
- });
- });
- XCTestExpectation *expectation = [self expectationWithDescription:@"callback"];
- [[FIRAuth auth] signOut:NULL];
- FIRAuthCredential *googleCredential =
- [FIRGoogleAuthProvider credentialWithIDToken:kGoogleIDToken accessToken:kGoogleAccessToken];
- [[FIRAuth auth]
- signInWithCredential:googleCredential
- completion:^(FIRAuthDataResult *_Nullable result, NSError *_Nullable error) {
- XCTAssertTrue([NSThread isMainThread]);
- XCTAssertEqual(error.code, FIRAuthErrorCodeAccountExistsWithDifferentCredential);
- XCTAssertEqualObjects(error.userInfo[FIRAuthErrorUserInfoEmailKey], kEmail);
- [expectation fulfill];
- }];
- [self waitForExpectationsWithTimeout:kExpectationTimeout handler:nil];
- OCMVerifyAll(_mockBackend);
- }
- /** @fn testSignInWithGoogleCredentialSuccess
- @brief Tests the flow of a successful @c signInWithCredential:completion: call with an
- Google Sign-In credential.
- */
- - (void)testSignInWithGoogleCredentialSuccess {
- OCMExpect([_mockBackend verifyAssertion:[OCMArg any] callback:[OCMArg any]])
- .andCallBlock2(^(FIRVerifyAssertionRequest *_Nullable request,
- FIRVerifyAssertionResponseCallback callback) {
- XCTAssertEqualObjects(request.APIKey, kAPIKey);
- XCTAssertEqualObjects(request.providerID, FIRGoogleAuthProviderID);
- XCTAssertEqualObjects(request.providerIDToken, kGoogleIDToken);
- XCTAssertEqualObjects(request.providerAccessToken, kGoogleAccessToken);
- XCTAssertTrue(request.returnSecureToken);
- dispatch_async(FIRAuthGlobalWorkQueue(), ^() {
- id mockVerifyAssertionResponse = OCMClassMock([FIRVerifyAssertionResponse class]);
- OCMStub([mockVerifyAssertionResponse federatedID]).andReturn(kGoogleID);
- OCMStub([mockVerifyAssertionResponse providerID]).andReturn(FIRGoogleAuthProviderID);
- OCMStub([mockVerifyAssertionResponse localID]).andReturn(kLocalID);
- OCMStub([mockVerifyAssertionResponse displayName]).andReturn(kGoogleDisplayName);
- [self stubTokensWithMockResponse:mockVerifyAssertionResponse];
- callback(mockVerifyAssertionResponse, nil);
- });
- });
- [self expectGetAccountInfoGoogle];
- XCTestExpectation *expectation = [self expectationWithDescription:@"callback"];
- [[FIRAuth auth] signOut:NULL];
- FIRAuthCredential *googleCredential =
- [FIRGoogleAuthProvider credentialWithIDToken:kGoogleIDToken accessToken:kGoogleAccessToken];
- [[FIRAuth auth]
- signInWithCredential:googleCredential
- completion:^(FIRAuthDataResult *_Nullable result, NSError *_Nullable error) {
- XCTAssertTrue([NSThread isMainThread]);
- [self assertUserGoogle:result.user];
- XCTAssertNil(error);
- [expectation fulfill];
- }];
- [self waitForExpectationsWithTimeout:kExpectationTimeout handler:nil];
- [self assertUserGoogle:[FIRAuth auth].currentUser];
- OCMVerifyAll(_mockBackend);
- }
- /** @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).
- */
- - (void)testSignInWithOAuthCredentialSuccess {
- OCMExpect([_mockBackend verifyAssertion:[OCMArg any] callback:[OCMArg any]])
- .andCallBlock2(^(FIRVerifyAssertionRequest *_Nullable request,
- FIRVerifyAssertionResponseCallback callback) {
- XCTAssertEqualObjects(request.APIKey, kAPIKey);
- XCTAssertEqualObjects(request.providerID, FIRGoogleAuthProviderID);
- XCTAssertEqualObjects(request.requestURI, kOAuthRequestURI);
- XCTAssertEqualObjects(request.sessionID, kOAuthSessionID);
- XCTAssertTrue(request.returnSecureToken);
- dispatch_async(FIRAuthGlobalWorkQueue(), ^() {
- id mockVerifyAssertionResponse = OCMClassMock([FIRVerifyAssertionResponse class]);
- OCMStub([mockVerifyAssertionResponse federatedID]).andReturn(kGoogleID);
- OCMStub([mockVerifyAssertionResponse providerID]).andReturn(FIRGoogleAuthProviderID);
- OCMStub([mockVerifyAssertionResponse localID]).andReturn(kLocalID);
- OCMStub([mockVerifyAssertionResponse displayName]).andReturn(kGoogleDisplayName);
- [self stubTokensWithMockResponse:mockVerifyAssertionResponse];
- callback(mockVerifyAssertionResponse, nil);
- });
- });
- [self expectGetAccountInfoGoogle];
- XCTestExpectation *expectation = [self expectationWithDescription:@"callback"];
- [[FIRAuth auth] signOut:NULL];
- id mockProvider = OCMClassMock([FIROAuthProvider class]);
- OCMExpect([mockProvider getCredentialWithUIDelegate:[OCMArg any] completion:[OCMArg any]])
- .andCallBlock2(^(id<FIRAuthUIDelegate> delegate, FIRAuthCredentialCallback callback) {
- dispatch_async(FIRAuthGlobalWorkQueue(), ^() {
- FIROAuthCredential *credential =
- [[FIROAuthCredential alloc] initWithProviderID:FIRGoogleAuthProviderID
- sessionID:kOAuthSessionID
- OAuthResponseURLString:kOAuthRequestURI];
- callback(credential, nil);
- });
- });
- [mockProvider
- getCredentialWithUIDelegate:nil
- completion:^(FIRAuthCredential *_Nullable credential,
- NSError *_Nullable error) {
- XCTAssertTrue([credential isKindOfClass:[FIROAuthCredential class]]);
- FIROAuthCredential *OAuthCredential = (FIROAuthCredential *)credential;
- XCTAssertEqualObjects(OAuthCredential.OAuthResponseURLString,
- kOAuthRequestURI);
- XCTAssertEqualObjects(OAuthCredential.sessionID, kOAuthSessionID);
- [[FIRAuth auth] signInWithCredential:OAuthCredential
- completion:^(FIRAuthDataResult *_Nullable result,
- NSError *_Nullable error) {
- XCTAssertTrue([NSThread isMainThread]);
- [self assertUserGoogle:result.user];
- XCTAssertNil(error);
- [expectation fulfill];
- }];
- }];
- [self waitForExpectationsWithTimeout:kExpectationTimeout handler:nil];
- [self assertUserGoogle:[FIRAuth auth].currentUser];
- OCMVerifyAll(_mockBackend);
- }
- #endif // TARGET_OS_IOS
- /** @fn testSignInWithCredentialSuccess
- @brief Tests the flow of a successful @c signInWithCredential:completion: call
- with an Google Sign-In credential.
- */
- - (void)testSignInWithCredentialSuccess {
- OCMExpect([_mockBackend verifyAssertion:[OCMArg any] callback:[OCMArg any]])
- .andCallBlock2(^(FIRVerifyAssertionRequest *_Nullable request,
- FIRVerifyAssertionResponseCallback callback) {
- XCTAssertEqualObjects(request.APIKey, kAPIKey);
- XCTAssertEqualObjects(request.providerID, FIRGoogleAuthProviderID);
- XCTAssertEqualObjects(request.providerIDToken, kGoogleIDToken);
- XCTAssertEqualObjects(request.providerAccessToken, kGoogleAccessToken);
- XCTAssertTrue(request.returnSecureToken);
- dispatch_async(FIRAuthGlobalWorkQueue(), ^() {
- id mockVerifyAssertionResponse = OCMClassMock([FIRVerifyAssertionResponse class]);
- OCMStub([mockVerifyAssertionResponse federatedID]).andReturn(kGoogleID);
- OCMStub([mockVerifyAssertionResponse providerID]).andReturn(FIRGoogleAuthProviderID);
- OCMStub([mockVerifyAssertionResponse localID]).andReturn(kLocalID);
- OCMStub([mockVerifyAssertionResponse displayName]).andReturn(kGoogleDisplayName);
- OCMStub([mockVerifyAssertionResponse profile]).andReturn([[self class] googleProfile]);
- OCMStub([mockVerifyAssertionResponse username]).andReturn(kDisplayName);
- [self stubTokensWithMockResponse:mockVerifyAssertionResponse];
- callback(mockVerifyAssertionResponse, nil);
- });
- });
- [self expectGetAccountInfoGoogle];
- XCTestExpectation *expectation = [self expectationWithDescription:@"callback"];
- [[FIRAuth auth] signOut:NULL];
- FIRAuthCredential *googleCredential =
- [FIRGoogleAuthProvider credentialWithIDToken:kGoogleIDToken accessToken:kGoogleAccessToken];
- [[FIRAuth auth]
- signInWithCredential:googleCredential
- completion:^(FIRAuthDataResult *_Nullable authResult, NSError *_Nullable error) {
- XCTAssertTrue([NSThread isMainThread]);
- [self assertUserGoogle:authResult.user];
- XCTAssertEqualObjects(authResult.additionalUserInfo.profile,
- [[self class] googleProfile]);
- XCTAssertEqualObjects(authResult.additionalUserInfo.username, kDisplayName);
- XCTAssertEqualObjects(authResult.additionalUserInfo.providerID,
- FIRGoogleAuthProviderID);
- XCTAssertNil(error);
- [expectation fulfill];
- }];
- [self waitForExpectationsWithTimeout:kExpectationTimeout handler:nil];
- [self assertUserGoogle:[FIRAuth auth].currentUser];
- OCMVerifyAll(_mockBackend);
- }
- /** @fn testSignInWithGoogleCredentialFailure
- @brief Tests the flow of a failed @c signInWithCredential:completion: call with an
- Google Sign-In credential.
- */
- - (void)testSignInWithGoogleCredentialFailure {
- OCMExpect([_mockBackend verifyAssertion:[OCMArg any] callback:[OCMArg any]])
- .andDispatchError2([FIRAuthErrorUtils emailAlreadyInUseErrorWithEmail:kGoogleEmail]);
- XCTestExpectation *expectation = [self expectationWithDescription:@"callback"];
- [[FIRAuth auth] signOut:NULL];
- FIRAuthCredential *googleCredential =
- [FIRGoogleAuthProvider credentialWithIDToken:kGoogleIDToken accessToken:kGoogleAccessToken];
- [[FIRAuth auth]
- signInWithCredential:googleCredential
- completion:^(FIRAuthDataResult *_Nullable result, NSError *_Nullable error) {
- XCTAssertTrue([NSThread isMainThread]);
- XCTAssertNil(result.user);
- XCTAssertEqual(error.code, FIRAuthErrorCodeEmailAlreadyInUse);
- XCTAssertNotNil(error.userInfo[NSLocalizedDescriptionKey]);
- [expectation fulfill];
- }];
- [self waitForExpectationsWithTimeout:kExpectationTimeout handler:nil];
- XCTAssertNil([FIRAuth auth].currentUser);
- OCMVerifyAll(_mockBackend);
- }
- /** @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.
- */
- - (void)testSignInWithAppleCredentialFullNameInRequestSuccess {
- NSPersonNameComponents *fullName = [[NSPersonNameComponents alloc] init];
- fullName.givenName = kFakeGivenName;
- fullName.familyName = kFakeFamilyName;
- OCMExpect([_mockBackend verifyAssertion:[OCMArg any] callback:[OCMArg any]])
- .andCallBlock2(^(FIRVerifyAssertionRequest *_Nullable request,
- FIRVerifyAssertionResponseCallback callback) {
- XCTAssertEqualObjects(request.APIKey, kAPIKey);
- XCTAssertEqualObjects(request.providerID, kAppleAuthProviderID);
- XCTAssertEqualObjects(request.providerIDToken, kAppleIDToken);
- // Verify that the full name is passed to the backend request.
- XCTAssertEqualObjects(request.fullName, fullName);
- XCTAssertTrue(request.returnSecureToken);
- dispatch_async(FIRAuthGlobalWorkQueue(), ^() {
- id mockVerifyAssertionResponse = OCMClassMock([FIRVerifyAssertionResponse class]);
- OCMStub([mockVerifyAssertionResponse providerID]).andReturn(kAppleAuthProviderID);
- [self stubTokensWithMockResponse:mockVerifyAssertionResponse];
- callback(mockVerifyAssertionResponse, nil);
- });
- });
- OCMExpect([_mockBackend getAccountInfo:[OCMArg any] callback:[OCMArg any]])
- .andCallBlock2(^(FIRGetAccountInfoRequest *_Nullable request,
- FIRGetAccountInfoResponseCallback callback) {
- XCTAssertEqualObjects(request.APIKey, kAPIKey);
- XCTAssertEqualObjects(request.accessToken, kAccessToken);
- dispatch_async(FIRAuthGlobalWorkQueue(), ^() {
- id mockAppleUserInfo = OCMClassMock([FIRGetAccountInfoResponseProviderUserInfo class]);
- OCMStub([mockAppleUserInfo providerID]).andReturn(kAppleAuthProviderID);
- id mockGetAccountInfoResponseUser = OCMClassMock([FIRGetAccountInfoResponseUser class]);
- OCMStub([mockGetAccountInfoResponseUser providerUserInfo])
- .andReturn((@[ mockAppleUserInfo ]));
- id mockGetAccountInfoResponse = OCMClassMock([FIRGetAccountInfoResponse class]);
- OCMStub([mockGetAccountInfoResponse users]).andReturn(@[
- mockGetAccountInfoResponseUser
- ]);
- callback(mockGetAccountInfoResponse, nil);
- });
- });
- XCTestExpectation *expectation = [self expectationWithDescription:@"callback"];
- [[FIRAuth auth] signOut:NULL];
- FIRAuthCredential *appleCredential = [FIROAuthProvider appleCredentialWithIDToken:kAppleIDToken
- rawNonce:nil
- fullName:fullName];
- [[FIRAuth auth]
- signInWithCredential:appleCredential
- completion:^(FIRAuthDataResult *_Nullable authResult, NSError *_Nullable error) {
- XCTAssertTrue([NSThread isMainThread]);
- XCTAssertNil(error);
- [expectation fulfill];
- }];
- [self waitForExpectationsWithTimeout:kExpectationTimeout handler:nil];
- XCTAssertNotNil([FIRAuth auth].currentUser);
- OCMVerifyAll(_mockBackend);
- }
- /** @fn testSignInAnonymouslySuccess
- @brief Tests the flow of a successful @c signInAnonymouslyWithCompletion: call.
- */
- - (void)testSignInAnonymouslySuccess {
- OCMExpect([_mockBackend signUpNewUser:[OCMArg any] callback:[OCMArg any]])
- .andCallBlock2(
- ^(FIRSignUpNewUserRequest *_Nullable request, FIRSignupNewUserCallback callback) {
- XCTAssertEqualObjects(request.APIKey, kAPIKey);
- XCTAssertNil(request.email);
- XCTAssertNil(request.password);
- XCTAssertTrue(request.returnSecureToken);
- dispatch_async(FIRAuthGlobalWorkQueue(), ^() {
- id mockSignUpNewUserResponse = OCMClassMock([FIRSignUpNewUserResponse class]);
- [self stubTokensWithMockResponse:mockSignUpNewUserResponse];
- callback(mockSignUpNewUserResponse, nil);
- });
- });
- [self expectGetAccountInfoAnonymous];
- XCTestExpectation *expectation = [self expectationWithDescription:@"callback"];
- [[FIRAuth auth] signOut:NULL];
- [[FIRAuth auth] signInAnonymouslyWithCompletion:^(FIRAuthDataResult *_Nullable result,
- NSError *_Nullable error) {
- XCTAssertTrue([NSThread isMainThread]);
- [self assertUserAnonymous:result.user];
- XCTAssertNil(error);
- FIRAdditionalUserInfo *userInfo = result.additionalUserInfo;
- XCTAssertNotNil(userInfo);
- XCTAssertTrue(userInfo.isNewUser);
- XCTAssertNil(userInfo.username);
- XCTAssertNil(userInfo.profile);
- XCTAssertNil(userInfo.providerID);
- [expectation fulfill];
- }];
- [self waitForExpectationsWithTimeout:kExpectationTimeout handler:nil];
- [self assertUserAnonymous:[FIRAuth auth].currentUser];
- OCMVerifyAll(_mockBackend);
- }
- /** @fn testSignInAnonymouslyFailure
- @brief Tests the flow of a failed @c signInAnonymouslyWithCompletion: call.
- */
- - (void)testSignInAnonymouslyFailure {
- OCMExpect([_mockBackend signUpNewUser:[OCMArg any] callback:[OCMArg any]])
- .andDispatchError2([FIRAuthErrorUtils operationNotAllowedErrorWithMessage:nil]);
- XCTestExpectation *expectation = [self expectationWithDescription:@"callback"];
- [[FIRAuth auth] signOut:NULL];
- [[FIRAuth auth] signInAnonymouslyWithCompletion:^(FIRAuthDataResult *_Nullable result,
- NSError *_Nullable error) {
- XCTAssertTrue([NSThread isMainThread]);
- XCTAssertNil(result.user);
- XCTAssertEqual(error.code, FIRAuthErrorCodeOperationNotAllowed);
- XCTAssertNotNil(error.userInfo[NSLocalizedDescriptionKey]);
- [expectation fulfill];
- }];
- [self waitForExpectationsWithTimeout:kExpectationTimeout handler:nil];
- XCTAssertNil([FIRAuth auth].currentUser);
- OCMVerifyAll(_mockBackend);
- }
- /** @fn testSignInAnonymouslyAndRetrieveDataSuccess
- @brief Tests the flow of a successful @c signInAnonymouslyAndRetrieveDataWithCompletion: call.
- */
- - (void)testSignInAnonymouslyAndRetrieveDataSuccess {
- OCMExpect([_mockBackend signUpNewUser:[OCMArg any] callback:[OCMArg any]])
- .andCallBlock2(
- ^(FIRSignUpNewUserRequest *_Nullable request, FIRSignupNewUserCallback callback) {
- XCTAssertEqualObjects(request.APIKey, kAPIKey);
- XCTAssertNil(request.email);
- XCTAssertNil(request.password);
- XCTAssertTrue(request.returnSecureToken);
- dispatch_async(FIRAuthGlobalWorkQueue(), ^() {
- id mockSignUpNewUserResponse = OCMClassMock([FIRSignUpNewUserResponse class]);
- [self stubTokensWithMockResponse:mockSignUpNewUserResponse];
- callback(mockSignUpNewUserResponse, nil);
- });
- });
- [self expectGetAccountInfoAnonymous];
- XCTestExpectation *expectation = [self expectationWithDescription:@"callback"];
- [[FIRAuth auth] signOut:NULL];
- [[FIRAuth auth] signInAnonymouslyWithCompletion:^(FIRAuthDataResult *_Nullable result,
- NSError *_Nullable error) {
- XCTAssertTrue([NSThread isMainThread]);
- [self assertUserAnonymous:result.user];
- XCTAssertNil(error);
- [expectation fulfill];
- }];
- [self waitForExpectationsWithTimeout:kExpectationTimeout handler:nil];
- [self assertUserAnonymous:[FIRAuth auth].currentUser];
- OCMVerifyAll(_mockBackend);
- }
- /** @fn testSignInAnonymouslyAndRetrieveDataFailure
- @brief Tests the flow of a failed @c signInAnonymouslyAndRetrieveDataWithCompletion: call.
- */
- - (void)testSignInAnonymouslyAndRetrieveDataFailure {
- OCMExpect([_mockBackend signUpNewUser:[OCMArg any] callback:[OCMArg any]])
- .andDispatchError2([FIRAuthErrorUtils operationNotAllowedErrorWithMessage:nil]);
- XCTestExpectation *expectation = [self expectationWithDescription:@"callback"];
- [[FIRAuth auth] signOut:NULL];
- [[FIRAuth auth] signInAnonymouslyWithCompletion:^(FIRAuthDataResult *_Nullable result,
- NSError *_Nullable error) {
- XCTAssertTrue([NSThread isMainThread]);
- XCTAssertNil(result);
- XCTAssertEqual(error.code, FIRAuthErrorCodeOperationNotAllowed);
- XCTAssertNotNil(error.userInfo[NSLocalizedDescriptionKey]);
- [expectation fulfill];
- }];
- [self waitForExpectationsWithTimeout:kExpectationTimeout handler:nil];
- XCTAssertNil([FIRAuth auth].currentUser);
- OCMVerifyAll(_mockBackend);
- }
- /** @fn testSignInWithCustomTokenSuccess
- @brief Tests the flow of a successful @c signInWithCustomToken:completion: call.
- */
- - (void)testSignInWithCustomTokenSuccess {
- OCMExpect([_mockBackend verifyCustomToken:[OCMArg any] callback:[OCMArg any]])
- .andCallBlock2(^(FIRVerifyCustomTokenRequest *_Nullable request,
- FIRVerifyCustomTokenResponseCallback callback) {
- XCTAssertEqualObjects(request.APIKey, kAPIKey);
- XCTAssertEqualObjects(request.token, kCustomToken);
- XCTAssertTrue(request.returnSecureToken);
- dispatch_async(FIRAuthGlobalWorkQueue(), ^() {
- id mockVerifyCustomTokenResponse = OCMClassMock([FIRVerifyCustomTokenResponse class]);
- [self stubTokensWithMockResponse:mockVerifyCustomTokenResponse];
- callback(mockVerifyCustomTokenResponse, nil);
- });
- });
- [self expectGetAccountInfo];
- XCTestExpectation *expectation = [self expectationWithDescription:@"callback"];
- [[FIRAuth auth] signOut:NULL];
- [[FIRAuth auth]
- signInWithCustomToken:kCustomToken
- completion:^(FIRAuthDataResult *_Nullable result, NSError *_Nullable error) {
- XCTAssertTrue([NSThread isMainThread]);
- [self assertUser:result.user];
- XCTAssertNil(error);
- [expectation fulfill];
- }];
- [self waitForExpectationsWithTimeout:kExpectationTimeout handler:nil];
- [self assertUser:[FIRAuth auth].currentUser];
- OCMVerifyAll(_mockBackend);
- }
- /** @fn testSignInWithCustomTokenFailure
- @brief Tests the flow of a failed @c signInWithCustomToken:completion: call.
- */
- - (void)testSignInWithCustomTokenFailure {
- OCMExpect([_mockBackend verifyCustomToken:[OCMArg any] callback:[OCMArg any]])
- .andDispatchError2([FIRAuthErrorUtils invalidCustomTokenErrorWithMessage:nil]);
- XCTestExpectation *expectation = [self expectationWithDescription:@"callback"];
- [[FIRAuth auth] signOut:NULL];
- [[FIRAuth auth]
- signInWithCustomToken:kCustomToken
- completion:^(FIRAuthDataResult *_Nullable result, NSError *_Nullable error) {
- XCTAssertTrue([NSThread isMainThread]);
- XCTAssertNil(result.user);
- XCTAssertEqual(error.code, FIRAuthErrorCodeInvalidCustomToken);
- XCTAssertNotNil(error.userInfo[NSLocalizedDescriptionKey]);
- [expectation fulfill];
- }];
- [self waitForExpectationsWithTimeout:kExpectationTimeout handler:nil];
- XCTAssertNil([FIRAuth auth].currentUser);
- OCMVerifyAll(_mockBackend);
- }
- /** @fn testSignInAndRetrieveDataWithCustomTokenSuccess
- @brief Tests the flow of a successful @c signInAndRetrieveDataWithCustomToken:completion: call.
- */
- - (void)testSignInAndRetrieveDataWithCustomTokenSuccess {
- OCMExpect([_mockBackend verifyCustomToken:[OCMArg any] callback:[OCMArg any]])
- .andCallBlock2(^(FIRVerifyCustomTokenRequest *_Nullable request,
- FIRVerifyCustomTokenResponseCallback callback) {
- XCTAssertEqualObjects(request.APIKey, kAPIKey);
- XCTAssertEqualObjects(request.token, kCustomToken);
- XCTAssertTrue(request.returnSecureToken);
- dispatch_async(FIRAuthGlobalWorkQueue(), ^() {
- id mockVerifyCustomTokenResponse = OCMClassMock([FIRVerifyCustomTokenResponse class]);
- [self stubTokensWithMockResponse:mockVerifyCustomTokenResponse];
- callback(mockVerifyCustomTokenResponse, nil);
- });
- });
- [self expectGetAccountInfo];
- XCTestExpectation *expectation = [self expectationWithDescription:@"callback"];
- [[FIRAuth auth] signOut:NULL];
- [[FIRAuth auth]
- signInWithCustomToken:kCustomToken
- completion:^(FIRAuthDataResult *_Nullable result, NSError *_Nullable error) {
- XCTAssertTrue([NSThread isMainThread]);
- [self assertUser:result.user];
- XCTAssertFalse(result.additionalUserInfo.isNewUser);
- XCTAssertNil(error);
- [expectation fulfill];
- }];
- [self waitForExpectationsWithTimeout:kExpectationTimeout handler:nil];
- [self assertUser:[FIRAuth auth].currentUser];
- OCMVerifyAll(_mockBackend);
- }
- /** @fn testSignInAndRetrieveDataWithCustomTokenFailure
- @brief Tests the flow of a failed @c signInAndRetrieveDataWithCustomToken:completion: call.
- */
- - (void)testSignInAndRetrieveDataWithCustomTokenFailure {
- OCMExpect([_mockBackend verifyCustomToken:[OCMArg any] callback:[OCMArg any]])
- .andDispatchError2([FIRAuthErrorUtils invalidCustomTokenErrorWithMessage:nil]);
- XCTestExpectation *expectation = [self expectationWithDescription:@"callback"];
- [[FIRAuth auth] signOut:NULL];
- [[FIRAuth auth]
- signInWithCustomToken:kCustomToken
- completion:^(FIRAuthDataResult *_Nullable result, NSError *_Nullable error) {
- XCTAssertTrue([NSThread isMainThread]);
- XCTAssertNil(result);
- XCTAssertEqual(error.code, FIRAuthErrorCodeInvalidCustomToken);
- XCTAssertNotNil(error.userInfo[NSLocalizedDescriptionKey]);
- [expectation fulfill];
- }];
- [self waitForExpectationsWithTimeout:kExpectationTimeout handler:nil];
- XCTAssertNil([FIRAuth auth].currentUser);
- OCMVerifyAll(_mockBackend);
- }
- #if TARGET_OS_IOS && !TARGET_OS_MACCATALYST
- /** @fn testCreateUserWithEmailPasswordWithRecaptchaVerificationSuccess
- @brief Tests the flow of a successful @c createUserWithEmail:password:completion: call.
- */
- - (void)testCreateUserWithEmailPasswordWithRecaptchaVerificationSuccess {
- id mockVerifier = OCMClassMock([FIRAuthRecaptchaVerifier class]);
- OCMStub([mockVerifier sharedRecaptchaVerifier:[FIRAuth auth]]).andReturn(mockVerifier);
- OCMExpect([mockVerifier enablementStatusForProvider:FIRAuthRecaptchaProviderPassword])
- .andReturn(YES);
- FIRSignUpNewUserRequest *constRequestWithRecaptchaToken =
- [[FIRSignUpNewUserRequest alloc] initWithEmail:kEmail
- password:kFakePassword
- displayName:kDisplayName
- requestConfiguration:[FIRAuth auth].requestConfiguration];
- [constRequestWithRecaptchaToken injectRecaptchaFields:kFakeRecaptchaResponse
- recaptchaVersion:kFakeRecaptchaVersion];
- OCMStub([mockVerifier
- injectRecaptchaFields:[OCMArg any]
- provider:FIRAuthRecaptchaProviderPassword
- action:FIRAuthRecaptchaActionSignUpPassword
- completion:([OCMArg invokeBlockWithArgs:constRequestWithRecaptchaToken, nil])]);
- OCMExpect([_mockBackend signUpNewUser:[OCMArg any] callback:[OCMArg any]])
- .andCallBlock2(
- ^(FIRSignUpNewUserRequest *_Nullable request, FIRSignupNewUserCallback callback) {
- XCTAssertEqualObjects(request.APIKey, kAPIKey);
- XCTAssertEqualObjects(request.email, kEmail);
- XCTAssertEqualObjects(request.password, kFakePassword);
- XCTAssertTrue(request.returnSecureToken);
- dispatch_async(FIRAuthGlobalWorkQueue(), ^() {
- id mockSignUpNewUserResponse = OCMClassMock([FIRSignUpNewUserResponse class]);
- [self stubTokensWithMockResponse:mockSignUpNewUserResponse];
- callback(mockSignUpNewUserResponse, nil);
- });
- });
- [self expectGetAccountInfo];
- XCTestExpectation *expectation = [self expectationWithDescription:@"callback"];
- [[FIRAuth auth] signOut:NULL];
- [[FIRAuth auth]
- createUserWithEmail:kEmail
- password:kFakePassword
- completion:^(FIRAuthDataResult *_Nullable result, NSError *_Nullable error) {
- XCTAssertTrue([NSThread isMainThread]);
- [self assertUser:result.user];
- XCTAssertNil(error);
- [expectation fulfill];
- }];
- [self waitForExpectationsWithTimeout:kExpectationTimeout handler:nil];
- [self assertUser:[FIRAuth auth].currentUser];
- }
- /** @fn testCreateUserWithEmailPasswordWithRecaptchaFallbackSuccess
- @brief Tests the flow of a successful @c createUserWithEmail:password:completion: call.
- */
- - (void)testCreateUserWithEmailPasswordWithRecaptchaFallbackSuccess {
- id mockVerifier = OCMClassMock([FIRAuthRecaptchaVerifier class]);
- OCMStub([mockVerifier sharedRecaptchaVerifier:[FIRAuth auth]]).andReturn(mockVerifier);
- OCMExpect([mockVerifier enablementStatusForProvider:FIRAuthRecaptchaProviderPassword])
- .andReturn(NO);
- FIRSignUpNewUserRequest *constRequestWithRecaptchaToken =
- [[FIRSignUpNewUserRequest alloc] initWithEmail:kEmail
- password:kFakePassword
- displayName:kDisplayName
- requestConfiguration:[FIRAuth auth].requestConfiguration];
- [constRequestWithRecaptchaToken injectRecaptchaFields:kFakeRecaptchaResponse
- recaptchaVersion:kFakeRecaptchaVersion];
- OCMStub([mockVerifier
- injectRecaptchaFields:[OCMArg any]
- provider:FIRAuthRecaptchaProviderPassword
- action:FIRAuthRecaptchaActionSignUpPassword
- completion:([OCMArg invokeBlockWithArgs:constRequestWithRecaptchaToken, nil])]);
- OCMExpect([_mockBackend signUpNewUser:[OCMArg any] callback:[OCMArg any]])
- .andCallBlock2(^(FIRSignUpNewUserRequest *_Nullable request,
- FIRSignupNewUserCallback callback) {
- XCTAssertEqualObjects(request.APIKey, kAPIKey);
- XCTAssertEqualObjects(request.email, kEmail);
- XCTAssertEqualObjects(request.password, kFakePassword);
- XCTAssertTrue(request.returnSecureToken);
- NSError *underlyingError =
- [[NSError alloc] initWithDomain:FIRAuthErrorDomain
- code:FIRAuthErrorCodeInternalError
- userInfo:@{
- FIRAuthErrorUserInfoDeserializedResponseKey :
- @{@"message" : @"MISSING_RECAPTCHA_TOKEN"}
- }];
- NSError *error = [[NSError alloc] initWithDomain:FIRAuthErrorDomain
- code:FIRAuthErrorCodeInternalError
- userInfo:@{NSUnderlyingErrorKey : underlyingError}];
- dispatch_async(FIRAuthGlobalWorkQueue(), ^() {
- callback(nil, error);
- });
- });
- OCMExpect([_mockBackend signUpNewUser:[OCMArg any] callback:[OCMArg any]])
- .andCallBlock2(
- ^(FIRSignUpNewUserRequest *_Nullable request, FIRSignupNewUserCallback callback) {
- XCTAssertEqualObjects(request.APIKey, kAPIKey);
- XCTAssertEqualObjects(request.email, kEmail);
- XCTAssertEqualObjects(request.password, kFakePassword);
- XCTAssertTrue(request.returnSecureToken);
- dispatch_async(FIRAuthGlobalWorkQueue(), ^() {
- id mockSignUpNewUserResponse = OCMClassMock([FIRSignUpNewUserResponse class]);
- [self stubTokensWithMockResponse:mockSignUpNewUserResponse];
- callback(mockSignUpNewUserResponse, nil);
- });
- });
- [self expectGetAccountInfo];
- XCTestExpectation *expectation = [self expectationWithDescription:@"callback"];
- [[FIRAuth auth] signOut:NULL];
- [[FIRAuth auth]
- createUserWithEmail:kEmail
- password:kFakePassword
- completion:^(FIRAuthDataResult *_Nullable result, NSError *_Nullable error) {
- XCTAssertTrue([NSThread isMainThread]);
- [self assertUser:result.user];
- XCTAssertNil(error);
- [expectation fulfill];
- }];
- [self waitForExpectationsWithTimeout:kExpectationTimeout handler:nil];
- [self assertUser:[FIRAuth auth].currentUser];
- }
- #endif
- /** @fn testCreateUserWithEmailPasswordSuccess
- @brief Tests the flow of a successful @c createUserWithEmail:password:completion: call.
- */
- - (void)testCreateUserWithEmailPasswordSuccess {
- OCMExpect([_mockBackend signUpNewUser:[OCMArg any] callback:[OCMArg any]])
- .andCallBlock2(
- ^(FIRSignUpNewUserRequest *_Nullable request, FIRSignupNewUserCallback callback) {
- XCTAssertEqualObjects(request.APIKey, kAPIKey);
- XCTAssertEqualObjects(request.email, kEmail);
- XCTAssertEqualObjects(request.password, kFakePassword);
- XCTAssertTrue(request.returnSecureToken);
- dispatch_async(FIRAuthGlobalWorkQueue(), ^() {
- id mockSignUpNewUserResponse = OCMClassMock([FIRSignUpNewUserResponse class]);
- [self stubTokensWithMockResponse:mockSignUpNewUserResponse];
- callback(mockSignUpNewUserResponse, nil);
- });
- });
- [self expectGetAccountInfo];
- XCTestExpectation *expectation = [self expectationWithDescription:@"callback"];
- [[FIRAuth auth] signOut:NULL];
- [[FIRAuth auth]
- createUserWithEmail:kEmail
- password:kFakePassword
- completion:^(FIRAuthDataResult *_Nullable result, NSError *_Nullable error) {
- XCTAssertTrue([NSThread isMainThread]);
- [self assertUser:result.user];
- XCTAssertNil(error);
- [expectation fulfill];
- }];
- [self waitForExpectationsWithTimeout:kExpectationTimeout handler:nil];
- [self assertUser:[FIRAuth auth].currentUser];
- OCMVerifyAll(_mockBackend);
- }
- /** @fn testCreateUserWithEmailPasswordFailure
- @brief Tests the flow of a failed @c createUserWithEmail:password:completion: call.
- */
- - (void)testCreateUserWithEmailPasswordFailure {
- NSString *reason = @"Password shouldn't be a common word.";
- OCMExpect([_mockBackend signUpNewUser:[OCMArg any] callback:[OCMArg any]])
- .andDispatchError2([FIRAuthErrorUtils weakPasswordErrorWithServerResponseReason:reason]);
- XCTestExpectation *expectation = [self expectationWithDescription:@"callback"];
- [[FIRAuth auth] signOut:NULL];
- [[FIRAuth auth]
- createUserWithEmail:kEmail
- password:kFakePassword
- completion:^(FIRAuthDataResult *_Nullable result, NSError *_Nullable error) {
- XCTAssertTrue([NSThread isMainThread]);
- XCTAssertNil(result.user);
- XCTAssertEqual(error.code, FIRAuthErrorCodeWeakPassword);
- XCTAssertNotNil(error.userInfo[NSLocalizedDescriptionKey]);
- XCTAssertEqualObjects(error.userInfo[NSLocalizedFailureReasonErrorKey], reason);
- [expectation fulfill];
- }];
- [self waitForExpectationsWithTimeout:kExpectationTimeout handler:nil];
- XCTAssertNil([FIRAuth auth].currentUser);
- OCMVerifyAll(_mockBackend);
- }
- /** @fn testCreateUserAndRetrieveDataWithEmailPasswordSuccess
- @brief Tests the flow of a successful @c createUserAndRetrieveDataWithEmail:password:completion:
- call.
- */
- - (void)testCreateUserAndRetrieveDataWithEmailPasswordSuccess {
- OCMExpect([_mockBackend signUpNewUser:[OCMArg any] callback:[OCMArg any]])
- .andCallBlock2(
- ^(FIRSignUpNewUserRequest *_Nullable request, FIRSignupNewUserCallback callback) {
- XCTAssertEqualObjects(request.APIKey, kAPIKey);
- XCTAssertEqualObjects(request.email, kEmail);
- XCTAssertEqualObjects(request.password, kFakePassword);
- XCTAssertTrue(request.returnSecureToken);
- dispatch_async(FIRAuthGlobalWorkQueue(), ^() {
- id mockSignUpNewUserResponse = OCMClassMock([FIRSignUpNewUserResponse class]);
- [self stubTokensWithMockResponse:mockSignUpNewUserResponse];
- callback(mockSignUpNewUserResponse, nil);
- });
- });
- [self expectGetAccountInfo];
- XCTestExpectation *expectation = [self expectationWithDescription:@"callback"];
- [[FIRAuth auth] signOut:NULL];
- [[FIRAuth auth]
- createUserWithEmail:kEmail
- password:kFakePassword
- completion:^(FIRAuthDataResult *_Nullable result, NSError *_Nullable error) {
- XCTAssertTrue([NSThread isMainThread]);
- [self assertUser:result.user];
- XCTAssertTrue(result.additionalUserInfo.isNewUser);
- XCTAssertNil(error);
- [expectation fulfill];
- }];
- [self waitForExpectationsWithTimeout:kExpectationTimeout handler:nil];
- [self assertUser:[FIRAuth auth].currentUser];
- OCMVerifyAll(_mockBackend);
- }
- /** @fn testCreateUserAndRetrieveDataWithEmailPasswordFailure
- @brief Tests the flow of a failed @c createUserAndRetrieveDataWithEmail:password:completion:
- call.
- */
- - (void)testCreateUserAndRetrieveDataWithEmailPasswordFailure {
- NSString *reason = @"Password shouldn't be a common word.";
- OCMExpect([_mockBackend signUpNewUser:[OCMArg any] callback:[OCMArg any]])
- .andDispatchError2([FIRAuthErrorUtils weakPasswordErrorWithServerResponseReason:reason]);
- XCTestExpectation *expectation = [self expectationWithDescription:@"callback"];
- [[FIRAuth auth] signOut:NULL];
- [[FIRAuth auth]
- createUserWithEmail:kEmail
- password:kFakePassword
- completion:^(FIRAuthDataResult *_Nullable result, NSError *_Nullable error) {
- XCTAssertTrue([NSThread isMainThread]);
- XCTAssertNil(result);
- XCTAssertEqual(error.code, FIRAuthErrorCodeWeakPassword);
- XCTAssertNotNil(error.userInfo[NSLocalizedDescriptionKey]);
- XCTAssertEqualObjects(error.userInfo[NSLocalizedFailureReasonErrorKey], reason);
- [expectation fulfill];
- }];
- [self waitForExpectationsWithTimeout:kExpectationTimeout handler:nil];
- XCTAssertNil([FIRAuth auth].currentUser);
- OCMVerifyAll(_mockBackend);
- }
- /** @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.
- */
- - (void)testCreateUserEmptyPasswordFailure {
- XCTestExpectation *expectation = [self expectationWithDescription:@"callback"];
- [[FIRAuth auth] signOut:NULL];
- [[FIRAuth auth]
- createUserWithEmail:kEmail
- password:@""
- completion:^(FIRAuthDataResult *_Nullable result, NSError *_Nullable error) {
- XCTAssertTrue([NSThread isMainThread]);
- XCTAssertEqual(error.code, FIRAuthErrorCodeWeakPassword);
- [expectation fulfill];
- }];
- [self waitForExpectationsWithTimeout:kExpectationTimeout handler:nil];
- }
- /** @fn testCreateUserEmptyEmailFailure
- @brief Tests the flow of a failed @c createUserWithEmail:password:completion: call due to an
- empty email adress. This error occurs on the client side, so there is no need to fake an RPC
- response.
- */
- - (void)testCreateUserEmptyEmailFailure {
- XCTestExpectation *expectation = [self expectationWithDescription:@"callback"];
- [[FIRAuth auth] signOut:NULL];
- [[FIRAuth auth]
- createUserWithEmail:@""
- password:kFakePassword
- completion:^(FIRAuthDataResult *_Nullable result, NSError *_Nullable error) {
- XCTAssertTrue([NSThread isMainThread]);
- XCTAssertEqual(error.code, FIRAuthErrorCodeMissingEmail);
- [expectation fulfill];
- }];
- [self waitForExpectationsWithTimeout:kExpectationTimeout handler:nil];
- }
- #if TARGET_OS_IOS && !TARGET_OS_MACCATALYST
- /** @fn testSendPasswordResetEmailWithRecaptchaSuccess
- @brief Tests the flow of a successful @c sendPasswordResetWithEmail:completion: call.
- */
- - (void)testSendPasswordResetEmailWithRecaptchaSuccess {
- id mockVerifier = OCMClassMock([FIRAuthRecaptchaVerifier class]);
- OCMStub([mockVerifier sharedRecaptchaVerifier:[FIRAuth auth]]).andReturn(mockVerifier);
- OCMExpect([mockVerifier enablementStatusForProvider:FIRAuthRecaptchaProviderPassword])
- .andReturn(YES);
- FIRGetOOBConfirmationCodeRequest *constRequestWithRecaptchaToken =
- [FIRGetOOBConfirmationCodeRequest
- passwordResetRequestWithEmail:kEmail
- actionCodeSettings:nil
- requestConfiguration:[FIRAuth auth].requestConfiguration];
- [constRequestWithRecaptchaToken injectRecaptchaFields:kFakeRecaptchaResponse
- recaptchaVersion:kFakeRecaptchaVersion];
- OCMStub([mockVerifier
- injectRecaptchaFields:[OCMArg any]
- provider:FIRAuthRecaptchaProviderPassword
- action:FIRAuthRecaptchaActionGetOobCode
- completion:([OCMArg invokeBlockWithArgs:constRequestWithRecaptchaToken, nil])]);
- OCMExpect([_mockBackend getOOBConfirmationCode:[OCMArg any] callback:[OCMArg any]])
- .andCallBlock2(^(FIRGetOOBConfirmationCodeRequest *_Nullable request,
- FIRGetOOBConfirmationCodeResponseCallback callback) {
- XCTAssertEqualObjects(request.APIKey, kAPIKey);
- XCTAssertEqualObjects(request.email, kEmail);
- dispatch_async(FIRAuthGlobalWorkQueue(), ^() {
- callback([[FIRGetOOBConfirmationCodeResponse alloc] init], nil);
- });
- });
- XCTestExpectation *expectation = [self expectationWithDescription:@"callback"];
- [[FIRAuth auth] sendPasswordResetWithEmail:kEmail
- completion:^(NSError *_Nullable error) {
- XCTAssertTrue([NSThread isMainThread]);
- XCTAssertNil(error);
- [expectation fulfill];
- }];
- [self waitForExpectationsWithTimeout:kExpectationTimeout handler:nil];
- }
- /** @fn testSendPasswordResetEmailWithRecaptchaFallbackSuccess
- @brief Tests the flow of a successful @c sendPasswordResetWithEmail:completion: call.
- */
- - (void)testSendPasswordResetEmailWithRecaptchaFallbackSuccess {
- id mockVerifier = OCMClassMock([FIRAuthRecaptchaVerifier class]);
- OCMStub([mockVerifier sharedRecaptchaVerifier:[FIRAuth auth]]).andReturn(mockVerifier);
- OCMExpect([mockVerifier enablementStatusForProvider:FIRAuthRecaptchaProviderPassword])
- .andReturn(NO);
- FIRGetOOBConfirmationCodeRequest *constRequestWithRecaptchaToken =
- [FIRGetOOBConfirmationCodeRequest
- passwordResetRequestWithEmail:kEmail
- actionCodeSettings:nil
- requestConfiguration:[FIRAuth auth].requestConfiguration];
- [constRequestWithRecaptchaToken injectRecaptchaFields:kFakeRecaptchaResponse
- recaptchaVersion:kFakeRecaptchaVersion];
- OCMStub([mockVerifier
- injectRecaptchaFields:[OCMArg any]
- provider:FIRAuthRecaptchaProviderPassword
- action:FIRAuthRecaptchaActionGetOobCode
- completion:([OCMArg invokeBlockWithArgs:constRequestWithRecaptchaToken, nil])]);
- OCMExpect([_mockBackend getOOBConfirmationCode:[OCMArg any] callback:[OCMArg any]])
- .andCallBlock2(^(FIRGetOOBConfirmationCodeRequest *_Nullable request,
- FIRGetOOBConfirmationCodeResponseCallback callback) {
- XCTAssertEqualObjects(request.APIKey, kAPIKey);
- XCTAssertEqualObjects(request.email, kEmail);
- NSError *underlyingError =
- [[NSError alloc] initWithDomain:FIRAuthErrorDomain
- code:FIRAuthErrorCodeInternalError
- userInfo:@{
- FIRAuthErrorUserInfoDeserializedResponseKey :
- @{@"message" : @"MISSING_RECAPTCHA_TOKEN"}
- }];
- NSError *error = [[NSError alloc] initWithDomain:FIRAuthErrorDomain
- code:FIRAuthErrorCodeInternalError
- userInfo:@{NSUnderlyingErrorKey : underlyingError}];
- dispatch_async(FIRAuthGlobalWorkQueue(), ^() {
- callback(nil, error);
- });
- });
- OCMExpect([_mockBackend getOOBConfirmationCode:[OCMArg any] callback:[OCMArg any]])
- .andCallBlock2(^(FIRGetOOBConfirmationCodeRequest *_Nullable request,
- FIRGetOOBConfirmationCodeResponseCallback callback) {
- XCTAssertEqualObjects(request.APIKey, kAPIKey);
- XCTAssertEqualObjects(request.email, kEmail);
- dispatch_async(FIRAuthGlobalWorkQueue(), ^() {
- callback([[FIRGetOOBConfirmationCodeResponse alloc] init], nil);
- });
- });
- XCTestExpectation *expectation = [self expectationWithDescription:@"callback"];
- [[FIRAuth auth] sendPasswordResetWithEmail:kEmail
- completion:^(NSError *_Nullable error) {
- XCTAssertTrue([NSThread isMainThread]);
- XCTAssertNil(error);
- [expectation fulfill];
- }];
- [self waitForExpectationsWithTimeout:kExpectationTimeout handler:nil];
- }
- #endif
- /** @fn testSendPasswordResetEmailSuccess
- @brief Tests the flow of a successful @c sendPasswordResetWithEmail:completion: call.
- */
- - (void)testSendPasswordResetEmailSuccess {
- OCMExpect([_mockBackend getOOBConfirmationCode:[OCMArg any] callback:[OCMArg any]])
- .andCallBlock2(^(FIRGetOOBConfirmationCodeRequest *_Nullable request,
- FIRGetOOBConfirmationCodeResponseCallback callback) {
- XCTAssertEqualObjects(request.APIKey, kAPIKey);
- XCTAssertEqualObjects(request.email, kEmail);
- dispatch_async(FIRAuthGlobalWorkQueue(), ^() {
- callback([[FIRGetOOBConfirmationCodeResponse alloc] init], nil);
- });
- });
- XCTestExpectation *expectation = [self expectationWithDescription:@"callback"];
- [[FIRAuth auth] sendPasswordResetWithEmail:kEmail
- completion:^(NSError *_Nullable error) {
- XCTAssertTrue([NSThread isMainThread]);
- XCTAssertNil(error);
- [expectation fulfill];
- }];
- [self waitForExpectationsWithTimeout:kExpectationTimeout handler:nil];
- OCMVerifyAll(_mockBackend);
- }
- /** @fn testSendPasswordResetEmailFailure
- @brief Tests the flow of a failed @c sendPasswordResetWithEmail:completion: call.
- */
- - (void)testSendPasswordResetEmailFailure {
- OCMExpect([_mockBackend getOOBConfirmationCode:[OCMArg any] callback:[OCMArg any]])
- .andDispatchError2([FIRAuthErrorUtils appNotAuthorizedError]);
- XCTestExpectation *expectation = [self expectationWithDescription:@"callback"];
- [[FIRAuth auth] sendPasswordResetWithEmail:kEmail
- completion:^(NSError *_Nullable error) {
- XCTAssertTrue([NSThread isMainThread]);
- XCTAssertEqual(error.code, FIRAuthErrorCodeAppNotAuthorized);
- XCTAssertNotNil(error.userInfo[NSLocalizedDescriptionKey]);
- [expectation fulfill];
- }];
- [self waitForExpectationsWithTimeout:kExpectationTimeout handler:nil];
- OCMVerifyAll(_mockBackend);
- }
- #if TARGET_OS_IOS && !TARGET_OS_MACCATALYST
- /** @fn testSendSignInLinkToEmailWithRecaptchaSuccess
- @brief Tests the flow of a successful @c sendSignInLinkToEmail:actionCodeSettings:completion:
- call.
- */
- - (void)testSendSignInLinkToEmailWithRecaptchaSuccess {
- id mockVerifier = OCMClassMock([FIRAuthRecaptchaVerifier class]);
- OCMStub([mockVerifier sharedRecaptchaVerifier:[FIRAuth auth]]).andReturn(mockVerifier);
- OCMExpect([mockVerifier enablementStatusForProvider:FIRAuthRecaptchaProviderPassword])
- .andReturn(YES);
- FIRGetOOBConfirmationCodeRequest *constRequestWithRecaptchaToken =
- [FIRGetOOBConfirmationCodeRequest
- signInWithEmailLinkRequest:kEmail
- actionCodeSettings:[self fakeActionCodeSettings]
- requestConfiguration:[FIRAuth auth].requestConfiguration];
- [constRequestWithRecaptchaToken injectRecaptchaFields:kFakeRecaptchaResponse
- recaptchaVersion:kFakeRecaptchaVersion];
- OCMStub([mockVerifier
- injectRecaptchaFields:[OCMArg any]
- provider:FIRAuthRecaptchaProviderPassword
- action:FIRAuthRecaptchaActionGetOobCode
- completion:([OCMArg invokeBlockWithArgs:constRequestWithRecaptchaToken, nil])]);
- OCMExpect([_mockBackend getOOBConfirmationCode:[OCMArg any] callback:[OCMArg any]])
- .andCallBlock2(^(FIRGetOOBConfirmationCodeRequest *_Nullable request,
- FIRGetOOBConfirmationCodeResponseCallback callback) {
- XCTAssertEqualObjects(request.APIKey, kAPIKey);
- XCTAssertEqualObjects(request.email, kEmail);
- XCTAssertEqualObjects(request.continueURL, kContinueURL);
- XCTAssertTrue(request.handleCodeInApp);
- dispatch_async(FIRAuthGlobalWorkQueue(), ^() {
- callback([[FIRGetOOBConfirmationCodeResponse alloc] init], nil);
- });
- });
- XCTestExpectation *expectation = [self expectationWithDescription:@"callback"];
- [[FIRAuth auth] sendSignInLinkToEmail:kEmail
- actionCodeSettings:[self fakeActionCodeSettings]
- completion:^(NSError *_Nullable error) {
- XCTAssertTrue([NSThread isMainThread]);
- XCTAssertNil(error);
- [expectation fulfill];
- }];
- [self waitForExpectationsWithTimeout:kExpectationTimeout handler:nil];
- }
- /** @fn testSendSignInLinkToEmailWithRecaptchaFallbackSuccess
- @brief Tests the flow of a successful @c sendSignInLinkToEmail:actionCodeSettings:completion:
- call.
- */
- - (void)testSendSignInLinkToEmailWithRecaptchaFallbackSuccess {
- id mockVerifier = OCMClassMock([FIRAuthRecaptchaVerifier class]);
- OCMStub([mockVerifier sharedRecaptchaVerifier:[FIRAuth auth]]).andReturn(mockVerifier);
- OCMExpect([mockVerifier enablementStatusForProvider:FIRAuthRecaptchaProviderPassword])
- .andReturn(NO);
- FIRGetOOBConfirmationCodeRequest *constRequestWithRecaptchaToken =
- [FIRGetOOBConfirmationCodeRequest
- signInWithEmailLinkRequest:kEmail
- actionCodeSettings:[self fakeActionCodeSettings]
- requestConfiguration:[FIRAuth auth].requestConfiguration];
- [constRequestWithRecaptchaToken injectRecaptchaFields:kFakeRecaptchaResponse
- recaptchaVersion:kFakeRecaptchaVersion];
- OCMStub([mockVerifier
- injectRecaptchaFields:[OCMArg any]
- provider:FIRAuthRecaptchaProviderPassword
- action:FIRAuthRecaptchaActionGetOobCode
- completion:([OCMArg invokeBlockWithArgs:constRequestWithRecaptchaToken, nil])]);
- OCMExpect([_mockBackend getOOBConfirmationCode:[OCMArg any] callback:[OCMArg any]])
- .andCallBlock2(^(FIRGetOOBConfirmationCodeRequest *_Nullable request,
- FIRGetOOBConfirmationCodeResponseCallback callback) {
- XCTAssertEqualObjects(request.APIKey, kAPIKey);
- XCTAssertEqualObjects(request.email, kEmail);
- XCTAssertEqualObjects(request.continueURL, kContinueURL);
- XCTAssertTrue(request.handleCodeInApp);
- NSError *underlyingError =
- [[NSError alloc] initWithDomain:FIRAuthErrorDomain
- code:FIRAuthErrorCodeInternalError
- userInfo:@{
- FIRAuthErrorUserInfoDeserializedResponseKey :
- @{@"message" : @"MISSING_RECAPTCHA_TOKEN"}
- }];
- NSError *error = [[NSError alloc] initWithDomain:FIRAuthErrorDomain
- code:FIRAuthErrorCodeInternalError
- userInfo:@{NSUnderlyingErrorKey : underlyingError}];
- dispatch_async(FIRAuthGlobalWorkQueue(), ^() {
- callback(nil, error);
- });
- });
- OCMExpect([_mockBackend getOOBConfirmationCode:[OCMArg any] callback:[OCMArg any]])
- .andCallBlock2(^(FIRGetOOBConfirmationCodeRequest *_Nullable request,
- FIRGetOOBConfirmationCodeResponseCallback callback) {
- XCTAssertEqualObjects(request.APIKey, kAPIKey);
- XCTAssertEqualObjects(request.email, kEmail);
- XCTAssertEqualObjects(request.continueURL, kContinueURL);
- XCTAssertTrue(request.handleCodeInApp);
- dispatch_async(FIRAuthGlobalWorkQueue(), ^() {
- callback([[FIRGetOOBConfirmationCodeResponse alloc] init], nil);
- });
- });
- XCTestExpectation *expectation = [self expectationWithDescription:@"callback"];
- [[FIRAuth auth] sendSignInLinkToEmail:kEmail
- actionCodeSettings:[self fakeActionCodeSettings]
- completion:^(NSError *_Nullable error) {
- XCTAssertTrue([NSThread isMainThread]);
- XCTAssertNil(error);
- [expectation fulfill];
- }];
- [self waitForExpectationsWithTimeout:kExpectationTimeout handler:nil];
- }
- #endif
- /** @fn testSendSignInLinkToEmailSuccess
- @brief Tests the flow of a successful @c sendSignInLinkToEmail:actionCodeSettings:completion:
- call.
- */
- - (void)testSendSignInLinkToEmailSuccess {
- OCMExpect([_mockBackend getOOBConfirmationCode:[OCMArg any] callback:[OCMArg any]])
- .andCallBlock2(^(FIRGetOOBConfirmationCodeRequest *_Nullable request,
- FIRGetOOBConfirmationCodeResponseCallback callback) {
- XCTAssertEqualObjects(request.APIKey, kAPIKey);
- XCTAssertEqualObjects(request.email, kEmail);
- XCTAssertEqualObjects(request.continueURL, kContinueURL);
- XCTAssertTrue(request.handleCodeInApp);
- dispatch_async(FIRAuthGlobalWorkQueue(), ^() {
- callback([[FIRGetOOBConfirmationCodeResponse alloc] init], nil);
- });
- });
- XCTestExpectation *expectation = [self expectationWithDescription:@"callback"];
- [[FIRAuth auth] sendSignInLinkToEmail:kEmail
- actionCodeSettings:[self fakeActionCodeSettings]
- completion:^(NSError *_Nullable error) {
- XCTAssertTrue([NSThread isMainThread]);
- XCTAssertNil(error);
- [expectation fulfill];
- }];
- [self waitForExpectationsWithTimeout:kExpectationTimeout handler:nil];
- OCMVerifyAll(_mockBackend);
- }
- /** @fn testSendSignInLinkToEmailFailure
- @brief Tests the flow of a failed @c sendSignInLinkToEmail:actionCodeSettings:completion:
- call.
- */
- - (void)testSendSignInLinkToEmailFailure {
- OCMExpect([_mockBackend getOOBConfirmationCode:[OCMArg any] callback:[OCMArg any]])
- .andDispatchError2([FIRAuthErrorUtils appNotAuthorizedError]);
- XCTestExpectation *expectation = [self expectationWithDescription:@"callback"];
- [[FIRAuth auth] sendSignInLinkToEmail:kEmail
- actionCodeSettings:[self fakeActionCodeSettings]
- completion:^(NSError *_Nullable error) {
- XCTAssertTrue([NSThread isMainThread]);
- XCTAssertEqual(error.code, FIRAuthErrorCodeAppNotAuthorized);
- XCTAssertNotNil(error.userInfo[NSLocalizedDescriptionKey]);
- [expectation fulfill];
- }];
- [self waitForExpectationsWithTimeout:kExpectationTimeout handler:nil];
- OCMVerifyAll(_mockBackend);
- }
- /** @fn fakeActionCodeSettings
- @brief Constructs and returns a fake instance of @c FIRActionCodeSettings for testing.
- @return An instance of @c FIRActionCodeSettings for testing.
- */
- - (FIRActionCodeSettings *)fakeActionCodeSettings {
- FIRActionCodeSettings *actionCodeSettings = [[FIRActionCodeSettings alloc] init];
- actionCodeSettings.URL = [NSURL URLWithString:kContinueURL];
- actionCodeSettings.handleCodeInApp = YES;
- return actionCodeSettings;
- }
- /** @fn testUpdateCurrentUserFailure
- @brief Tests the flow of a failed @c updateCurrentUser:completion:
- call.
- */
- - (void)testUpdateCurrentUserFailure {
- NSString *kTestAccessToken = @"fakeAccessToken";
- NSString *kTestAPIKey = @"fakeAPIKey";
- [self waitForSignInWithAccessToken:kTestAccessToken APIKey:kTestAPIKey completion:nil];
- NSString *kTestAPIKey2 = @"fakeAPIKey2";
- FIRUser *user2 = [FIRAuth auth].currentUser;
- user2.requestConfiguration = [[FIRAuthRequestConfiguration alloc] initWithAPIKey:kTestAPIKey2
- appID:kFirebaseAppID];
- OCMExpect([_mockBackend getAccountInfo:[OCMArg any] callback:[OCMArg any]])
- .andDispatchError2([FIRAuthErrorUtils invalidAPIKeyError]);
- XCTestExpectation *expectation = [self expectationWithDescription:@"callback"];
- [[FIRAuth auth] updateCurrentUser:user2
- completion:^(NSError *_Nullable error) {
- XCTAssertEqual(error.code, FIRAuthErrorCodeInvalidAPIKey);
- [expectation fulfill];
- }];
- [self waitForExpectationsWithTimeout:kExpectationTimeout handler:nil];
- OCMVerifyAll(_mockBackend);
- }
- /** @fn testUpdateCurrentUserFailureNetworkError
- @brief Tests the flow of a failed @c updateCurrentUser:completion:
- call with a network error.
- */
- - (void)testUpdateCurrentUserFailureNetworkError {
- NSString *kTestAPIKey = @"fakeAPIKey";
- NSString *kTestAccessToken = @"fakeAccessToken";
- [self waitForSignInWithAccessToken:kTestAccessToken APIKey:kTestAPIKey completion:nil];
- NSString *kTestAPIKey2 = @"fakeAPIKey2";
- FIRUser *user2 = [FIRAuth auth].currentUser;
- user2.requestConfiguration = [[FIRAuthRequestConfiguration alloc] initWithAPIKey:kTestAPIKey2
- appID:kFirebaseAppID];
- NSError *underlyingError = [NSError errorWithDomain:@"Test Error" code:1 userInfo:nil];
- OCMExpect([_mockBackend getAccountInfo:[OCMArg any] callback:[OCMArg any]])
- .andDispatchError2([FIRAuthErrorUtils networkErrorWithUnderlyingError:underlyingError]);
- XCTestExpectation *expectation = [self expectationWithDescription:@"callback"];
- [[FIRAuth auth] updateCurrentUser:user2
- completion:^(NSError *_Nullable error) {
- XCTAssertEqual(error.code, FIRAuthErrorCodeNetworkError);
- [expectation fulfill];
- }];
- [self waitForExpectationsWithTimeout:kExpectationTimeout handler:nil];
- OCMVerifyAll(_mockBackend);
- }
- /** @fn testUpdateCurrentUserFailureNUllUser
- @brief Tests the flow of a failed @c updateCurrentUser:completion:
- call with FIRAuthErrorCodeNullUser.
- */
- - (void)testUpdateCurrentUserFailureNUllUser {
- NSString *kTestAccessToken = @"fakeAccessToken";
- NSString *kTestAPIKey = @"fakeAPIKey";
- [self waitForSignInWithAccessToken:kTestAccessToken APIKey:kTestAPIKey completion:nil];
- FIRUser *fakeNilUser = nil;
- XCTestExpectation *expectation = [self expectationWithDescription:@"callback"];
- [[FIRAuth auth] updateCurrentUser:fakeNilUser
- completion:^(NSError *_Nullable error) {
- XCTAssertEqual(error.code, FIRAuthErrorCodeNullUser);
- [expectation fulfill];
- }];
- [self waitForExpectationsWithTimeout:kExpectationTimeout handler:nil];
- OCMVerifyAll(_mockBackend);
- }
- /** @fn testUpdateCurrentUserFailureTenantIDMismatch
- @brief Tests the flow of a failed @c updateCurrentUser:completion:
- call with FIRAuthErrorCodeTenantIDMismatch.
- */
- - (void)testUpdateCurrentUserFailureTenantIDMismatch {
- // User without tenant id
- [self waitForSignInWithAccessToken:kAccessToken APIKey:kAPIKey completion:nil];
- FIRUser *user1 = [FIRAuth auth].currentUser;
- [[FIRAuth auth] signOut:nil];
- // User with tenant id "tenant-id"
- [FIRAuth auth].tenantID = @"tenant-id-1";
- NSString *kTestAccessToken2 = @"fakeAccessToken2";
- [self waitForSignInWithAccessToken:kTestAccessToken2 APIKey:kAPIKey completion:nil];
- FIRUser *user2 = [FIRAuth auth].currentUser;
- [[FIRAuth auth] signOut:nil];
- [FIRAuth auth].tenantID = @"tenant-id-2";
- XCTestExpectation *expectation1 = [self expectationWithDescription:@"callback"];
- [[FIRAuth auth] updateCurrentUser:user1
- completion:^(NSError *_Nullable error) {
- XCTAssertEqual(error.code, FIRAuthErrorCodeTenantIDMismatch);
- [expectation1 fulfill];
- }];
- [[FIRAuth auth] signOut:nil];
- [FIRAuth auth].tenantID = @"tenant-id-2";
- XCTestExpectation *expectation2 = [self expectationWithDescription:@"callback"];
- [[FIRAuth auth] updateCurrentUser:user2
- completion:^(NSError *_Nullable error) {
- XCTAssertEqual(error.code, FIRAuthErrorCodeTenantIDMismatch);
- [expectation2 fulfill];
- }];
- [[FIRAuth auth] signOut:nil];
- [FIRAuth auth].tenantID = nil;
- XCTestExpectation *expectation3 = [self expectationWithDescription:@"callback"];
- [[FIRAuth auth] updateCurrentUser:user2
- completion:^(NSError *_Nullable error) {
- XCTAssertEqual(error.code, FIRAuthErrorCodeTenantIDMismatch);
- [expectation3 fulfill];
- }];
- [self waitForExpectationsWithTimeout:kExpectationTimeout handler:nil];
- OCMVerifyAll(_mockBackend);
- }
- /** @fn testUpdateCurrentUserSuccess
- @brief Tests the flow of a successful @c updateCurrentUser:completion:
- call with a network error.
- */
- - (void)testUpdateCurrentUserSuccess {
- // Sign in with the first user.
- [self waitForSignInWithAccessToken:kAccessToken APIKey:kAPIKey completion:nil];
- FIRUser *user1 = [FIRAuth auth].currentUser;
- NSString *kTestAPIKey = @"fakeAPIKey";
- user1.requestConfiguration = [[FIRAuthRequestConfiguration alloc] initWithAPIKey:kTestAPIKey
- appID:kFirebaseAppID];
- [[FIRAuth auth] signOut:nil];
- NSString *kTestAccessToken2 = @"fakeAccessToken2";
- [self waitForSignInWithAccessToken:kTestAccessToken2 APIKey:kAPIKey completion:nil];
- FIRUser *user2 = [FIRAuth auth].currentUser;
- [self expectGetAccountInfoWithAccessToken:kAccessToken];
- XCTestExpectation *expectation = [self expectationWithDescription:@"callback"];
- // Current user should now be user2.
- XCTAssertEqualObjects([FIRAuth auth].currentUser, user2);
- [[FIRAuth auth] updateCurrentUser:user1
- completion:^(NSError *_Nullable error) {
- XCTAssertNil(error);
- // Current user should now be user1.
- XCTAssertEqualObjects([FIRAuth auth].currentUser, user1);
- XCTAssertNotEqualObjects([FIRAuth auth].currentUser, user2);
- [expectation fulfill];
- }];
- [self waitForExpectationsWithTimeout:kExpectationTimeout handler:nil];
- OCMVerifyAll(_mockBackend);
- }
- /** @fn testSignOut
- @brief Tests the @c signOut: method.
- */
- - (void)testSignOut {
- [self waitForSignIn];
- // Verify signing out succeeds and clears the current user.
- NSError *error;
- XCTAssertTrue([[FIRAuth auth] signOut:&error]);
- XCTAssertNil([FIRAuth auth].currentUser);
- }
- /** @fn testIsSignInWithEmailLink
- @brief Tests the @c isSignInWithEmailLink: method.
- */
- - (void)testIsSignInWithEmailLink {
- XCTAssertTrue([[FIRAuth auth] isSignInWithEmailLink:kFakeEmailSignInlink]);
- XCTAssertTrue([[FIRAuth auth] isSignInWithEmailLink:kFakeEmailSignInDeeplink]);
- XCTAssertFalse([[FIRAuth auth] isSignInWithEmailLink:kBadSignInEmailLink]);
- XCTAssertFalse([[FIRAuth auth] isSignInWithEmailLink:@""]);
- }
- /** @fn testAuthStateChanges
- @brief Tests @c addAuthStateDidChangeListener: and @c removeAuthStateDidChangeListener: methods.
- */
- - (void)testAuthStateChanges {
- // Set up listener.
- __block XCTestExpectation *expectation;
- __block BOOL shouldHaveUser;
- FIRAuthStateDidChangeListenerBlock listener = ^(FIRAuth *auth, FIRUser *_Nullable user) {
- XCTAssertTrue([NSThread isMainThread]);
- XCTAssertEqual(auth, [FIRAuth auth]);
- XCTAssertEqual(user, [FIRAuth 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];
- };
- [[FIRAuth auth] signOut:NULL];
- [self waitForTimeIntervel:kWaitInterval]; // Wait until dust settled from previous tests.
- // Listener should fire immediately when attached.
- expectation = [self expectationWithDescription:@"initial"];
- shouldHaveUser = NO;
- FIRAuthStateDidChangeListenerHandle handle =
- [[FIRAuth auth] addAuthStateDidChangeListener:listener];
- [self waitForExpectationsWithTimeout:kExpectationTimeout handler:nil];
- // Listener should fire for signing in.
- expectation = [self expectationWithDescription:@"sign-in"];
- shouldHaveUser = YES;
- [self waitForSignIn];
- // Listener should not fire for signing in again.
- shouldHaveUser = YES;
- [self waitForSignIn];
- [self waitForTimeIntervel:kWaitInterval]; // make sure listener is not called
- // Listener should fire for signing out.
- expectation = [self expectationWithDescription:@"sign-out"];
- shouldHaveUser = NO;
- [[FIRAuth auth] signOut:NULL];
- [self waitForExpectationsWithTimeout:kExpectationTimeout handler:nil];
- // Listener should no longer fire once detached.
- expectation = nil;
- [[FIRAuth auth] removeAuthStateDidChangeListener:handle];
- [self waitForSignIn];
- [self waitForTimeIntervel:kWaitInterval]; // make sure listener is no longer called
- }
- /** @fn testIDTokenChanges
- @brief Tests @c addIDTokenDidChangeListener: and @c removeIDTokenDidChangeListener: methods.
- */
- - (void)testIDTokenChanges {
- // Set up listener.
- __block XCTestExpectation *expectation;
- __block BOOL shouldHaveUser;
- FIRIDTokenDidChangeListenerBlock listener = ^(FIRAuth *auth, FIRUser *_Nullable user) {
- XCTAssertTrue([NSThread isMainThread]);
- XCTAssertEqual(auth, [FIRAuth auth]);
- XCTAssertEqual(user, [FIRAuth 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];
- };
- [[FIRAuth auth] signOut:NULL];
- [self waitForTimeIntervel:kWaitInterval]; // Wait until dust settled from previous tests.
- // Listener should fire immediately when attached.
- expectation = [self expectationWithDescription:@"initial"];
- shouldHaveUser = NO;
- FIRIDTokenDidChangeListenerHandle handle = [[FIRAuth auth] addIDTokenDidChangeListener:listener];
- [self waitForExpectationsWithTimeout:kExpectationTimeout handler:nil];
- // Listener should fire for signing in.
- expectation = [self expectationWithDescription:@"sign-in"];
- shouldHaveUser = YES;
- [self waitForSignIn];
- // Listener should fire for signing in again as the same user with another access token.
- expectation = [self expectationWithDescription:@"sign-in again"];
- shouldHaveUser = YES;
- [self waitForSignInWithAccessToken:kNewAccessToken APIKey:nil completion:nil];
- // Listener should fire for signing out.
- expectation = [self expectationWithDescription:@"sign-out"];
- shouldHaveUser = NO;
- [[FIRAuth auth] signOut:NULL];
- [self waitForExpectationsWithTimeout:kExpectationTimeout handler:nil];
- // Listener should no longer fire once detached.
- expectation = nil;
- [[FIRAuth auth] removeIDTokenDidChangeListener:handle];
- [self waitForSignIn];
- [self waitForTimeIntervel:kWaitInterval]; // make sure listener is no longer called
- }
- /** @fn testUseEmulator
- @brief Tests the @c useEmulatorWithHost:port: method.
- */
- - (void)testUseEmulator {
- [[FIRAuth auth] useEmulatorWithHost:@"host" port:12345];
- XCTAssertEqualObjects(@"host:12345", [FIRAuth auth].requestConfiguration.emulatorHostAndPort);
- #if TARGET_OS_IOS
- XCTAssertTrue([FIRAuth auth].settings.isAppVerificationDisabledForTesting);
- #endif
- }
- /** @fn testUseEmulatorNeverCalled
- @brief Tests that the emulatorHostAndPort stored in @c FIRAuthRequestConfiguration is nil if the
- @c useEmulatorWithHost:port: is not called.
- */
- - (void)testUseEmulatorNeverCalled {
- XCTAssertEqualObjects(nil, [FIRAuth auth].requestConfiguration.emulatorHostAndPort);
- #if TARGET_OS_IOS
- XCTAssertFalse([FIRAuth auth].settings.isAppVerificationDisabledForTesting);
- #endif
- }
- /** @fn testUseEmulatorIPv6Address
- @brief Tests the @c useEmulatorWithHost:port: method with an IPv6 host address.
- */
- - (void)testUseEmulatorIPv6Address {
- [[FIRAuth auth] useEmulatorWithHost:@"::1" port:12345];
- XCTAssertEqualObjects(@"[::1]:12345", [FIRAuth auth].requestConfiguration.emulatorHostAndPort);
- #if TARGET_OS_IOS
- XCTAssertTrue([FIRAuth auth].settings.isAppVerificationDisabledForTesting);
- #endif
- }
- #pragma mark - Automatic Token Refresh Tests.
- /** @fn testAutomaticTokenRefresh
- @brief Tests a successful flow to automatically refresh tokens for a signed in user.
- */
- - (void)testAutomaticTokenRefresh {
- [[FIRAuth auth] signOut:NULL];
- // Enable auto refresh
- [self enableAutoTokenRefresh];
- // Sign in a user.
- [self waitForSignIn];
- // Set up expectation for secureToken RPC made by token refresh task. We call this twice, because
- // we retry once if the access token is already expired.
- [self mockSecureTokenResponseWithError:nil];
- [self mockSecureTokenResponseWithError:nil];
- // Verify that the current user's access token is the "old" access token before automatic token
- // refresh.
- XCTAssertEqualObjects(kAccessToken, [FIRAuth auth].currentUser.rawAccessToken);
- // Execute saved token refresh task.
- XCTestExpectation *dispatchAfterExpectation =
- [self expectationWithDescription:@"dispatchAfterExpectation"];
- dispatch_async(FIRAuthGlobalWorkQueue(), ^() {
- XCTAssertNotNil(self->_FIRAuthDispatcherCallback);
- self->_FIRAuthDispatcherCallback();
- [dispatchAfterExpectation fulfill];
- });
- [self waitForExpectationsWithTimeout:kExpectationTimeout handler:nil];
- // Verify that current user's access token is the "new" access token provided in the mock secure
- // token response during automatic token refresh.
- XCTAssertEqualObjects(kNewAccessToken, [FIRAuth auth].currentUser.rawAccessToken);
- OCMVerifyAll(_mockBackend);
- }
- /** @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.
- */
- - (void)testAutomaticTokenRefreshInvalidTokenFailure {
- [[FIRAuth auth] signOut:NULL];
- // Enable auto refresh
- [self enableAutoTokenRefresh];
- // Sign in a user.
- [self waitForSignIn];
- // Set up expectation for secureToken RPC made by a failed attempt to refresh tokens.
- [self mockSecureTokenResponseWithError:[FIRAuthErrorUtils invalidUserTokenErrorWithMessage:nil]];
- // Verify that current user is still valid.
- XCTAssertEqualObjects(kAccessToken, [FIRAuth auth].currentUser.rawAccessToken);
- // Execute saved token refresh task.
- XCTestExpectation *dispatchAfterExpectation =
- [self expectationWithDescription:@"dispatchAfterExpectation"];
- dispatch_async(FIRAuthGlobalWorkQueue(), ^() {
- XCTAssertNotNil(self->_FIRAuthDispatcherCallback);
- self->_FIRAuthDispatcherCallback();
- [dispatchAfterExpectation fulfill];
- });
- [self waitForExpectationsWithTimeout:kExpectationTimeout handler:nil];
- // Verify that the user is nil after failed attempt to refresh tokens caused signed out.
- XCTAssertNil([FIRAuth auth].currentUser);
- OCMVerifyAll(_mockBackend);
- }
- /** @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.
- */
- - (void)testAutomaticTokenRefreshRetry {
- [[FIRAuth auth] signOut:NULL];
- // Enable auto refresh
- [self enableAutoTokenRefresh];
- // Sign in a user.
- [self waitForSignIn];
- // Set up expectation for secureToken RPC made by a failed attempt to refresh tokens.
- [self mockSecureTokenResponseWithError:[NSError errorWithDomain:@"ERROR" code:-1 userInfo:nil]];
- // Execute saved token refresh task.
- XCTestExpectation *expectation = [self expectationWithDescription:@"callback"];
- dispatch_async(FIRAuthGlobalWorkQueue(), ^() {
- XCTAssertNotNil(self->_FIRAuthDispatcherCallback);
- self->_FIRAuthDispatcherCallback();
- self->_FIRAuthDispatcherCallback = nil;
- [expectation fulfill];
- });
- [self waitForExpectationsWithTimeout:kExpectationTimeout handler:nil];
- // The old access token should still be the current user's access token and not the new access
- // token (kNewAccessToken).
- XCTAssertEqualObjects(kAccessToken, [FIRAuth auth].currentUser.rawAccessToken);
- // Set up expectation for secureToken RPC made by a successful attempt to refresh tokens. We call
- // this twice, because we retry once if the access token is already expired.
- [self mockSecureTokenResponseWithError:nil];
- [self mockSecureTokenResponseWithError:nil];
- // Execute saved token refresh task.
- XCTestExpectation *dispatchAfterExpectation =
- [self expectationWithDescription:@"dispatchAfterExpectation"];
- dispatch_async(FIRAuthGlobalWorkQueue(), ^() {
- XCTAssertNotNil(self->_FIRAuthDispatcherCallback);
- self->_FIRAuthDispatcherCallback();
- [dispatchAfterExpectation fulfill];
- });
- [self waitForExpectationsWithTimeout:kExpectationTimeout handler:nil];
- // Verify that current user's access token is the "new" access token provided in the mock secure
- // token response during automatic token refresh.
- XCTAssertEqualObjects([FIRAuth auth].currentUser.rawAccessToken, kNewAccessToken);
- OCMVerifyAll(_mockBackend);
- }
- #if TARGET_OS_IOS
- /** @fn testAutomaticTokenRefreshInvalidTokenFailure
- @brief Tests that app foreground notification triggers the scheduling of an automatic token
- refresh task.
- */
- - (void)testAutoRefreshAppForegroundedNotification {
- [[FIRAuth auth] signOut:NULL];
- // Enable auto refresh
- [self enableAutoTokenRefresh];
- // Sign in a user.
- [self waitForSignIn];
- // Post "UIApplicationDidBecomeActiveNotification" to trigger scheduling token refresh task.
- [[NSNotificationCenter defaultCenter]
- postNotificationName:UIApplicationDidBecomeActiveNotification
- object:nil];
- // Verify that current user is still valid with old access token.
- XCTAssertEqualObjects(kAccessToken, [FIRAuth auth].currentUser.rawAccessToken);
- // Set up expectation for secureToken RPC made by a successful attempt to refresh tokens. We call
- // this twice, because we retry once if the access token is already expired.
- [self mockSecureTokenResponseWithError:nil];
- [self mockSecureTokenResponseWithError:nil];
- // Execute saved token refresh task.
- XCTestExpectation *dispatchAfterExpectation =
- [self expectationWithDescription:@"dispatchAfterExpectation"];
- dispatch_async(FIRAuthGlobalWorkQueue(), ^() {
- XCTAssertNotNil(self->_FIRAuthDispatcherCallback);
- self->_FIRAuthDispatcherCallback();
- [dispatchAfterExpectation fulfill];
- });
- [self waitForExpectationsWithTimeout:kExpectationTimeout handler:nil];
- // Verify that current user is still valid with new access token.
- XCTAssertEqualObjects(kNewAccessToken, [FIRAuth auth].currentUser.rawAccessToken);
- OCMVerifyAll(_mockBackend);
- }
- #endif
- #if TARGET_OS_IOS
- #pragma mark - Application Delegate tests
- - (void)testAppDidRegisterForRemoteNotifications_APNSTokenUpdated {
- NSData *apnsToken = [NSData data];
- OCMExpect([self.mockTokenManager setToken:[OCMArg checkWithBlock:^BOOL(FIRAuthAPNSToken *token) {
- XCTAssertEqual(token.data, apnsToken);
- XCTAssertEqual(token.type, FIRAuthAPNSTokenTypeUnknown);
- return YES;
- }]]);
- [self.fakeApplicationDelegate application:[GULAppDelegateSwizzler sharedApplication]
- didRegisterForRemoteNotificationsWithDeviceToken:apnsToken];
- [self.mockTokenManager verify];
- }
- - (void)testAppDidFailToRegisterForRemoteNotifications_TokenManagerCancels {
- NSError *error = [NSError errorWithDomain:@"FIRAuthTests" code:-1 userInfo:nil];
- OCMExpect([self.mockTokenManager cancelWithError:error]);
- [self.fakeApplicationDelegate application:[GULAppDelegateSwizzler sharedApplication]
- didFailToRegisterForRemoteNotificationsWithError:error];
- [self.mockTokenManager verify];
- }
- - (void)testAppDidReceiveRemoteNotification_NotificationManagerHandleCanNotification {
- NSDictionary *notification = @{@"test" : @""};
- OCMExpect([self.mockNotificationManager canHandleNotification:notification]);
- #pragma clang diagnostic push
- #pragma clang diagnostic ignored "-Wdeprecated-declarations"
- [self.fakeApplicationDelegate application:[GULAppDelegateSwizzler sharedApplication]
- didReceiveRemoteNotification:notification];
- #pragma clang diagnostic pop
- [self.mockNotificationManager verify];
- }
- - (void)testAppDidReceiveRemoteNotificationWithCompletion_NotificationManagerHandleCanNotification {
- NSDictionary *notification = @{@"test" : @""};
- OCMExpect([self.mockNotificationManager canHandleNotification:notification]);
- [self.fakeApplicationDelegate application:[GULAppDelegateSwizzler sharedApplication]
- didReceiveRemoteNotification:notification
- fetchCompletionHandler:^(UIBackgroundFetchResult result){
- }];
- [self.mockNotificationManager verify];
- }
- - (void)testAppOpenURL_AuthPresenterCanHandleURL {
- if (@available(iOS 9.0, *)) {
- // 'application:openURL:options:' is only available on iOS 9.0 or newer.
- NSURL *url = [NSURL URLWithString:@"https://localhost"];
- OCMExpect([self.mockAuthURLPresenter canHandleURL:url]).andReturn(YES);
- XCTAssertTrue([self.fakeApplicationDelegate
- application:[GULAppDelegateSwizzler sharedApplication]
- openURL:url
- options:@{}]);
- [self.mockAuthURLPresenter verify];
- }
- }
- - (void)testAppOpenURLWithSourceApplication_AuthPresenterCanHandleURL {
- NSURL *url = [NSURL URLWithString:@"https://localhost"];
- OCMExpect([self.mockAuthURLPresenter canHandleURL:url]).andReturn(YES);
- #pragma clang diagnostic push
- #pragma clang diagnostic ignored "-Wdeprecated-declarations"
- XCTAssertTrue([self.fakeApplicationDelegate application:[GULAppDelegateSwizzler sharedApplication]
- openURL:url
- sourceApplication:@""
- annotation:[[NSObject alloc] init]]);
- #pragma clang diagnostic pop
- [self.mockAuthURLPresenter verify];
- }
- #endif // TARGET_OS_IOS
- #pragma mark - Interoperability Tests
- /** @fn testComponentsBeingRegistered
- @brief Tests that Auth provides the necessary components for interoperability with other SDKs.
- */
- - (void)testComponentsBeingRegistered {
- // 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.
- NSArray<FIRComponent *> *components = [FIRAuth componentsToRegister];
- XCTAssertTrue(components.count == 1);
- FIRComponent *component = [components firstObject];
- XCTAssert(component.protocol == @protocol(FIRAuthInterop));
- }
- #pragma mark - Helpers
- /** @fn mockSecureTokenResponseWithError:
- @brief Set up expectation for secureToken RPC.
- @param error The error that the mock should return if any.
- */
- - (void)mockSecureTokenResponseWithError:(nullable NSError *)error {
- // Set up expectation for secureToken RPC made by a successful attempt to refresh tokens.
- XCTestExpectation *secureTokenResponseExpectation =
- [self expectationWithDescription:@"secureTokenResponseExpectation"];
- OCMExpect([_mockBackend secureToken:[OCMArg any] callback:[OCMArg any]])
- .andCallBlock2(
- ^(FIRSecureTokenRequest *_Nullable request, FIRSecureTokenResponseCallback callback) {
- XCTAssertEqualObjects(request.APIKey, kAPIKey);
- XCTAssertEqualObjects(request.refreshToken, kRefreshToken);
- dispatch_async(FIRAuthGlobalWorkQueue(), ^() {
- if (error) {
- callback(nil, error);
- [secureTokenResponseExpectation fulfill];
- return;
- }
- id mockSecureTokenResponse = OCMClassMock([FIRSecureTokenResponse class]);
- OCMStub([mockSecureTokenResponse accessToken]).andReturn(kNewAccessToken);
- NSDate *futureDate =
- [[NSDate date] dateByAddingTimeInterval:kTestTokenExpirationTimeInterval];
- OCMStub([mockSecureTokenResponse approximateExpirationDate]).andReturn(futureDate);
- callback(mockSecureTokenResponse, nil);
- [secureTokenResponseExpectation fulfill];
- });
- });
- }
- /** @fn enableAutoTokenRefresh
- @brief Enables automatic token refresh by invoking FIRAuth's implementation of FIRApp's
- |getTokenWithImplementation|.
- */
- - (void)enableAutoTokenRefresh {
- XCTestExpectation *expectation = [self expectationWithDescription:@"autoTokenRefreshcallback"];
- [[FIRAuth auth] getTokenForcingRefresh:NO
- withCallback:^(NSString *_Nullable token, NSError *_Nullable error) {
- [expectation fulfill];
- }];
- [self waitForExpectationsWithTimeout:kExpectationTimeout handler:nil];
- }
- /** @fn stubSecureTokensWithMockResponse
- @brief Creates stubs on the mock response object with access and refresh tokens
- @param mockResponse The mock response object.
- */
- - (void)stubTokensWithMockResponse:(id)mockResponse {
- OCMStub([mockResponse IDToken]).andReturn(kAccessToken);
- OCMStub([mockResponse approximateExpirationDate])
- .andReturn([NSDate dateWithTimeIntervalSinceNow:kAccessTokenTimeToLive]);
- OCMStub([mockResponse refreshToken]).andReturn(kRefreshToken);
- }
- /** @fn expectGetAccountInfo
- @brief Expects a GetAccountInfo request on the mock backend and calls back with fake account
- data.
- */
- - (void)expectGetAccountInfo {
- [self expectGetAccountInfoWithAccessToken:kAccessToken];
- }
- /** @fn expectGetAccountInfoWithAccessToken
- @param accessToken The access token for the user to check against.
- @brief Expects a GetAccountInfo request on the mock backend and calls back with fake account
- data.
- */
- - (void)expectGetAccountInfoWithAccessToken:(NSString *)accessToken {
- OCMExpect([_mockBackend getAccountInfo:[OCMArg any] callback:[OCMArg any]])
- .andCallBlock2(^(FIRGetAccountInfoRequest *_Nullable request,
- FIRGetAccountInfoResponseCallback callback) {
- XCTAssertEqualObjects(request.APIKey, kAPIKey);
- XCTAssertEqualObjects(request.accessToken, accessToken);
- dispatch_async(FIRAuthGlobalWorkQueue(), ^() {
- id mockGetAccountInfoResponseUser = OCMClassMock([FIRGetAccountInfoResponseUser class]);
- OCMStub([mockGetAccountInfoResponseUser localID]).andReturn(kLocalID);
- OCMStub([mockGetAccountInfoResponseUser displayName]).andReturn(kDisplayName);
- OCMStub([mockGetAccountInfoResponseUser email]).andReturn(kEmail);
- OCMStub([mockGetAccountInfoResponseUser passwordHash]).andReturn(kPasswordHash);
- id mockGetAccountInfoResponse = OCMClassMock([FIRGetAccountInfoResponse class]);
- OCMStub([mockGetAccountInfoResponse users]).andReturn(@[
- mockGetAccountInfoResponseUser
- ]);
- callback(mockGetAccountInfoResponse, nil);
- });
- });
- }
- /** @fn assertUser
- @brief Asserts the given FIRUser matching the fake data returned by @c expectGetAccountInfo.
- @param user The user object to be verified.
- */
- - (void)assertUser:(FIRUser *)user {
- XCTAssertNotNil(user);
- XCTAssertEqualObjects(user.uid, kLocalID);
- XCTAssertEqualObjects(user.displayName, kDisplayName);
- XCTAssertEqualObjects(user.email, kEmail);
- XCTAssertFalse(user.anonymous);
- XCTAssertEqual(user.providerData.count, 0u);
- }
- /** @fn expectGetAccountInfoGoogle
- @brief Expects a GetAccountInfo request on the mock backend and calls back with fake account
- data for a Google Sign-In user.
- */
- - (void)expectGetAccountInfoGoogle {
- OCMExpect([_mockBackend getAccountInfo:[OCMArg any] callback:[OCMArg any]])
- .andCallBlock2(^(FIRGetAccountInfoRequest *_Nullable request,
- FIRGetAccountInfoResponseCallback callback) {
- XCTAssertEqualObjects(request.APIKey, kAPIKey);
- XCTAssertEqualObjects(request.accessToken, kAccessToken);
- dispatch_async(FIRAuthGlobalWorkQueue(), ^() {
- id mockGoogleUserInfo = OCMClassMock([FIRGetAccountInfoResponseProviderUserInfo class]);
- OCMStub([mockGoogleUserInfo providerID]).andReturn(FIRGoogleAuthProviderID);
- OCMStub([mockGoogleUserInfo displayName]).andReturn(kGoogleDisplayName);
- OCMStub([mockGoogleUserInfo federatedID]).andReturn(kGoogleID);
- OCMStub([mockGoogleUserInfo email]).andReturn(kGoogleEmail);
- id mockGetAccountInfoResponseUser = OCMClassMock([FIRGetAccountInfoResponseUser class]);
- OCMStub([mockGetAccountInfoResponseUser localID]).andReturn(kLocalID);
- OCMStub([mockGetAccountInfoResponseUser displayName]).andReturn(kDisplayName);
- OCMStub([mockGetAccountInfoResponseUser providerUserInfo])
- .andReturn((@[ mockGoogleUserInfo ]));
- id mockGetAccountInfoResponse = OCMClassMock([FIRGetAccountInfoResponse class]);
- OCMStub([mockGetAccountInfoResponse users]).andReturn(@[
- mockGetAccountInfoResponseUser
- ]);
- callback(mockGetAccountInfoResponse, nil);
- });
- });
- }
- /** @fn assertUserGoogle
- @brief Asserts the given FIRUser matching the fake data returned by
- @c expectGetAccountInfoGoogle.
- @param user The user object to be verified.
- */
- - (void)assertUserGoogle:(FIRUser *)user {
- XCTAssertNotNil(user);
- XCTAssertEqualObjects(user.uid, kLocalID);
- XCTAssertEqualObjects(user.displayName, kDisplayName);
- XCTAssertEqual(user.providerData.count, 1u);
- id<FIRUserInfo> googleUserInfo = user.providerData[0];
- XCTAssertEqualObjects(googleUserInfo.providerID, FIRGoogleAuthProviderID);
- XCTAssertEqualObjects(googleUserInfo.uid, kGoogleID);
- XCTAssertEqualObjects(googleUserInfo.displayName, kGoogleDisplayName);
- XCTAssertEqualObjects(googleUserInfo.email, kGoogleEmail);
- }
- /** @fn expectGetAccountInfoAnonymous
- @brief Expects a GetAccountInfo request on the mock backend and calls back with fake anonymous
- account data.
- */
- - (void)expectGetAccountInfoAnonymous {
- OCMExpect([_mockBackend getAccountInfo:[OCMArg any] callback:[OCMArg any]])
- .andCallBlock2(^(FIRGetAccountInfoRequest *_Nullable request,
- FIRGetAccountInfoResponseCallback callback) {
- XCTAssertEqualObjects(request.APIKey, kAPIKey);
- XCTAssertEqualObjects(request.accessToken, kAccessToken);
- dispatch_async(FIRAuthGlobalWorkQueue(), ^() {
- id mockGetAccountInfoResponseUser = OCMClassMock([FIRGetAccountInfoResponseUser class]);
- OCMStub([mockGetAccountInfoResponseUser localID]).andReturn(kLocalID);
- id mockGetAccountInfoResponse = OCMClassMock([FIRGetAccountInfoResponse class]);
- OCMStub([mockGetAccountInfoResponse users]).andReturn(@[
- mockGetAccountInfoResponseUser
- ]);
- callback(mockGetAccountInfoResponse, nil);
- });
- });
- }
- /** @fn assertUserAnonymous
- @brief Asserts the given FIRUser matching the fake data returned by
- @c expectGetAccountInfoAnonymous.
- @param user The user object to be verified.
- */
- - (void)assertUserAnonymous:(FIRUser *)user {
- XCTAssertNotNil(user);
- XCTAssertEqualObjects(user.uid, kLocalID);
- XCTAssertNil(user.displayName);
- XCTAssertTrue(user.anonymous);
- XCTAssertEqual(user.providerData.count, 0u);
- }
- /** @fn waitForSignIn
- @brief Signs in a user to prepare for tests.
- @remarks This method also waits for all other pending @c XCTestExpectation instances.
- */
- - (void)waitForSignIn {
- [self waitForSignInWithAccessToken:kAccessToken APIKey:nil completion:nil];
- }
- /** @fn waitForSignInWithAccessToken:
- @brief Signs in a user to prepare for tests.
- @param accessToken The access token for the user to have.
- @param APIKey Optionally, The API key associated with the user.
- @param completion Optionally, The completion invoked at the end of the flow.
- @remarks This method also waits for all other pending @c XCTestExpectation instances.
- */
- - (void)waitForSignInWithAccessToken:(NSString *)accessToken
- APIKey:(nullable NSString *)APIKey
- completion:(nullable FIRAuthResultCallback)completion {
- OCMExpect([_mockBackend verifyPassword:[OCMArg any] callback:[OCMArg any]])
- .andCallBlock2(^(FIRVerifyPasswordRequest *_Nullable request,
- FIRVerifyPasswordResponseCallback callback) {
- dispatch_async(FIRAuthGlobalWorkQueue(), ^() {
- id mockVerifyPasswordResponse = OCMClassMock([FIRVerifyPasswordResponse class]);
- OCMStub([mockVerifyPasswordResponse IDToken]).andReturn(accessToken);
- OCMStub([mockVerifyPasswordResponse approximateExpirationDate])
- .andReturn([NSDate dateWithTimeIntervalSinceNow:kAccessTokenTimeToLive]);
- OCMStub([mockVerifyPasswordResponse refreshToken]).andReturn(kRefreshToken);
- callback(mockVerifyPasswordResponse, nil);
- });
- });
- [self expectGetAccountInfoWithAccessToken:accessToken];
- XCTestExpectation *expectation = [self expectationWithDescription:@"callback"];
- [[FIRAuth auth] signInWithEmail:kEmail
- password:kFakePassword
- completion:^(FIRAuthDataResult *_Nullable result, NSError *_Nullable error) {
- result.user.requestConfiguration =
- [[FIRAuthRequestConfiguration alloc] initWithAPIKey:APIKey
- appID:kFirebaseAppID];
- [expectation fulfill];
- if (completion) {
- completion(result.user, error);
- }
- }];
- [self waitForExpectationsWithTimeout:kExpectationTimeout handler:nil];
- OCMVerifyAll(_mockBackend);
- XCTAssertNotNil([FIRAuth auth].currentUser);
- }
- /** @fn waitForTimeInterval:
- @brief Wait for a particular time interval.
- @remarks This method also waits for all other pending @c XCTestExpectation instances.
- */
- - (void)waitForTimeIntervel:(NSTimeInterval)timeInterval {
- static dispatch_queue_t queue;
- static dispatch_once_t onceToken;
- XCTestExpectation *expectation = [self expectationWithDescription:@"waitForTimeIntervel:"];
- dispatch_once(&onceToken, ^{
- queue = dispatch_queue_create("com.google.FIRAuthUnitTests.waitForTimeIntervel", NULL);
- });
- dispatch_after(dispatch_time(DISPATCH_TIME_NOW, timeInterval * NSEC_PER_SEC), queue, ^() {
- [expectation fulfill];
- });
- [self waitForExpectationsWithTimeout:timeInterval + kExpectationTimeout handler:nil];
- }
- - (void)waitForAuthGlobalWorkQueueDrain {
- dispatch_semaphore_t workerSemaphore = dispatch_semaphore_create(0);
- dispatch_async(FIRAuthGlobalWorkQueue(), ^{
- dispatch_semaphore_signal(workerSemaphore);
- });
- dispatch_semaphore_wait(workerSemaphore,
- DISPATCH_TIME_FOREVER /*DISPATCH_TIME_NOW + 10 * NSEC_PER_SEC*/);
- }
- /** @fn testRevokeTokenSuccess
- @brief Tests the flow of a successful @c revokeToken:completion.
- */
- - (void)testRevokeTokenSuccess {
- OCMExpect([_mockBackend verifyPassword:[OCMArg any] callback:[OCMArg any]])
- .andCallBlock2(^(FIRVerifyPasswordRequest *_Nullable request,
- FIRVerifyPasswordResponseCallback callback) {
- XCTAssertEqualObjects(request.APIKey, kAPIKey);
- XCTAssertEqualObjects(request.email, kEmail);
- XCTAssertEqualObjects(request.password, kFakePassword);
- XCTAssertTrue(request.returnSecureToken);
- dispatch_async(FIRAuthGlobalWorkQueue(), ^() {
- id mockVerifyPasswordResponse = OCMClassMock([FIRVerifyPasswordResponse class]);
- [self stubTokensWithMockResponse:mockVerifyPasswordResponse];
- callback(mockVerifyPasswordResponse, nil);
- });
- });
- [self expectGetAccountInfo];
- XCTestExpectation *signInExpectation = [self expectationWithDescription:@"signIn"];
- [[FIRAuth auth] signOut:NULL];
- [[FIRAuth auth] signInWithEmail:kEmail
- password:kFakePassword
- completion:^(FIRAuthDataResult *_Nullable result, NSError *_Nullable error) {
- [self assertUser:result.user];
- XCTAssertNil(error);
- [signInExpectation fulfill];
- }];
- [self waitForExpectationsWithTimeout:kExpectationTimeout handler:nil];
- [self assertUser:[FIRAuth auth].currentUser];
- OCMExpect([_mockBackend revokeToken:[OCMArg any] callback:[OCMArg any]])
- .andCallBlock2(
- ^(FIRRevokeTokenRequest *_Nullable request, FIRRevokeTokenResponseCallback callback) {
- dispatch_async(FIRAuthGlobalWorkQueue(), ^() {
- id mockRevokeTokenResponse = OCMClassMock([FIRRevokeTokenResponse class]);
- callback(mockRevokeTokenResponse, nil);
- });
- });
- XCTestExpectation *revokeExpectation = [self expectationWithDescription:@"callback"];
- NSString *code = @"code";
- [[FIRAuth auth] revokeTokenWithAuthorizationCode:code
- completion:^(NSError *_Nullable error) {
- XCTAssertNil(error);
- [revokeExpectation fulfill];
- }];
- [self waitForExpectationsWithTimeout:kExpectationTimeout handler:nil];
- }
- /** @fn testRevokeTokenMissingCallback
- @brief Tests the flow of @c revokeToken:completion with a nil callback.
- */
- - (void)testRevokeTokenMissingCallback {
- OCMExpect([_mockBackend verifyPassword:[OCMArg any] callback:[OCMArg any]])
- .andCallBlock2(^(FIRVerifyPasswordRequest *_Nullable request,
- FIRVerifyPasswordResponseCallback callback) {
- XCTAssertEqualObjects(request.APIKey, kAPIKey);
- XCTAssertEqualObjects(request.email, kEmail);
- XCTAssertEqualObjects(request.password, kFakePassword);
- XCTAssertTrue(request.returnSecureToken);
- dispatch_async(FIRAuthGlobalWorkQueue(), ^() {
- id mockVerifyPasswordResponse = OCMClassMock([FIRVerifyPasswordResponse class]);
- [self stubTokensWithMockResponse:mockVerifyPasswordResponse];
- callback(mockVerifyPasswordResponse, nil);
- });
- });
- [self expectGetAccountInfo];
- XCTestExpectation *signInExpectation = [self expectationWithDescription:@"signIn"];
- [[FIRAuth auth] signOut:NULL];
- [[FIRAuth auth] signInWithEmail:kEmail
- password:kFakePassword
- completion:^(FIRAuthDataResult *_Nullable result, NSError *_Nullable error) {
- [self assertUser:result.user];
- XCTAssertNil(error);
- [signInExpectation fulfill];
- }];
- [self waitForExpectationsWithTimeout:kExpectationTimeout handler:nil];
- [self assertUser:[FIRAuth auth].currentUser];
- XCTestExpectation *revokeExpectation = [self expectationWithDescription:@"revoke"];
- OCMExpect([_mockBackend revokeToken:[OCMArg any] callback:[OCMArg any]])
- .andCallBlock2(
- ^(FIRRevokeTokenRequest *_Nullable request, FIRRevokeTokenResponseCallback callback) {
- dispatch_async(FIRAuthGlobalWorkQueue(), ^() {
- id mockRevokeTokenResponse = OCMClassMock([FIRRevokeTokenResponse class]);
- callback(mockRevokeTokenResponse, nil);
- [revokeExpectation fulfill];
- });
- });
- NSString *code = @"code";
- [[FIRAuth auth] revokeTokenWithAuthorizationCode:code completion:nil];
- [self waitForExpectationsWithTimeout:kExpectationTimeout handler:nil];
- }
- @end
|