FIRAuthTests.m 122 KB

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