FIRAuthTests.m 122 KB

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