FIRAuthTests.m 106 KB

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