FIRAuthTests.m 107 KB

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