FIRAuthTests.m 111 KB

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