FIRAuthTests.m 106 KB

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