FIRAuthTests.m 122 KB

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