FIRAuthTests.m 132 KB

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