FIRAuthTests.m 105 KB

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