FIRAuthTests.m 122 KB

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