FIRAuthTests.m 86 KB

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