FIRAuthTests.m 120 KB

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