FIRAuthTests.m 114 KB

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