FIRAuthTests.m 157 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335
  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. NSURL *url = [NSURL URLWithString:@"https://localhost"];
  2737. OCMExpect([self.mockAuthURLPresenter canHandleURL:url]).andReturn(YES);
  2738. XCTAssertTrue([self.fakeApplicationDelegate application:[GULAppDelegateSwizzler sharedApplication]
  2739. openURL:url
  2740. options:@{}]);
  2741. [self.mockAuthURLPresenter verify];
  2742. }
  2743. - (void)testAppOpenURLWithSourceApplication_AuthPresenterCanHandleURL {
  2744. NSURL *url = [NSURL URLWithString:@"https://localhost"];
  2745. OCMExpect([self.mockAuthURLPresenter canHandleURL:url]).andReturn(YES);
  2746. #pragma clang diagnostic push
  2747. #pragma clang diagnostic ignored "-Wdeprecated-declarations"
  2748. XCTAssertTrue([self.fakeApplicationDelegate application:[GULAppDelegateSwizzler sharedApplication]
  2749. openURL:url
  2750. sourceApplication:@""
  2751. annotation:[[NSObject alloc] init]]);
  2752. #pragma clang diagnostic pop
  2753. [self.mockAuthURLPresenter verify];
  2754. }
  2755. #endif // TARGET_OS_IOS
  2756. #pragma mark - Interoperability Tests
  2757. /** @fn testComponentsBeingRegistered
  2758. @brief Tests that Auth provides the necessary components for interoperability with other SDKs.
  2759. */
  2760. - (void)testComponentsBeingRegistered {
  2761. // Verify that the components are registered properly. Check the count, because any time a new
  2762. // component is added it should be added to the test suite as well.
  2763. NSArray<FIRComponent *> *components = [FIRAuth componentsToRegister];
  2764. XCTAssertTrue(components.count == 1);
  2765. FIRComponent *component = [components firstObject];
  2766. XCTAssert(component.protocol == @protocol(FIRAuthInterop));
  2767. }
  2768. #pragma mark - Helpers
  2769. /** @fn mockSecureTokenResponseWithError:
  2770. @brief Set up expectation for secureToken RPC.
  2771. @param error The error that the mock should return if any.
  2772. */
  2773. - (void)mockSecureTokenResponseWithError:(nullable NSError *)error {
  2774. // Set up expectation for secureToken RPC made by a successful attempt to refresh tokens.
  2775. XCTestExpectation *secureTokenResponseExpectation =
  2776. [self expectationWithDescription:@"secureTokenResponseExpectation"];
  2777. OCMExpect([_mockBackend secureToken:[OCMArg any] callback:[OCMArg any]])
  2778. .andCallBlock2(
  2779. ^(FIRSecureTokenRequest *_Nullable request, FIRSecureTokenResponseCallback callback) {
  2780. XCTAssertEqualObjects(request.APIKey, kAPIKey);
  2781. XCTAssertEqualObjects(request.refreshToken, kRefreshToken);
  2782. dispatch_async(FIRAuthGlobalWorkQueue(), ^() {
  2783. if (error) {
  2784. callback(nil, error);
  2785. [secureTokenResponseExpectation fulfill];
  2786. return;
  2787. }
  2788. id mockSecureTokenResponse = OCMClassMock([FIRSecureTokenResponse class]);
  2789. OCMStub([mockSecureTokenResponse accessToken]).andReturn(kNewAccessToken);
  2790. NSDate *futureDate =
  2791. [[NSDate date] dateByAddingTimeInterval:kTestTokenExpirationTimeInterval];
  2792. OCMStub([mockSecureTokenResponse approximateExpirationDate]).andReturn(futureDate);
  2793. callback(mockSecureTokenResponse, nil);
  2794. [secureTokenResponseExpectation fulfill];
  2795. });
  2796. });
  2797. }
  2798. /** @fn enableAutoTokenRefresh
  2799. @brief Enables automatic token refresh by invoking FIRAuth's implementation of FIRApp's
  2800. |getTokenWithImplementation|.
  2801. */
  2802. - (void)enableAutoTokenRefresh {
  2803. XCTestExpectation *expectation = [self expectationWithDescription:@"autoTokenRefreshcallback"];
  2804. [[FIRAuth auth] getTokenForcingRefresh:NO
  2805. withCallback:^(NSString *_Nullable token, NSError *_Nullable error) {
  2806. [expectation fulfill];
  2807. }];
  2808. [self waitForExpectationsWithTimeout:kExpectationTimeout handler:nil];
  2809. }
  2810. /** @fn stubSecureTokensWithMockResponse
  2811. @brief Creates stubs on the mock response object with access and refresh tokens
  2812. @param mockResponse The mock response object.
  2813. */
  2814. - (void)stubTokensWithMockResponse:(id)mockResponse {
  2815. OCMStub([mockResponse IDToken]).andReturn(kAccessToken);
  2816. OCMStub([mockResponse approximateExpirationDate])
  2817. .andReturn([NSDate dateWithTimeIntervalSinceNow:kAccessTokenTimeToLive]);
  2818. OCMStub([mockResponse refreshToken]).andReturn(kRefreshToken);
  2819. }
  2820. /** @fn expectGetAccountInfo
  2821. @brief Expects a GetAccountInfo request on the mock backend and calls back with fake account
  2822. data.
  2823. */
  2824. - (void)expectGetAccountInfo {
  2825. [self expectGetAccountInfoWithAccessToken:kAccessToken];
  2826. }
  2827. /** @fn expectGetAccountInfoWithAccessToken
  2828. @param accessToken The access token for the user to check against.
  2829. @brief Expects a GetAccountInfo request on the mock backend and calls back with fake account
  2830. data.
  2831. */
  2832. - (void)expectGetAccountInfoWithAccessToken:(NSString *)accessToken {
  2833. OCMExpect([_mockBackend getAccountInfo:[OCMArg any] callback:[OCMArg any]])
  2834. .andCallBlock2(^(FIRGetAccountInfoRequest *_Nullable request,
  2835. FIRGetAccountInfoResponseCallback callback) {
  2836. XCTAssertEqualObjects(request.APIKey, kAPIKey);
  2837. XCTAssertEqualObjects(request.accessToken, accessToken);
  2838. dispatch_async(FIRAuthGlobalWorkQueue(), ^() {
  2839. id mockGetAccountInfoResponseUser = OCMClassMock([FIRGetAccountInfoResponseUser class]);
  2840. OCMStub([mockGetAccountInfoResponseUser localID]).andReturn(kLocalID);
  2841. OCMStub([mockGetAccountInfoResponseUser displayName]).andReturn(kDisplayName);
  2842. OCMStub([mockGetAccountInfoResponseUser email]).andReturn(kEmail);
  2843. OCMStub([mockGetAccountInfoResponseUser passwordHash]).andReturn(kPasswordHash);
  2844. id mockGetAccountInfoResponse = OCMClassMock([FIRGetAccountInfoResponse class]);
  2845. OCMStub([mockGetAccountInfoResponse users]).andReturn(@[
  2846. mockGetAccountInfoResponseUser
  2847. ]);
  2848. callback(mockGetAccountInfoResponse, nil);
  2849. });
  2850. });
  2851. }
  2852. /** @fn assertUser
  2853. @brief Asserts the given FIRUser matching the fake data returned by @c expectGetAccountInfo.
  2854. @param user The user object to be verified.
  2855. */
  2856. - (void)assertUser:(FIRUser *)user {
  2857. XCTAssertNotNil(user);
  2858. XCTAssertEqualObjects(user.uid, kLocalID);
  2859. XCTAssertEqualObjects(user.displayName, kDisplayName);
  2860. XCTAssertEqualObjects(user.email, kEmail);
  2861. XCTAssertFalse(user.anonymous);
  2862. XCTAssertEqual(user.providerData.count, 0u);
  2863. }
  2864. /** @fn expectGetAccountInfoGoogle
  2865. @brief Expects a GetAccountInfo request on the mock backend and calls back with fake account
  2866. data for a Google Sign-In user.
  2867. */
  2868. - (void)expectGetAccountInfoGoogle {
  2869. OCMExpect([_mockBackend getAccountInfo:[OCMArg any] callback:[OCMArg any]])
  2870. .andCallBlock2(^(FIRGetAccountInfoRequest *_Nullable request,
  2871. FIRGetAccountInfoResponseCallback callback) {
  2872. XCTAssertEqualObjects(request.APIKey, kAPIKey);
  2873. XCTAssertEqualObjects(request.accessToken, kAccessToken);
  2874. dispatch_async(FIRAuthGlobalWorkQueue(), ^() {
  2875. id mockGoogleUserInfo = OCMClassMock([FIRGetAccountInfoResponseProviderUserInfo class]);
  2876. OCMStub([mockGoogleUserInfo providerID]).andReturn(FIRGoogleAuthProviderID);
  2877. OCMStub([mockGoogleUserInfo displayName]).andReturn(kGoogleDisplayName);
  2878. OCMStub([mockGoogleUserInfo federatedID]).andReturn(kGoogleID);
  2879. OCMStub([mockGoogleUserInfo email]).andReturn(kGoogleEmail);
  2880. id mockGetAccountInfoResponseUser = OCMClassMock([FIRGetAccountInfoResponseUser class]);
  2881. OCMStub([mockGetAccountInfoResponseUser localID]).andReturn(kLocalID);
  2882. OCMStub([mockGetAccountInfoResponseUser displayName]).andReturn(kDisplayName);
  2883. OCMStub([mockGetAccountInfoResponseUser providerUserInfo])
  2884. .andReturn((@[ mockGoogleUserInfo ]));
  2885. id mockGetAccountInfoResponse = OCMClassMock([FIRGetAccountInfoResponse class]);
  2886. OCMStub([mockGetAccountInfoResponse users]).andReturn(@[
  2887. mockGetAccountInfoResponseUser
  2888. ]);
  2889. callback(mockGetAccountInfoResponse, nil);
  2890. });
  2891. });
  2892. }
  2893. /** @fn assertUserGoogle
  2894. @brief Asserts the given FIRUser matching the fake data returned by
  2895. @c expectGetAccountInfoGoogle.
  2896. @param user The user object to be verified.
  2897. */
  2898. - (void)assertUserGoogle:(FIRUser *)user {
  2899. XCTAssertNotNil(user);
  2900. XCTAssertEqualObjects(user.uid, kLocalID);
  2901. XCTAssertEqualObjects(user.displayName, kDisplayName);
  2902. XCTAssertEqual(user.providerData.count, 1u);
  2903. id<FIRUserInfo> googleUserInfo = user.providerData[0];
  2904. XCTAssertEqualObjects(googleUserInfo.providerID, FIRGoogleAuthProviderID);
  2905. XCTAssertEqualObjects(googleUserInfo.uid, kGoogleID);
  2906. XCTAssertEqualObjects(googleUserInfo.displayName, kGoogleDisplayName);
  2907. XCTAssertEqualObjects(googleUserInfo.email, kGoogleEmail);
  2908. }
  2909. /** @fn expectGetAccountInfoAnonymous
  2910. @brief Expects a GetAccountInfo request on the mock backend and calls back with fake anonymous
  2911. account data.
  2912. */
  2913. - (void)expectGetAccountInfoAnonymous {
  2914. OCMExpect([_mockBackend getAccountInfo:[OCMArg any] callback:[OCMArg any]])
  2915. .andCallBlock2(^(FIRGetAccountInfoRequest *_Nullable request,
  2916. FIRGetAccountInfoResponseCallback callback) {
  2917. XCTAssertEqualObjects(request.APIKey, kAPIKey);
  2918. XCTAssertEqualObjects(request.accessToken, kAccessToken);
  2919. dispatch_async(FIRAuthGlobalWorkQueue(), ^() {
  2920. id mockGetAccountInfoResponseUser = OCMClassMock([FIRGetAccountInfoResponseUser class]);
  2921. OCMStub([mockGetAccountInfoResponseUser localID]).andReturn(kLocalID);
  2922. id mockGetAccountInfoResponse = OCMClassMock([FIRGetAccountInfoResponse class]);
  2923. OCMStub([mockGetAccountInfoResponse users]).andReturn(@[
  2924. mockGetAccountInfoResponseUser
  2925. ]);
  2926. callback(mockGetAccountInfoResponse, nil);
  2927. });
  2928. });
  2929. }
  2930. /** @fn assertUserAnonymous
  2931. @brief Asserts the given FIRUser matching the fake data returned by
  2932. @c expectGetAccountInfoAnonymous.
  2933. @param user The user object to be verified.
  2934. */
  2935. - (void)assertUserAnonymous:(FIRUser *)user {
  2936. XCTAssertNotNil(user);
  2937. XCTAssertEqualObjects(user.uid, kLocalID);
  2938. XCTAssertNil(user.displayName);
  2939. XCTAssertTrue(user.anonymous);
  2940. XCTAssertEqual(user.providerData.count, 0u);
  2941. }
  2942. /** @fn waitForSignIn
  2943. @brief Signs in a user to prepare for tests.
  2944. @remarks This method also waits for all other pending @c XCTestExpectation instances.
  2945. */
  2946. - (void)waitForSignIn {
  2947. [self waitForSignInWithAccessToken:kAccessToken APIKey:nil completion:nil];
  2948. }
  2949. /** @fn waitForSignInWithAccessToken:
  2950. @brief Signs in a user to prepare for tests.
  2951. @param accessToken The access token for the user to have.
  2952. @param APIKey Optionally, The API key associated with the user.
  2953. @param completion Optionally, The completion invoked at the end of the flow.
  2954. @remarks This method also waits for all other pending @c XCTestExpectation instances.
  2955. */
  2956. - (void)waitForSignInWithAccessToken:(NSString *)accessToken
  2957. APIKey:(nullable NSString *)APIKey
  2958. completion:(nullable FIRAuthResultCallback)completion {
  2959. OCMExpect([_mockBackend verifyPassword:[OCMArg any] callback:[OCMArg any]])
  2960. .andCallBlock2(^(FIRVerifyPasswordRequest *_Nullable request,
  2961. FIRVerifyPasswordResponseCallback callback) {
  2962. dispatch_async(FIRAuthGlobalWorkQueue(), ^() {
  2963. id mockVerifyPasswordResponse = OCMClassMock([FIRVerifyPasswordResponse class]);
  2964. OCMStub([mockVerifyPasswordResponse IDToken]).andReturn(accessToken);
  2965. OCMStub([mockVerifyPasswordResponse approximateExpirationDate])
  2966. .andReturn([NSDate dateWithTimeIntervalSinceNow:kAccessTokenTimeToLive]);
  2967. OCMStub([mockVerifyPasswordResponse refreshToken]).andReturn(kRefreshToken);
  2968. callback(mockVerifyPasswordResponse, nil);
  2969. });
  2970. });
  2971. [self expectGetAccountInfoWithAccessToken:accessToken];
  2972. XCTestExpectation *expectation = [self expectationWithDescription:@"callback"];
  2973. [[FIRAuth auth] signInWithEmail:kEmail
  2974. password:kFakePassword
  2975. completion:^(FIRAuthDataResult *_Nullable result, NSError *_Nullable error) {
  2976. result.user.requestConfiguration =
  2977. [[FIRAuthRequestConfiguration alloc] initWithAPIKey:APIKey
  2978. appID:kFirebaseAppID];
  2979. [expectation fulfill];
  2980. if (completion) {
  2981. completion(result.user, error);
  2982. }
  2983. }];
  2984. [self waitForExpectationsWithTimeout:kExpectationTimeout handler:nil];
  2985. OCMVerifyAll(_mockBackend);
  2986. XCTAssertNotNil([FIRAuth auth].currentUser);
  2987. }
  2988. /** @fn waitForTimeInterval:
  2989. @brief Wait for a particular time interval.
  2990. @remarks This method also waits for all other pending @c XCTestExpectation instances.
  2991. */
  2992. - (void)waitForTimeIntervel:(NSTimeInterval)timeInterval {
  2993. static dispatch_queue_t queue;
  2994. static dispatch_once_t onceToken;
  2995. XCTestExpectation *expectation = [self expectationWithDescription:@"waitForTimeIntervel:"];
  2996. dispatch_once(&onceToken, ^{
  2997. queue = dispatch_queue_create("com.google.FIRAuthUnitTests.waitForTimeIntervel", NULL);
  2998. });
  2999. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, timeInterval * NSEC_PER_SEC), queue, ^() {
  3000. [expectation fulfill];
  3001. });
  3002. [self waitForExpectationsWithTimeout:timeInterval + kExpectationTimeout handler:nil];
  3003. }
  3004. - (void)waitForAuthGlobalWorkQueueDrain {
  3005. dispatch_semaphore_t workerSemaphore = dispatch_semaphore_create(0);
  3006. dispatch_async(FIRAuthGlobalWorkQueue(), ^{
  3007. dispatch_semaphore_signal(workerSemaphore);
  3008. });
  3009. dispatch_semaphore_wait(workerSemaphore,
  3010. DISPATCH_TIME_FOREVER /*DISPATCH_TIME_NOW + 10 * NSEC_PER_SEC*/);
  3011. }
  3012. /** @fn testRevokeTokenSuccess
  3013. @brief Tests the flow of a successful @c revokeToken:completion.
  3014. */
  3015. - (void)testRevokeTokenSuccess {
  3016. OCMExpect([_mockBackend verifyPassword:[OCMArg any] callback:[OCMArg any]])
  3017. .andCallBlock2(^(FIRVerifyPasswordRequest *_Nullable request,
  3018. FIRVerifyPasswordResponseCallback callback) {
  3019. XCTAssertEqualObjects(request.APIKey, kAPIKey);
  3020. XCTAssertEqualObjects(request.email, kEmail);
  3021. XCTAssertEqualObjects(request.password, kFakePassword);
  3022. XCTAssertTrue(request.returnSecureToken);
  3023. dispatch_async(FIRAuthGlobalWorkQueue(), ^() {
  3024. id mockVerifyPasswordResponse = OCMClassMock([FIRVerifyPasswordResponse class]);
  3025. [self stubTokensWithMockResponse:mockVerifyPasswordResponse];
  3026. callback(mockVerifyPasswordResponse, nil);
  3027. });
  3028. });
  3029. [self expectGetAccountInfo];
  3030. XCTestExpectation *signInExpectation = [self expectationWithDescription:@"signIn"];
  3031. [[FIRAuth auth] signOut:NULL];
  3032. [[FIRAuth auth] signInWithEmail:kEmail
  3033. password:kFakePassword
  3034. completion:^(FIRAuthDataResult *_Nullable result, NSError *_Nullable error) {
  3035. [self assertUser:result.user];
  3036. XCTAssertNil(error);
  3037. [signInExpectation fulfill];
  3038. }];
  3039. [self waitForExpectationsWithTimeout:kExpectationTimeout handler:nil];
  3040. [self assertUser:[FIRAuth auth].currentUser];
  3041. OCMExpect([_mockBackend revokeToken:[OCMArg any] callback:[OCMArg any]])
  3042. .andCallBlock2(
  3043. ^(FIRRevokeTokenRequest *_Nullable request, FIRRevokeTokenResponseCallback callback) {
  3044. dispatch_async(FIRAuthGlobalWorkQueue(), ^() {
  3045. id mockRevokeTokenResponse = OCMClassMock([FIRRevokeTokenResponse class]);
  3046. callback(mockRevokeTokenResponse, nil);
  3047. });
  3048. });
  3049. XCTestExpectation *revokeExpectation = [self expectationWithDescription:@"callback"];
  3050. NSString *code = @"code";
  3051. [[FIRAuth auth] revokeTokenWithAuthorizationCode:code
  3052. completion:^(NSError *_Nullable error) {
  3053. XCTAssertNil(error);
  3054. [revokeExpectation fulfill];
  3055. }];
  3056. [self waitForExpectationsWithTimeout:kExpectationTimeout handler:nil];
  3057. }
  3058. /** @fn testRevokeTokenMissingCallback
  3059. @brief Tests the flow of @c revokeToken:completion with a nil callback.
  3060. */
  3061. - (void)testRevokeTokenMissingCallback {
  3062. OCMExpect([_mockBackend verifyPassword:[OCMArg any] callback:[OCMArg any]])
  3063. .andCallBlock2(^(FIRVerifyPasswordRequest *_Nullable request,
  3064. FIRVerifyPasswordResponseCallback callback) {
  3065. XCTAssertEqualObjects(request.APIKey, kAPIKey);
  3066. XCTAssertEqualObjects(request.email, kEmail);
  3067. XCTAssertEqualObjects(request.password, kFakePassword);
  3068. XCTAssertTrue(request.returnSecureToken);
  3069. dispatch_async(FIRAuthGlobalWorkQueue(), ^() {
  3070. id mockVerifyPasswordResponse = OCMClassMock([FIRVerifyPasswordResponse class]);
  3071. [self stubTokensWithMockResponse:mockVerifyPasswordResponse];
  3072. callback(mockVerifyPasswordResponse, nil);
  3073. });
  3074. });
  3075. [self expectGetAccountInfo];
  3076. XCTestExpectation *signInExpectation = [self expectationWithDescription:@"signIn"];
  3077. [[FIRAuth auth] signOut:NULL];
  3078. [[FIRAuth auth] signInWithEmail:kEmail
  3079. password:kFakePassword
  3080. completion:^(FIRAuthDataResult *_Nullable result, NSError *_Nullable error) {
  3081. [self assertUser:result.user];
  3082. XCTAssertNil(error);
  3083. [signInExpectation fulfill];
  3084. }];
  3085. [self waitForExpectationsWithTimeout:kExpectationTimeout handler:nil];
  3086. [self assertUser:[FIRAuth auth].currentUser];
  3087. XCTestExpectation *revokeExpectation = [self expectationWithDescription:@"revoke"];
  3088. OCMExpect([_mockBackend revokeToken:[OCMArg any] callback:[OCMArg any]])
  3089. .andCallBlock2(
  3090. ^(FIRRevokeTokenRequest *_Nullable request, FIRRevokeTokenResponseCallback callback) {
  3091. dispatch_async(FIRAuthGlobalWorkQueue(), ^() {
  3092. id mockRevokeTokenResponse = OCMClassMock([FIRRevokeTokenResponse class]);
  3093. callback(mockRevokeTokenResponse, nil);
  3094. [revokeExpectation fulfill];
  3095. });
  3096. });
  3097. NSString *code = @"code";
  3098. [[FIRAuth auth] revokeTokenWithAuthorizationCode:code completion:nil];
  3099. [self waitForExpectationsWithTimeout:kExpectationTimeout handler:nil];
  3100. }
  3101. @end