FIRAuthTests.m 157 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339
  1. /*
  2. * Copyright 2017 Google
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License");
  5. * you may not use this file except in compliance with the License.
  6. * You may obtain a copy of the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS,
  12. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. * See the License for the specific language governing permissions and
  14. * limitations under the License.
  15. */
  16. #import <Foundation/Foundation.h>
  17. #import <OCMock/OCMock.h>
  18. #import <XCTest/XCTest.h>
  19. #import <GoogleUtilities/GULAppDelegateSwizzler.h>
  20. #import "FirebaseAuth/Interop/FIRAuthInterop.h"
  21. #import "FirebaseAuth/Sources/Public/FirebaseAuth/FIRActionCodeSettings.h"
  22. #import "FirebaseAuth/Sources/Public/FirebaseAuth/FIRAdditionalUserInfo.h"
  23. #import "FirebaseAuth/Sources/Public/FirebaseAuth/FIRAuthSettings.h"
  24. #import "FirebaseAuth/Sources/Public/FirebaseAuth/FIREmailAuthProvider.h"
  25. #import "FirebaseAuth/Sources/Public/FirebaseAuth/FIRFacebookAuthProvider.h"
  26. #import "FirebaseAuth/Sources/Public/FirebaseAuth/FIRGoogleAuthProvider.h"
  27. #import "FirebaseAuth/Sources/Public/FirebaseAuth/FIROAuthProvider.h"
  28. #import "FirebaseCore/Extension/FirebaseCoreInternal.h"
  29. #import "FirebaseAuth/Sources/Auth/FIRAuthDispatcher.h"
  30. #import "FirebaseAuth/Sources/Auth/FIRAuthGlobalWorkQueue.h"
  31. #import "FirebaseAuth/Sources/Auth/FIRAuthOperationType.h"
  32. #import "FirebaseAuth/Sources/Auth/FIRAuth_Internal.h"
  33. #import "FirebaseAuth/Sources/AuthProvider/OAuth/FIROAuthCredential_Internal.h"
  34. #import "FirebaseAuth/Sources/Backend/FIRAuthBackend.h"
  35. #import "FirebaseAuth/Sources/Backend/RPC/FIRCreateAuthURIRequest.h"
  36. #import "FirebaseAuth/Sources/Backend/RPC/FIRCreateAuthURIResponse.h"
  37. #import "FirebaseAuth/Sources/Backend/RPC/FIREmailLinkSignInRequest.h"
  38. #import "FirebaseAuth/Sources/Backend/RPC/FIREmailLinkSignInResponse.h"
  39. #import "FirebaseAuth/Sources/Backend/RPC/FIRGetAccountInfoRequest.h"
  40. #import "FirebaseAuth/Sources/Backend/RPC/FIRGetAccountInfoResponse.h"
  41. #import "FirebaseAuth/Sources/Backend/RPC/FIRGetOOBConfirmationCodeRequest.h"
  42. #import "FirebaseAuth/Sources/Backend/RPC/FIRGetOOBConfirmationCodeResponse.h"
  43. #import "FirebaseAuth/Sources/Backend/RPC/FIRResetPasswordRequest.h"
  44. #import "FirebaseAuth/Sources/Backend/RPC/FIRResetPasswordResponse.h"
  45. #import "FirebaseAuth/Sources/Backend/RPC/FIRRevokeTokenRequest.h"
  46. #import "FirebaseAuth/Sources/Backend/RPC/FIRRevokeTokenResponse.h"
  47. #import "FirebaseAuth/Sources/Backend/RPC/FIRSecureTokenRequest.h"
  48. #import "FirebaseAuth/Sources/Backend/RPC/FIRSecureTokenResponse.h"
  49. #import "FirebaseAuth/Sources/Backend/RPC/FIRSetAccountInfoRequest.h"
  50. #import "FirebaseAuth/Sources/Backend/RPC/FIRSetAccountInfoResponse.h"
  51. #import "FirebaseAuth/Sources/Backend/RPC/FIRSignUpNewUserRequest.h"
  52. #import "FirebaseAuth/Sources/Backend/RPC/FIRSignUpNewUserResponse.h"
  53. #import "FirebaseAuth/Sources/Backend/RPC/FIRVerifyAssertionRequest.h"
  54. #import "FirebaseAuth/Sources/Backend/RPC/FIRVerifyAssertionResponse.h"
  55. #import "FirebaseAuth/Sources/Backend/RPC/FIRVerifyCustomTokenRequest.h"
  56. #import "FirebaseAuth/Sources/Backend/RPC/FIRVerifyCustomTokenResponse.h"
  57. #import "FirebaseAuth/Sources/Backend/RPC/FIRVerifyPasswordRequest.h"
  58. #import "FirebaseAuth/Sources/Backend/RPC/FIRVerifyPasswordResponse.h"
  59. #import "FirebaseAuth/Sources/Backend/RPC/FIRVerifyPhoneNumberRequest.h"
  60. #import "FirebaseAuth/Sources/Backend/RPC/FIRVerifyPhoneNumberResponse.h"
  61. #import "FirebaseAuth/Sources/User/FIRUser_Internal.h"
  62. #import "FirebaseAuth/Sources/Utilities/FIRAuthErrorUtils.h"
  63. #import "FirebaseAuth/Sources/Utilities/FIRAuthRecaptchaVerifier.h"
  64. #import "FirebaseAuth/Tests/Unit/FIRApp+FIRAuthUnitTests.h"
  65. #import "FirebaseAuth/Tests/Unit/OCMStubRecorder+FIRAuthUnitTests.h"
  66. #if TARGET_OS_IOS
  67. #import "FirebaseAuth/Sources/Public/FirebaseAuth/FIRAuthUIDelegate.h"
  68. #import "FirebaseAuth/Sources/Public/FirebaseAuth/FIRPhoneAuthCredential.h"
  69. #import "FirebaseAuth/Sources/Public/FirebaseAuth/FIRPhoneAuthProvider.h"
  70. #import "FirebaseAuth/Sources/SystemService/FIRAuthAPNSToken.h"
  71. #import "FirebaseAuth/Sources/SystemService/FIRAuthAPNSTokenManager.h"
  72. #import "FirebaseAuth/Sources/SystemService/FIRAuthNotificationManager.h"
  73. #import "FirebaseAuth/Sources/Utilities/FIRAuthURLPresenter.h"
  74. #endif // TARGET_OS_IOS
  75. /** @var kAPIKey
  76. @brief The fake API key.
  77. */
  78. static NSString *const kAPIKey = @"FAKE_API_KEY";
  79. /** @var kFirebaseAppID
  80. @brief The fake Firebase app ID.
  81. */
  82. static NSString *const kFirebaseAppID = @"FAKE_APP_ID";
  83. /** @var kAccessToken
  84. @brief The fake access token.
  85. */
  86. static NSString *const kAccessToken = @"ACCESS_TOKEN";
  87. /** @var kNewAccessToken
  88. @brief Another fake access token used to simulate token refreshed via automatic token refresh.
  89. */
  90. NSString *kNewAccessToken = @"NewAccessToken";
  91. /** @var kAccessTokenValidInterval
  92. @brief The time to live for the fake access token.
  93. */
  94. static const NSTimeInterval kAccessTokenTimeToLive = 60 * 60;
  95. /** @var kTestTokenExpirationTimeInterval
  96. @brief The fake time interval that it takes a token to expire.
  97. */
  98. static const NSTimeInterval kTestTokenExpirationTimeInterval = 55 * 60;
  99. /** @var kRefreshToken
  100. @brief The fake refresh token.
  101. */
  102. static NSString *const kRefreshToken = @"REFRESH_TOKEN";
  103. /** @var kEmail
  104. @brief The fake user email.
  105. */
  106. static NSString *const kEmail = @"user@company.com";
  107. /** @var kFakePassword
  108. @brief The fake user password.
  109. */
  110. static NSString *const kFakePassword = @"!@#$%^";
  111. /** @var kPasswordHash
  112. @brief The fake user password hash.
  113. */
  114. static NSString *const kPasswordHash = @"UkVEQUNURUQ=";
  115. /** @var kLocalID
  116. @brief The fake local user ID.
  117. */
  118. static NSString *const kLocalID = @"LOCAL_ID";
  119. /** @var kDisplayName
  120. @brief The fake user display name.
  121. */
  122. static NSString *const kDisplayName = @"User Doe";
  123. /** @var kIDToken
  124. @brief The fake id token.
  125. */
  126. static NSString *const kIDToken = @"IDToken";
  127. /** @var kFakeGivenName
  128. @brief The fake user given name.
  129. */
  130. static NSString *const kFakeGivenName = @"Firstname";
  131. /** @var kFakeFamilyName
  132. @brief The fake user family name.
  133. */
  134. static NSString *const kFakeFamilyName = @"Lastname";
  135. /** @var kGoogleUD
  136. @brief The fake user ID under Google Sign-In.
  137. */
  138. static NSString *const kGoogleID = @"GOOGLE_ID";
  139. /** @var kGoogleEmail
  140. @brief The fake user email under Google Sign-In.
  141. */
  142. static NSString *const kGoogleEmail = @"user@gmail.com";
  143. /** @var kGoogleDisplayName
  144. @brief The fake user display name under Google Sign-In.
  145. */
  146. static NSString *const kGoogleDisplayName = @"Google Doe";
  147. /** @var kGoogleAccessToken
  148. @brief The fake access token from Google Sign-In.
  149. */
  150. static NSString *const kGoogleAccessToken = @"GOOGLE_ACCESS_TOKEN";
  151. /** @var kGoogleIDToken
  152. @brief The fake ID token from Google Sign-In.
  153. */
  154. static NSString *const kGoogleIDToken = @"GOOGLE_ID_TOKEN";
  155. /** @var kAppleAuthProviderID
  156. @brief The provider ID for Apple Sign-In.
  157. */
  158. static NSString *const kAppleAuthProviderID = @"apple.com";
  159. /** @var kAppleIDToken
  160. @brief The fake ID token from Apple Sign-In.
  161. */
  162. static NSString *const kAppleIDToken = @"APPLE_ID_TOKEN";
  163. /** @var kCustomToken
  164. @brief The fake custom token to sign in.
  165. */
  166. static NSString *const kCustomToken = @"CUSTOM_TOKEN";
  167. /** @var kVerificationCode
  168. @brief Fake verification code used for testing.
  169. */
  170. static NSString *const kVerificationCode = @"12345678";
  171. /** @var kVerificationID
  172. @brief Fake verification ID for testing.
  173. */
  174. static NSString *const kVerificationID = @"55432";
  175. /** @var kOAuthRequestURI
  176. @brief Fake OAuthRequest URI for testing.
  177. */
  178. static NSString *const kOAuthRequestURI = @"requestURI";
  179. /** @var kOAuthSessionID
  180. @brief Fake session ID for testing.
  181. */
  182. static NSString *const kOAuthSessionID = @"sessionID";
  183. /** @var kFakeWebSignInUserInteractionFailureReason
  184. @brief Fake reason for FIRAuthErrorCodeWebSignInUserInteractionFailure error while testing.
  185. */
  186. static NSString *const kFakeWebSignInUserInteractionFailureReason = @"fake_reason";
  187. /** @var kContinueURL
  188. @brief Fake string value of continue url.
  189. */
  190. static NSString *const kContinueURL = @"continueURL";
  191. /** @var kCanHandleCodeInAppKey
  192. @brief The key for the request parameter indicating whether the action code can be handled in
  193. the app or not.
  194. */
  195. static NSString *const kCanHandleCodeInAppKey = @"canHandleCodeInApp";
  196. /** @var kFIREmailLinkAuthSignInMethod
  197. @brief Fake email link sign-in method for testing.
  198. */
  199. static NSString *const kFIREmailLinkAuthSignInMethod = @"emailLink";
  200. /** @var kFIRFacebookAuthSignInMethod
  201. @brief Fake Facebook sign-in method for testing.
  202. */
  203. static NSString *const kFIRFacebookAuthSignInMethod = @"facebook.com";
  204. /** @var kBadSignInEmailLink
  205. @brief Bad sign-in link to test email link sign-in
  206. */
  207. static NSString *const kBadSignInEmailLink = @"http://www.facebook.com";
  208. /** @var kFakeEmailSignInDeeplink
  209. @brief Fake email sign-in link
  210. */
  211. static NSString *const kFakeEmailSignInDeeplink =
  212. @"https://example.domain.com/?apiKey=testAPIKey&oobCode=testoobcode&mode=signIn";
  213. /** @var kFakeEmailSignInlink
  214. @brief Fake email sign-in link
  215. */
  216. static NSString *const kFakeEmailSignInlink =
  217. @"https://test.app.goo.gl/?link=https://test.firebase"
  218. "app.com/__/auth/"
  219. "action?apiKey%3DtestAPIKey%26mode%3DsignIn%26oobCode%3Dtestoobcode%26continueU"
  220. "rl%3Dhttps://test.apps.com&ibi=com.test.com&ifl=https://test.firebaseapp.com/__/auth/"
  221. "action?ap"
  222. "iKey%3DtestAPIKey%26mode%3DsignIn%26oobCode%3Dtestoobcode%26continueUrl%3Dhttps://"
  223. "test.apps.co"
  224. "m";
  225. /** @var kExpectationTimeout
  226. @brief The maximum time waiting for expectations to fulfill.
  227. */
  228. static const NSTimeInterval kExpectationTimeout = 2;
  229. /** @var kWaitInterval
  230. @brief The time waiting for background tasks to finish before continue when necessary.
  231. */
  232. static const NSTimeInterval kWaitInterval = .5;
  233. /** @var kFakeRecaptchaResponse
  234. @brief The fake recaptcha response.
  235. */
  236. static NSString *const kFakeRecaptchaResponse = @"RecaptchaResponse";
  237. /** @var kFakeRecaptchaVersion
  238. @brief The fake recaptcha version.
  239. */
  240. static NSString *const kFakeRecaptchaVersion = @"RecaptchaVersion";
  241. #if TARGET_OS_IOS
  242. /** @class FIRAuthAppDelegate
  243. @brief Application delegate implementation to test the app delegate proxying
  244. */
  245. @interface FIRAuthAppDelegate : NSObject <UIApplicationDelegate>
  246. @end
  247. @implementation FIRAuthAppDelegate
  248. - (void)application:(UIApplication *)application
  249. didReceiveRemoteNotification:(NSDictionary *)userInfo
  250. fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler {
  251. }
  252. - (BOOL)application:(UIApplication *)app
  253. openURL:(NSURL *)url
  254. options:(NSDictionary<UIApplicationOpenURLOptionsKey, id> *)options {
  255. return NO;
  256. }
  257. @end
  258. #endif // TARGET_OS_IOS
  259. @interface GULAppDelegateSwizzler (FIRMessagingRemoteNotificationsProxyTest)
  260. + (void)resetProxyOriginalDelegateOnceToken;
  261. @end
  262. /** Category for FIRAuth to expose FIRComponentRegistrant conformance. */
  263. @interface FIRAuth () <FIRLibrary>
  264. @end
  265. /** @class FIRAuthTests
  266. @brief Tests for @c FIRAuth.
  267. */
  268. @interface FIRAuthTests : XCTestCase
  269. #if TARGET_OS_IOS
  270. /// A partial mock of `[FIRAuth auth].tokenManager`
  271. @property(nonatomic, strong) id mockTokenManager;
  272. /// A partial mock of `[FIRAuth auth].notificationManager`
  273. @property(nonatomic, strong) id mockNotificationManager;
  274. /// A partial mock of `[FIRAuth auth].authURLPresenter`
  275. @property(nonatomic, strong) id mockAuthURLPresenter;
  276. /// An application delegate instance returned by `self.mockApplication.delegate`
  277. @property(nonatomic, strong) FIRAuthAppDelegate *fakeApplicationDelegate;
  278. #endif // TARGET_OS_IOS
  279. @end
  280. @implementation FIRAuthTests {
  281. /** @var _mockBackend
  282. @brief The mock @c FIRAuthBackendImplementation .
  283. */
  284. id _mockBackend;
  285. /** @var _FIRAuthDispatcherCallback
  286. @brief Used to save a task from FIRAuthDispatcher to be executed later.
  287. */
  288. __block void (^_Nonnull _FIRAuthDispatcherCallback)(void);
  289. }
  290. /** @fn googleProfile
  291. @brief The fake user profile under additional user data in @c FIRVerifyAssertionResponse.
  292. */
  293. + (NSDictionary *)googleProfile {
  294. static NSDictionary *kGoogleProfile = nil;
  295. static dispatch_once_t onceToken;
  296. dispatch_once(&onceToken, ^{
  297. kGoogleProfile = @{
  298. @"iss" : @"https://accounts.google.com\\",
  299. @"email" : kGoogleEmail,
  300. @"given_name" : @"User",
  301. @"family_name" : @"Doe"
  302. };
  303. });
  304. return kGoogleProfile;
  305. }
  306. - (void)setUp {
  307. [super setUp];
  308. #if TARGET_OS_IOS
  309. // Make sure the `self.fakeApplicationDelegate` will be swizzled on FIRAuth init.
  310. [GULAppDelegateSwizzler resetProxyOriginalDelegateOnceToken];
  311. self.fakeApplicationDelegate = [[FIRAuthAppDelegate alloc] init];
  312. [[GULAppDelegateSwizzler sharedApplication]
  313. setDelegate:(id<UIApplicationDelegate>)self.fakeApplicationDelegate];
  314. #endif // TARGET_OS_IOS
  315. _mockBackend = OCMProtocolMock(@protocol(FIRAuthBackendImplementation));
  316. [FIRAuthBackend setBackendImplementation:_mockBackend];
  317. [FIRApp resetAppForAuthUnitTests];
  318. // Set FIRAuthDispatcher implementation in order to save the token refresh task for later
  319. // execution.
  320. [[FIRAuthDispatcher sharedInstance]
  321. setDispatchAfterImplementation:^(NSTimeInterval delay, dispatch_queue_t _Nonnull queue,
  322. void (^task)(void)) {
  323. XCTAssertNotNil(task);
  324. XCTAssert(delay > 0);
  325. XCTAssertEqualObjects(FIRAuthGlobalWorkQueue(), queue);
  326. self->_FIRAuthDispatcherCallback = task;
  327. }];
  328. #if TARGET_OS_IOS
  329. // Wait until FIRAuth initialization completes
  330. [self waitForAuthGlobalWorkQueueDrain];
  331. self.mockTokenManager = OCMPartialMock([FIRAuth auth].tokenManager);
  332. self.mockNotificationManager = OCMPartialMock([FIRAuth auth].notificationManager);
  333. self.mockAuthURLPresenter = OCMPartialMock([FIRAuth auth].authURLPresenter);
  334. #endif // TARGET_OS_IOS
  335. }
  336. - (void)tearDown {
  337. [FIRAuthBackend setDefaultBackendImplementationWithRPCIssuer:nil];
  338. [[FIRAuthDispatcher sharedInstance] setDispatchAfterImplementation:nil];
  339. #if TARGET_OS_IOS
  340. [self.mockAuthURLPresenter stopMocking];
  341. self.mockAuthURLPresenter = nil;
  342. [self.mockNotificationManager stopMocking];
  343. self.mockNotificationManager = nil;
  344. [self.mockTokenManager stopMocking];
  345. self.mockTokenManager = nil;
  346. self.fakeApplicationDelegate = nil;
  347. #endif // TARGET_OS_IOS
  348. [super tearDown];
  349. }
  350. #pragma mark - Server API Tests
  351. /** @fn testFetchSignInMethodsForEmailSuccess
  352. @brief Tests the flow of a successful @c fetchSignInMethodsForEmail:completion: call.
  353. */
  354. - (void)testFetchSignInMethodsForEmailSuccess {
  355. NSArray<NSString *> *allSignInMethods =
  356. @[ kFIREmailLinkAuthSignInMethod, kFIRFacebookAuthSignInMethod ];
  357. OCMExpect([_mockBackend createAuthURI:[OCMArg any] callback:[OCMArg any]])
  358. .andCallBlock2(
  359. ^(FIRCreateAuthURIRequest *_Nullable request, FIRCreateAuthURIResponseCallback callback) {
  360. XCTAssertEqualObjects(request.identifier, kEmail);
  361. XCTAssertNotNil(request.endpoint);
  362. XCTAssertEqualObjects(request.APIKey, kAPIKey);
  363. dispatch_async(FIRAuthGlobalWorkQueue(), ^() {
  364. id mockCreateAuthURIResponse = OCMClassMock([FIRCreateAuthURIResponse class]);
  365. OCMStub([mockCreateAuthURIResponse signinMethods]).andReturn(allSignInMethods);
  366. callback(mockCreateAuthURIResponse, nil);
  367. });
  368. });
  369. XCTestExpectation *expectation = [self expectationWithDescription:@"callback"];
  370. #pragma clang diagnostic push
  371. #pragma clang diagnostic ignored "-Wdeprecated-declarations"
  372. [[FIRAuth auth] fetchSignInMethodsForEmail:kEmail
  373. completion:^(NSArray<NSString *> *_Nullable signInMethods,
  374. NSError *_Nullable error) {
  375. XCTAssertTrue([NSThread isMainThread]);
  376. XCTAssertEqualObjects(signInMethods, allSignInMethods);
  377. XCTAssertTrue([allSignInMethods isKindOfClass:[NSArray class]]);
  378. XCTAssertNil(error);
  379. [expectation fulfill];
  380. }];
  381. #pragma clang diagnostic pop
  382. [self waitForExpectationsWithTimeout:kExpectationTimeout handler:nil];
  383. OCMVerifyAll(_mockBackend);
  384. }
  385. /** @fn testFetchSignInMethodsForEmailFailure
  386. @brief Tests the flow of a failed @c fetchSignInMethodsForEmail:completion: call.
  387. */
  388. - (void)testFetchSignInMethodsForEmailFailure {
  389. OCMExpect([_mockBackend createAuthURI:[OCMArg any] callback:[OCMArg any]])
  390. .andDispatchError2([FIRAuthErrorUtils tooManyRequestsErrorWithMessage:nil]);
  391. XCTestExpectation *expectation = [self expectationWithDescription:@"callback"];
  392. #pragma clang diagnostic push
  393. #pragma clang diagnostic ignored "-Wdeprecated-declarations"
  394. [[FIRAuth auth] fetchSignInMethodsForEmail:kEmail
  395. completion:^(NSArray<NSString *> *_Nullable signInMethods,
  396. NSError *_Nullable error) {
  397. XCTAssertTrue([NSThread isMainThread]);
  398. XCTAssertNil(signInMethods);
  399. XCTAssertEqual(error.code, FIRAuthErrorCodeTooManyRequests);
  400. XCTAssertNotNil(error.userInfo[NSLocalizedDescriptionKey]);
  401. [expectation fulfill];
  402. }];
  403. #pragma clang diagnostic pop
  404. [self waitForExpectationsWithTimeout:kExpectationTimeout handler:nil];
  405. OCMVerifyAll(_mockBackend);
  406. }
  407. #if TARGET_OS_IOS
  408. /** @fn testPhoneAuthSuccess
  409. @brief Tests the flow of a successful @c signInWithCredential:completion for phone auth.
  410. */
  411. - (void)testPhoneAuthSuccess {
  412. OCMExpect([_mockBackend verifyPhoneNumber:[OCMArg any] callback:[OCMArg any]])
  413. .andCallBlock2(^(FIRVerifyPhoneNumberRequest *_Nullable request,
  414. FIRVerifyPhoneNumberResponseCallback callback) {
  415. XCTAssertEqualObjects(request.verificationCode, kVerificationCode);
  416. XCTAssertEqualObjects(request.verificationID, kVerificationID);
  417. XCTAssertEqual(request.operation, FIRAuthOperationTypeSignUpOrSignIn);
  418. dispatch_async(FIRAuthGlobalWorkQueue(), ^() {
  419. id mockVerifyPhoneResponse = OCMClassMock([FIRVerifyPhoneNumberResponse class]);
  420. [self stubTokensWithMockResponse:mockVerifyPhoneResponse];
  421. // Stub isNewUser flag in the response.
  422. OCMStub([mockVerifyPhoneResponse isNewUser]).andReturn(YES);
  423. callback(mockVerifyPhoneResponse, nil);
  424. });
  425. });
  426. [self expectGetAccountInfo];
  427. XCTestExpectation *expectation = [self expectationWithDescription:@"callback"];
  428. [[FIRAuth auth] signOut:NULL];
  429. FIRAuthCredential *credential =
  430. [[FIRPhoneAuthProvider provider] credentialWithVerificationID:kVerificationID
  431. verificationCode:kVerificationCode];
  432. [[FIRAuth auth] signInWithCredential:credential
  433. completion:^(FIRAuthDataResult *_Nullable authDataResult,
  434. NSError *_Nullable error) {
  435. XCTAssertTrue([NSThread isMainThread]);
  436. [self assertUser:authDataResult.user];
  437. XCTAssertTrue(authDataResult.additionalUserInfo.isNewUser);
  438. XCTAssertNil(error);
  439. [expectation fulfill];
  440. }];
  441. [self waitForExpectationsWithTimeout:kExpectationTimeout handler:nil];
  442. [self assertUser:[FIRAuth auth].currentUser];
  443. OCMVerifyAll(_mockBackend);
  444. }
  445. /** @fn testPhoneAuthMissingVerificationCode
  446. @brief Tests the flow of an unsuccessful @c signInWithCredential:completion for phone auth due
  447. to an empty verification code
  448. */
  449. - (void)testPhoneAuthMissingVerificationCode {
  450. XCTestExpectation *expectation = [self expectationWithDescription:@"callback"];
  451. [[FIRAuth auth] signOut:NULL];
  452. FIRAuthCredential *credential =
  453. [[FIRPhoneAuthProvider provider] credentialWithVerificationID:kVerificationID
  454. verificationCode:@""];
  455. [[FIRAuth auth]
  456. signInWithCredential:credential
  457. completion:^(FIRAuthDataResult *_Nullable result, NSError *_Nullable error) {
  458. XCTAssertTrue([NSThread isMainThread]);
  459. XCTAssertNil(result);
  460. XCTAssertEqual(error.code, FIRAuthErrorCodeMissingVerificationCode);
  461. [expectation fulfill];
  462. }];
  463. [self waitForExpectationsWithTimeout:kExpectationTimeout handler:nil];
  464. }
  465. /** @fn testPhoneAuthMissingVerificationID
  466. @brief Tests the flow of an unsuccessful @c signInWithCredential:completion for phone auth due
  467. to an empty verification ID.
  468. */
  469. - (void)testPhoneAuthMissingVerificationID {
  470. XCTestExpectation *expectation = [self expectationWithDescription:@"callback"];
  471. [[FIRAuth auth] signOut:NULL];
  472. FIRAuthCredential *credential =
  473. [[FIRPhoneAuthProvider provider] credentialWithVerificationID:@""
  474. verificationCode:kVerificationCode];
  475. [[FIRAuth auth]
  476. signInWithCredential:credential
  477. completion:^(FIRAuthDataResult *_Nullable result, NSError *_Nullable error) {
  478. XCTAssertTrue([NSThread isMainThread]);
  479. XCTAssertNil(result);
  480. XCTAssertEqual(error.code, FIRAuthErrorCodeMissingVerificationID);
  481. [expectation fulfill];
  482. }];
  483. [self waitForExpectationsWithTimeout:kExpectationTimeout handler:nil];
  484. }
  485. #endif
  486. /** @fn testSignInWithEmailLinkSuccess
  487. @brief Tests the flow of a successful @c signInWithEmail:link:completion: call.
  488. */
  489. - (void)testSignInWithEmailLinkSuccess {
  490. NSString *fakeCode = @"testoobcode";
  491. OCMExpect([_mockBackend emailLinkSignin:[OCMArg any] callback:[OCMArg any]])
  492. .andCallBlock2(^(FIREmailLinkSignInRequest *_Nullable request,
  493. FIREmailLinkSigninResponseCallback callback) {
  494. XCTAssertEqualObjects(request.email, kEmail);
  495. XCTAssertEqualObjects(request.oobCode, fakeCode);
  496. dispatch_async(FIRAuthGlobalWorkQueue(), ^() {
  497. id mockEmailLinkSignInResponse = OCMClassMock([FIREmailLinkSignInResponse class]);
  498. [self stubTokensWithMockResponse:mockEmailLinkSignInResponse];
  499. callback(mockEmailLinkSignInResponse, nil);
  500. OCMStub([mockEmailLinkSignInResponse refreshToken]).andReturn(kRefreshToken);
  501. });
  502. });
  503. [self expectGetAccountInfo];
  504. XCTestExpectation *expectation = [self expectationWithDescription:@"callback"];
  505. [[FIRAuth auth] signOut:NULL];
  506. [[FIRAuth auth]
  507. signInWithEmail:kEmail
  508. link:kFakeEmailSignInlink
  509. completion:^(FIRAuthDataResult *_Nullable authResult, NSError *_Nullable error) {
  510. XCTAssertTrue([NSThread isMainThread]);
  511. XCTAssertNotNil(authResult.user);
  512. XCTAssertEqualObjects(authResult.user.refreshToken, kRefreshToken);
  513. XCTAssertFalse(authResult.user.anonymous);
  514. XCTAssertEqualObjects(authResult.user.email, kEmail);
  515. XCTAssertNil(error);
  516. [expectation fulfill];
  517. }];
  518. [self waitForExpectationsWithTimeout:kExpectationTimeout handler:nil];
  519. [self assertUser:[FIRAuth auth].currentUser];
  520. OCMVerifyAll(_mockBackend);
  521. }
  522. /** @fn testSignInWithEmailLinkSuccessDeeplink
  523. @brief Tests the flow of a successful @c signInWithEmail:link:completion: call using a deep
  524. link.
  525. */
  526. - (void)testSignInWithEmailLinkSuccessDeeplink {
  527. NSString *fakeCode = @"testoobcode";
  528. OCMExpect([_mockBackend emailLinkSignin:[OCMArg any] callback:[OCMArg any]])
  529. .andCallBlock2(^(FIREmailLinkSignInRequest *_Nullable request,
  530. FIREmailLinkSigninResponseCallback callback) {
  531. XCTAssertEqualObjects(request.email, kEmail);
  532. XCTAssertEqualObjects(request.oobCode, fakeCode);
  533. dispatch_async(FIRAuthGlobalWorkQueue(), ^() {
  534. id mockEmailLinkSignInResponse = OCMClassMock([FIREmailLinkSignInResponse class]);
  535. [self stubTokensWithMockResponse:mockEmailLinkSignInResponse];
  536. callback(mockEmailLinkSignInResponse, nil);
  537. OCMStub([mockEmailLinkSignInResponse refreshToken]).andReturn(kRefreshToken);
  538. });
  539. });
  540. [self expectGetAccountInfo];
  541. XCTestExpectation *expectation = [self expectationWithDescription:@"callback"];
  542. [[FIRAuth auth] signOut:NULL];
  543. [[FIRAuth auth]
  544. signInWithEmail:kEmail
  545. link:kFakeEmailSignInDeeplink
  546. completion:^(FIRAuthDataResult *_Nullable authResult, NSError *_Nullable error) {
  547. XCTAssertTrue([NSThread isMainThread]);
  548. XCTAssertNotNil(authResult.user);
  549. XCTAssertEqualObjects(authResult.user.refreshToken, kRefreshToken);
  550. XCTAssertFalse(authResult.user.anonymous);
  551. XCTAssertEqualObjects(authResult.user.email, kEmail);
  552. XCTAssertNil(error);
  553. [expectation fulfill];
  554. }];
  555. [self waitForExpectationsWithTimeout:kExpectationTimeout handler:nil];
  556. [self assertUser:[FIRAuth auth].currentUser];
  557. OCMVerifyAll(_mockBackend);
  558. }
  559. /** @fn testSignInWithEmailLinkFailure
  560. @brief Tests the flow of a failed @c signInWithEmail:link:completion: call.
  561. */
  562. - (void)testSignInWithEmailLinkFailure {
  563. OCMExpect([_mockBackend emailLinkSignin:[OCMArg any] callback:[OCMArg any]])
  564. ._andDispatchError2([FIRAuthErrorUtils invalidActionCodeErrorWithMessage:nil]);
  565. XCTestExpectation *expectation = [self expectationWithDescription:@"callback"];
  566. [[FIRAuth auth] signOut:NULL];
  567. [[FIRAuth auth]
  568. signInWithEmail:kEmail
  569. link:kFakeEmailSignInlink
  570. completion:^(FIRAuthDataResult *_Nullable authResult, NSError *_Nullable error) {
  571. XCTAssertTrue([NSThread isMainThread]);
  572. XCTAssertEqual(error.code, FIRAuthErrorCodeInvalidActionCode);
  573. [expectation fulfill];
  574. }];
  575. [self waitForExpectationsWithTimeout:kExpectationTimeout handler:nil];
  576. OCMVerifyAll(_mockBackend);
  577. }
  578. #if TARGET_OS_IOS && !TARGET_OS_MACCATALYST
  579. /** @fn testSignInWithEmailPasswordWithRecaptchaSuccess
  580. @brief Tests the flow of a successful @c signInWithEmail:password:completion: call.
  581. */
  582. - (void)testSignInWithEmailPasswordWithRecaptchaSuccess {
  583. id mockVerifier = OCMClassMock([FIRAuthRecaptchaVerifier class]);
  584. OCMStub([mockVerifier sharedRecaptchaVerifier:[FIRAuth auth]]).andReturn(mockVerifier);
  585. OCMExpect([mockVerifier enablementStatusForProvider:FIRAuthRecaptchaProviderPassword])
  586. .andReturn(YES);
  587. FIRVerifyPasswordRequest *constRequestWithRecaptchaToken =
  588. [[FIRVerifyPasswordRequest alloc] initWithEmail:kEmail
  589. password:kFakePassword
  590. requestConfiguration:[FIRAuth auth].requestConfiguration];
  591. [constRequestWithRecaptchaToken injectRecaptchaFields:kFakeRecaptchaResponse
  592. recaptchaVersion:kFakeRecaptchaVersion];
  593. OCMStub([mockVerifier
  594. injectRecaptchaFields:[OCMArg any]
  595. provider:FIRAuthRecaptchaProviderPassword
  596. action:FIRAuthRecaptchaActionSignInWithPassword
  597. completion:([OCMArg invokeBlockWithArgs:constRequestWithRecaptchaToken, nil])]);
  598. OCMExpect([_mockBackend verifyPassword:[OCMArg any] callback:[OCMArg any]])
  599. .andCallBlock2(^(FIRVerifyPasswordRequest *_Nullable request,
  600. FIRVerifyPasswordResponseCallback callback) {
  601. XCTAssertEqualObjects(request.APIKey, kAPIKey);
  602. XCTAssertEqualObjects(request.email, kEmail);
  603. XCTAssertEqualObjects(request.password, kFakePassword);
  604. XCTAssertTrue(request.returnSecureToken);
  605. dispatch_async(FIRAuthGlobalWorkQueue(), ^() {
  606. id mockVerifyPasswordResponse = OCMClassMock([FIRVerifyPasswordResponse class]);
  607. [self stubTokensWithMockResponse:mockVerifyPasswordResponse];
  608. callback(mockVerifyPasswordResponse, nil);
  609. });
  610. });
  611. [self expectGetAccountInfo];
  612. XCTestExpectation *expectation = [self expectationWithDescription:@"callback"];
  613. [[FIRAuth auth] signOut:NULL];
  614. [[FIRAuth auth] signInWithEmail:kEmail
  615. password:kFakePassword
  616. completion:^(FIRAuthDataResult *_Nullable result, NSError *_Nullable error) {
  617. XCTAssertTrue([NSThread isMainThread]);
  618. [self assertUser:result.user];
  619. XCTAssertNil(error);
  620. [expectation fulfill];
  621. }];
  622. [self waitForExpectationsWithTimeout:kExpectationTimeout handler:nil];
  623. [self assertUser:[FIRAuth auth].currentUser];
  624. }
  625. /** @fn testSignInWithEmailPasswordWithRecaptchaFallbackSuccess
  626. @brief Tests the flow of a successful @c signInWithEmail:password:completion: call.
  627. */
  628. - (void)testSignInWithEmailPasswordWithRecaptchaFallbackSuccess {
  629. id mockVerifier = OCMClassMock([FIRAuthRecaptchaVerifier class]);
  630. OCMStub([mockVerifier sharedRecaptchaVerifier:[FIRAuth auth]]).andReturn(mockVerifier);
  631. OCMExpect([mockVerifier enablementStatusForProvider:FIRAuthRecaptchaProviderPassword])
  632. .andReturn(NO);
  633. FIRVerifyPasswordRequest *constRequestWithRecaptchaToken =
  634. [[FIRVerifyPasswordRequest alloc] initWithEmail:kEmail
  635. password:kFakePassword
  636. requestConfiguration:[FIRAuth auth].requestConfiguration];
  637. [constRequestWithRecaptchaToken injectRecaptchaFields:kFakeRecaptchaResponse
  638. recaptchaVersion:kFakeRecaptchaVersion];
  639. OCMStub([mockVerifier
  640. injectRecaptchaFields:[OCMArg any]
  641. provider:FIRAuthRecaptchaProviderPassword
  642. action:FIRAuthRecaptchaActionSignInWithPassword
  643. completion:([OCMArg invokeBlockWithArgs:constRequestWithRecaptchaToken, nil])]);
  644. OCMExpect([_mockBackend verifyPassword:[OCMArg any] callback:[OCMArg any]])
  645. .andCallBlock2(^(FIRVerifyPasswordRequest *_Nullable request,
  646. FIRVerifyPasswordResponseCallback callback) {
  647. XCTAssertEqualObjects(request.APIKey, kAPIKey);
  648. XCTAssertEqualObjects(request.email, kEmail);
  649. XCTAssertEqualObjects(request.password, kFakePassword);
  650. XCTAssertTrue(request.returnSecureToken);
  651. NSError *underlyingError =
  652. [[NSError alloc] initWithDomain:FIRAuthErrorDomain
  653. code:FIRAuthErrorCodeInternalError
  654. userInfo:@{
  655. FIRAuthErrorUserInfoDeserializedResponseKey :
  656. @{@"message" : @"MISSING_RECAPTCHA_TOKEN"}
  657. }];
  658. NSError *error = [[NSError alloc] initWithDomain:FIRAuthErrorDomain
  659. code:FIRAuthErrorCodeInternalError
  660. userInfo:@{NSUnderlyingErrorKey : underlyingError}];
  661. dispatch_async(FIRAuthGlobalWorkQueue(), ^() {
  662. callback(nil, error);
  663. });
  664. });
  665. OCMExpect([_mockBackend verifyPassword:[OCMArg any] callback:[OCMArg any]])
  666. .andCallBlock2(^(FIRVerifyPasswordRequest *_Nullable request,
  667. FIRVerifyPasswordResponseCallback callback) {
  668. XCTAssertEqualObjects(request.APIKey, kAPIKey);
  669. XCTAssertEqualObjects(request.email, kEmail);
  670. XCTAssertEqualObjects(request.password, kFakePassword);
  671. XCTAssertTrue(request.returnSecureToken);
  672. dispatch_async(FIRAuthGlobalWorkQueue(), ^() {
  673. id mockVerifyPasswordResponse = OCMClassMock([FIRVerifyPasswordResponse class]);
  674. [self stubTokensWithMockResponse:mockVerifyPasswordResponse];
  675. callback(mockVerifyPasswordResponse, nil);
  676. });
  677. });
  678. [self expectGetAccountInfo];
  679. XCTestExpectation *expectation = [self expectationWithDescription:@"callback"];
  680. [[FIRAuth auth] signOut:NULL];
  681. [[FIRAuth auth] signInWithEmail:kEmail
  682. password:kFakePassword
  683. completion:^(FIRAuthDataResult *_Nullable result, NSError *_Nullable error) {
  684. XCTAssertTrue([NSThread isMainThread]);
  685. [self assertUser:result.user];
  686. XCTAssertNil(error);
  687. [expectation fulfill];
  688. }];
  689. [self waitForExpectationsWithTimeout:kExpectationTimeout handler:nil];
  690. [self assertUser:[FIRAuth auth].currentUser];
  691. }
  692. #endif
  693. /** @fn testSignInWithEmailPasswordSuccess
  694. @brief Tests the flow of a successful @c signInWithEmail:password:completion: call.
  695. */
  696. - (void)testSignInWithEmailPasswordSuccess {
  697. OCMExpect([_mockBackend verifyPassword:[OCMArg any] callback:[OCMArg any]])
  698. .andCallBlock2(^(FIRVerifyPasswordRequest *_Nullable request,
  699. FIRVerifyPasswordResponseCallback callback) {
  700. XCTAssertEqualObjects(request.APIKey, kAPIKey);
  701. XCTAssertEqualObjects(request.email, kEmail);
  702. XCTAssertEqualObjects(request.password, kFakePassword);
  703. XCTAssertTrue(request.returnSecureToken);
  704. dispatch_async(FIRAuthGlobalWorkQueue(), ^() {
  705. id mockVerifyPasswordResponse = OCMClassMock([FIRVerifyPasswordResponse class]);
  706. [self stubTokensWithMockResponse:mockVerifyPasswordResponse];
  707. callback(mockVerifyPasswordResponse, nil);
  708. });
  709. });
  710. [self expectGetAccountInfo];
  711. XCTestExpectation *expectation = [self expectationWithDescription:@"callback"];
  712. [[FIRAuth auth] signOut:NULL];
  713. [[FIRAuth auth] signInWithEmail:kEmail
  714. password:kFakePassword
  715. completion:^(FIRAuthDataResult *_Nullable result, NSError *_Nullable error) {
  716. XCTAssertTrue([NSThread isMainThread]);
  717. [self assertUser:result.user];
  718. XCTAssertNil(error);
  719. [expectation fulfill];
  720. }];
  721. [self waitForExpectationsWithTimeout:kExpectationTimeout handler:nil];
  722. [self assertUser:[FIRAuth auth].currentUser];
  723. OCMVerifyAll(_mockBackend);
  724. }
  725. /** @fn testSignInWithEmailPasswordFailure
  726. @brief Tests the flow of a failed @c signInWithEmail:password:completion: call.
  727. */
  728. - (void)testSignInWithEmailPasswordFailure {
  729. OCMExpect([_mockBackend verifyPassword:[OCMArg any] callback:[OCMArg any]])
  730. .andDispatchError2([FIRAuthErrorUtils wrongPasswordErrorWithMessage:nil]);
  731. XCTestExpectation *expectation = [self expectationWithDescription:@"callback"];
  732. [[FIRAuth auth] signOut:NULL];
  733. [[FIRAuth auth] signInWithEmail:kEmail
  734. password:kFakePassword
  735. completion:^(FIRAuthDataResult *_Nullable result, NSError *_Nullable error) {
  736. XCTAssertTrue([NSThread isMainThread]);
  737. XCTAssertNil(result.user);
  738. XCTAssertEqual(error.code, FIRAuthErrorCodeWrongPassword);
  739. XCTAssertNotNil(error.userInfo[NSLocalizedDescriptionKey]);
  740. [expectation fulfill];
  741. }];
  742. [self waitForExpectationsWithTimeout:kExpectationTimeout handler:nil];
  743. XCTAssertNil([FIRAuth auth].currentUser);
  744. OCMVerifyAll(_mockBackend);
  745. }
  746. /** @fn testSignInAndRetrieveDataWithEmailPasswordSuccess
  747. @brief Tests the flow of a successful @c signInAndRetrieveDataWithEmail:password:completion:
  748. call.
  749. */
  750. - (void)testSignInAndRetrieveDataWithEmailPasswordSuccess {
  751. OCMExpect([_mockBackend verifyPassword:[OCMArg any] callback:[OCMArg any]])
  752. .andCallBlock2(^(FIRVerifyPasswordRequest *_Nullable request,
  753. FIRVerifyPasswordResponseCallback callback) {
  754. XCTAssertEqualObjects(request.APIKey, kAPIKey);
  755. XCTAssertEqualObjects(request.email, kEmail);
  756. XCTAssertEqualObjects(request.password, kFakePassword);
  757. XCTAssertTrue(request.returnSecureToken);
  758. dispatch_async(FIRAuthGlobalWorkQueue(), ^() {
  759. id mockVerifyPasswordResponse = OCMClassMock([FIRVerifyPasswordResponse class]);
  760. [self stubTokensWithMockResponse:mockVerifyPasswordResponse];
  761. callback(mockVerifyPasswordResponse, nil);
  762. });
  763. });
  764. [self expectGetAccountInfo];
  765. XCTestExpectation *expectation = [self expectationWithDescription:@"callback"];
  766. [[FIRAuth auth] signOut:NULL];
  767. [[FIRAuth auth]
  768. signInWithEmail:kEmail
  769. password:kFakePassword
  770. completion:^(FIRAuthDataResult *_Nullable result, NSError *_Nullable error) {
  771. XCTAssertTrue([NSThread isMainThread]);
  772. [self assertUser:result.user];
  773. XCTAssertFalse(result.additionalUserInfo.isNewUser);
  774. XCTAssertEqualObjects(result.additionalUserInfo.providerID, FIREmailAuthProviderID);
  775. XCTAssertNil(error);
  776. [expectation fulfill];
  777. }];
  778. [self waitForExpectationsWithTimeout:kExpectationTimeout handler:nil];
  779. [self assertUser:[FIRAuth auth].currentUser];
  780. OCMVerifyAll(_mockBackend);
  781. }
  782. /** @fn testSignInAndRetrieveDataWithEmailPasswordFailure
  783. @brief Tests the flow of a failed @c signInAndRetrieveDataWithEmail:password:completion: call.
  784. */
  785. - (void)testSignInAndRetrieveDataWithEmailPasswordFailure {
  786. OCMExpect([_mockBackend verifyPassword:[OCMArg any] callback:[OCMArg any]])
  787. .andDispatchError2([FIRAuthErrorUtils wrongPasswordErrorWithMessage:nil]);
  788. XCTestExpectation *expectation = [self expectationWithDescription:@"callback"];
  789. [[FIRAuth auth] signOut:NULL];
  790. [[FIRAuth auth] signInWithEmail:kEmail
  791. password:kFakePassword
  792. completion:^(FIRAuthDataResult *_Nullable result, NSError *_Nullable error) {
  793. XCTAssertTrue([NSThread isMainThread]);
  794. XCTAssertNil(result);
  795. XCTAssertEqual(error.code, FIRAuthErrorCodeWrongPassword);
  796. XCTAssertNotNil(error.userInfo[NSLocalizedDescriptionKey]);
  797. [expectation fulfill];
  798. }];
  799. [self waitForExpectationsWithTimeout:kExpectationTimeout handler:nil];
  800. XCTAssertNil([FIRAuth auth].currentUser);
  801. OCMVerifyAll(_mockBackend);
  802. }
  803. /** @fn testResetPasswordSuccess
  804. @brief Tests the flow of a successful @c confirmPasswordResetWithCode:newPassword:completion:
  805. call.
  806. */
  807. - (void)testResetPasswordSuccess {
  808. NSString *fakeEmail = @"fakeEmail";
  809. NSString *fakeCode = @"fakeCode";
  810. NSString *fakeNewPassword = @"fakeNewPassword";
  811. OCMExpect([_mockBackend resetPassword:[OCMArg any] callback:[OCMArg any]])
  812. .andCallBlock2(
  813. ^(FIRResetPasswordRequest *_Nullable request, FIRResetPasswordCallback callback) {
  814. XCTAssertEqualObjects(request.APIKey, kAPIKey);
  815. XCTAssertEqualObjects(request.oobCode, fakeCode);
  816. XCTAssertEqualObjects(request.updatedPassword, fakeNewPassword);
  817. dispatch_async(FIRAuthGlobalWorkQueue(), ^() {
  818. id mockResetPasswordResponse = OCMClassMock([FIRResetPasswordResponse class]);
  819. OCMStub([mockResetPasswordResponse email]).andReturn(fakeEmail);
  820. callback(mockResetPasswordResponse, nil);
  821. });
  822. });
  823. XCTestExpectation *expectation = [self expectationWithDescription:@"callback"];
  824. [[FIRAuth auth] signOut:NULL];
  825. [[FIRAuth auth] confirmPasswordResetWithCode:fakeCode
  826. newPassword:fakeNewPassword
  827. completion:^(NSError *_Nullable error) {
  828. XCTAssertTrue([NSThread isMainThread]);
  829. XCTAssertNil(error);
  830. [expectation fulfill];
  831. }];
  832. [self waitForExpectationsWithTimeout:kExpectationTimeout handler:nil];
  833. OCMVerifyAll(_mockBackend);
  834. }
  835. /** @fn testResetPasswordFailure
  836. @brief Tests the flow of a failed @c confirmPasswordResetWithCode:newPassword:completion:
  837. call.
  838. */
  839. - (void)testResetPasswordFailure {
  840. NSString *fakeCode = @"fakeCode";
  841. NSString *fakeNewPassword = @"fakeNewPassword";
  842. OCMExpect([_mockBackend resetPassword:[OCMArg any] callback:[OCMArg any]])
  843. ._andDispatchError2([FIRAuthErrorUtils invalidActionCodeErrorWithMessage:nil]);
  844. XCTestExpectation *expectation = [self expectationWithDescription:@"callback"];
  845. [[FIRAuth auth] signOut:NULL];
  846. [[FIRAuth auth] confirmPasswordResetWithCode:fakeCode
  847. newPassword:fakeNewPassword
  848. completion:^(NSError *_Nullable error) {
  849. XCTAssertTrue([NSThread isMainThread]);
  850. XCTAssertEqual(error.code, FIRAuthErrorCodeInvalidActionCode);
  851. [expectation fulfill];
  852. }];
  853. [self waitForExpectationsWithTimeout:kExpectationTimeout handler:nil];
  854. OCMVerifyAll(_mockBackend);
  855. }
  856. /** @fn testCheckActionCodeSuccess
  857. @brief Tests the flow of a successful @c checkActionCode:completion call.
  858. */
  859. - (void)testCheckActionCodeSuccess {
  860. NSString *verifyEmailRequestType = @"VERIFY_EMAIL";
  861. NSString *fakeEmail = @"fakeEmail";
  862. NSString *fakeNewEmail = @"fakeNewEmail";
  863. NSString *fakeCode = @"fakeCode";
  864. OCMExpect([_mockBackend resetPassword:[OCMArg any] callback:[OCMArg any]])
  865. .andCallBlock2(
  866. ^(FIRResetPasswordRequest *_Nullable request, FIRResetPasswordCallback callback) {
  867. XCTAssertEqualObjects(request.APIKey, kAPIKey);
  868. XCTAssertEqualObjects(request.oobCode, fakeCode);
  869. dispatch_async(FIRAuthGlobalWorkQueue(), ^() {
  870. id mockResetPasswordResponse = OCMClassMock([FIRResetPasswordResponse class]);
  871. OCMStub([mockResetPasswordResponse email]).andReturn(fakeEmail);
  872. OCMStub([mockResetPasswordResponse verifiedEmail]).andReturn(fakeNewEmail);
  873. OCMStubRecorder *stub =
  874. OCMStub([(FIRResetPasswordResponse *)mockResetPasswordResponse requestType]);
  875. stub.andReturn(verifyEmailRequestType);
  876. callback(mockResetPasswordResponse, nil);
  877. });
  878. });
  879. XCTestExpectation *expectation = [self expectationWithDescription:@"callback"];
  880. [[FIRAuth auth] checkActionCode:fakeCode
  881. completion:^(FIRActionCodeInfo *_Nullable info, NSError *_Nullable error) {
  882. XCTAssertTrue([NSThread isMainThread]);
  883. XCTAssertNil(error);
  884. XCTAssertEqual(info.operation, FIRActionCodeOperationVerifyEmail);
  885. XCTAssert([fakeNewEmail isEqualToString:info.email]);
  886. [expectation fulfill];
  887. }];
  888. [self waitForExpectationsWithTimeout:kExpectationTimeout handler:nil];
  889. OCMVerifyAll(_mockBackend);
  890. }
  891. /** @fn testCheckActionCodeFailure
  892. @brief Tests the flow of a failed @c checkActionCode:completion call.
  893. */
  894. - (void)testCheckActionCodeFailure {
  895. NSString *fakeCode = @"fakeCode";
  896. OCMExpect([_mockBackend resetPassword:[OCMArg any] callback:[OCMArg any]])
  897. ._andDispatchError2([FIRAuthErrorUtils expiredActionCodeErrorWithMessage:nil]);
  898. XCTestExpectation *expectation = [self expectationWithDescription:@"callback"];
  899. [[FIRAuth auth] signOut:NULL];
  900. [[FIRAuth auth] checkActionCode:fakeCode
  901. completion:^(FIRActionCodeInfo *_Nullable info, NSError *_Nullable error) {
  902. XCTAssertTrue([NSThread isMainThread]);
  903. XCTAssertNotNil(error);
  904. XCTAssertEqual(error.code, FIRAuthErrorCodeExpiredActionCode);
  905. [expectation fulfill];
  906. }];
  907. [self waitForExpectationsWithTimeout:kExpectationTimeout handler:nil];
  908. OCMVerifyAll(_mockBackend);
  909. }
  910. /** @fn testApplyActionCodeSuccess
  911. @brief Tests the flow of a successful @c applyActionCode:completion call.
  912. */
  913. - (void)testApplyActionCodeSuccess {
  914. NSString *fakeCode = @"fakeCode";
  915. OCMExpect([_mockBackend setAccountInfo:[OCMArg any] callback:[OCMArg any]])
  916. .andCallBlock2(^(FIRSetAccountInfoRequest *_Nullable request,
  917. FIRSetAccountInfoResponseCallback callback) {
  918. XCTAssertEqualObjects(request.APIKey, kAPIKey);
  919. XCTAssertEqualObjects(request.OOBCode, fakeCode);
  920. dispatch_async(FIRAuthGlobalWorkQueue(), ^() {
  921. id mockSetAccountInfoResponse = OCMClassMock([FIRSetAccountInfoResponse class]);
  922. callback(mockSetAccountInfoResponse, nil);
  923. });
  924. });
  925. XCTestExpectation *expectation = [self expectationWithDescription:@"callback"];
  926. [[FIRAuth auth] applyActionCode:fakeCode
  927. completion:^(NSError *_Nullable error) {
  928. XCTAssertTrue([NSThread isMainThread]);
  929. XCTAssertNil(error);
  930. [expectation fulfill];
  931. }];
  932. [self waitForExpectationsWithTimeout:kExpectationTimeout handler:nil];
  933. OCMVerifyAll(_mockBackend);
  934. }
  935. /** @fn testApplyActionCodeFailure
  936. @brief Tests the flow of a failed @c checkActionCode:completion call.
  937. */
  938. - (void)testApplyActionCodeFailure {
  939. NSString *fakeCode = @"fakeCode";
  940. OCMExpect([_mockBackend setAccountInfo:[OCMArg any] callback:[OCMArg any]])
  941. ._andDispatchError2([FIRAuthErrorUtils invalidActionCodeErrorWithMessage:nil]);
  942. XCTestExpectation *expectation = [self expectationWithDescription:@"callback"];
  943. [[FIRAuth auth] signOut:NULL];
  944. [[FIRAuth auth] applyActionCode:fakeCode
  945. completion:^(NSError *_Nullable error) {
  946. XCTAssertTrue([NSThread isMainThread]);
  947. XCTAssertNotNil(error);
  948. XCTAssertEqual(error.code, FIRAuthErrorCodeInvalidActionCode);
  949. [expectation fulfill];
  950. }];
  951. [self waitForExpectationsWithTimeout:kExpectationTimeout handler:nil];
  952. OCMVerifyAll(_mockBackend);
  953. }
  954. /** @fn testVerifyPasswordResetCodeSuccess
  955. @brief Tests the flow of a successful @c verifyPasswordResetCode:completion call.
  956. */
  957. - (void)testVerifyPasswordResetCodeSuccess {
  958. NSString *passwordResetRequestType = @"PASSWORD_RESET";
  959. NSString *fakeEmail = @"fakeEmail";
  960. NSString *fakeCode = @"fakeCode";
  961. OCMExpect([_mockBackend resetPassword:[OCMArg any] callback:[OCMArg any]])
  962. .andCallBlock2(
  963. ^(FIRResetPasswordRequest *_Nullable request, FIRResetPasswordCallback callback) {
  964. XCTAssertEqualObjects(request.APIKey, kAPIKey);
  965. XCTAssertEqualObjects(request.oobCode, fakeCode);
  966. dispatch_async(FIRAuthGlobalWorkQueue(), ^() {
  967. id mockResetPasswordResponse = OCMClassMock([FIRResetPasswordResponse class]);
  968. OCMStub([mockResetPasswordResponse email]).andReturn(fakeEmail);
  969. OCMStubRecorder *stub =
  970. OCMStub([(FIRResetPasswordResponse *)mockResetPasswordResponse requestType]);
  971. stub.andReturn(passwordResetRequestType);
  972. callback(mockResetPasswordResponse, nil);
  973. });
  974. });
  975. XCTestExpectation *expectation = [self expectationWithDescription:@"callback"];
  976. [[FIRAuth auth] verifyPasswordResetCode:fakeCode
  977. completion:^(NSString *_Nullable email, NSError *_Nullable error) {
  978. XCTAssertTrue([NSThread isMainThread]);
  979. XCTAssertNil(error);
  980. XCTAssertEqual(email, fakeEmail);
  981. [expectation fulfill];
  982. }];
  983. [self waitForExpectationsWithTimeout:kExpectationTimeout handler:nil];
  984. OCMVerifyAll(_mockBackend);
  985. }
  986. /** @fn testVerifyPasswordResetCodeFailure
  987. @brief Tests the flow of a failed @c verifyPasswordResetCode:completion call.
  988. */
  989. - (void)testVeridyPasswordResetCodeFailure {
  990. NSString *fakeCode = @"fakeCode";
  991. OCMExpect([_mockBackend resetPassword:[OCMArg any] callback:[OCMArg any]])
  992. ._andDispatchError2([FIRAuthErrorUtils invalidActionCodeErrorWithMessage:nil]);
  993. XCTestExpectation *expectation = [self expectationWithDescription:@"callback"];
  994. [[FIRAuth auth] signOut:NULL];
  995. [[FIRAuth auth] verifyPasswordResetCode:fakeCode
  996. completion:^(NSString *_Nullable email, NSError *_Nullable error) {
  997. XCTAssertTrue([NSThread isMainThread]);
  998. XCTAssertNotNil(error);
  999. XCTAssertEqual(error.code, FIRAuthErrorCodeInvalidActionCode);
  1000. [expectation fulfill];
  1001. }];
  1002. [self waitForExpectationsWithTimeout:kExpectationTimeout handler:nil];
  1003. OCMVerifyAll(_mockBackend);
  1004. }
  1005. /** @fn testSignInWithEmailLinkCredentialSuccess
  1006. @brief Tests the flow of a successfully @c signInWithCredential:completion: call with an
  1007. email sign-in link credential using FIREmailAuthProvider.
  1008. */
  1009. - (void)testSignInWithEmailLinkCredentialSuccess {
  1010. NSString *fakeCode = @"testoobcode";
  1011. OCMExpect([_mockBackend emailLinkSignin:[OCMArg any] callback:[OCMArg any]])
  1012. .andCallBlock2(^(FIREmailLinkSignInRequest *_Nullable request,
  1013. FIREmailLinkSigninResponseCallback callback) {
  1014. XCTAssertEqualObjects(request.email, kEmail);
  1015. XCTAssertEqualObjects(request.oobCode, fakeCode);
  1016. dispatch_async(FIRAuthGlobalWorkQueue(), ^() {
  1017. id mockEmailLinkSigninResponse = OCMClassMock([FIREmailLinkSignInResponse class]);
  1018. [self stubTokensWithMockResponse:mockEmailLinkSigninResponse];
  1019. callback(mockEmailLinkSigninResponse, nil);
  1020. });
  1021. });
  1022. [self expectGetAccountInfo];
  1023. XCTestExpectation *expectation = [self expectationWithDescription:@"callback"];
  1024. [[FIRAuth auth] signOut:NULL];
  1025. FIRAuthCredential *emailCredential =
  1026. [FIREmailAuthProvider credentialWithEmail:kEmail link:kFakeEmailSignInlink];
  1027. [[FIRAuth auth]
  1028. signInWithCredential:emailCredential
  1029. completion:^(FIRAuthDataResult *_Nullable authResult, NSError *_Nullable error) {
  1030. XCTAssertTrue([NSThread isMainThread]);
  1031. XCTAssertNotNil(authResult.user);
  1032. XCTAssertEqualObjects(authResult.user.refreshToken, kRefreshToken);
  1033. XCTAssertFalse(authResult.user.anonymous);
  1034. XCTAssertEqualObjects(authResult.user.email, kEmail);
  1035. XCTAssertNil(error);
  1036. [expectation fulfill];
  1037. }];
  1038. [self waitForExpectationsWithTimeout:kExpectationTimeout handler:nil];
  1039. [self assertUser:[FIRAuth auth].currentUser];
  1040. OCMVerifyAll(_mockBackend);
  1041. }
  1042. /** @fn testSignInWithEmailLinkCredentialFailure
  1043. @brief Tests the flow of a failed @c signInWithCredential:completion: call with an
  1044. email-email sign-in link credential using FIREmailAuthProvider.
  1045. */
  1046. - (void)testSignInWithEmailLinkCredentialFailure {
  1047. OCMExpect([_mockBackend emailLinkSignin:[OCMArg any] callback:[OCMArg any]])
  1048. .andDispatchError2([FIRAuthErrorUtils userDisabledErrorWithMessage:nil]);
  1049. XCTestExpectation *expectation = [self expectationWithDescription:@"callback"];
  1050. [[FIRAuth auth] signOut:NULL];
  1051. FIRAuthCredential *emailCredential =
  1052. [FIREmailAuthProvider credentialWithEmail:kEmail link:kFakeEmailSignInlink];
  1053. [[FIRAuth auth]
  1054. signInWithCredential:emailCredential
  1055. completion:^(FIRAuthDataResult *_Nullable result, NSError *_Nullable error) {
  1056. XCTAssertTrue([NSThread isMainThread]);
  1057. XCTAssertNil(result);
  1058. XCTAssertEqual(error.code, FIRAuthErrorCodeUserDisabled);
  1059. XCTAssertNotNil(error.userInfo[NSLocalizedDescriptionKey]);
  1060. [expectation fulfill];
  1061. }];
  1062. [self waitForExpectationsWithTimeout:kExpectationTimeout handler:nil];
  1063. XCTAssertNil([FIRAuth auth].currentUser);
  1064. OCMVerifyAll(_mockBackend);
  1065. }
  1066. /** @fn testSignInWithEmailCredentialSuccess
  1067. @brief Tests the flow of a successfully @c signInWithCredential:completion: call with an
  1068. email-password credential.
  1069. */
  1070. - (void)testSignInWithEmailCredentialSuccess {
  1071. OCMExpect([_mockBackend verifyPassword:[OCMArg any] callback:[OCMArg any]])
  1072. .andCallBlock2(^(FIRVerifyPasswordRequest *_Nullable request,
  1073. FIRVerifyPasswordResponseCallback callback) {
  1074. XCTAssertEqualObjects(request.APIKey, kAPIKey);
  1075. XCTAssertEqualObjects(request.email, kEmail);
  1076. XCTAssertEqualObjects(request.password, kFakePassword);
  1077. XCTAssertTrue(request.returnSecureToken);
  1078. dispatch_async(FIRAuthGlobalWorkQueue(), ^() {
  1079. id mockVerifyPasswordResponse = OCMClassMock([FIRVerifyPasswordResponse class]);
  1080. [self stubTokensWithMockResponse:mockVerifyPasswordResponse];
  1081. callback(mockVerifyPasswordResponse, nil);
  1082. });
  1083. });
  1084. [self expectGetAccountInfo];
  1085. XCTestExpectation *expectation = [self expectationWithDescription:@"callback"];
  1086. [[FIRAuth auth] signOut:NULL];
  1087. FIRAuthCredential *emailCredential = [FIREmailAuthProvider credentialWithEmail:kEmail
  1088. password:kFakePassword];
  1089. [[FIRAuth auth]
  1090. signInWithCredential:emailCredential
  1091. completion:^(FIRAuthDataResult *_Nullable result, NSError *_Nullable error) {
  1092. XCTAssertTrue([NSThread isMainThread]);
  1093. [self assertUser:result.user];
  1094. XCTAssertNil(error);
  1095. [expectation fulfill];
  1096. }];
  1097. [self waitForExpectationsWithTimeout:kExpectationTimeout handler:nil];
  1098. [self assertUser:[FIRAuth auth].currentUser];
  1099. OCMVerifyAll(_mockBackend);
  1100. }
  1101. /** @fn testSignInWithEmailCredentialFailure
  1102. @brief Tests the flow of a failed @c signInWithCredential:completion: call with an
  1103. email-password credential.
  1104. */
  1105. - (void)testSignInWithEmailCredentialFailure {
  1106. OCMExpect([_mockBackend verifyPassword:[OCMArg any] callback:[OCMArg any]])
  1107. .andDispatchError2([FIRAuthErrorUtils userDisabledErrorWithMessage:nil]);
  1108. XCTestExpectation *expectation = [self expectationWithDescription:@"callback"];
  1109. [[FIRAuth auth] signOut:NULL];
  1110. FIRAuthCredential *emailCredential = [FIREmailAuthProvider credentialWithEmail:kEmail
  1111. password:kFakePassword];
  1112. [[FIRAuth auth]
  1113. signInWithCredential:emailCredential
  1114. completion:^(FIRAuthDataResult *_Nullable result, NSError *_Nullable error) {
  1115. XCTAssertTrue([NSThread isMainThread]);
  1116. XCTAssertNil(result);
  1117. XCTAssertEqual(error.code, FIRAuthErrorCodeUserDisabled);
  1118. XCTAssertNotNil(error.userInfo[NSLocalizedDescriptionKey]);
  1119. [expectation fulfill];
  1120. }];
  1121. [self waitForExpectationsWithTimeout:kExpectationTimeout handler:nil];
  1122. XCTAssertNil([FIRAuth auth].currentUser);
  1123. OCMVerifyAll(_mockBackend);
  1124. }
  1125. /** @fn testSignInWithEmailCredentialEmptyPassword
  1126. @brief Tests the flow of a failed @c signInWithCredential:completion: call with an
  1127. email-password credential using an empty password. This error occurs on the client side,
  1128. so there is no need to fake an RPC response.
  1129. */
  1130. - (void)testSignInWithEmailCredentialEmptyPassword {
  1131. NSString *emptyString = @"";
  1132. XCTestExpectation *expectation = [self expectationWithDescription:@"callback"];
  1133. [[FIRAuth auth] signOut:NULL];
  1134. FIRAuthCredential *emailCredential = [FIREmailAuthProvider credentialWithEmail:kEmail
  1135. password:emptyString];
  1136. [[FIRAuth auth]
  1137. signInWithCredential:emailCredential
  1138. completion:^(FIRAuthDataResult *_Nullable result, NSError *_Nullable error) {
  1139. XCTAssertTrue([NSThread isMainThread]);
  1140. XCTAssertEqual(error.code, FIRAuthErrorCodeWrongPassword);
  1141. [expectation fulfill];
  1142. }];
  1143. [self waitForExpectationsWithTimeout:kExpectationTimeout handler:nil];
  1144. }
  1145. #if TARGET_OS_IOS
  1146. /** @fn testSignInWithProviderSuccess
  1147. @brief Tests a successful @c signInWithProvider:UIDelegate:completion: call with an OAuth
  1148. provider configured for Google.
  1149. */
  1150. - (void)testSignInWithProviderSuccess {
  1151. OCMExpect([_mockBackend verifyAssertion:[OCMArg any] callback:[OCMArg any]])
  1152. .andCallBlock2(^(FIRVerifyAssertionRequest *_Nullable request,
  1153. FIRVerifyAssertionResponseCallback callback) {
  1154. XCTAssertEqualObjects(request.APIKey, kAPIKey);
  1155. XCTAssertEqualObjects(request.providerID, FIRGoogleAuthProviderID);
  1156. XCTAssertTrue(request.returnSecureToken);
  1157. dispatch_async(FIRAuthGlobalWorkQueue(), ^() {
  1158. id mockVerifyAssertionResponse = OCMClassMock([FIRVerifyAssertionResponse class]);
  1159. OCMStub([mockVerifyAssertionResponse federatedID]).andReturn(kGoogleID);
  1160. OCMStub([mockVerifyAssertionResponse providerID]).andReturn(FIRGoogleAuthProviderID);
  1161. OCMStub([mockVerifyAssertionResponse localID]).andReturn(kLocalID);
  1162. OCMStub([mockVerifyAssertionResponse displayName]).andReturn(kGoogleDisplayName);
  1163. [self stubTokensWithMockResponse:mockVerifyAssertionResponse];
  1164. callback(mockVerifyAssertionResponse, nil);
  1165. });
  1166. });
  1167. [self expectGetAccountInfoGoogle];
  1168. XCTestExpectation *expectation = [self expectationWithDescription:@"callback"];
  1169. [[FIRAuth auth] signOut:NULL];
  1170. id mockProvider = OCMClassMock([FIROAuthProvider class]);
  1171. OCMExpect([mockProvider getCredentialWithUIDelegate:[OCMArg any] completion:[OCMArg any]])
  1172. .andCallBlock2(^(id<FIRAuthUIDelegate> delegate, FIRAuthCredentialCallback callback) {
  1173. dispatch_async(FIRAuthGlobalWorkQueue(), ^() {
  1174. FIROAuthCredential *credential =
  1175. [[FIROAuthCredential alloc] initWithProviderID:FIRGoogleAuthProviderID
  1176. sessionID:kOAuthSessionID
  1177. OAuthResponseURLString:kOAuthRequestURI];
  1178. callback(credential, nil);
  1179. });
  1180. });
  1181. [[FIRAuth auth]
  1182. signInWithProvider:mockProvider
  1183. UIDelegate:nil
  1184. completion:^(FIRAuthDataResult *_Nullable authResult, NSError *_Nullable error) {
  1185. XCTAssertTrue([NSThread isMainThread]);
  1186. [self assertUserGoogle:authResult.user];
  1187. XCTAssertNil(error);
  1188. [expectation fulfill];
  1189. }];
  1190. [self waitForExpectationsWithTimeout:kExpectationTimeout handler:nil];
  1191. OCMVerifyAll(_mockBackend);
  1192. }
  1193. /** @fn testSignInWithProviderFailure
  1194. @brief Tests a failed @c signInWithProvider:UIDelegate:completion: call with the error code
  1195. FIRAuthErrorCodeWebSignInUserInteractionFailure.
  1196. */
  1197. - (void)testSignInWithProviderFailure {
  1198. OCMExpect([_mockBackend verifyAssertion:[OCMArg any] callback:[OCMArg any]])
  1199. .andDispatchError2([FIRAuthErrorUtils
  1200. webSignInUserInteractionFailureWithReason:kFakeWebSignInUserInteractionFailureReason]);
  1201. [[FIRAuth auth] signOut:NULL];
  1202. id mockProvider = OCMClassMock([FIROAuthProvider class]);
  1203. OCMExpect([mockProvider getCredentialWithUIDelegate:[OCMArg any] completion:[OCMArg any]])
  1204. .andCallBlock2(^(id<FIRAuthUIDelegate> delegate, FIRAuthCredentialCallback callback) {
  1205. dispatch_async(FIRAuthGlobalWorkQueue(), ^() {
  1206. FIROAuthCredential *credential =
  1207. [[FIROAuthCredential alloc] initWithProviderID:FIRGoogleAuthProviderID
  1208. sessionID:kOAuthSessionID
  1209. OAuthResponseURLString:kOAuthRequestURI];
  1210. callback(credential, nil);
  1211. });
  1212. });
  1213. XCTestExpectation *expectation = [self expectationWithDescription:@"callback"];
  1214. [[FIRAuth auth]
  1215. signInWithProvider:mockProvider
  1216. UIDelegate:nil
  1217. completion:^(FIRAuthDataResult *_Nullable authResult, NSError *_Nullable error) {
  1218. XCTAssertTrue([NSThread isMainThread]);
  1219. XCTAssertNil(authResult);
  1220. XCTAssertEqual(error.code, FIRAuthErrorCodeWebSignInUserInteractionFailure);
  1221. XCTAssertEqualObjects(error.userInfo[NSLocalizedFailureReasonErrorKey],
  1222. kFakeWebSignInUserInteractionFailureReason);
  1223. [expectation fulfill];
  1224. }];
  1225. [self waitForExpectationsWithTimeout:kExpectationTimeout handler:nil];
  1226. OCMVerifyAll(_mockBackend);
  1227. }
  1228. /** @fn testSignInWithGoogleAccountExistsError
  1229. @brief Tests the flow of a failed @c signInWithCredential:completion: with a Google credential
  1230. where the backend returns a needs @needConfirmation equal to true. An
  1231. FIRAuthErrorCodeAccountExistsWithDifferentCredential error should be thrown.
  1232. */
  1233. - (void)testSignInWithGoogleAccountExistsError {
  1234. OCMExpect([_mockBackend verifyAssertion:[OCMArg any] callback:[OCMArg any]])
  1235. .andCallBlock2(^(FIRVerifyAssertionRequest *_Nullable request,
  1236. FIRVerifyAssertionResponseCallback callback) {
  1237. XCTAssertEqualObjects(request.APIKey, kAPIKey);
  1238. XCTAssertEqualObjects(request.providerID, FIRGoogleAuthProviderID);
  1239. XCTAssertEqualObjects(request.providerIDToken, kGoogleIDToken);
  1240. XCTAssertEqualObjects(request.providerAccessToken, kGoogleAccessToken);
  1241. XCTAssertTrue(request.returnSecureToken);
  1242. dispatch_async(FIRAuthGlobalWorkQueue(), ^() {
  1243. id mockVerifyAssertionResponse = OCMClassMock([FIRVerifyAssertionResponse class]);
  1244. OCMStub([mockVerifyAssertionResponse needConfirmation]).andReturn(YES);
  1245. OCMStub([mockVerifyAssertionResponse email]).andReturn(kEmail);
  1246. [self stubTokensWithMockResponse:mockVerifyAssertionResponse];
  1247. callback(mockVerifyAssertionResponse, nil);
  1248. });
  1249. });
  1250. XCTestExpectation *expectation = [self expectationWithDescription:@"callback"];
  1251. [[FIRAuth auth] signOut:NULL];
  1252. FIRAuthCredential *googleCredential =
  1253. [FIRGoogleAuthProvider credentialWithIDToken:kGoogleIDToken accessToken:kGoogleAccessToken];
  1254. [[FIRAuth auth]
  1255. signInWithCredential:googleCredential
  1256. completion:^(FIRAuthDataResult *_Nullable result, NSError *_Nullable error) {
  1257. XCTAssertTrue([NSThread isMainThread]);
  1258. XCTAssertEqual(error.code, FIRAuthErrorCodeAccountExistsWithDifferentCredential);
  1259. XCTAssertEqualObjects(error.userInfo[FIRAuthErrorUserInfoEmailKey], kEmail);
  1260. [expectation fulfill];
  1261. }];
  1262. [self waitForExpectationsWithTimeout:kExpectationTimeout handler:nil];
  1263. OCMVerifyAll(_mockBackend);
  1264. }
  1265. /** @fn testSignInWithGoogleCredentialSuccess
  1266. @brief Tests the flow of a successful @c signInWithCredential:completion: call with an
  1267. Google Sign-In credential.
  1268. */
  1269. - (void)testSignInWithGoogleCredentialSuccess {
  1270. OCMExpect([_mockBackend verifyAssertion:[OCMArg any] callback:[OCMArg any]])
  1271. .andCallBlock2(^(FIRVerifyAssertionRequest *_Nullable request,
  1272. FIRVerifyAssertionResponseCallback callback) {
  1273. XCTAssertEqualObjects(request.APIKey, kAPIKey);
  1274. XCTAssertEqualObjects(request.providerID, FIRGoogleAuthProviderID);
  1275. XCTAssertEqualObjects(request.providerIDToken, kGoogleIDToken);
  1276. XCTAssertEqualObjects(request.providerAccessToken, kGoogleAccessToken);
  1277. XCTAssertTrue(request.returnSecureToken);
  1278. dispatch_async(FIRAuthGlobalWorkQueue(), ^() {
  1279. id mockVerifyAssertionResponse = OCMClassMock([FIRVerifyAssertionResponse class]);
  1280. OCMStub([mockVerifyAssertionResponse federatedID]).andReturn(kGoogleID);
  1281. OCMStub([mockVerifyAssertionResponse providerID]).andReturn(FIRGoogleAuthProviderID);
  1282. OCMStub([mockVerifyAssertionResponse localID]).andReturn(kLocalID);
  1283. OCMStub([mockVerifyAssertionResponse displayName]).andReturn(kGoogleDisplayName);
  1284. [self stubTokensWithMockResponse:mockVerifyAssertionResponse];
  1285. callback(mockVerifyAssertionResponse, nil);
  1286. });
  1287. });
  1288. [self expectGetAccountInfoGoogle];
  1289. XCTestExpectation *expectation = [self expectationWithDescription:@"callback"];
  1290. [[FIRAuth auth] signOut:NULL];
  1291. FIRAuthCredential *googleCredential =
  1292. [FIRGoogleAuthProvider credentialWithIDToken:kGoogleIDToken accessToken:kGoogleAccessToken];
  1293. [[FIRAuth auth]
  1294. signInWithCredential:googleCredential
  1295. completion:^(FIRAuthDataResult *_Nullable result, NSError *_Nullable error) {
  1296. XCTAssertTrue([NSThread isMainThread]);
  1297. [self assertUserGoogle:result.user];
  1298. XCTAssertNil(error);
  1299. [expectation fulfill];
  1300. }];
  1301. [self waitForExpectationsWithTimeout:kExpectationTimeout handler:nil];
  1302. [self assertUserGoogle:[FIRAuth auth].currentUser];
  1303. OCMVerifyAll(_mockBackend);
  1304. }
  1305. /** @fn testSignInWithOAuthCredentialSuccess
  1306. @brief Tests the flow of a successful @c signInWithCredential:completion: call with a generic
  1307. OAuth credential (In this case, configured for the Google IDP).
  1308. */
  1309. - (void)testSignInWithOAuthCredentialSuccess {
  1310. OCMExpect([_mockBackend verifyAssertion:[OCMArg any] callback:[OCMArg any]])
  1311. .andCallBlock2(^(FIRVerifyAssertionRequest *_Nullable request,
  1312. FIRVerifyAssertionResponseCallback callback) {
  1313. XCTAssertEqualObjects(request.APIKey, kAPIKey);
  1314. XCTAssertEqualObjects(request.providerID, FIRGoogleAuthProviderID);
  1315. XCTAssertEqualObjects(request.requestURI, kOAuthRequestURI);
  1316. XCTAssertEqualObjects(request.sessionID, kOAuthSessionID);
  1317. XCTAssertTrue(request.returnSecureToken);
  1318. dispatch_async(FIRAuthGlobalWorkQueue(), ^() {
  1319. id mockVerifyAssertionResponse = OCMClassMock([FIRVerifyAssertionResponse class]);
  1320. OCMStub([mockVerifyAssertionResponse federatedID]).andReturn(kGoogleID);
  1321. OCMStub([mockVerifyAssertionResponse providerID]).andReturn(FIRGoogleAuthProviderID);
  1322. OCMStub([mockVerifyAssertionResponse localID]).andReturn(kLocalID);
  1323. OCMStub([mockVerifyAssertionResponse displayName]).andReturn(kGoogleDisplayName);
  1324. [self stubTokensWithMockResponse:mockVerifyAssertionResponse];
  1325. callback(mockVerifyAssertionResponse, nil);
  1326. });
  1327. });
  1328. [self expectGetAccountInfoGoogle];
  1329. XCTestExpectation *expectation = [self expectationWithDescription:@"callback"];
  1330. [[FIRAuth auth] signOut:NULL];
  1331. id mockProvider = OCMClassMock([FIROAuthProvider class]);
  1332. OCMExpect([mockProvider getCredentialWithUIDelegate:[OCMArg any] completion:[OCMArg any]])
  1333. .andCallBlock2(^(id<FIRAuthUIDelegate> delegate, FIRAuthCredentialCallback callback) {
  1334. dispatch_async(FIRAuthGlobalWorkQueue(), ^() {
  1335. FIROAuthCredential *credential =
  1336. [[FIROAuthCredential alloc] initWithProviderID:FIRGoogleAuthProviderID
  1337. sessionID:kOAuthSessionID
  1338. OAuthResponseURLString:kOAuthRequestURI];
  1339. callback(credential, nil);
  1340. });
  1341. });
  1342. [mockProvider
  1343. getCredentialWithUIDelegate:nil
  1344. completion:^(FIRAuthCredential *_Nullable credential,
  1345. NSError *_Nullable error) {
  1346. XCTAssertTrue([credential isKindOfClass:[FIROAuthCredential class]]);
  1347. FIROAuthCredential *OAuthCredential = (FIROAuthCredential *)credential;
  1348. XCTAssertEqualObjects(OAuthCredential.OAuthResponseURLString,
  1349. kOAuthRequestURI);
  1350. XCTAssertEqualObjects(OAuthCredential.sessionID, kOAuthSessionID);
  1351. [[FIRAuth auth] signInWithCredential:OAuthCredential
  1352. completion:^(FIRAuthDataResult *_Nullable result,
  1353. NSError *_Nullable error) {
  1354. XCTAssertTrue([NSThread isMainThread]);
  1355. [self assertUserGoogle:result.user];
  1356. XCTAssertNil(error);
  1357. [expectation fulfill];
  1358. }];
  1359. }];
  1360. [self waitForExpectationsWithTimeout:kExpectationTimeout handler:nil];
  1361. [self assertUserGoogle:[FIRAuth auth].currentUser];
  1362. OCMVerifyAll(_mockBackend);
  1363. }
  1364. #endif // TARGET_OS_IOS
  1365. /** @fn testSignInWithCredentialSuccess
  1366. @brief Tests the flow of a successful @c signInWithCredential:completion: call
  1367. with an Google Sign-In credential.
  1368. */
  1369. - (void)testSignInWithCredentialSuccess {
  1370. OCMExpect([_mockBackend verifyAssertion:[OCMArg any] callback:[OCMArg any]])
  1371. .andCallBlock2(^(FIRVerifyAssertionRequest *_Nullable request,
  1372. FIRVerifyAssertionResponseCallback callback) {
  1373. XCTAssertEqualObjects(request.APIKey, kAPIKey);
  1374. XCTAssertEqualObjects(request.providerID, FIRGoogleAuthProviderID);
  1375. XCTAssertEqualObjects(request.providerIDToken, kGoogleIDToken);
  1376. XCTAssertEqualObjects(request.providerAccessToken, kGoogleAccessToken);
  1377. XCTAssertTrue(request.returnSecureToken);
  1378. dispatch_async(FIRAuthGlobalWorkQueue(), ^() {
  1379. id mockVerifyAssertionResponse = OCMClassMock([FIRVerifyAssertionResponse class]);
  1380. OCMStub([mockVerifyAssertionResponse federatedID]).andReturn(kGoogleID);
  1381. OCMStub([mockVerifyAssertionResponse providerID]).andReturn(FIRGoogleAuthProviderID);
  1382. OCMStub([mockVerifyAssertionResponse localID]).andReturn(kLocalID);
  1383. OCMStub([mockVerifyAssertionResponse displayName]).andReturn(kGoogleDisplayName);
  1384. OCMStub([mockVerifyAssertionResponse profile]).andReturn([[self class] googleProfile]);
  1385. OCMStub([mockVerifyAssertionResponse username]).andReturn(kDisplayName);
  1386. [self stubTokensWithMockResponse:mockVerifyAssertionResponse];
  1387. callback(mockVerifyAssertionResponse, nil);
  1388. });
  1389. });
  1390. [self expectGetAccountInfoGoogle];
  1391. XCTestExpectation *expectation = [self expectationWithDescription:@"callback"];
  1392. [[FIRAuth auth] signOut:NULL];
  1393. FIRAuthCredential *googleCredential =
  1394. [FIRGoogleAuthProvider credentialWithIDToken:kGoogleIDToken accessToken:kGoogleAccessToken];
  1395. [[FIRAuth auth]
  1396. signInWithCredential:googleCredential
  1397. completion:^(FIRAuthDataResult *_Nullable authResult, NSError *_Nullable error) {
  1398. XCTAssertTrue([NSThread isMainThread]);
  1399. [self assertUserGoogle:authResult.user];
  1400. XCTAssertEqualObjects(authResult.additionalUserInfo.profile,
  1401. [[self class] googleProfile]);
  1402. XCTAssertEqualObjects(authResult.additionalUserInfo.username, kDisplayName);
  1403. XCTAssertEqualObjects(authResult.additionalUserInfo.providerID,
  1404. FIRGoogleAuthProviderID);
  1405. XCTAssertNil(error);
  1406. [expectation fulfill];
  1407. }];
  1408. [self waitForExpectationsWithTimeout:kExpectationTimeout handler:nil];
  1409. [self assertUserGoogle:[FIRAuth auth].currentUser];
  1410. OCMVerifyAll(_mockBackend);
  1411. }
  1412. /** @fn testSignInWithGoogleCredentialFailure
  1413. @brief Tests the flow of a failed @c signInWithCredential:completion: call with an
  1414. Google Sign-In credential.
  1415. */
  1416. - (void)testSignInWithGoogleCredentialFailure {
  1417. OCMExpect([_mockBackend verifyAssertion:[OCMArg any] callback:[OCMArg any]])
  1418. .andDispatchError2([FIRAuthErrorUtils emailAlreadyInUseErrorWithEmail:kGoogleEmail]);
  1419. XCTestExpectation *expectation = [self expectationWithDescription:@"callback"];
  1420. [[FIRAuth auth] signOut:NULL];
  1421. FIRAuthCredential *googleCredential =
  1422. [FIRGoogleAuthProvider credentialWithIDToken:kGoogleIDToken accessToken:kGoogleAccessToken];
  1423. [[FIRAuth auth]
  1424. signInWithCredential:googleCredential
  1425. completion:^(FIRAuthDataResult *_Nullable result, NSError *_Nullable error) {
  1426. XCTAssertTrue([NSThread isMainThread]);
  1427. XCTAssertNil(result.user);
  1428. XCTAssertEqual(error.code, FIRAuthErrorCodeEmailAlreadyInUse);
  1429. XCTAssertNotNil(error.userInfo[NSLocalizedDescriptionKey]);
  1430. [expectation fulfill];
  1431. }];
  1432. [self waitForExpectationsWithTimeout:kExpectationTimeout handler:nil];
  1433. XCTAssertNil([FIRAuth auth].currentUser);
  1434. OCMVerifyAll(_mockBackend);
  1435. }
  1436. /** @fn testSignInWithAppleCredentialFullNameInRequest
  1437. @brief Tests the flow of a successful @c signInWithCredential:completion: call
  1438. with an Apple Sign-In credential with a full name. This test differentiates from
  1439. @c testSignInWithCredentialSuccess only in verifying the full name.
  1440. */
  1441. - (void)testSignInWithAppleCredentialFullNameInRequestSuccess {
  1442. NSPersonNameComponents *fullName = [[NSPersonNameComponents alloc] init];
  1443. fullName.givenName = kFakeGivenName;
  1444. fullName.familyName = kFakeFamilyName;
  1445. OCMExpect([_mockBackend verifyAssertion:[OCMArg any] callback:[OCMArg any]])
  1446. .andCallBlock2(^(FIRVerifyAssertionRequest *_Nullable request,
  1447. FIRVerifyAssertionResponseCallback callback) {
  1448. XCTAssertEqualObjects(request.APIKey, kAPIKey);
  1449. XCTAssertEqualObjects(request.providerID, kAppleAuthProviderID);
  1450. XCTAssertEqualObjects(request.providerIDToken, kAppleIDToken);
  1451. // Verify that the full name is passed to the backend request.
  1452. XCTAssertEqualObjects(request.fullName, fullName);
  1453. XCTAssertTrue(request.returnSecureToken);
  1454. dispatch_async(FIRAuthGlobalWorkQueue(), ^() {
  1455. id mockVerifyAssertionResponse = OCMClassMock([FIRVerifyAssertionResponse class]);
  1456. OCMStub([mockVerifyAssertionResponse providerID]).andReturn(kAppleAuthProviderID);
  1457. [self stubTokensWithMockResponse:mockVerifyAssertionResponse];
  1458. callback(mockVerifyAssertionResponse, nil);
  1459. });
  1460. });
  1461. OCMExpect([_mockBackend getAccountInfo:[OCMArg any] callback:[OCMArg any]])
  1462. .andCallBlock2(^(FIRGetAccountInfoRequest *_Nullable request,
  1463. FIRGetAccountInfoResponseCallback callback) {
  1464. XCTAssertEqualObjects(request.APIKey, kAPIKey);
  1465. XCTAssertEqualObjects(request.accessToken, kAccessToken);
  1466. dispatch_async(FIRAuthGlobalWorkQueue(), ^() {
  1467. id mockAppleUserInfo = OCMClassMock([FIRGetAccountInfoResponseProviderUserInfo class]);
  1468. OCMStub([mockAppleUserInfo providerID]).andReturn(kAppleAuthProviderID);
  1469. id mockGetAccountInfoResponseUser = OCMClassMock([FIRGetAccountInfoResponseUser class]);
  1470. OCMStub([mockGetAccountInfoResponseUser providerUserInfo])
  1471. .andReturn((@[ mockAppleUserInfo ]));
  1472. id mockGetAccountInfoResponse = OCMClassMock([FIRGetAccountInfoResponse class]);
  1473. OCMStub([mockGetAccountInfoResponse users]).andReturn(@[
  1474. mockGetAccountInfoResponseUser
  1475. ]);
  1476. callback(mockGetAccountInfoResponse, nil);
  1477. });
  1478. });
  1479. XCTestExpectation *expectation = [self expectationWithDescription:@"callback"];
  1480. [[FIRAuth auth] signOut:NULL];
  1481. FIRAuthCredential *appleCredential = [FIROAuthProvider appleCredentialWithIDToken:kAppleIDToken
  1482. rawNonce:nil
  1483. fullName:fullName];
  1484. [[FIRAuth auth]
  1485. signInWithCredential:appleCredential
  1486. completion:^(FIRAuthDataResult *_Nullable authResult, NSError *_Nullable error) {
  1487. XCTAssertTrue([NSThread isMainThread]);
  1488. XCTAssertNil(error);
  1489. [expectation fulfill];
  1490. }];
  1491. [self waitForExpectationsWithTimeout:kExpectationTimeout handler:nil];
  1492. XCTAssertNotNil([FIRAuth auth].currentUser);
  1493. OCMVerifyAll(_mockBackend);
  1494. }
  1495. /** @fn testSignInAnonymouslySuccess
  1496. @brief Tests the flow of a successful @c signInAnonymouslyWithCompletion: call.
  1497. */
  1498. - (void)testSignInAnonymouslySuccess {
  1499. OCMExpect([_mockBackend signUpNewUser:[OCMArg any] callback:[OCMArg any]])
  1500. .andCallBlock2(
  1501. ^(FIRSignUpNewUserRequest *_Nullable request, FIRSignupNewUserCallback callback) {
  1502. XCTAssertEqualObjects(request.APIKey, kAPIKey);
  1503. XCTAssertNil(request.email);
  1504. XCTAssertNil(request.password);
  1505. XCTAssertTrue(request.returnSecureToken);
  1506. dispatch_async(FIRAuthGlobalWorkQueue(), ^() {
  1507. id mockSignUpNewUserResponse = OCMClassMock([FIRSignUpNewUserResponse class]);
  1508. [self stubTokensWithMockResponse:mockSignUpNewUserResponse];
  1509. callback(mockSignUpNewUserResponse, nil);
  1510. });
  1511. });
  1512. [self expectGetAccountInfoAnonymous];
  1513. XCTestExpectation *expectation = [self expectationWithDescription:@"callback"];
  1514. [[FIRAuth auth] signOut:NULL];
  1515. [[FIRAuth auth] signInAnonymouslyWithCompletion:^(FIRAuthDataResult *_Nullable result,
  1516. NSError *_Nullable error) {
  1517. XCTAssertTrue([NSThread isMainThread]);
  1518. [self assertUserAnonymous:result.user];
  1519. XCTAssertNil(error);
  1520. FIRAdditionalUserInfo *userInfo = result.additionalUserInfo;
  1521. XCTAssertNotNil(userInfo);
  1522. XCTAssertTrue(userInfo.isNewUser);
  1523. XCTAssertNil(userInfo.username);
  1524. XCTAssertNil(userInfo.profile);
  1525. XCTAssertNil(userInfo.providerID);
  1526. [expectation fulfill];
  1527. }];
  1528. [self waitForExpectationsWithTimeout:kExpectationTimeout handler:nil];
  1529. [self assertUserAnonymous:[FIRAuth auth].currentUser];
  1530. OCMVerifyAll(_mockBackend);
  1531. }
  1532. /** @fn testSignInAnonymouslyFailure
  1533. @brief Tests the flow of a failed @c signInAnonymouslyWithCompletion: call.
  1534. */
  1535. - (void)testSignInAnonymouslyFailure {
  1536. OCMExpect([_mockBackend signUpNewUser:[OCMArg any] callback:[OCMArg any]])
  1537. .andDispatchError2([FIRAuthErrorUtils operationNotAllowedErrorWithMessage:nil]);
  1538. XCTestExpectation *expectation = [self expectationWithDescription:@"callback"];
  1539. [[FIRAuth auth] signOut:NULL];
  1540. [[FIRAuth auth] signInAnonymouslyWithCompletion:^(FIRAuthDataResult *_Nullable result,
  1541. NSError *_Nullable error) {
  1542. XCTAssertTrue([NSThread isMainThread]);
  1543. XCTAssertNil(result.user);
  1544. XCTAssertEqual(error.code, FIRAuthErrorCodeOperationNotAllowed);
  1545. XCTAssertNotNil(error.userInfo[NSLocalizedDescriptionKey]);
  1546. [expectation fulfill];
  1547. }];
  1548. [self waitForExpectationsWithTimeout:kExpectationTimeout handler:nil];
  1549. XCTAssertNil([FIRAuth auth].currentUser);
  1550. OCMVerifyAll(_mockBackend);
  1551. }
  1552. /** @fn testSignInAnonymouslyAndRetrieveDataSuccess
  1553. @brief Tests the flow of a successful @c signInAnonymouslyAndRetrieveDataWithCompletion: call.
  1554. */
  1555. - (void)testSignInAnonymouslyAndRetrieveDataSuccess {
  1556. OCMExpect([_mockBackend signUpNewUser:[OCMArg any] callback:[OCMArg any]])
  1557. .andCallBlock2(
  1558. ^(FIRSignUpNewUserRequest *_Nullable request, FIRSignupNewUserCallback callback) {
  1559. XCTAssertEqualObjects(request.APIKey, kAPIKey);
  1560. XCTAssertNil(request.email);
  1561. XCTAssertNil(request.password);
  1562. XCTAssertTrue(request.returnSecureToken);
  1563. dispatch_async(FIRAuthGlobalWorkQueue(), ^() {
  1564. id mockSignUpNewUserResponse = OCMClassMock([FIRSignUpNewUserResponse class]);
  1565. [self stubTokensWithMockResponse:mockSignUpNewUserResponse];
  1566. callback(mockSignUpNewUserResponse, nil);
  1567. });
  1568. });
  1569. [self expectGetAccountInfoAnonymous];
  1570. XCTestExpectation *expectation = [self expectationWithDescription:@"callback"];
  1571. [[FIRAuth auth] signOut:NULL];
  1572. [[FIRAuth auth] signInAnonymouslyWithCompletion:^(FIRAuthDataResult *_Nullable result,
  1573. NSError *_Nullable error) {
  1574. XCTAssertTrue([NSThread isMainThread]);
  1575. [self assertUserAnonymous:result.user];
  1576. XCTAssertNil(error);
  1577. [expectation fulfill];
  1578. }];
  1579. [self waitForExpectationsWithTimeout:kExpectationTimeout handler:nil];
  1580. [self assertUserAnonymous:[FIRAuth auth].currentUser];
  1581. OCMVerifyAll(_mockBackend);
  1582. }
  1583. /** @fn testSignInAnonymouslyAndRetrieveDataFailure
  1584. @brief Tests the flow of a failed @c signInAnonymouslyAndRetrieveDataWithCompletion: call.
  1585. */
  1586. - (void)testSignInAnonymouslyAndRetrieveDataFailure {
  1587. OCMExpect([_mockBackend signUpNewUser:[OCMArg any] callback:[OCMArg any]])
  1588. .andDispatchError2([FIRAuthErrorUtils operationNotAllowedErrorWithMessage:nil]);
  1589. XCTestExpectation *expectation = [self expectationWithDescription:@"callback"];
  1590. [[FIRAuth auth] signOut:NULL];
  1591. [[FIRAuth auth] signInAnonymouslyWithCompletion:^(FIRAuthDataResult *_Nullable result,
  1592. NSError *_Nullable error) {
  1593. XCTAssertTrue([NSThread isMainThread]);
  1594. XCTAssertNil(result);
  1595. XCTAssertEqual(error.code, FIRAuthErrorCodeOperationNotAllowed);
  1596. XCTAssertNotNil(error.userInfo[NSLocalizedDescriptionKey]);
  1597. [expectation fulfill];
  1598. }];
  1599. [self waitForExpectationsWithTimeout:kExpectationTimeout handler:nil];
  1600. XCTAssertNil([FIRAuth auth].currentUser);
  1601. OCMVerifyAll(_mockBackend);
  1602. }
  1603. /** @fn testSignInWithCustomTokenSuccess
  1604. @brief Tests the flow of a successful @c signInWithCustomToken:completion: call.
  1605. */
  1606. - (void)testSignInWithCustomTokenSuccess {
  1607. OCMExpect([_mockBackend verifyCustomToken:[OCMArg any] callback:[OCMArg any]])
  1608. .andCallBlock2(^(FIRVerifyCustomTokenRequest *_Nullable request,
  1609. FIRVerifyCustomTokenResponseCallback callback) {
  1610. XCTAssertEqualObjects(request.APIKey, kAPIKey);
  1611. XCTAssertEqualObjects(request.token, kCustomToken);
  1612. XCTAssertTrue(request.returnSecureToken);
  1613. dispatch_async(FIRAuthGlobalWorkQueue(), ^() {
  1614. id mockVerifyCustomTokenResponse = OCMClassMock([FIRVerifyCustomTokenResponse class]);
  1615. [self stubTokensWithMockResponse:mockVerifyCustomTokenResponse];
  1616. callback(mockVerifyCustomTokenResponse, nil);
  1617. });
  1618. });
  1619. [self expectGetAccountInfo];
  1620. XCTestExpectation *expectation = [self expectationWithDescription:@"callback"];
  1621. [[FIRAuth auth] signOut:NULL];
  1622. [[FIRAuth auth]
  1623. signInWithCustomToken:kCustomToken
  1624. completion:^(FIRAuthDataResult *_Nullable result, NSError *_Nullable error) {
  1625. XCTAssertTrue([NSThread isMainThread]);
  1626. [self assertUser:result.user];
  1627. XCTAssertNil(error);
  1628. [expectation fulfill];
  1629. }];
  1630. [self waitForExpectationsWithTimeout:kExpectationTimeout handler:nil];
  1631. [self assertUser:[FIRAuth auth].currentUser];
  1632. OCMVerifyAll(_mockBackend);
  1633. }
  1634. /** @fn testSignInWithCustomTokenFailure
  1635. @brief Tests the flow of a failed @c signInWithCustomToken:completion: call.
  1636. */
  1637. - (void)testSignInWithCustomTokenFailure {
  1638. OCMExpect([_mockBackend verifyCustomToken:[OCMArg any] callback:[OCMArg any]])
  1639. .andDispatchError2([FIRAuthErrorUtils invalidCustomTokenErrorWithMessage:nil]);
  1640. XCTestExpectation *expectation = [self expectationWithDescription:@"callback"];
  1641. [[FIRAuth auth] signOut:NULL];
  1642. [[FIRAuth auth]
  1643. signInWithCustomToken:kCustomToken
  1644. completion:^(FIRAuthDataResult *_Nullable result, NSError *_Nullable error) {
  1645. XCTAssertTrue([NSThread isMainThread]);
  1646. XCTAssertNil(result.user);
  1647. XCTAssertEqual(error.code, FIRAuthErrorCodeInvalidCustomToken);
  1648. XCTAssertNotNil(error.userInfo[NSLocalizedDescriptionKey]);
  1649. [expectation fulfill];
  1650. }];
  1651. [self waitForExpectationsWithTimeout:kExpectationTimeout handler:nil];
  1652. XCTAssertNil([FIRAuth auth].currentUser);
  1653. OCMVerifyAll(_mockBackend);
  1654. }
  1655. /** @fn testSignInAndRetrieveDataWithCustomTokenSuccess
  1656. @brief Tests the flow of a successful @c signInAndRetrieveDataWithCustomToken:completion: call.
  1657. */
  1658. - (void)testSignInAndRetrieveDataWithCustomTokenSuccess {
  1659. OCMExpect([_mockBackend verifyCustomToken:[OCMArg any] callback:[OCMArg any]])
  1660. .andCallBlock2(^(FIRVerifyCustomTokenRequest *_Nullable request,
  1661. FIRVerifyCustomTokenResponseCallback callback) {
  1662. XCTAssertEqualObjects(request.APIKey, kAPIKey);
  1663. XCTAssertEqualObjects(request.token, kCustomToken);
  1664. XCTAssertTrue(request.returnSecureToken);
  1665. dispatch_async(FIRAuthGlobalWorkQueue(), ^() {
  1666. id mockVerifyCustomTokenResponse = OCMClassMock([FIRVerifyCustomTokenResponse class]);
  1667. [self stubTokensWithMockResponse:mockVerifyCustomTokenResponse];
  1668. callback(mockVerifyCustomTokenResponse, nil);
  1669. });
  1670. });
  1671. [self expectGetAccountInfo];
  1672. XCTestExpectation *expectation = [self expectationWithDescription:@"callback"];
  1673. [[FIRAuth auth] signOut:NULL];
  1674. [[FIRAuth auth]
  1675. signInWithCustomToken:kCustomToken
  1676. completion:^(FIRAuthDataResult *_Nullable result, NSError *_Nullable error) {
  1677. XCTAssertTrue([NSThread isMainThread]);
  1678. [self assertUser:result.user];
  1679. XCTAssertFalse(result.additionalUserInfo.isNewUser);
  1680. XCTAssertNil(error);
  1681. [expectation fulfill];
  1682. }];
  1683. [self waitForExpectationsWithTimeout:kExpectationTimeout handler:nil];
  1684. [self assertUser:[FIRAuth auth].currentUser];
  1685. OCMVerifyAll(_mockBackend);
  1686. }
  1687. /** @fn testSignInAndRetrieveDataWithCustomTokenFailure
  1688. @brief Tests the flow of a failed @c signInAndRetrieveDataWithCustomToken:completion: call.
  1689. */
  1690. - (void)testSignInAndRetrieveDataWithCustomTokenFailure {
  1691. OCMExpect([_mockBackend verifyCustomToken:[OCMArg any] callback:[OCMArg any]])
  1692. .andDispatchError2([FIRAuthErrorUtils invalidCustomTokenErrorWithMessage:nil]);
  1693. XCTestExpectation *expectation = [self expectationWithDescription:@"callback"];
  1694. [[FIRAuth auth] signOut:NULL];
  1695. [[FIRAuth auth]
  1696. signInWithCustomToken:kCustomToken
  1697. completion:^(FIRAuthDataResult *_Nullable result, NSError *_Nullable error) {
  1698. XCTAssertTrue([NSThread isMainThread]);
  1699. XCTAssertNil(result);
  1700. XCTAssertEqual(error.code, FIRAuthErrorCodeInvalidCustomToken);
  1701. XCTAssertNotNil(error.userInfo[NSLocalizedDescriptionKey]);
  1702. [expectation fulfill];
  1703. }];
  1704. [self waitForExpectationsWithTimeout:kExpectationTimeout handler:nil];
  1705. XCTAssertNil([FIRAuth auth].currentUser);
  1706. OCMVerifyAll(_mockBackend);
  1707. }
  1708. #if TARGET_OS_IOS && !TARGET_OS_MACCATALYST
  1709. /** @fn testCreateUserWithEmailPasswordWithRecaptchaVerificationSuccess
  1710. @brief Tests the flow of a successful @c createUserWithEmail:password:completion: call.
  1711. */
  1712. - (void)testCreateUserWithEmailPasswordWithRecaptchaVerificationSuccess {
  1713. id mockVerifier = OCMClassMock([FIRAuthRecaptchaVerifier class]);
  1714. OCMStub([mockVerifier sharedRecaptchaVerifier:[FIRAuth auth]]).andReturn(mockVerifier);
  1715. OCMExpect([mockVerifier enablementStatusForProvider:FIRAuthRecaptchaProviderPassword])
  1716. .andReturn(YES);
  1717. FIRSignUpNewUserRequest *constRequestWithRecaptchaToken =
  1718. [[FIRSignUpNewUserRequest alloc] initWithEmail:kEmail
  1719. password:kFakePassword
  1720. displayName:kDisplayName
  1721. idToken:kIDToken
  1722. requestConfiguration:[FIRAuth auth].requestConfiguration];
  1723. [constRequestWithRecaptchaToken injectRecaptchaFields:kFakeRecaptchaResponse
  1724. recaptchaVersion:kFakeRecaptchaVersion];
  1725. OCMStub([mockVerifier
  1726. injectRecaptchaFields:[OCMArg any]
  1727. provider:FIRAuthRecaptchaProviderPassword
  1728. action:FIRAuthRecaptchaActionSignUpPassword
  1729. completion:([OCMArg invokeBlockWithArgs:constRequestWithRecaptchaToken, nil])]);
  1730. OCMExpect([_mockBackend signUpNewUser:[OCMArg any] callback:[OCMArg any]])
  1731. .andCallBlock2(
  1732. ^(FIRSignUpNewUserRequest *_Nullable request, FIRSignupNewUserCallback callback) {
  1733. XCTAssertEqualObjects(request.APIKey, kAPIKey);
  1734. XCTAssertEqualObjects(request.email, kEmail);
  1735. XCTAssertEqualObjects(request.password, kFakePassword);
  1736. XCTAssertTrue(request.returnSecureToken);
  1737. dispatch_async(FIRAuthGlobalWorkQueue(), ^() {
  1738. id mockSignUpNewUserResponse = OCMClassMock([FIRSignUpNewUserResponse class]);
  1739. [self stubTokensWithMockResponse:mockSignUpNewUserResponse];
  1740. callback(mockSignUpNewUserResponse, nil);
  1741. });
  1742. });
  1743. [self expectGetAccountInfo];
  1744. XCTestExpectation *expectation = [self expectationWithDescription:@"callback"];
  1745. [[FIRAuth auth] signOut:NULL];
  1746. [[FIRAuth auth]
  1747. createUserWithEmail:kEmail
  1748. password:kFakePassword
  1749. completion:^(FIRAuthDataResult *_Nullable result, NSError *_Nullable error) {
  1750. XCTAssertTrue([NSThread isMainThread]);
  1751. [self assertUser:result.user];
  1752. XCTAssertNil(error);
  1753. [expectation fulfill];
  1754. }];
  1755. [self waitForExpectationsWithTimeout:kExpectationTimeout handler:nil];
  1756. [self assertUser:[FIRAuth auth].currentUser];
  1757. }
  1758. /** @fn testCreateUserWithEmailPasswordWithRecaptchaFallbackSuccess
  1759. @brief Tests the flow of a successful @c createUserWithEmail:password:completion: call.
  1760. */
  1761. - (void)testCreateUserWithEmailPasswordWithRecaptchaFallbackSuccess {
  1762. id mockVerifier = OCMClassMock([FIRAuthRecaptchaVerifier class]);
  1763. OCMStub([mockVerifier sharedRecaptchaVerifier:[FIRAuth auth]]).andReturn(mockVerifier);
  1764. OCMExpect([mockVerifier enablementStatusForProvider:FIRAuthRecaptchaProviderPassword])
  1765. .andReturn(NO);
  1766. FIRSignUpNewUserRequest *constRequestWithRecaptchaToken =
  1767. [[FIRSignUpNewUserRequest alloc] initWithEmail:kEmail
  1768. password:kFakePassword
  1769. displayName:kDisplayName
  1770. idToken:kIDToken
  1771. requestConfiguration:[FIRAuth auth].requestConfiguration];
  1772. [constRequestWithRecaptchaToken injectRecaptchaFields:kFakeRecaptchaResponse
  1773. recaptchaVersion:kFakeRecaptchaVersion];
  1774. OCMStub([mockVerifier
  1775. injectRecaptchaFields:[OCMArg any]
  1776. provider:FIRAuthRecaptchaProviderPassword
  1777. action:FIRAuthRecaptchaActionSignUpPassword
  1778. completion:([OCMArg invokeBlockWithArgs:constRequestWithRecaptchaToken, nil])]);
  1779. OCMExpect([_mockBackend signUpNewUser:[OCMArg any] callback:[OCMArg any]])
  1780. .andCallBlock2(^(FIRSignUpNewUserRequest *_Nullable request,
  1781. FIRSignupNewUserCallback callback) {
  1782. XCTAssertEqualObjects(request.APIKey, kAPIKey);
  1783. XCTAssertEqualObjects(request.email, kEmail);
  1784. XCTAssertEqualObjects(request.password, kFakePassword);
  1785. XCTAssertTrue(request.returnSecureToken);
  1786. NSError *underlyingError =
  1787. [[NSError alloc] initWithDomain:FIRAuthErrorDomain
  1788. code:FIRAuthErrorCodeInternalError
  1789. userInfo:@{
  1790. FIRAuthErrorUserInfoDeserializedResponseKey :
  1791. @{@"message" : @"MISSING_RECAPTCHA_TOKEN"}
  1792. }];
  1793. NSError *error = [[NSError alloc] initWithDomain:FIRAuthErrorDomain
  1794. code:FIRAuthErrorCodeInternalError
  1795. userInfo:@{NSUnderlyingErrorKey : underlyingError}];
  1796. dispatch_async(FIRAuthGlobalWorkQueue(), ^() {
  1797. callback(nil, error);
  1798. });
  1799. });
  1800. OCMExpect([_mockBackend signUpNewUser:[OCMArg any] callback:[OCMArg any]])
  1801. .andCallBlock2(
  1802. ^(FIRSignUpNewUserRequest *_Nullable request, FIRSignupNewUserCallback callback) {
  1803. XCTAssertEqualObjects(request.APIKey, kAPIKey);
  1804. XCTAssertEqualObjects(request.email, kEmail);
  1805. XCTAssertEqualObjects(request.password, kFakePassword);
  1806. XCTAssertTrue(request.returnSecureToken);
  1807. dispatch_async(FIRAuthGlobalWorkQueue(), ^() {
  1808. id mockSignUpNewUserResponse = OCMClassMock([FIRSignUpNewUserResponse class]);
  1809. [self stubTokensWithMockResponse:mockSignUpNewUserResponse];
  1810. callback(mockSignUpNewUserResponse, nil);
  1811. });
  1812. });
  1813. [self expectGetAccountInfo];
  1814. XCTestExpectation *expectation = [self expectationWithDescription:@"callback"];
  1815. [[FIRAuth auth] signOut:NULL];
  1816. [[FIRAuth auth]
  1817. createUserWithEmail:kEmail
  1818. password:kFakePassword
  1819. completion:^(FIRAuthDataResult *_Nullable result, NSError *_Nullable error) {
  1820. XCTAssertTrue([NSThread isMainThread]);
  1821. [self assertUser:result.user];
  1822. XCTAssertNil(error);
  1823. [expectation fulfill];
  1824. }];
  1825. [self waitForExpectationsWithTimeout:kExpectationTimeout handler:nil];
  1826. [self assertUser:[FIRAuth auth].currentUser];
  1827. }
  1828. #endif
  1829. /** @fn testCreateUserWithEmailPasswordSuccess
  1830. @brief Tests the flow of a successful @c createUserWithEmail:password:completion: call.
  1831. */
  1832. - (void)testCreateUserWithEmailPasswordSuccess {
  1833. OCMExpect([_mockBackend signUpNewUser:[OCMArg any] callback:[OCMArg any]])
  1834. .andCallBlock2(
  1835. ^(FIRSignUpNewUserRequest *_Nullable request, FIRSignupNewUserCallback callback) {
  1836. XCTAssertEqualObjects(request.APIKey, kAPIKey);
  1837. XCTAssertEqualObjects(request.email, kEmail);
  1838. XCTAssertEqualObjects(request.password, kFakePassword);
  1839. XCTAssertTrue(request.returnSecureToken);
  1840. dispatch_async(FIRAuthGlobalWorkQueue(), ^() {
  1841. id mockSignUpNewUserResponse = OCMClassMock([FIRSignUpNewUserResponse class]);
  1842. [self stubTokensWithMockResponse:mockSignUpNewUserResponse];
  1843. callback(mockSignUpNewUserResponse, nil);
  1844. });
  1845. });
  1846. [self expectGetAccountInfo];
  1847. XCTestExpectation *expectation = [self expectationWithDescription:@"callback"];
  1848. [[FIRAuth auth] signOut:NULL];
  1849. [[FIRAuth auth]
  1850. createUserWithEmail:kEmail
  1851. password:kFakePassword
  1852. completion:^(FIRAuthDataResult *_Nullable result, NSError *_Nullable error) {
  1853. XCTAssertTrue([NSThread isMainThread]);
  1854. [self assertUser:result.user];
  1855. XCTAssertNil(error);
  1856. [expectation fulfill];
  1857. }];
  1858. [self waitForExpectationsWithTimeout:kExpectationTimeout handler:nil];
  1859. [self assertUser:[FIRAuth auth].currentUser];
  1860. OCMVerifyAll(_mockBackend);
  1861. }
  1862. /** @fn testCreateUserWithEmailPasswordFailure
  1863. @brief Tests the flow of a failed @c createUserWithEmail:password:completion: call.
  1864. */
  1865. - (void)testCreateUserWithEmailPasswordFailure {
  1866. NSString *reason = @"Password shouldn't be a common word.";
  1867. OCMExpect([_mockBackend signUpNewUser:[OCMArg any] callback:[OCMArg any]])
  1868. .andDispatchError2([FIRAuthErrorUtils weakPasswordErrorWithServerResponseReason:reason]);
  1869. XCTestExpectation *expectation = [self expectationWithDescription:@"callback"];
  1870. [[FIRAuth auth] signOut:NULL];
  1871. [[FIRAuth auth]
  1872. createUserWithEmail:kEmail
  1873. password:kFakePassword
  1874. completion:^(FIRAuthDataResult *_Nullable result, NSError *_Nullable error) {
  1875. XCTAssertTrue([NSThread isMainThread]);
  1876. XCTAssertNil(result.user);
  1877. XCTAssertEqual(error.code, FIRAuthErrorCodeWeakPassword);
  1878. XCTAssertNotNil(error.userInfo[NSLocalizedDescriptionKey]);
  1879. XCTAssertEqualObjects(error.userInfo[NSLocalizedFailureReasonErrorKey], reason);
  1880. [expectation fulfill];
  1881. }];
  1882. [self waitForExpectationsWithTimeout:kExpectationTimeout handler:nil];
  1883. XCTAssertNil([FIRAuth auth].currentUser);
  1884. OCMVerifyAll(_mockBackend);
  1885. }
  1886. /** @fn testCreateUserAndRetrieveDataWithEmailPasswordSuccess
  1887. @brief Tests the flow of a successful @c createUserAndRetrieveDataWithEmail:password:completion:
  1888. call.
  1889. */
  1890. - (void)testCreateUserAndRetrieveDataWithEmailPasswordSuccess {
  1891. OCMExpect([_mockBackend signUpNewUser:[OCMArg any] callback:[OCMArg any]])
  1892. .andCallBlock2(
  1893. ^(FIRSignUpNewUserRequest *_Nullable request, FIRSignupNewUserCallback callback) {
  1894. XCTAssertEqualObjects(request.APIKey, kAPIKey);
  1895. XCTAssertEqualObjects(request.email, kEmail);
  1896. XCTAssertEqualObjects(request.password, kFakePassword);
  1897. XCTAssertTrue(request.returnSecureToken);
  1898. dispatch_async(FIRAuthGlobalWorkQueue(), ^() {
  1899. id mockSignUpNewUserResponse = OCMClassMock([FIRSignUpNewUserResponse class]);
  1900. [self stubTokensWithMockResponse:mockSignUpNewUserResponse];
  1901. callback(mockSignUpNewUserResponse, nil);
  1902. });
  1903. });
  1904. [self expectGetAccountInfo];
  1905. XCTestExpectation *expectation = [self expectationWithDescription:@"callback"];
  1906. [[FIRAuth auth] signOut:NULL];
  1907. [[FIRAuth auth]
  1908. createUserWithEmail:kEmail
  1909. password:kFakePassword
  1910. completion:^(FIRAuthDataResult *_Nullable result, NSError *_Nullable error) {
  1911. XCTAssertTrue([NSThread isMainThread]);
  1912. [self assertUser:result.user];
  1913. XCTAssertTrue(result.additionalUserInfo.isNewUser);
  1914. XCTAssertNil(error);
  1915. [expectation fulfill];
  1916. }];
  1917. [self waitForExpectationsWithTimeout:kExpectationTimeout handler:nil];
  1918. [self assertUser:[FIRAuth auth].currentUser];
  1919. OCMVerifyAll(_mockBackend);
  1920. }
  1921. /** @fn testCreateUserAndRetrieveDataWithEmailPasswordFailure
  1922. @brief Tests the flow of a failed @c createUserAndRetrieveDataWithEmail:password:completion:
  1923. call.
  1924. */
  1925. - (void)testCreateUserAndRetrieveDataWithEmailPasswordFailure {
  1926. NSString *reason = @"Password shouldn't be a common word.";
  1927. OCMExpect([_mockBackend signUpNewUser:[OCMArg any] callback:[OCMArg any]])
  1928. .andDispatchError2([FIRAuthErrorUtils weakPasswordErrorWithServerResponseReason:reason]);
  1929. XCTestExpectation *expectation = [self expectationWithDescription:@"callback"];
  1930. [[FIRAuth auth] signOut:NULL];
  1931. [[FIRAuth auth]
  1932. createUserWithEmail:kEmail
  1933. password:kFakePassword
  1934. completion:^(FIRAuthDataResult *_Nullable result, NSError *_Nullable error) {
  1935. XCTAssertTrue([NSThread isMainThread]);
  1936. XCTAssertNil(result);
  1937. XCTAssertEqual(error.code, FIRAuthErrorCodeWeakPassword);
  1938. XCTAssertNotNil(error.userInfo[NSLocalizedDescriptionKey]);
  1939. XCTAssertEqualObjects(error.userInfo[NSLocalizedFailureReasonErrorKey], reason);
  1940. [expectation fulfill];
  1941. }];
  1942. [self waitForExpectationsWithTimeout:kExpectationTimeout handler:nil];
  1943. XCTAssertNil([FIRAuth auth].currentUser);
  1944. OCMVerifyAll(_mockBackend);
  1945. }
  1946. /** @fn testCreateUserEmptyPasswordFailure
  1947. @brief Tests the flow of a failed @c createUserWithEmail:password:completion: call due to an
  1948. empty password. This error occurs on the client side, so there is no need to fake an RPC
  1949. response.
  1950. */
  1951. - (void)testCreateUserEmptyPasswordFailure {
  1952. XCTestExpectation *expectation = [self expectationWithDescription:@"callback"];
  1953. [[FIRAuth auth] signOut:NULL];
  1954. [[FIRAuth auth]
  1955. createUserWithEmail:kEmail
  1956. password:@""
  1957. completion:^(FIRAuthDataResult *_Nullable result, NSError *_Nullable error) {
  1958. XCTAssertTrue([NSThread isMainThread]);
  1959. XCTAssertEqual(error.code, FIRAuthErrorCodeWeakPassword);
  1960. [expectation fulfill];
  1961. }];
  1962. [self waitForExpectationsWithTimeout:kExpectationTimeout handler:nil];
  1963. }
  1964. /** @fn testCreateUserEmptyEmailFailure
  1965. @brief Tests the flow of a failed @c createUserWithEmail:password:completion: call due to an
  1966. empty email adress. This error occurs on the client side, so there is no need to fake an RPC
  1967. response.
  1968. */
  1969. - (void)testCreateUserEmptyEmailFailure {
  1970. XCTestExpectation *expectation = [self expectationWithDescription:@"callback"];
  1971. [[FIRAuth auth] signOut:NULL];
  1972. [[FIRAuth auth]
  1973. createUserWithEmail:@""
  1974. password:kFakePassword
  1975. completion:^(FIRAuthDataResult *_Nullable result, NSError *_Nullable error) {
  1976. XCTAssertTrue([NSThread isMainThread]);
  1977. XCTAssertEqual(error.code, FIRAuthErrorCodeMissingEmail);
  1978. [expectation fulfill];
  1979. }];
  1980. [self waitForExpectationsWithTimeout:kExpectationTimeout handler:nil];
  1981. }
  1982. #if TARGET_OS_IOS && !TARGET_OS_MACCATALYST
  1983. /** @fn testSendPasswordResetEmailWithRecaptchaSuccess
  1984. @brief Tests the flow of a successful @c sendPasswordResetWithEmail:completion: call.
  1985. */
  1986. - (void)testSendPasswordResetEmailWithRecaptchaSuccess {
  1987. id mockVerifier = OCMClassMock([FIRAuthRecaptchaVerifier class]);
  1988. OCMStub([mockVerifier sharedRecaptchaVerifier:[FIRAuth auth]]).andReturn(mockVerifier);
  1989. OCMExpect([mockVerifier enablementStatusForProvider:FIRAuthRecaptchaProviderPassword])
  1990. .andReturn(YES);
  1991. FIRGetOOBConfirmationCodeRequest *constRequestWithRecaptchaToken =
  1992. [FIRGetOOBConfirmationCodeRequest
  1993. passwordResetRequestWithEmail:kEmail
  1994. actionCodeSettings:nil
  1995. requestConfiguration:[FIRAuth auth].requestConfiguration];
  1996. [constRequestWithRecaptchaToken injectRecaptchaFields:kFakeRecaptchaResponse
  1997. recaptchaVersion:kFakeRecaptchaVersion];
  1998. OCMStub([mockVerifier
  1999. injectRecaptchaFields:[OCMArg any]
  2000. provider:FIRAuthRecaptchaProviderPassword
  2001. action:FIRAuthRecaptchaActionGetOobCode
  2002. completion:([OCMArg invokeBlockWithArgs:constRequestWithRecaptchaToken, nil])]);
  2003. OCMExpect([_mockBackend getOOBConfirmationCode:[OCMArg any] callback:[OCMArg any]])
  2004. .andCallBlock2(^(FIRGetOOBConfirmationCodeRequest *_Nullable request,
  2005. FIRGetOOBConfirmationCodeResponseCallback callback) {
  2006. XCTAssertEqualObjects(request.APIKey, kAPIKey);
  2007. XCTAssertEqualObjects(request.email, kEmail);
  2008. dispatch_async(FIRAuthGlobalWorkQueue(), ^() {
  2009. callback([[FIRGetOOBConfirmationCodeResponse alloc] init], nil);
  2010. });
  2011. });
  2012. XCTestExpectation *expectation = [self expectationWithDescription:@"callback"];
  2013. [[FIRAuth auth] sendPasswordResetWithEmail:kEmail
  2014. completion:^(NSError *_Nullable error) {
  2015. XCTAssertTrue([NSThread isMainThread]);
  2016. XCTAssertNil(error);
  2017. [expectation fulfill];
  2018. }];
  2019. [self waitForExpectationsWithTimeout:kExpectationTimeout handler:nil];
  2020. }
  2021. /** @fn testSendPasswordResetEmailWithRecaptchaFallbackSuccess
  2022. @brief Tests the flow of a successful @c sendPasswordResetWithEmail:completion: call.
  2023. */
  2024. - (void)testSendPasswordResetEmailWithRecaptchaFallbackSuccess {
  2025. id mockVerifier = OCMClassMock([FIRAuthRecaptchaVerifier class]);
  2026. OCMStub([mockVerifier sharedRecaptchaVerifier:[FIRAuth auth]]).andReturn(mockVerifier);
  2027. OCMExpect([mockVerifier enablementStatusForProvider:FIRAuthRecaptchaProviderPassword])
  2028. .andReturn(NO);
  2029. FIRGetOOBConfirmationCodeRequest *constRequestWithRecaptchaToken =
  2030. [FIRGetOOBConfirmationCodeRequest
  2031. passwordResetRequestWithEmail:kEmail
  2032. actionCodeSettings:nil
  2033. requestConfiguration:[FIRAuth auth].requestConfiguration];
  2034. [constRequestWithRecaptchaToken injectRecaptchaFields:kFakeRecaptchaResponse
  2035. recaptchaVersion:kFakeRecaptchaVersion];
  2036. OCMStub([mockVerifier
  2037. injectRecaptchaFields:[OCMArg any]
  2038. provider:FIRAuthRecaptchaProviderPassword
  2039. action:FIRAuthRecaptchaActionGetOobCode
  2040. completion:([OCMArg invokeBlockWithArgs:constRequestWithRecaptchaToken, nil])]);
  2041. OCMExpect([_mockBackend getOOBConfirmationCode:[OCMArg any] callback:[OCMArg any]])
  2042. .andCallBlock2(^(FIRGetOOBConfirmationCodeRequest *_Nullable request,
  2043. FIRGetOOBConfirmationCodeResponseCallback callback) {
  2044. XCTAssertEqualObjects(request.APIKey, kAPIKey);
  2045. XCTAssertEqualObjects(request.email, kEmail);
  2046. NSError *underlyingError =
  2047. [[NSError alloc] initWithDomain:FIRAuthErrorDomain
  2048. code:FIRAuthErrorCodeInternalError
  2049. userInfo:@{
  2050. FIRAuthErrorUserInfoDeserializedResponseKey :
  2051. @{@"message" : @"MISSING_RECAPTCHA_TOKEN"}
  2052. }];
  2053. NSError *error = [[NSError alloc] initWithDomain:FIRAuthErrorDomain
  2054. code:FIRAuthErrorCodeInternalError
  2055. userInfo:@{NSUnderlyingErrorKey : underlyingError}];
  2056. dispatch_async(FIRAuthGlobalWorkQueue(), ^() {
  2057. callback(nil, error);
  2058. });
  2059. });
  2060. OCMExpect([_mockBackend getOOBConfirmationCode:[OCMArg any] callback:[OCMArg any]])
  2061. .andCallBlock2(^(FIRGetOOBConfirmationCodeRequest *_Nullable request,
  2062. FIRGetOOBConfirmationCodeResponseCallback callback) {
  2063. XCTAssertEqualObjects(request.APIKey, kAPIKey);
  2064. XCTAssertEqualObjects(request.email, kEmail);
  2065. dispatch_async(FIRAuthGlobalWorkQueue(), ^() {
  2066. callback([[FIRGetOOBConfirmationCodeResponse alloc] init], nil);
  2067. });
  2068. });
  2069. XCTestExpectation *expectation = [self expectationWithDescription:@"callback"];
  2070. [[FIRAuth auth] sendPasswordResetWithEmail:kEmail
  2071. completion:^(NSError *_Nullable error) {
  2072. XCTAssertTrue([NSThread isMainThread]);
  2073. XCTAssertNil(error);
  2074. [expectation fulfill];
  2075. }];
  2076. [self waitForExpectationsWithTimeout:kExpectationTimeout handler:nil];
  2077. }
  2078. #endif
  2079. /** @fn testSendPasswordResetEmailSuccess
  2080. @brief Tests the flow of a successful @c sendPasswordResetWithEmail:completion: call.
  2081. */
  2082. - (void)testSendPasswordResetEmailSuccess {
  2083. OCMExpect([_mockBackend getOOBConfirmationCode:[OCMArg any] callback:[OCMArg any]])
  2084. .andCallBlock2(^(FIRGetOOBConfirmationCodeRequest *_Nullable request,
  2085. FIRGetOOBConfirmationCodeResponseCallback callback) {
  2086. XCTAssertEqualObjects(request.APIKey, kAPIKey);
  2087. XCTAssertEqualObjects(request.email, kEmail);
  2088. dispatch_async(FIRAuthGlobalWorkQueue(), ^() {
  2089. callback([[FIRGetOOBConfirmationCodeResponse alloc] init], nil);
  2090. });
  2091. });
  2092. XCTestExpectation *expectation = [self expectationWithDescription:@"callback"];
  2093. [[FIRAuth auth] sendPasswordResetWithEmail:kEmail
  2094. completion:^(NSError *_Nullable error) {
  2095. XCTAssertTrue([NSThread isMainThread]);
  2096. XCTAssertNil(error);
  2097. [expectation fulfill];
  2098. }];
  2099. [self waitForExpectationsWithTimeout:kExpectationTimeout handler:nil];
  2100. OCMVerifyAll(_mockBackend);
  2101. }
  2102. /** @fn testSendPasswordResetEmailFailure
  2103. @brief Tests the flow of a failed @c sendPasswordResetWithEmail:completion: call.
  2104. */
  2105. - (void)testSendPasswordResetEmailFailure {
  2106. OCMExpect([_mockBackend getOOBConfirmationCode:[OCMArg any] callback:[OCMArg any]])
  2107. .andDispatchError2([FIRAuthErrorUtils appNotAuthorizedError]);
  2108. XCTestExpectation *expectation = [self expectationWithDescription:@"callback"];
  2109. [[FIRAuth auth] sendPasswordResetWithEmail:kEmail
  2110. completion:^(NSError *_Nullable error) {
  2111. XCTAssertTrue([NSThread isMainThread]);
  2112. XCTAssertEqual(error.code, FIRAuthErrorCodeAppNotAuthorized);
  2113. XCTAssertNotNil(error.userInfo[NSLocalizedDescriptionKey]);
  2114. [expectation fulfill];
  2115. }];
  2116. [self waitForExpectationsWithTimeout:kExpectationTimeout handler:nil];
  2117. OCMVerifyAll(_mockBackend);
  2118. }
  2119. #if TARGET_OS_IOS && !TARGET_OS_MACCATALYST
  2120. /** @fn testSendSignInLinkToEmailWithRecaptchaSuccess
  2121. @brief Tests the flow of a successful @c sendSignInLinkToEmail:actionCodeSettings:completion:
  2122. call.
  2123. */
  2124. - (void)testSendSignInLinkToEmailWithRecaptchaSuccess {
  2125. id mockVerifier = OCMClassMock([FIRAuthRecaptchaVerifier class]);
  2126. OCMStub([mockVerifier sharedRecaptchaVerifier:[FIRAuth auth]]).andReturn(mockVerifier);
  2127. OCMExpect([mockVerifier enablementStatusForProvider:FIRAuthRecaptchaProviderPassword])
  2128. .andReturn(YES);
  2129. FIRGetOOBConfirmationCodeRequest *constRequestWithRecaptchaToken =
  2130. [FIRGetOOBConfirmationCodeRequest
  2131. signInWithEmailLinkRequest:kEmail
  2132. actionCodeSettings:[self fakeActionCodeSettings]
  2133. requestConfiguration:[FIRAuth auth].requestConfiguration];
  2134. [constRequestWithRecaptchaToken injectRecaptchaFields:kFakeRecaptchaResponse
  2135. recaptchaVersion:kFakeRecaptchaVersion];
  2136. OCMStub([mockVerifier
  2137. injectRecaptchaFields:[OCMArg any]
  2138. provider:FIRAuthRecaptchaProviderPassword
  2139. action:FIRAuthRecaptchaActionGetOobCode
  2140. completion:([OCMArg invokeBlockWithArgs:constRequestWithRecaptchaToken, nil])]);
  2141. OCMExpect([_mockBackend getOOBConfirmationCode:[OCMArg any] callback:[OCMArg any]])
  2142. .andCallBlock2(^(FIRGetOOBConfirmationCodeRequest *_Nullable request,
  2143. FIRGetOOBConfirmationCodeResponseCallback callback) {
  2144. XCTAssertEqualObjects(request.APIKey, kAPIKey);
  2145. XCTAssertEqualObjects(request.email, kEmail);
  2146. XCTAssertEqualObjects(request.continueURL, kContinueURL);
  2147. XCTAssertTrue(request.handleCodeInApp);
  2148. dispatch_async(FIRAuthGlobalWorkQueue(), ^() {
  2149. callback([[FIRGetOOBConfirmationCodeResponse alloc] init], nil);
  2150. });
  2151. });
  2152. XCTestExpectation *expectation = [self expectationWithDescription:@"callback"];
  2153. [[FIRAuth auth] sendSignInLinkToEmail:kEmail
  2154. actionCodeSettings:[self fakeActionCodeSettings]
  2155. completion:^(NSError *_Nullable error) {
  2156. XCTAssertTrue([NSThread isMainThread]);
  2157. XCTAssertNil(error);
  2158. [expectation fulfill];
  2159. }];
  2160. [self waitForExpectationsWithTimeout:kExpectationTimeout handler:nil];
  2161. }
  2162. /** @fn testSendSignInLinkToEmailWithRecaptchaFallbackSuccess
  2163. @brief Tests the flow of a successful @c sendSignInLinkToEmail:actionCodeSettings:completion:
  2164. call.
  2165. */
  2166. - (void)testSendSignInLinkToEmailWithRecaptchaFallbackSuccess {
  2167. id mockVerifier = OCMClassMock([FIRAuthRecaptchaVerifier class]);
  2168. OCMStub([mockVerifier sharedRecaptchaVerifier:[FIRAuth auth]]).andReturn(mockVerifier);
  2169. OCMExpect([mockVerifier enablementStatusForProvider:FIRAuthRecaptchaProviderPassword])
  2170. .andReturn(NO);
  2171. FIRGetOOBConfirmationCodeRequest *constRequestWithRecaptchaToken =
  2172. [FIRGetOOBConfirmationCodeRequest
  2173. signInWithEmailLinkRequest:kEmail
  2174. actionCodeSettings:[self fakeActionCodeSettings]
  2175. requestConfiguration:[FIRAuth auth].requestConfiguration];
  2176. [constRequestWithRecaptchaToken injectRecaptchaFields:kFakeRecaptchaResponse
  2177. recaptchaVersion:kFakeRecaptchaVersion];
  2178. OCMStub([mockVerifier
  2179. injectRecaptchaFields:[OCMArg any]
  2180. provider:FIRAuthRecaptchaProviderPassword
  2181. action:FIRAuthRecaptchaActionGetOobCode
  2182. completion:([OCMArg invokeBlockWithArgs:constRequestWithRecaptchaToken, nil])]);
  2183. OCMExpect([_mockBackend getOOBConfirmationCode:[OCMArg any] callback:[OCMArg any]])
  2184. .andCallBlock2(^(FIRGetOOBConfirmationCodeRequest *_Nullable request,
  2185. FIRGetOOBConfirmationCodeResponseCallback callback) {
  2186. XCTAssertEqualObjects(request.APIKey, kAPIKey);
  2187. XCTAssertEqualObjects(request.email, kEmail);
  2188. XCTAssertEqualObjects(request.continueURL, kContinueURL);
  2189. XCTAssertTrue(request.handleCodeInApp);
  2190. NSError *underlyingError =
  2191. [[NSError alloc] initWithDomain:FIRAuthErrorDomain
  2192. code:FIRAuthErrorCodeInternalError
  2193. userInfo:@{
  2194. FIRAuthErrorUserInfoDeserializedResponseKey :
  2195. @{@"message" : @"MISSING_RECAPTCHA_TOKEN"}
  2196. }];
  2197. NSError *error = [[NSError alloc] initWithDomain:FIRAuthErrorDomain
  2198. code:FIRAuthErrorCodeInternalError
  2199. userInfo:@{NSUnderlyingErrorKey : underlyingError}];
  2200. dispatch_async(FIRAuthGlobalWorkQueue(), ^() {
  2201. callback(nil, error);
  2202. });
  2203. });
  2204. OCMExpect([_mockBackend getOOBConfirmationCode:[OCMArg any] callback:[OCMArg any]])
  2205. .andCallBlock2(^(FIRGetOOBConfirmationCodeRequest *_Nullable request,
  2206. FIRGetOOBConfirmationCodeResponseCallback callback) {
  2207. XCTAssertEqualObjects(request.APIKey, kAPIKey);
  2208. XCTAssertEqualObjects(request.email, kEmail);
  2209. XCTAssertEqualObjects(request.continueURL, kContinueURL);
  2210. XCTAssertTrue(request.handleCodeInApp);
  2211. dispatch_async(FIRAuthGlobalWorkQueue(), ^() {
  2212. callback([[FIRGetOOBConfirmationCodeResponse alloc] init], nil);
  2213. });
  2214. });
  2215. XCTestExpectation *expectation = [self expectationWithDescription:@"callback"];
  2216. [[FIRAuth auth] sendSignInLinkToEmail:kEmail
  2217. actionCodeSettings:[self fakeActionCodeSettings]
  2218. completion:^(NSError *_Nullable error) {
  2219. XCTAssertTrue([NSThread isMainThread]);
  2220. XCTAssertNil(error);
  2221. [expectation fulfill];
  2222. }];
  2223. [self waitForExpectationsWithTimeout:kExpectationTimeout handler:nil];
  2224. }
  2225. #endif
  2226. /** @fn testSendSignInLinkToEmailSuccess
  2227. @brief Tests the flow of a successful @c sendSignInLinkToEmail:actionCodeSettings:completion:
  2228. call.
  2229. */
  2230. - (void)testSendSignInLinkToEmailSuccess {
  2231. OCMExpect([_mockBackend getOOBConfirmationCode:[OCMArg any] callback:[OCMArg any]])
  2232. .andCallBlock2(^(FIRGetOOBConfirmationCodeRequest *_Nullable request,
  2233. FIRGetOOBConfirmationCodeResponseCallback callback) {
  2234. XCTAssertEqualObjects(request.APIKey, kAPIKey);
  2235. XCTAssertEqualObjects(request.email, kEmail);
  2236. XCTAssertEqualObjects(request.continueURL, kContinueURL);
  2237. XCTAssertTrue(request.handleCodeInApp);
  2238. dispatch_async(FIRAuthGlobalWorkQueue(), ^() {
  2239. callback([[FIRGetOOBConfirmationCodeResponse alloc] init], nil);
  2240. });
  2241. });
  2242. XCTestExpectation *expectation = [self expectationWithDescription:@"callback"];
  2243. [[FIRAuth auth] sendSignInLinkToEmail:kEmail
  2244. actionCodeSettings:[self fakeActionCodeSettings]
  2245. completion:^(NSError *_Nullable error) {
  2246. XCTAssertTrue([NSThread isMainThread]);
  2247. XCTAssertNil(error);
  2248. [expectation fulfill];
  2249. }];
  2250. [self waitForExpectationsWithTimeout:kExpectationTimeout handler:nil];
  2251. OCMVerifyAll(_mockBackend);
  2252. }
  2253. /** @fn testSendSignInLinkToEmailFailure
  2254. @brief Tests the flow of a failed @c sendSignInLinkToEmail:actionCodeSettings:completion:
  2255. call.
  2256. */
  2257. - (void)testSendSignInLinkToEmailFailure {
  2258. OCMExpect([_mockBackend getOOBConfirmationCode:[OCMArg any] callback:[OCMArg any]])
  2259. .andDispatchError2([FIRAuthErrorUtils appNotAuthorizedError]);
  2260. XCTestExpectation *expectation = [self expectationWithDescription:@"callback"];
  2261. [[FIRAuth auth] sendSignInLinkToEmail:kEmail
  2262. actionCodeSettings:[self fakeActionCodeSettings]
  2263. completion:^(NSError *_Nullable error) {
  2264. XCTAssertTrue([NSThread isMainThread]);
  2265. XCTAssertEqual(error.code, FIRAuthErrorCodeAppNotAuthorized);
  2266. XCTAssertNotNil(error.userInfo[NSLocalizedDescriptionKey]);
  2267. [expectation fulfill];
  2268. }];
  2269. [self waitForExpectationsWithTimeout:kExpectationTimeout handler:nil];
  2270. OCMVerifyAll(_mockBackend);
  2271. }
  2272. /** @fn fakeActionCodeSettings
  2273. @brief Constructs and returns a fake instance of @c FIRActionCodeSettings for testing.
  2274. @return An instance of @c FIRActionCodeSettings for testing.
  2275. */
  2276. - (FIRActionCodeSettings *)fakeActionCodeSettings {
  2277. FIRActionCodeSettings *actionCodeSettings = [[FIRActionCodeSettings alloc] init];
  2278. actionCodeSettings.URL = [NSURL URLWithString:kContinueURL];
  2279. actionCodeSettings.handleCodeInApp = YES;
  2280. return actionCodeSettings;
  2281. }
  2282. /** @fn testUpdateCurrentUserFailure
  2283. @brief Tests the flow of a failed @c updateCurrentUser:completion:
  2284. call.
  2285. */
  2286. - (void)testUpdateCurrentUserFailure {
  2287. NSString *kTestAccessToken = @"fakeAccessToken";
  2288. NSString *kTestAPIKey = @"fakeAPIKey";
  2289. [self waitForSignInWithAccessToken:kTestAccessToken APIKey:kTestAPIKey completion:nil];
  2290. NSString *kTestAPIKey2 = @"fakeAPIKey2";
  2291. FIRUser *user2 = [FIRAuth auth].currentUser;
  2292. user2.requestConfiguration = [[FIRAuthRequestConfiguration alloc] initWithAPIKey:kTestAPIKey2
  2293. appID:kFirebaseAppID];
  2294. OCMExpect([_mockBackend getAccountInfo:[OCMArg any] callback:[OCMArg any]])
  2295. .andDispatchError2([FIRAuthErrorUtils invalidAPIKeyError]);
  2296. XCTestExpectation *expectation = [self expectationWithDescription:@"callback"];
  2297. [[FIRAuth auth] updateCurrentUser:user2
  2298. completion:^(NSError *_Nullable error) {
  2299. XCTAssertEqual(error.code, FIRAuthErrorCodeInvalidAPIKey);
  2300. [expectation fulfill];
  2301. }];
  2302. [self waitForExpectationsWithTimeout:kExpectationTimeout handler:nil];
  2303. OCMVerifyAll(_mockBackend);
  2304. }
  2305. /** @fn testUpdateCurrentUserFailureNetworkError
  2306. @brief Tests the flow of a failed @c updateCurrentUser:completion:
  2307. call with a network error.
  2308. */
  2309. - (void)testUpdateCurrentUserFailureNetworkError {
  2310. NSString *kTestAPIKey = @"fakeAPIKey";
  2311. NSString *kTestAccessToken = @"fakeAccessToken";
  2312. [self waitForSignInWithAccessToken:kTestAccessToken APIKey:kTestAPIKey completion:nil];
  2313. NSString *kTestAPIKey2 = @"fakeAPIKey2";
  2314. FIRUser *user2 = [FIRAuth auth].currentUser;
  2315. user2.requestConfiguration = [[FIRAuthRequestConfiguration alloc] initWithAPIKey:kTestAPIKey2
  2316. appID:kFirebaseAppID];
  2317. NSError *underlyingError = [NSError errorWithDomain:@"Test Error" code:1 userInfo:nil];
  2318. OCMExpect([_mockBackend getAccountInfo:[OCMArg any] callback:[OCMArg any]])
  2319. .andDispatchError2([FIRAuthErrorUtils networkErrorWithUnderlyingError:underlyingError]);
  2320. XCTestExpectation *expectation = [self expectationWithDescription:@"callback"];
  2321. [[FIRAuth auth] updateCurrentUser:user2
  2322. completion:^(NSError *_Nullable error) {
  2323. XCTAssertEqual(error.code, FIRAuthErrorCodeNetworkError);
  2324. [expectation fulfill];
  2325. }];
  2326. [self waitForExpectationsWithTimeout:kExpectationTimeout handler:nil];
  2327. OCMVerifyAll(_mockBackend);
  2328. }
  2329. /** @fn testUpdateCurrentUserFailureNUllUser
  2330. @brief Tests the flow of a failed @c updateCurrentUser:completion:
  2331. call with FIRAuthErrorCodeNullUser.
  2332. */
  2333. - (void)testUpdateCurrentUserFailureNUllUser {
  2334. NSString *kTestAccessToken = @"fakeAccessToken";
  2335. NSString *kTestAPIKey = @"fakeAPIKey";
  2336. [self waitForSignInWithAccessToken:kTestAccessToken APIKey:kTestAPIKey completion:nil];
  2337. FIRUser *fakeNilUser = nil;
  2338. XCTestExpectation *expectation = [self expectationWithDescription:@"callback"];
  2339. [[FIRAuth auth] updateCurrentUser:fakeNilUser
  2340. completion:^(NSError *_Nullable error) {
  2341. XCTAssertEqual(error.code, FIRAuthErrorCodeNullUser);
  2342. [expectation fulfill];
  2343. }];
  2344. [self waitForExpectationsWithTimeout:kExpectationTimeout handler:nil];
  2345. OCMVerifyAll(_mockBackend);
  2346. }
  2347. /** @fn testUpdateCurrentUserFailureTenantIDMismatch
  2348. @brief Tests the flow of a failed @c updateCurrentUser:completion:
  2349. call with FIRAuthErrorCodeTenantIDMismatch.
  2350. */
  2351. - (void)testUpdateCurrentUserFailureTenantIDMismatch {
  2352. // User without tenant id
  2353. [self waitForSignInWithAccessToken:kAccessToken APIKey:kAPIKey completion:nil];
  2354. FIRUser *user1 = [FIRAuth auth].currentUser;
  2355. [[FIRAuth auth] signOut:nil];
  2356. // User with tenant id "tenant-id"
  2357. [FIRAuth auth].tenantID = @"tenant-id-1";
  2358. NSString *kTestAccessToken2 = @"fakeAccessToken2";
  2359. [self waitForSignInWithAccessToken:kTestAccessToken2 APIKey:kAPIKey completion:nil];
  2360. FIRUser *user2 = [FIRAuth auth].currentUser;
  2361. [[FIRAuth auth] signOut:nil];
  2362. [FIRAuth auth].tenantID = @"tenant-id-2";
  2363. XCTestExpectation *expectation1 = [self expectationWithDescription:@"callback"];
  2364. [[FIRAuth auth] updateCurrentUser:user1
  2365. completion:^(NSError *_Nullable error) {
  2366. XCTAssertEqual(error.code, FIRAuthErrorCodeTenantIDMismatch);
  2367. [expectation1 fulfill];
  2368. }];
  2369. [[FIRAuth auth] signOut:nil];
  2370. [FIRAuth auth].tenantID = @"tenant-id-2";
  2371. XCTestExpectation *expectation2 = [self expectationWithDescription:@"callback"];
  2372. [[FIRAuth auth] updateCurrentUser:user2
  2373. completion:^(NSError *_Nullable error) {
  2374. XCTAssertEqual(error.code, FIRAuthErrorCodeTenantIDMismatch);
  2375. [expectation2 fulfill];
  2376. }];
  2377. [[FIRAuth auth] signOut:nil];
  2378. [FIRAuth auth].tenantID = nil;
  2379. XCTestExpectation *expectation3 = [self expectationWithDescription:@"callback"];
  2380. [[FIRAuth auth] updateCurrentUser:user2
  2381. completion:^(NSError *_Nullable error) {
  2382. XCTAssertEqual(error.code, FIRAuthErrorCodeTenantIDMismatch);
  2383. [expectation3 fulfill];
  2384. }];
  2385. [self waitForExpectationsWithTimeout:kExpectationTimeout handler:nil];
  2386. OCMVerifyAll(_mockBackend);
  2387. }
  2388. /** @fn testUpdateCurrentUserSuccess
  2389. @brief Tests the flow of a successful @c updateCurrentUser:completion:
  2390. call with a network error.
  2391. */
  2392. - (void)testUpdateCurrentUserSuccess {
  2393. // Sign in with the first user.
  2394. [self waitForSignInWithAccessToken:kAccessToken APIKey:kAPIKey completion:nil];
  2395. FIRUser *user1 = [FIRAuth auth].currentUser;
  2396. NSString *kTestAPIKey = @"fakeAPIKey";
  2397. user1.requestConfiguration = [[FIRAuthRequestConfiguration alloc] initWithAPIKey:kTestAPIKey
  2398. appID:kFirebaseAppID];
  2399. [[FIRAuth auth] signOut:nil];
  2400. NSString *kTestAccessToken2 = @"fakeAccessToken2";
  2401. [self waitForSignInWithAccessToken:kTestAccessToken2 APIKey:kAPIKey completion:nil];
  2402. FIRUser *user2 = [FIRAuth auth].currentUser;
  2403. [self expectGetAccountInfoWithAccessToken:kAccessToken];
  2404. XCTestExpectation *expectation = [self expectationWithDescription:@"callback"];
  2405. // Current user should now be user2.
  2406. XCTAssertEqualObjects([FIRAuth auth].currentUser, user2);
  2407. [[FIRAuth auth] updateCurrentUser:user1
  2408. completion:^(NSError *_Nullable error) {
  2409. XCTAssertNil(error);
  2410. // Current user should now be user1.
  2411. XCTAssertEqualObjects([FIRAuth auth].currentUser, user1);
  2412. XCTAssertNotEqualObjects([FIRAuth auth].currentUser, user2);
  2413. [expectation fulfill];
  2414. }];
  2415. [self waitForExpectationsWithTimeout:kExpectationTimeout handler:nil];
  2416. OCMVerifyAll(_mockBackend);
  2417. }
  2418. /** @fn testSignOut
  2419. @brief Tests the @c signOut: method.
  2420. */
  2421. - (void)testSignOut {
  2422. [self waitForSignIn];
  2423. // Verify signing out succeeds and clears the current user.
  2424. NSError *error;
  2425. XCTAssertTrue([[FIRAuth auth] signOut:&error]);
  2426. XCTAssertNil([FIRAuth auth].currentUser);
  2427. }
  2428. /** @fn testIsSignInWithEmailLink
  2429. @brief Tests the @c isSignInWithEmailLink: method.
  2430. */
  2431. - (void)testIsSignInWithEmailLink {
  2432. XCTAssertTrue([[FIRAuth auth] isSignInWithEmailLink:kFakeEmailSignInlink]);
  2433. XCTAssertTrue([[FIRAuth auth] isSignInWithEmailLink:kFakeEmailSignInDeeplink]);
  2434. XCTAssertFalse([[FIRAuth auth] isSignInWithEmailLink:kBadSignInEmailLink]);
  2435. XCTAssertFalse([[FIRAuth auth] isSignInWithEmailLink:@""]);
  2436. }
  2437. /** @fn testAuthStateChanges
  2438. @brief Tests @c addAuthStateDidChangeListener: and @c removeAuthStateDidChangeListener: methods.
  2439. */
  2440. - (void)testAuthStateChanges {
  2441. // Set up listener.
  2442. __block XCTestExpectation *expectation;
  2443. __block BOOL shouldHaveUser;
  2444. FIRAuthStateDidChangeListenerBlock listener = ^(FIRAuth *auth, FIRUser *_Nullable user) {
  2445. XCTAssertTrue([NSThread isMainThread]);
  2446. XCTAssertEqual(auth, [FIRAuth auth]);
  2447. XCTAssertEqual(user, [FIRAuth auth].currentUser);
  2448. if (shouldHaveUser) {
  2449. XCTAssertNotNil(user);
  2450. } else {
  2451. XCTAssertNil(user);
  2452. }
  2453. // `expectation` being nil means the listener is not expected to be fired at this moment.
  2454. XCTAssertNotNil(expectation);
  2455. [expectation fulfill];
  2456. };
  2457. [[FIRAuth auth] signOut:NULL];
  2458. [self waitForTimeIntervel:kWaitInterval]; // Wait until dust settled from previous tests.
  2459. // Listener should fire immediately when attached.
  2460. expectation = [self expectationWithDescription:@"initial"];
  2461. shouldHaveUser = NO;
  2462. FIRAuthStateDidChangeListenerHandle handle =
  2463. [[FIRAuth auth] addAuthStateDidChangeListener:listener];
  2464. [self waitForExpectationsWithTimeout:kExpectationTimeout handler:nil];
  2465. // Listener should fire for signing in.
  2466. expectation = [self expectationWithDescription:@"sign-in"];
  2467. shouldHaveUser = YES;
  2468. [self waitForSignIn];
  2469. // Listener should not fire for signing in again.
  2470. shouldHaveUser = YES;
  2471. [self waitForSignIn];
  2472. [self waitForTimeIntervel:kWaitInterval]; // make sure listener is not called
  2473. // Listener should fire for signing out.
  2474. expectation = [self expectationWithDescription:@"sign-out"];
  2475. shouldHaveUser = NO;
  2476. [[FIRAuth auth] signOut:NULL];
  2477. [self waitForExpectationsWithTimeout:kExpectationTimeout handler:nil];
  2478. // Listener should no longer fire once detached.
  2479. expectation = nil;
  2480. [[FIRAuth auth] removeAuthStateDidChangeListener:handle];
  2481. [self waitForSignIn];
  2482. [self waitForTimeIntervel:kWaitInterval]; // make sure listener is no longer called
  2483. }
  2484. /** @fn testIDTokenChanges
  2485. @brief Tests @c addIDTokenDidChangeListener: and @c removeIDTokenDidChangeListener: methods.
  2486. */
  2487. - (void)testIDTokenChanges {
  2488. // Set up listener.
  2489. __block XCTestExpectation *expectation;
  2490. __block BOOL shouldHaveUser;
  2491. FIRIDTokenDidChangeListenerBlock listener = ^(FIRAuth *auth, FIRUser *_Nullable user) {
  2492. XCTAssertTrue([NSThread isMainThread]);
  2493. XCTAssertEqual(auth, [FIRAuth auth]);
  2494. XCTAssertEqual(user, [FIRAuth auth].currentUser);
  2495. if (shouldHaveUser) {
  2496. XCTAssertNotNil(user);
  2497. } else {
  2498. XCTAssertNil(user);
  2499. }
  2500. // `expectation` being nil means the listener is not expected to be fired at this moment.
  2501. XCTAssertNotNil(expectation);
  2502. [expectation fulfill];
  2503. };
  2504. [[FIRAuth auth] signOut:NULL];
  2505. [self waitForTimeIntervel:kWaitInterval]; // Wait until dust settled from previous tests.
  2506. // Listener should fire immediately when attached.
  2507. expectation = [self expectationWithDescription:@"initial"];
  2508. shouldHaveUser = NO;
  2509. FIRIDTokenDidChangeListenerHandle handle = [[FIRAuth auth] addIDTokenDidChangeListener:listener];
  2510. [self waitForExpectationsWithTimeout:kExpectationTimeout handler:nil];
  2511. // Listener should fire for signing in.
  2512. expectation = [self expectationWithDescription:@"sign-in"];
  2513. shouldHaveUser = YES;
  2514. [self waitForSignIn];
  2515. // Listener should fire for signing in again as the same user with another access token.
  2516. expectation = [self expectationWithDescription:@"sign-in again"];
  2517. shouldHaveUser = YES;
  2518. [self waitForSignInWithAccessToken:kNewAccessToken APIKey:nil completion:nil];
  2519. // Listener should fire for signing out.
  2520. expectation = [self expectationWithDescription:@"sign-out"];
  2521. shouldHaveUser = NO;
  2522. [[FIRAuth auth] signOut:NULL];
  2523. [self waitForExpectationsWithTimeout:kExpectationTimeout handler:nil];
  2524. // Listener should no longer fire once detached.
  2525. expectation = nil;
  2526. [[FIRAuth auth] removeIDTokenDidChangeListener:handle];
  2527. [self waitForSignIn];
  2528. [self waitForTimeIntervel:kWaitInterval]; // make sure listener is no longer called
  2529. }
  2530. /** @fn testUseEmulator
  2531. @brief Tests the @c useEmulatorWithHost:port: method.
  2532. */
  2533. - (void)testUseEmulator {
  2534. [[FIRAuth auth] useEmulatorWithHost:@"host" port:12345];
  2535. XCTAssertEqualObjects(@"host:12345", [FIRAuth auth].requestConfiguration.emulatorHostAndPort);
  2536. #if TARGET_OS_IOS
  2537. XCTAssertTrue([FIRAuth auth].settings.isAppVerificationDisabledForTesting);
  2538. #endif
  2539. }
  2540. /** @fn testUseEmulatorNeverCalled
  2541. @brief Tests that the emulatorHostAndPort stored in @c FIRAuthRequestConfiguration is nil if the
  2542. @c useEmulatorWithHost:port: is not called.
  2543. */
  2544. - (void)testUseEmulatorNeverCalled {
  2545. XCTAssertEqualObjects(nil, [FIRAuth auth].requestConfiguration.emulatorHostAndPort);
  2546. #if TARGET_OS_IOS
  2547. XCTAssertFalse([FIRAuth auth].settings.isAppVerificationDisabledForTesting);
  2548. #endif
  2549. }
  2550. /** @fn testUseEmulatorIPv6Address
  2551. @brief Tests the @c useEmulatorWithHost:port: method with an IPv6 host address.
  2552. */
  2553. - (void)testUseEmulatorIPv6Address {
  2554. [[FIRAuth auth] useEmulatorWithHost:@"::1" port:12345];
  2555. XCTAssertEqualObjects(@"[::1]:12345", [FIRAuth auth].requestConfiguration.emulatorHostAndPort);
  2556. #if TARGET_OS_IOS
  2557. XCTAssertTrue([FIRAuth auth].settings.isAppVerificationDisabledForTesting);
  2558. #endif
  2559. }
  2560. #pragma mark - Automatic Token Refresh Tests.
  2561. /** @fn testAutomaticTokenRefresh
  2562. @brief Tests a successful flow to automatically refresh tokens for a signed in user.
  2563. */
  2564. - (void)testAutomaticTokenRefresh {
  2565. [[FIRAuth auth] signOut:NULL];
  2566. // Enable auto refresh
  2567. [self enableAutoTokenRefresh];
  2568. // Sign in a user.
  2569. [self waitForSignIn];
  2570. // Set up expectation for secureToken RPC made by token refresh task. We call this twice, because
  2571. // we retry once if the access token is already expired.
  2572. [self mockSecureTokenResponseWithError:nil];
  2573. [self mockSecureTokenResponseWithError:nil];
  2574. // Verify that the current user's access token is the "old" access token before automatic token
  2575. // refresh.
  2576. XCTAssertEqualObjects(kAccessToken, [FIRAuth auth].currentUser.rawAccessToken);
  2577. // Execute saved token refresh task.
  2578. XCTestExpectation *dispatchAfterExpectation =
  2579. [self expectationWithDescription:@"dispatchAfterExpectation"];
  2580. dispatch_async(FIRAuthGlobalWorkQueue(), ^() {
  2581. XCTAssertNotNil(self->_FIRAuthDispatcherCallback);
  2582. self->_FIRAuthDispatcherCallback();
  2583. [dispatchAfterExpectation fulfill];
  2584. });
  2585. [self waitForExpectationsWithTimeout:kExpectationTimeout handler:nil];
  2586. // Verify that current user's access token is the "new" access token provided in the mock secure
  2587. // token response during automatic token refresh.
  2588. XCTAssertEqualObjects(kNewAccessToken, [FIRAuth auth].currentUser.rawAccessToken);
  2589. OCMVerifyAll(_mockBackend);
  2590. }
  2591. /** @fn testAutomaticTokenRefreshInvalidTokenFailure
  2592. @brief Tests an unsuccessful flow to auto refresh tokens with an "invalid token" error.
  2593. This error should cause the user to be signed out.
  2594. */
  2595. - (void)testAutomaticTokenRefreshInvalidTokenFailure {
  2596. [[FIRAuth auth] signOut:NULL];
  2597. // Enable auto refresh
  2598. [self enableAutoTokenRefresh];
  2599. // Sign in a user.
  2600. [self waitForSignIn];
  2601. // Set up expectation for secureToken RPC made by a failed attempt to refresh tokens.
  2602. [self mockSecureTokenResponseWithError:[FIRAuthErrorUtils invalidUserTokenErrorWithMessage:nil]];
  2603. // Verify that current user is still valid.
  2604. XCTAssertEqualObjects(kAccessToken, [FIRAuth auth].currentUser.rawAccessToken);
  2605. // Execute saved token refresh task.
  2606. XCTestExpectation *dispatchAfterExpectation =
  2607. [self expectationWithDescription:@"dispatchAfterExpectation"];
  2608. dispatch_async(FIRAuthGlobalWorkQueue(), ^() {
  2609. XCTAssertNotNil(self->_FIRAuthDispatcherCallback);
  2610. self->_FIRAuthDispatcherCallback();
  2611. [dispatchAfterExpectation fulfill];
  2612. });
  2613. [self waitForExpectationsWithTimeout:kExpectationTimeout handler:nil];
  2614. // Verify that the user is nil after failed attempt to refresh tokens caused signed out.
  2615. XCTAssertNil([FIRAuth auth].currentUser);
  2616. OCMVerifyAll(_mockBackend);
  2617. }
  2618. /** @fn testAutomaticTokenRefreshRetry
  2619. @brief Tests that a retry is attempted for a automatic token refresh task (which is not due to
  2620. invalid tokens). The initial attempt to refresh the access token fails, but the second
  2621. attempt is successful.
  2622. */
  2623. - (void)testAutomaticTokenRefreshRetry {
  2624. [[FIRAuth auth] signOut:NULL];
  2625. // Enable auto refresh
  2626. [self enableAutoTokenRefresh];
  2627. // Sign in a user.
  2628. [self waitForSignIn];
  2629. // Set up expectation for secureToken RPC made by a failed attempt to refresh tokens.
  2630. [self mockSecureTokenResponseWithError:[NSError errorWithDomain:@"ERROR" code:-1 userInfo:nil]];
  2631. // Execute saved token refresh task.
  2632. XCTestExpectation *expectation = [self expectationWithDescription:@"callback"];
  2633. dispatch_async(FIRAuthGlobalWorkQueue(), ^() {
  2634. XCTAssertNotNil(self->_FIRAuthDispatcherCallback);
  2635. self->_FIRAuthDispatcherCallback();
  2636. self->_FIRAuthDispatcherCallback = nil;
  2637. [expectation fulfill];
  2638. });
  2639. [self waitForExpectationsWithTimeout:kExpectationTimeout handler:nil];
  2640. // The old access token should still be the current user's access token and not the new access
  2641. // token (kNewAccessToken).
  2642. XCTAssertEqualObjects(kAccessToken, [FIRAuth auth].currentUser.rawAccessToken);
  2643. // Set up expectation for secureToken RPC made by a successful attempt to refresh tokens. We call
  2644. // this twice, because we retry once if the access token is already expired.
  2645. [self mockSecureTokenResponseWithError:nil];
  2646. [self mockSecureTokenResponseWithError:nil];
  2647. // Execute saved token refresh task.
  2648. XCTestExpectation *dispatchAfterExpectation =
  2649. [self expectationWithDescription:@"dispatchAfterExpectation"];
  2650. dispatch_async(FIRAuthGlobalWorkQueue(), ^() {
  2651. XCTAssertNotNil(self->_FIRAuthDispatcherCallback);
  2652. self->_FIRAuthDispatcherCallback();
  2653. [dispatchAfterExpectation fulfill];
  2654. });
  2655. [self waitForExpectationsWithTimeout:kExpectationTimeout handler:nil];
  2656. // Verify that current user's access token is the "new" access token provided in the mock secure
  2657. // token response during automatic token refresh.
  2658. XCTAssertEqualObjects([FIRAuth auth].currentUser.rawAccessToken, kNewAccessToken);
  2659. OCMVerifyAll(_mockBackend);
  2660. }
  2661. #if TARGET_OS_IOS
  2662. /** @fn testAutomaticTokenRefreshInvalidTokenFailure
  2663. @brief Tests that app foreground notification triggers the scheduling of an automatic token
  2664. refresh task.
  2665. */
  2666. - (void)testAutoRefreshAppForegroundedNotification {
  2667. [[FIRAuth auth] signOut:NULL];
  2668. // Enable auto refresh
  2669. [self enableAutoTokenRefresh];
  2670. // Sign in a user.
  2671. [self waitForSignIn];
  2672. // Post "UIApplicationDidBecomeActiveNotification" to trigger scheduling token refresh task.
  2673. [[NSNotificationCenter defaultCenter]
  2674. postNotificationName:UIApplicationDidBecomeActiveNotification
  2675. object:nil];
  2676. // Verify that current user is still valid with old access token.
  2677. XCTAssertEqualObjects(kAccessToken, [FIRAuth auth].currentUser.rawAccessToken);
  2678. // Set up expectation for secureToken RPC made by a successful attempt to refresh tokens. We call
  2679. // this twice, because we retry once if the access token is already expired.
  2680. [self mockSecureTokenResponseWithError:nil];
  2681. [self mockSecureTokenResponseWithError:nil];
  2682. // Execute saved token refresh task.
  2683. XCTestExpectation *dispatchAfterExpectation =
  2684. [self expectationWithDescription:@"dispatchAfterExpectation"];
  2685. dispatch_async(FIRAuthGlobalWorkQueue(), ^() {
  2686. XCTAssertNotNil(self->_FIRAuthDispatcherCallback);
  2687. self->_FIRAuthDispatcherCallback();
  2688. [dispatchAfterExpectation fulfill];
  2689. });
  2690. [self waitForExpectationsWithTimeout:kExpectationTimeout handler:nil];
  2691. // Verify that current user is still valid with new access token.
  2692. XCTAssertEqualObjects(kNewAccessToken, [FIRAuth auth].currentUser.rawAccessToken);
  2693. OCMVerifyAll(_mockBackend);
  2694. }
  2695. #endif
  2696. #if TARGET_OS_IOS
  2697. #pragma mark - Application Delegate tests
  2698. - (void)testAppDidRegisterForRemoteNotifications_APNSTokenUpdated {
  2699. NSData *apnsToken = [NSData data];
  2700. OCMExpect([self.mockTokenManager setToken:[OCMArg checkWithBlock:^BOOL(FIRAuthAPNSToken *token) {
  2701. XCTAssertEqual(token.data, apnsToken);
  2702. XCTAssertEqual(token.type, FIRAuthAPNSTokenTypeUnknown);
  2703. return YES;
  2704. }]]);
  2705. [self.fakeApplicationDelegate application:[GULAppDelegateSwizzler sharedApplication]
  2706. didRegisterForRemoteNotificationsWithDeviceToken:apnsToken];
  2707. [self.mockTokenManager verify];
  2708. }
  2709. - (void)testAppDidFailToRegisterForRemoteNotifications_TokenManagerCancels {
  2710. NSError *error = [NSError errorWithDomain:@"FIRAuthTests" code:-1 userInfo:nil];
  2711. OCMExpect([self.mockTokenManager cancelWithError:error]);
  2712. [self.fakeApplicationDelegate application:[GULAppDelegateSwizzler sharedApplication]
  2713. didFailToRegisterForRemoteNotificationsWithError:error];
  2714. [self.mockTokenManager verify];
  2715. }
  2716. - (void)testAppDidReceiveRemoteNotification_NotificationManagerHandleCanNotification {
  2717. NSDictionary *notification = @{@"test" : @""};
  2718. OCMExpect([self.mockNotificationManager canHandleNotification:notification]);
  2719. #pragma clang diagnostic push
  2720. #pragma clang diagnostic ignored "-Wdeprecated-declarations"
  2721. [self.fakeApplicationDelegate application:[GULAppDelegateSwizzler sharedApplication]
  2722. didReceiveRemoteNotification:notification];
  2723. #pragma clang diagnostic pop
  2724. [self.mockNotificationManager verify];
  2725. }
  2726. - (void)testAppDidReceiveRemoteNotificationWithCompletion_NotificationManagerHandleCanNotification {
  2727. NSDictionary *notification = @{@"test" : @""};
  2728. OCMExpect([self.mockNotificationManager canHandleNotification:notification]);
  2729. [self.fakeApplicationDelegate application:[GULAppDelegateSwizzler sharedApplication]
  2730. didReceiveRemoteNotification:notification
  2731. fetchCompletionHandler:^(UIBackgroundFetchResult result){
  2732. }];
  2733. [self.mockNotificationManager verify];
  2734. }
  2735. - (void)testAppOpenURL_AuthPresenterCanHandleURL {
  2736. if (@available(iOS 9.0, *)) {
  2737. // 'application:openURL:options:' is only available on iOS 9.0 or newer.
  2738. NSURL *url = [NSURL URLWithString:@"https://localhost"];
  2739. OCMExpect([self.mockAuthURLPresenter canHandleURL:url]).andReturn(YES);
  2740. XCTAssertTrue([self.fakeApplicationDelegate
  2741. application:[GULAppDelegateSwizzler sharedApplication]
  2742. openURL:url
  2743. options:@{}]);
  2744. [self.mockAuthURLPresenter verify];
  2745. }
  2746. }
  2747. - (void)testAppOpenURLWithSourceApplication_AuthPresenterCanHandleURL {
  2748. NSURL *url = [NSURL URLWithString:@"https://localhost"];
  2749. OCMExpect([self.mockAuthURLPresenter canHandleURL:url]).andReturn(YES);
  2750. #pragma clang diagnostic push
  2751. #pragma clang diagnostic ignored "-Wdeprecated-declarations"
  2752. XCTAssertTrue([self.fakeApplicationDelegate application:[GULAppDelegateSwizzler sharedApplication]
  2753. openURL:url
  2754. sourceApplication:@""
  2755. annotation:[[NSObject alloc] init]]);
  2756. #pragma clang diagnostic pop
  2757. [self.mockAuthURLPresenter verify];
  2758. }
  2759. #endif // TARGET_OS_IOS
  2760. #pragma mark - Interoperability Tests
  2761. /** @fn testComponentsBeingRegistered
  2762. @brief Tests that Auth provides the necessary components for interoperability with other SDKs.
  2763. */
  2764. - (void)testComponentsBeingRegistered {
  2765. // Verify that the components are registered properly. Check the count, because any time a new
  2766. // component is added it should be added to the test suite as well.
  2767. NSArray<FIRComponent *> *components = [FIRAuth componentsToRegister];
  2768. XCTAssertTrue(components.count == 1);
  2769. FIRComponent *component = [components firstObject];
  2770. XCTAssert(component.protocol == @protocol(FIRAuthInterop));
  2771. }
  2772. #pragma mark - Helpers
  2773. /** @fn mockSecureTokenResponseWithError:
  2774. @brief Set up expectation for secureToken RPC.
  2775. @param error The error that the mock should return if any.
  2776. */
  2777. - (void)mockSecureTokenResponseWithError:(nullable NSError *)error {
  2778. // Set up expectation for secureToken RPC made by a successful attempt to refresh tokens.
  2779. XCTestExpectation *secureTokenResponseExpectation =
  2780. [self expectationWithDescription:@"secureTokenResponseExpectation"];
  2781. OCMExpect([_mockBackend secureToken:[OCMArg any] callback:[OCMArg any]])
  2782. .andCallBlock2(
  2783. ^(FIRSecureTokenRequest *_Nullable request, FIRSecureTokenResponseCallback callback) {
  2784. XCTAssertEqualObjects(request.APIKey, kAPIKey);
  2785. XCTAssertEqualObjects(request.refreshToken, kRefreshToken);
  2786. dispatch_async(FIRAuthGlobalWorkQueue(), ^() {
  2787. if (error) {
  2788. callback(nil, error);
  2789. [secureTokenResponseExpectation fulfill];
  2790. return;
  2791. }
  2792. id mockSecureTokenResponse = OCMClassMock([FIRSecureTokenResponse class]);
  2793. OCMStub([mockSecureTokenResponse accessToken]).andReturn(kNewAccessToken);
  2794. NSDate *futureDate =
  2795. [[NSDate date] dateByAddingTimeInterval:kTestTokenExpirationTimeInterval];
  2796. OCMStub([mockSecureTokenResponse approximateExpirationDate]).andReturn(futureDate);
  2797. callback(mockSecureTokenResponse, nil);
  2798. [secureTokenResponseExpectation fulfill];
  2799. });
  2800. });
  2801. }
  2802. /** @fn enableAutoTokenRefresh
  2803. @brief Enables automatic token refresh by invoking FIRAuth's implementation of FIRApp's
  2804. |getTokenWithImplementation|.
  2805. */
  2806. - (void)enableAutoTokenRefresh {
  2807. XCTestExpectation *expectation = [self expectationWithDescription:@"autoTokenRefreshcallback"];
  2808. [[FIRAuth auth] getTokenForcingRefresh:NO
  2809. withCallback:^(NSString *_Nullable token, NSError *_Nullable error) {
  2810. [expectation fulfill];
  2811. }];
  2812. [self waitForExpectationsWithTimeout:kExpectationTimeout handler:nil];
  2813. }
  2814. /** @fn stubSecureTokensWithMockResponse
  2815. @brief Creates stubs on the mock response object with access and refresh tokens
  2816. @param mockResponse The mock response object.
  2817. */
  2818. - (void)stubTokensWithMockResponse:(id)mockResponse {
  2819. OCMStub([mockResponse IDToken]).andReturn(kAccessToken);
  2820. OCMStub([mockResponse approximateExpirationDate])
  2821. .andReturn([NSDate dateWithTimeIntervalSinceNow:kAccessTokenTimeToLive]);
  2822. OCMStub([mockResponse refreshToken]).andReturn(kRefreshToken);
  2823. }
  2824. /** @fn expectGetAccountInfo
  2825. @brief Expects a GetAccountInfo request on the mock backend and calls back with fake account
  2826. data.
  2827. */
  2828. - (void)expectGetAccountInfo {
  2829. [self expectGetAccountInfoWithAccessToken:kAccessToken];
  2830. }
  2831. /** @fn expectGetAccountInfoWithAccessToken
  2832. @param accessToken The access token for the user to check against.
  2833. @brief Expects a GetAccountInfo request on the mock backend and calls back with fake account
  2834. data.
  2835. */
  2836. - (void)expectGetAccountInfoWithAccessToken:(NSString *)accessToken {
  2837. OCMExpect([_mockBackend getAccountInfo:[OCMArg any] callback:[OCMArg any]])
  2838. .andCallBlock2(^(FIRGetAccountInfoRequest *_Nullable request,
  2839. FIRGetAccountInfoResponseCallback callback) {
  2840. XCTAssertEqualObjects(request.APIKey, kAPIKey);
  2841. XCTAssertEqualObjects(request.accessToken, accessToken);
  2842. dispatch_async(FIRAuthGlobalWorkQueue(), ^() {
  2843. id mockGetAccountInfoResponseUser = OCMClassMock([FIRGetAccountInfoResponseUser class]);
  2844. OCMStub([mockGetAccountInfoResponseUser localID]).andReturn(kLocalID);
  2845. OCMStub([mockGetAccountInfoResponseUser displayName]).andReturn(kDisplayName);
  2846. OCMStub([mockGetAccountInfoResponseUser email]).andReturn(kEmail);
  2847. OCMStub([mockGetAccountInfoResponseUser passwordHash]).andReturn(kPasswordHash);
  2848. id mockGetAccountInfoResponse = OCMClassMock([FIRGetAccountInfoResponse class]);
  2849. OCMStub([mockGetAccountInfoResponse users]).andReturn(@[
  2850. mockGetAccountInfoResponseUser
  2851. ]);
  2852. callback(mockGetAccountInfoResponse, nil);
  2853. });
  2854. });
  2855. }
  2856. /** @fn assertUser
  2857. @brief Asserts the given FIRUser matching the fake data returned by @c expectGetAccountInfo.
  2858. @param user The user object to be verified.
  2859. */
  2860. - (void)assertUser:(FIRUser *)user {
  2861. XCTAssertNotNil(user);
  2862. XCTAssertEqualObjects(user.uid, kLocalID);
  2863. XCTAssertEqualObjects(user.displayName, kDisplayName);
  2864. XCTAssertEqualObjects(user.email, kEmail);
  2865. XCTAssertFalse(user.anonymous);
  2866. XCTAssertEqual(user.providerData.count, 0u);
  2867. }
  2868. /** @fn expectGetAccountInfoGoogle
  2869. @brief Expects a GetAccountInfo request on the mock backend and calls back with fake account
  2870. data for a Google Sign-In user.
  2871. */
  2872. - (void)expectGetAccountInfoGoogle {
  2873. OCMExpect([_mockBackend getAccountInfo:[OCMArg any] callback:[OCMArg any]])
  2874. .andCallBlock2(^(FIRGetAccountInfoRequest *_Nullable request,
  2875. FIRGetAccountInfoResponseCallback callback) {
  2876. XCTAssertEqualObjects(request.APIKey, kAPIKey);
  2877. XCTAssertEqualObjects(request.accessToken, kAccessToken);
  2878. dispatch_async(FIRAuthGlobalWorkQueue(), ^() {
  2879. id mockGoogleUserInfo = OCMClassMock([FIRGetAccountInfoResponseProviderUserInfo class]);
  2880. OCMStub([mockGoogleUserInfo providerID]).andReturn(FIRGoogleAuthProviderID);
  2881. OCMStub([mockGoogleUserInfo displayName]).andReturn(kGoogleDisplayName);
  2882. OCMStub([mockGoogleUserInfo federatedID]).andReturn(kGoogleID);
  2883. OCMStub([mockGoogleUserInfo email]).andReturn(kGoogleEmail);
  2884. id mockGetAccountInfoResponseUser = OCMClassMock([FIRGetAccountInfoResponseUser class]);
  2885. OCMStub([mockGetAccountInfoResponseUser localID]).andReturn(kLocalID);
  2886. OCMStub([mockGetAccountInfoResponseUser displayName]).andReturn(kDisplayName);
  2887. OCMStub([mockGetAccountInfoResponseUser providerUserInfo])
  2888. .andReturn((@[ mockGoogleUserInfo ]));
  2889. id mockGetAccountInfoResponse = OCMClassMock([FIRGetAccountInfoResponse class]);
  2890. OCMStub([mockGetAccountInfoResponse users]).andReturn(@[
  2891. mockGetAccountInfoResponseUser
  2892. ]);
  2893. callback(mockGetAccountInfoResponse, nil);
  2894. });
  2895. });
  2896. }
  2897. /** @fn assertUserGoogle
  2898. @brief Asserts the given FIRUser matching the fake data returned by
  2899. @c expectGetAccountInfoGoogle.
  2900. @param user The user object to be verified.
  2901. */
  2902. - (void)assertUserGoogle:(FIRUser *)user {
  2903. XCTAssertNotNil(user);
  2904. XCTAssertEqualObjects(user.uid, kLocalID);
  2905. XCTAssertEqualObjects(user.displayName, kDisplayName);
  2906. XCTAssertEqual(user.providerData.count, 1u);
  2907. id<FIRUserInfo> googleUserInfo = user.providerData[0];
  2908. XCTAssertEqualObjects(googleUserInfo.providerID, FIRGoogleAuthProviderID);
  2909. XCTAssertEqualObjects(googleUserInfo.uid, kGoogleID);
  2910. XCTAssertEqualObjects(googleUserInfo.displayName, kGoogleDisplayName);
  2911. XCTAssertEqualObjects(googleUserInfo.email, kGoogleEmail);
  2912. }
  2913. /** @fn expectGetAccountInfoAnonymous
  2914. @brief Expects a GetAccountInfo request on the mock backend and calls back with fake anonymous
  2915. account data.
  2916. */
  2917. - (void)expectGetAccountInfoAnonymous {
  2918. OCMExpect([_mockBackend getAccountInfo:[OCMArg any] callback:[OCMArg any]])
  2919. .andCallBlock2(^(FIRGetAccountInfoRequest *_Nullable request,
  2920. FIRGetAccountInfoResponseCallback callback) {
  2921. XCTAssertEqualObjects(request.APIKey, kAPIKey);
  2922. XCTAssertEqualObjects(request.accessToken, kAccessToken);
  2923. dispatch_async(FIRAuthGlobalWorkQueue(), ^() {
  2924. id mockGetAccountInfoResponseUser = OCMClassMock([FIRGetAccountInfoResponseUser class]);
  2925. OCMStub([mockGetAccountInfoResponseUser localID]).andReturn(kLocalID);
  2926. id mockGetAccountInfoResponse = OCMClassMock([FIRGetAccountInfoResponse class]);
  2927. OCMStub([mockGetAccountInfoResponse users]).andReturn(@[
  2928. mockGetAccountInfoResponseUser
  2929. ]);
  2930. callback(mockGetAccountInfoResponse, nil);
  2931. });
  2932. });
  2933. }
  2934. /** @fn assertUserAnonymous
  2935. @brief Asserts the given FIRUser matching the fake data returned by
  2936. @c expectGetAccountInfoAnonymous.
  2937. @param user The user object to be verified.
  2938. */
  2939. - (void)assertUserAnonymous:(FIRUser *)user {
  2940. XCTAssertNotNil(user);
  2941. XCTAssertEqualObjects(user.uid, kLocalID);
  2942. XCTAssertNil(user.displayName);
  2943. XCTAssertTrue(user.anonymous);
  2944. XCTAssertEqual(user.providerData.count, 0u);
  2945. }
  2946. /** @fn waitForSignIn
  2947. @brief Signs in a user to prepare for tests.
  2948. @remarks This method also waits for all other pending @c XCTestExpectation instances.
  2949. */
  2950. - (void)waitForSignIn {
  2951. [self waitForSignInWithAccessToken:kAccessToken APIKey:nil completion:nil];
  2952. }
  2953. /** @fn waitForSignInWithAccessToken:
  2954. @brief Signs in a user to prepare for tests.
  2955. @param accessToken The access token for the user to have.
  2956. @param APIKey Optionally, The API key associated with the user.
  2957. @param completion Optionally, The completion invoked at the end of the flow.
  2958. @remarks This method also waits for all other pending @c XCTestExpectation instances.
  2959. */
  2960. - (void)waitForSignInWithAccessToken:(NSString *)accessToken
  2961. APIKey:(nullable NSString *)APIKey
  2962. completion:(nullable FIRAuthResultCallback)completion {
  2963. OCMExpect([_mockBackend verifyPassword:[OCMArg any] callback:[OCMArg any]])
  2964. .andCallBlock2(^(FIRVerifyPasswordRequest *_Nullable request,
  2965. FIRVerifyPasswordResponseCallback callback) {
  2966. dispatch_async(FIRAuthGlobalWorkQueue(), ^() {
  2967. id mockVerifyPasswordResponse = OCMClassMock([FIRVerifyPasswordResponse class]);
  2968. OCMStub([mockVerifyPasswordResponse IDToken]).andReturn(accessToken);
  2969. OCMStub([mockVerifyPasswordResponse approximateExpirationDate])
  2970. .andReturn([NSDate dateWithTimeIntervalSinceNow:kAccessTokenTimeToLive]);
  2971. OCMStub([mockVerifyPasswordResponse refreshToken]).andReturn(kRefreshToken);
  2972. callback(mockVerifyPasswordResponse, nil);
  2973. });
  2974. });
  2975. [self expectGetAccountInfoWithAccessToken:accessToken];
  2976. XCTestExpectation *expectation = [self expectationWithDescription:@"callback"];
  2977. [[FIRAuth auth] signInWithEmail:kEmail
  2978. password:kFakePassword
  2979. completion:^(FIRAuthDataResult *_Nullable result, NSError *_Nullable error) {
  2980. result.user.requestConfiguration =
  2981. [[FIRAuthRequestConfiguration alloc] initWithAPIKey:APIKey
  2982. appID:kFirebaseAppID];
  2983. [expectation fulfill];
  2984. if (completion) {
  2985. completion(result.user, error);
  2986. }
  2987. }];
  2988. [self waitForExpectationsWithTimeout:kExpectationTimeout handler:nil];
  2989. OCMVerifyAll(_mockBackend);
  2990. XCTAssertNotNil([FIRAuth auth].currentUser);
  2991. }
  2992. /** @fn waitForTimeInterval:
  2993. @brief Wait for a particular time interval.
  2994. @remarks This method also waits for all other pending @c XCTestExpectation instances.
  2995. */
  2996. - (void)waitForTimeIntervel:(NSTimeInterval)timeInterval {
  2997. static dispatch_queue_t queue;
  2998. static dispatch_once_t onceToken;
  2999. XCTestExpectation *expectation = [self expectationWithDescription:@"waitForTimeIntervel:"];
  3000. dispatch_once(&onceToken, ^{
  3001. queue = dispatch_queue_create("com.google.FIRAuthUnitTests.waitForTimeIntervel", NULL);
  3002. });
  3003. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, timeInterval * NSEC_PER_SEC), queue, ^() {
  3004. [expectation fulfill];
  3005. });
  3006. [self waitForExpectationsWithTimeout:timeInterval + kExpectationTimeout handler:nil];
  3007. }
  3008. - (void)waitForAuthGlobalWorkQueueDrain {
  3009. dispatch_semaphore_t workerSemaphore = dispatch_semaphore_create(0);
  3010. dispatch_async(FIRAuthGlobalWorkQueue(), ^{
  3011. dispatch_semaphore_signal(workerSemaphore);
  3012. });
  3013. dispatch_semaphore_wait(workerSemaphore,
  3014. DISPATCH_TIME_FOREVER /*DISPATCH_TIME_NOW + 10 * NSEC_PER_SEC*/);
  3015. }
  3016. /** @fn testRevokeTokenSuccess
  3017. @brief Tests the flow of a successful @c revokeToken:completion.
  3018. */
  3019. - (void)testRevokeTokenSuccess {
  3020. OCMExpect([_mockBackend verifyPassword:[OCMArg any] callback:[OCMArg any]])
  3021. .andCallBlock2(^(FIRVerifyPasswordRequest *_Nullable request,
  3022. FIRVerifyPasswordResponseCallback callback) {
  3023. XCTAssertEqualObjects(request.APIKey, kAPIKey);
  3024. XCTAssertEqualObjects(request.email, kEmail);
  3025. XCTAssertEqualObjects(request.password, kFakePassword);
  3026. XCTAssertTrue(request.returnSecureToken);
  3027. dispatch_async(FIRAuthGlobalWorkQueue(), ^() {
  3028. id mockVerifyPasswordResponse = OCMClassMock([FIRVerifyPasswordResponse class]);
  3029. [self stubTokensWithMockResponse:mockVerifyPasswordResponse];
  3030. callback(mockVerifyPasswordResponse, nil);
  3031. });
  3032. });
  3033. [self expectGetAccountInfo];
  3034. XCTestExpectation *signInExpectation = [self expectationWithDescription:@"signIn"];
  3035. [[FIRAuth auth] signOut:NULL];
  3036. [[FIRAuth auth] signInWithEmail:kEmail
  3037. password:kFakePassword
  3038. completion:^(FIRAuthDataResult *_Nullable result, NSError *_Nullable error) {
  3039. [self assertUser:result.user];
  3040. XCTAssertNil(error);
  3041. [signInExpectation fulfill];
  3042. }];
  3043. [self waitForExpectationsWithTimeout:kExpectationTimeout handler:nil];
  3044. [self assertUser:[FIRAuth auth].currentUser];
  3045. OCMExpect([_mockBackend revokeToken:[OCMArg any] callback:[OCMArg any]])
  3046. .andCallBlock2(
  3047. ^(FIRRevokeTokenRequest *_Nullable request, FIRRevokeTokenResponseCallback callback) {
  3048. dispatch_async(FIRAuthGlobalWorkQueue(), ^() {
  3049. id mockRevokeTokenResponse = OCMClassMock([FIRRevokeTokenResponse class]);
  3050. callback(mockRevokeTokenResponse, nil);
  3051. });
  3052. });
  3053. XCTestExpectation *revokeExpectation = [self expectationWithDescription:@"callback"];
  3054. NSString *code = @"code";
  3055. [[FIRAuth auth] revokeTokenWithAuthorizationCode:code
  3056. completion:^(NSError *_Nullable error) {
  3057. XCTAssertNil(error);
  3058. [revokeExpectation fulfill];
  3059. }];
  3060. [self waitForExpectationsWithTimeout:kExpectationTimeout handler:nil];
  3061. }
  3062. /** @fn testRevokeTokenMissingCallback
  3063. @brief Tests the flow of @c revokeToken:completion with a nil callback.
  3064. */
  3065. - (void)testRevokeTokenMissingCallback {
  3066. OCMExpect([_mockBackend verifyPassword:[OCMArg any] callback:[OCMArg any]])
  3067. .andCallBlock2(^(FIRVerifyPasswordRequest *_Nullable request,
  3068. FIRVerifyPasswordResponseCallback callback) {
  3069. XCTAssertEqualObjects(request.APIKey, kAPIKey);
  3070. XCTAssertEqualObjects(request.email, kEmail);
  3071. XCTAssertEqualObjects(request.password, kFakePassword);
  3072. XCTAssertTrue(request.returnSecureToken);
  3073. dispatch_async(FIRAuthGlobalWorkQueue(), ^() {
  3074. id mockVerifyPasswordResponse = OCMClassMock([FIRVerifyPasswordResponse class]);
  3075. [self stubTokensWithMockResponse:mockVerifyPasswordResponse];
  3076. callback(mockVerifyPasswordResponse, nil);
  3077. });
  3078. });
  3079. [self expectGetAccountInfo];
  3080. XCTestExpectation *signInExpectation = [self expectationWithDescription:@"signIn"];
  3081. [[FIRAuth auth] signOut:NULL];
  3082. [[FIRAuth auth] signInWithEmail:kEmail
  3083. password:kFakePassword
  3084. completion:^(FIRAuthDataResult *_Nullable result, NSError *_Nullable error) {
  3085. [self assertUser:result.user];
  3086. XCTAssertNil(error);
  3087. [signInExpectation fulfill];
  3088. }];
  3089. [self waitForExpectationsWithTimeout:kExpectationTimeout handler:nil];
  3090. [self assertUser:[FIRAuth auth].currentUser];
  3091. XCTestExpectation *revokeExpectation = [self expectationWithDescription:@"revoke"];
  3092. OCMExpect([_mockBackend revokeToken:[OCMArg any] callback:[OCMArg any]])
  3093. .andCallBlock2(
  3094. ^(FIRRevokeTokenRequest *_Nullable request, FIRRevokeTokenResponseCallback callback) {
  3095. dispatch_async(FIRAuthGlobalWorkQueue(), ^() {
  3096. id mockRevokeTokenResponse = OCMClassMock([FIRRevokeTokenResponse class]);
  3097. callback(mockRevokeTokenResponse, nil);
  3098. [revokeExpectation fulfill];
  3099. });
  3100. });
  3101. NSString *code = @"code";
  3102. [[FIRAuth auth] revokeTokenWithAuthorizationCode:code completion:nil];
  3103. [self waitForExpectationsWithTimeout:kExpectationTimeout handler:nil];
  3104. }
  3105. @end