FIRAuthTests.m 125 KB

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