FIRAuthTests.m 114 KB

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