FIRInstanceIDTest.m 65 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513
  1. /*
  2. * Copyright 2019 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 <XCTest/XCTest.h>
  17. #import "FirebaseInstallations/Source/Library/Private/FirebaseInstallationsInternal.h"
  18. #import <OCMock/OCMock.h>
  19. #import "Firebase/InstanceID/Private/FIRInstanceID_Private.h"
  20. #import "FirebaseCore/Sources/Private/FirebaseCoreInternal.h"
  21. #import "Firebase/InstanceID/FIRInstanceIDAuthService.h"
  22. #import "Firebase/InstanceID/FIRInstanceIDCheckinPreferences+Internal.h"
  23. #import "Firebase/InstanceID/FIRInstanceIDConstants.h"
  24. #import "Firebase/InstanceID/FIRInstanceIDTokenInfo.h"
  25. #import "Firebase/InstanceID/FIRInstanceIDTokenManager.h"
  26. #import "Firebase/InstanceID/FIRInstanceIDUtilities.h"
  27. #import "Firebase/InstanceID/NSError+FIRInstanceID.h"
  28. #import "Firebase/InstanceID/Private/FIRInstanceID+Private.h"
  29. static NSString *const kFakeIID = @"12345678";
  30. static NSString *const kFakeAPNSToken = @"this is a fake apns token";
  31. static NSString *const kAuthorizedEntity = @"test-audience";
  32. static NSString *const kScope = @"test-scope";
  33. static NSString *const kToken = @"12345678:test-token";
  34. static FIRInstanceIDTokenInfo *sTokenInfo;
  35. // Faking checkin calls
  36. static NSString *const kDeviceAuthId = @"device-id";
  37. static NSString *const kSecretToken = @"secret-token";
  38. static NSString *const kVersionInfo = @"1.0";
  39. // FIRApp configuration.
  40. static NSString *const kGCMSenderID = @"correct_gcm_sender_id";
  41. static NSString *const kGoogleAppID = @"1:123:ios:123abc";
  42. @interface FIRInstanceID (ExposedForTest)
  43. @property(nonatomic, readwrite, strong) FIRInstanceIDTokenManager *tokenManager;
  44. @property(nonatomic, readwrite, strong) FIRInstallations *installations;
  45. @property(nonatomic, readwrite, copy) NSString *fcmSenderID;
  46. @property(nonatomic, readwrite, copy) NSString *firebaseAppID;
  47. @property(nonatomic, readwrite, copy) NSString *defaultFCMToken;
  48. - (NSInteger)retryIntervalToFetchDefaultToken;
  49. - (BOOL)isFCMAutoInitEnabled;
  50. - (void)didCompleteConfigure;
  51. - (NSString *)cachedTokenIfAvailable;
  52. - (void)deleteIdentityWithHandler:(FIRInstanceIDDeleteHandler)handler;
  53. + (FIRInstanceID *)instanceIDForTests;
  54. - (void)defaultTokenWithHandler:(FIRInstanceIDTokenHandler)handler;
  55. - (instancetype)initPrivately;
  56. - (void)start;
  57. + (int64_t)maxRetryCountForDefaultToken;
  58. + (int64_t)minIntervalForDefaultTokenRetry;
  59. + (int64_t)maxRetryIntervalForDefaultTokenInSeconds;
  60. - (void)fetchNewTokenWithAuthorizedEntity:(NSString *)authorizedEntity
  61. scope:(NSString *)scope
  62. instanceID:(NSString *)instanceID
  63. options:(NSDictionary *)options
  64. handler:(FIRInstanceIDTokenHandler)handler;
  65. @end
  66. @interface FIRInstanceIDTest : XCTestCase
  67. @property(nonatomic, readwrite, assign) BOOL hasCheckinInfo;
  68. #pragma clang diagnostic push
  69. #pragma clang diagnostic ignored "-Wdeprecated-declarations"
  70. @property(nonatomic, readwrite, strong) FIRInstanceID *instanceID;
  71. #pragma clang diagnostic pop
  72. @property(nonatomic, readwrite, strong) id mockInstanceID;
  73. @property(nonatomic, readwrite, strong) id mockTokenManager;
  74. @property(nonatomic, readwrite, strong) id mockInstallations;
  75. @property(nonatomic, readwrite, strong) id mockAuthService;
  76. @property(nonatomic, readwrite, strong) id<NSObject> tokenRefreshNotificationObserver;
  77. @property(nonatomic, readwrite, copy) FIRInstanceIDTokenHandler newTokenCompletion;
  78. @property(nonatomic, readwrite, copy) FIRInstanceIDDeleteTokenHandler deleteTokenCompletion;
  79. @end
  80. @implementation FIRInstanceIDTest
  81. #pragma clang diagnostic push
  82. #pragma clang diagnostic ignored "-Wdeprecated-declarations"
  83. - (void)setUp {
  84. [super setUp];
  85. // `+[FIRInstallations installations]` supposed to be used on `-[FIRInstanceID start]` to get
  86. // `FIRInstallations` default instance. Need to stub it before.
  87. self.mockInstallations = OCMClassMock([FIRInstallations class]);
  88. OCMStub([self.mockInstallations installations]).andReturn(self.mockInstallations);
  89. _instanceID = [[FIRInstanceID alloc] initPrivately];
  90. [_instanceID start];
  91. if (!sTokenInfo) {
  92. sTokenInfo = [[FIRInstanceIDTokenInfo alloc] initWithAuthorizedEntity:kAuthorizedEntity
  93. scope:kScope
  94. token:kToken
  95. appVersion:nil
  96. firebaseAppID:nil];
  97. sTokenInfo.cacheTime = [NSDate date];
  98. }
  99. [self mockInstanceIDObjects];
  100. }
  101. - (void)tearDown {
  102. [[NSNotificationCenter defaultCenter] removeObserver:self.tokenRefreshNotificationObserver];
  103. self.mockInstanceID = nil;
  104. self.instanceID = nil;
  105. self.mockTokenManager = nil;
  106. self.mockInstallations = nil;
  107. [super tearDown];
  108. }
  109. - (void)mockInstanceIDObjects {
  110. // Mock that we have valid checkin info. Individual tests can override this.
  111. self.hasCheckinInfo = YES;
  112. self.mockAuthService = OCMClassMock([FIRInstanceIDAuthService class]);
  113. [[[self.mockAuthService stub] andDo:^(NSInvocation *invocation) {
  114. [invocation setReturnValue:&self->_hasCheckinInfo];
  115. }] hasValidCheckinInfo];
  116. self.mockTokenManager = OCMClassMock([FIRInstanceIDTokenManager class]);
  117. [[[self.mockTokenManager stub] andReturn:self.mockAuthService] authService];
  118. _instanceID.fcmSenderID = kAuthorizedEntity;
  119. self.mockInstanceID = OCMPartialMock(_instanceID);
  120. [self.mockInstanceID setTokenManager:self.mockTokenManager];
  121. #pragma clang diagnostic push
  122. #pragma clang diagnostic ignored "-Wdeprecated-declarations"
  123. id instanceIDClassMock = OCMClassMock([FIRInstanceID class]);
  124. #pragma clang diagnostic pop
  125. OCMStub(ClassMethod([instanceIDClassMock minIntervalForDefaultTokenRetry])).andReturn(2);
  126. OCMStub(ClassMethod([instanceIDClassMock maxRetryIntervalForDefaultTokenInSeconds]))
  127. .andReturn(10);
  128. }
  129. /**
  130. * Tests that the FIRInstanceID's sharedInstance class method produces an instance of
  131. * FIRInstanceID with an associated FIRInstanceIDTokenManager.
  132. */
  133. - (void)testSharedInstance {
  134. #pragma clang diagnostic push
  135. #pragma clang diagnostic ignored "-Wdeprecated-declarations"
  136. // The shared instance should be `nil` before the app is configured.
  137. XCTAssertNil([FIRInstanceID instanceID]);
  138. // The shared instance relies on the default app being configured. Configure it.
  139. FIROptions *options = [[FIROptions alloc] initWithGoogleAppID:kGoogleAppID
  140. GCMSenderID:kGCMSenderID];
  141. options.APIKey = @"AIzaSy-ApiKeyWithValidFormat_0123456789";
  142. options.projectID = @"project-id";
  143. [FIRApp configureWithName:kFIRDefaultAppName options:options];
  144. FIRInstanceID *instanceID = [FIRInstanceID instanceID];
  145. XCTAssertNotNil(instanceID);
  146. XCTAssertNotNil(instanceID.tokenManager);
  147. // Ensure a second call returns the same instance as the first.
  148. FIRInstanceID *secondInstanceID = [FIRInstanceID instanceID];
  149. XCTAssertEqualObjects(instanceID, secondInstanceID);
  150. // Reset the default app for the next test.
  151. [FIRApp resetApps];
  152. }
  153. - (void)testFCMAutoInitEnabled {
  154. XCTAssertFalse([_instanceID isFCMAutoInitEnabled],
  155. @"When FCM is not available, FCM Auto Init Enabled should be NO.");
  156. }
  157. - (void)testTokenShouldBeRefreshedIfCacheTokenNeedsToBeRefreshed {
  158. [[[self.mockInstanceID stub] andReturn:kToken] cachedTokenIfAvailable];
  159. [[[self.mockTokenManager stub] andReturnValue:@(YES)]
  160. checkTokenRefreshPolicyWithIID:[OCMArg any]];
  161. [[self.mockInstanceID stub] tokenWithAuthorizedEntity:[OCMArg any]
  162. scope:[OCMArg any]
  163. options:[OCMArg any]
  164. handler:[OCMArg any]];
  165. [self expectInstallationsInstallationIDWithFID:kToken error:nil];
  166. [self.mockInstanceID didCompleteConfigure];
  167. OCMVerify([self.mockInstanceID defaultTokenWithHandler:nil]);
  168. XCTAssertEqualObjects([self.mockInstanceID token], kToken);
  169. }
  170. - (void)testTokenShouldBeRefreshedIfNoCacheTokenButAutoInitAllowed {
  171. [[[self.mockInstanceID stub] andReturn:nil] cachedTokenIfAvailable];
  172. [[[self.mockInstanceID stub] andReturnValue:@(YES)] isFCMAutoInitEnabled];
  173. [[self.mockInstanceID stub] tokenWithAuthorizedEntity:[OCMArg any]
  174. scope:[OCMArg any]
  175. options:[OCMArg any]
  176. handler:[OCMArg any]];
  177. [self.mockInstanceID didCompleteConfigure];
  178. OCMVerify([self.mockInstanceID defaultTokenWithHandler:nil]);
  179. }
  180. - (void)testTokenShouldBeRefreshedIfIIDAndTokenAreNotConsistent {
  181. XCTestExpectation *expectation = [self expectationWithDescription:@"token request is complete"];
  182. NSString *APNSKey = kFIRInstanceIDTokenOptionsAPNSKey;
  183. NSString *serverKey = kFIRInstanceIDTokenOptionsAPNSIsSandboxKey;
  184. [self mockAuthServiceToAlwaysReturnValidCheckin];
  185. NSData *fakeAPNSDeviceToken = [kFakeAPNSToken dataUsingEncoding:NSUTF8StringEncoding];
  186. BOOL isSandbox = YES;
  187. NSDictionary *tokenOptions = @{
  188. APNSKey : fakeAPNSDeviceToken,
  189. serverKey : @(isSandbox),
  190. };
  191. FIRInstanceIDAPNSInfo *optionsAPNSInfo =
  192. [[FIRInstanceIDAPNSInfo alloc] initWithTokenOptionsDictionary:tokenOptions];
  193. sTokenInfo.APNSInfo = optionsAPNSInfo;
  194. [[[self.mockTokenManager stub] andReturn:sTokenInfo]
  195. cachedTokenInfoWithAuthorizedEntity:[OCMArg any]
  196. scope:[OCMArg any]];
  197. [[self.mockTokenManager stub]
  198. fetchNewTokenWithAuthorizedEntity:kGCMSenderID
  199. scope:@"*"
  200. instanceID:@"differentIID"
  201. options:tokenOptions
  202. handler:[OCMArg invokeBlockWithArgs:@"differentIID:newToken",
  203. [NSNull null], nil]];
  204. [self expectInstallationsInstallationIDWithFID:@"differentIID" error:nil];
  205. [self.mockInstanceID
  206. tokenWithAuthorizedEntity:kGCMSenderID
  207. scope:@"*"
  208. options:tokenOptions
  209. handler:^(NSString *_Nullable token, NSError *_Nullable error) {
  210. XCTAssertEqualObjects(token, @"differentIID:newToken");
  211. [expectation fulfill];
  212. }];
  213. [self waitForExpectationsWithTimeout:1.0 handler:NULL];
  214. }
  215. - (void)testTokenIsDeletedAlongWithIdentity {
  216. [[[self.mockInstanceID stub] andReturnValue:@(YES)] isFCMAutoInitEnabled];
  217. [[self.mockInstanceID stub] tokenWithAuthorizedEntity:[OCMArg any]
  218. scope:[OCMArg any]
  219. options:[OCMArg any]
  220. handler:[OCMArg any]];
  221. [self.mockInstanceID deleteIdentityWithHandler:^(NSError *_Nullable error) {
  222. XCTAssertNil([self.mockInstanceID token]);
  223. }];
  224. }
  225. - (void)testTokenIsFetchedDuringIIDGeneration {
  226. XCTestExpectation *tokenExpectation = [self
  227. expectationWithDescription:@"Token is refreshed when getID is called to avoid IID conflict."];
  228. [self expectInstallationsInstallationIDWithFID:kFakeIID error:nil];
  229. [self.mockInstanceID getIDWithHandler:^(NSString *identity, NSError *error) {
  230. XCTAssertNotNil(identity);
  231. XCTAssertEqual(identity, kFakeIID);
  232. OCMVerify([self.mockInstanceID token]);
  233. [tokenExpectation fulfill];
  234. }];
  235. [self waitForExpectationsWithTimeout:0.1
  236. handler:^(NSError *error) {
  237. XCTAssertNil(error);
  238. }];
  239. }
  240. /**
  241. * Tests that when a new InstanceID token is successfully produced,
  242. * the callback is invoked with a token that is not an empty string and with no error.
  243. */
  244. - (void)testNewTokenSuccess {
  245. XCTestExpectation *tokenExpectation =
  246. [self expectationWithDescription:@"New token handler invoked."];
  247. NSString *APNSKey = kFIRInstanceIDTokenOptionsAPNSKey;
  248. NSString *serverKey = kFIRInstanceIDTokenOptionsAPNSIsSandboxKey;
  249. [self stubInstallationsToReturnValidID];
  250. [self mockAuthServiceToAlwaysReturnValidCheckin];
  251. NSData *fakeAPNSDeviceToken = [kFakeAPNSToken dataUsingEncoding:NSUTF8StringEncoding];
  252. BOOL isSandbox = YES;
  253. NSDictionary *tokenOptions = @{
  254. APNSKey : fakeAPNSDeviceToken,
  255. serverKey : @(isSandbox),
  256. };
  257. [[[self.mockTokenManager stub] andDo:^(NSInvocation *invocation) {
  258. self.newTokenCompletion(kToken, nil);
  259. }] fetchNewTokenWithAuthorizedEntity:kAuthorizedEntity
  260. scope:kScope
  261. instanceID:[OCMArg any]
  262. options:[OCMArg checkWithBlock:^BOOL(id obj) {
  263. NSDictionary *options = (NSDictionary *)obj;
  264. XCTAssertTrue([options[APNSKey] isEqual:fakeAPNSDeviceToken]);
  265. XCTAssertTrue([options[serverKey] isEqual:@(isSandbox)]);
  266. return YES;
  267. }]
  268. handler:[OCMArg checkWithBlock:^BOOL(id obj) {
  269. self.newTokenCompletion = obj;
  270. return obj != nil;
  271. }]];
  272. [self.instanceID tokenWithAuthorizedEntity:kAuthorizedEntity
  273. scope:kScope
  274. options:tokenOptions
  275. handler:^(NSString *token, NSError *error) {
  276. XCTAssertNotNil(token);
  277. XCTAssertGreaterThan(token.length, 0);
  278. XCTAssertNil(error);
  279. [tokenExpectation fulfill];
  280. }];
  281. [self waitForExpectationsWithTimeout:1
  282. handler:^(NSError *error) {
  283. XCTAssertNil(error);
  284. }];
  285. }
  286. /**
  287. * Get Token should fail if we do not have valid checkin info and are unable to
  288. * retreive one.
  289. */
  290. - (void)testNewTokenCheckinFailure {
  291. self.hasCheckinInfo = NO;
  292. __block FIRInstanceIDDeviceCheckinCompletion checkinHandler;
  293. [[[self.mockAuthService stub] andDo:^(NSInvocation *invocation) {
  294. if (checkinHandler) {
  295. FIRInstanceIDErrorCode code = kFIRInstanceIDErrorCodeUnknown;
  296. NSError *error = [NSError errorWithFIRInstanceIDErrorCode:code];
  297. checkinHandler(nil, error);
  298. }
  299. }] fetchCheckinInfoWithHandler:[OCMArg checkWithBlock:^BOOL(id obj) {
  300. return (checkinHandler = obj) != nil;
  301. }]];
  302. XCTestExpectation *tokenExpectation =
  303. [self expectationWithDescription:@"New token handler invoked."];
  304. NSDictionary *tokenOptions = @{
  305. kFIRInstanceIDTokenOptionsAPNSKey : [kFakeAPNSToken dataUsingEncoding:NSUTF8StringEncoding],
  306. kFIRInstanceIDTokenOptionsAPNSIsSandboxKey : @(YES),
  307. };
  308. [[[self.mockTokenManager stub] andDo:^(NSInvocation *invocation) {
  309. self.newTokenCompletion(kToken, nil);
  310. }] fetchNewTokenWithAuthorizedEntity:kAuthorizedEntity
  311. scope:kScope
  312. instanceID:[OCMArg any]
  313. options:[OCMArg any]
  314. handler:[OCMArg checkWithBlock:^BOOL(id obj) {
  315. self.newTokenCompletion = obj;
  316. return obj != nil;
  317. }]];
  318. [self.instanceID tokenWithAuthorizedEntity:kAuthorizedEntity
  319. scope:kScope
  320. options:tokenOptions
  321. handler:^(NSString *token, NSError *error) {
  322. XCTAssertNil(token);
  323. XCTAssertNotNil(error);
  324. [tokenExpectation fulfill];
  325. }];
  326. [self waitForExpectationsWithTimeout:60.0
  327. handler:^(NSError *error) {
  328. XCTAssertNil(error);
  329. }];
  330. }
  331. /**
  332. * Get token with no valid checkin should wait for any existing checkin operation to finish.
  333. * If the checkin succeeds within a stipulated amount of time period getting the token should
  334. * also succeed.
  335. */
  336. - (void)testNewTokenSuccessAfterWaiting {
  337. self.hasCheckinInfo = NO;
  338. __block FIRInstanceIDDeviceCheckinCompletion checkinHandler;
  339. [[[self.mockAuthService stub] andDo:^(NSInvocation *invocation) {
  340. if (checkinHandler) {
  341. FIRInstanceIDErrorCode code = kFIRInstanceIDErrorCodeUnknown;
  342. NSError *error = [NSError errorWithFIRInstanceIDErrorCode:code];
  343. checkinHandler(nil, error);
  344. }
  345. }] fetchCheckinInfoWithHandler:[OCMArg checkWithBlock:^BOOL(id obj) {
  346. return (checkinHandler = obj) != nil;
  347. }]];
  348. XCTestExpectation *tokenExpectation =
  349. [self expectationWithDescription:@"New token handler invoked."];
  350. NSDictionary *tokenOptions = @{
  351. kFIRInstanceIDTokenOptionsAPNSKey : [kFakeAPNSToken dataUsingEncoding:NSUTF8StringEncoding],
  352. kFIRInstanceIDTokenOptionsAPNSIsSandboxKey : @(YES),
  353. };
  354. [[[self.mockTokenManager stub] andDo:^(NSInvocation *invocation) {
  355. self.newTokenCompletion(kToken, nil);
  356. }] fetchNewTokenWithAuthorizedEntity:kAuthorizedEntity
  357. scope:kScope
  358. instanceID:[OCMArg any]
  359. options:[OCMArg any]
  360. handler:[OCMArg checkWithBlock:^BOOL(id obj) {
  361. self.newTokenCompletion = obj;
  362. return obj != nil;
  363. }]];
  364. [self.instanceID tokenWithAuthorizedEntity:kAuthorizedEntity
  365. scope:kScope
  366. options:tokenOptions
  367. handler:^(NSString *token, NSError *error) {
  368. XCTAssertNil(token);
  369. XCTAssertNotNil(error);
  370. [tokenExpectation fulfill];
  371. }];
  372. [self waitForExpectationsWithTimeout:60.0
  373. handler:^(NSError *error) {
  374. XCTAssertNil(error);
  375. }];
  376. }
  377. /**
  378. * Test that the prod APNS token is correctly prefixed with "prod".
  379. */
  380. - (void)testAPNSTokenIsPrefixedCorrectlyForServerType {
  381. NSString *APNSKey = kFIRInstanceIDTokenOptionsAPNSKey;
  382. NSString *serverTypeKey = kFIRInstanceIDTokenOptionsAPNSIsSandboxKey;
  383. NSDictionary *prodTokenOptions = @{
  384. APNSKey : [kFakeAPNSToken dataUsingEncoding:NSUTF8StringEncoding],
  385. serverTypeKey : @(NO),
  386. };
  387. [[self.mockTokenManager stub]
  388. fetchNewTokenWithAuthorizedEntity:kAuthorizedEntity
  389. scope:kScope
  390. instanceID:[OCMArg any]
  391. options:[OCMArg checkWithBlock:^BOOL(id obj) {
  392. NSDictionary *options = (NSDictionary *)obj;
  393. XCTAssertTrue([options[APNSKey] hasPrefix:@"p_"]);
  394. XCTAssertFalse([options[serverTypeKey] boolValue]);
  395. return YES;
  396. }]
  397. handler:OCMOCK_ANY];
  398. [self.instanceID tokenWithAuthorizedEntity:kAuthorizedEntity
  399. scope:kScope
  400. options:prodTokenOptions
  401. handler:^(NSString *token, NSError *error){
  402. }];
  403. }
  404. /**
  405. * Tests that when there is a failure in producing a new InstanceID token,
  406. * the callback is invoked with an error and a nil token.
  407. */
  408. - (void)testNewTokenFailure {
  409. XCTestExpectation *tokenExpectation =
  410. [self expectationWithDescription:@"New token handler invoked."];
  411. NSDictionary *tokenOptions = [NSDictionary dictionary];
  412. [self mockAuthServiceToAlwaysReturnValidCheckin];
  413. [self stubInstallationsToReturnValidID];
  414. [[[self.mockTokenManager stub] andDo:^(NSInvocation *invocation) {
  415. NSError *someError = [[NSError alloc] initWithDomain:@"InstanceIDUnitTest" code:0 userInfo:nil];
  416. self.newTokenCompletion(nil, someError);
  417. }] fetchNewTokenWithAuthorizedEntity:kAuthorizedEntity
  418. scope:kScope
  419. instanceID:[OCMArg any]
  420. options:tokenOptions
  421. handler:[OCMArg checkWithBlock:^BOOL(id obj) {
  422. self.newTokenCompletion = obj;
  423. return obj != nil;
  424. }]];
  425. [self.instanceID tokenWithAuthorizedEntity:kAuthorizedEntity
  426. scope:kScope
  427. options:tokenOptions
  428. handler:^(NSString *token, NSError *error) {
  429. XCTAssertNil(token);
  430. XCTAssertNotNil(error);
  431. [tokenExpectation fulfill];
  432. }];
  433. [self waitForExpectationsWithTimeout:1
  434. handler:^(NSError *error) {
  435. XCTAssertNil(error);
  436. }];
  437. }
  438. /**
  439. * Tests that when a token is deleted successfully, the callback is invoked with no error.
  440. */
  441. - (void)testDeleteTokenSuccess {
  442. XCTestExpectation *deleteExpectation =
  443. [self expectationWithDescription:@"Delete handler invoked."];
  444. [self stubInstallationsToReturnValidID];
  445. [self mockAuthServiceToAlwaysReturnValidCheckin];
  446. [[[self.mockTokenManager stub] andDo:^(NSInvocation *invocation) {
  447. #pragma clang diagnostic push
  448. #pragma clang diagnostic ignored "-Wnonnull"
  449. self.deleteTokenCompletion(nil);
  450. #pragma clang diagnostic pop
  451. }] deleteTokenWithAuthorizedEntity:kAuthorizedEntity
  452. scope:kScope
  453. instanceID:[OCMArg any]
  454. handler:[OCMArg checkWithBlock:^BOOL(id obj) {
  455. self.deleteTokenCompletion = obj;
  456. return obj != nil;
  457. }]];
  458. [self.instanceID deleteTokenWithAuthorizedEntity:kAuthorizedEntity
  459. scope:kScope
  460. handler:^(NSError *error) {
  461. XCTAssertNil(error);
  462. [deleteExpectation fulfill];
  463. }];
  464. [self waitForExpectationsWithTimeout:1
  465. handler:^(NSError *error) {
  466. XCTAssertNil(error);
  467. }];
  468. }
  469. /**
  470. * Tests that when a token deletion fails, the callback is invoked with an error.
  471. */
  472. - (void)testDeleteTokenFailure {
  473. XCTestExpectation *deleteExpectation =
  474. [self expectationWithDescription:@"Delete handler invoked."];
  475. [self stubInstallationsToReturnValidID];
  476. [self mockAuthServiceToAlwaysReturnValidCheckin];
  477. [[[self.mockTokenManager stub] andDo:^(NSInvocation *invocation) {
  478. NSError *someError = [[NSError alloc] initWithDomain:@"InstanceIDUnitTest" code:0 userInfo:nil];
  479. self.deleteTokenCompletion(someError);
  480. }] deleteTokenWithAuthorizedEntity:kAuthorizedEntity
  481. scope:kScope
  482. instanceID:[OCMArg any]
  483. handler:[OCMArg checkWithBlock:^BOOL(id obj) {
  484. self.deleteTokenCompletion = obj;
  485. return obj != nil;
  486. }]];
  487. [self.instanceID deleteTokenWithAuthorizedEntity:kAuthorizedEntity
  488. scope:kScope
  489. handler:^(NSError *error) {
  490. XCTAssertNotNil(error);
  491. [deleteExpectation fulfill];
  492. }];
  493. [self waitForExpectationsWithTimeout:1
  494. handler:^(NSError *error) {
  495. XCTAssertNil(error);
  496. }];
  497. }
  498. /**
  499. * Tests that not having a senderID will fetch a `nil` default token.
  500. */
  501. - (void)testDefaultToken_noSenderID {
  502. _instanceID.fcmSenderID = nil;
  503. XCTAssertNil([self.mockInstanceID token]);
  504. }
  505. /**
  506. * Tests that not having a cached token results in trying to fetch a new default token.
  507. */
  508. - (void)testDefaultToken_noCachedToken {
  509. [[[self.mockTokenManager stub] andReturn:nil]
  510. cachedTokenInfoWithAuthorizedEntity:kAuthorizedEntity
  511. scope:@"*"];
  512. OCMExpect([self.mockInstanceID defaultTokenWithHandler:nil]);
  513. XCTAssertNil([self.mockInstanceID token]);
  514. OCMVerify([self.mockInstanceID defaultTokenWithHandler:nil]);
  515. [self.mockInstanceID stopMocking];
  516. }
  517. /**
  518. * Tests that when we have a cached default token, calling `getToken` returns that token
  519. * without hitting the network.
  520. */
  521. - (void)testDefaultToken_validCachedToken {
  522. [[[self.mockTokenManager stub] andReturn:sTokenInfo]
  523. cachedTokenInfoWithAuthorizedEntity:kAuthorizedEntity
  524. scope:@"*"];
  525. [[self.mockInstanceID reject] defaultTokenWithHandler:nil];
  526. XCTAssertEqualObjects([self.mockInstanceID token], kToken);
  527. }
  528. /**
  529. * Tests that the callback handler will be invoked when the default token is fetched
  530. * despite the token being unchanged.
  531. */
  532. - (void)testDefaultToken_callbackInvokedForUnchangedToken {
  533. XCTestExpectation *defaultTokenExpectation =
  534. [self expectationWithDescription:@"Token fetch was successful."];
  535. __block FIRInstanceIDTokenInfo *cachedTokenInfo = nil;
  536. [self stubInstallationsToReturnValidID];
  537. [self mockAuthServiceToAlwaysReturnValidCheckin];
  538. // Mock Token manager to always succeed the token fetch, and return
  539. // a particular cached value.
  540. // Return a dynamic cachedToken variable whenever the cached is checked.
  541. // This uses an invocation-based mock because the |cachedToken| pointer
  542. // will change. Normal stubbing will always return the initial pointer,
  543. // which in this case is 0x0 (nil).
  544. [[[self.mockTokenManager stub] andDo:^(NSInvocation *invocation) {
  545. __autoreleasing FIRInstanceIDTokenInfo *tokenInfo = cachedTokenInfo;
  546. [invocation setReturnValue:&tokenInfo];
  547. }] cachedTokenInfoWithAuthorizedEntity:kAuthorizedEntity scope:kFIRInstanceIDDefaultTokenScope];
  548. [[[self.mockTokenManager stub] andDo:^(NSInvocation *invocation) {
  549. self.newTokenCompletion(kToken, nil);
  550. }] fetchNewTokenWithAuthorizedEntity:kAuthorizedEntity
  551. scope:kFIRInstanceIDDefaultTokenScope
  552. instanceID:[OCMArg any]
  553. options:[OCMArg any]
  554. handler:[OCMArg checkWithBlock:^BOOL(id obj) {
  555. self.newTokenCompletion = obj;
  556. return obj != nil;
  557. }]];
  558. __block NSString *notificationToken = nil;
  559. // Fetch token once to store token state
  560. NSString *notificationName = kFIRInstanceIDTokenRefreshNotification;
  561. self.tokenRefreshNotificationObserver = [[NSNotificationCenter defaultCenter]
  562. addObserverForName:notificationName
  563. object:nil
  564. queue:nil
  565. usingBlock:^(NSNotification *_Nonnull note) {
  566. // Should have saved token to cache
  567. cachedTokenInfo = sTokenInfo;
  568. notificationToken = [[self.instanceID token] copy];
  569. [defaultTokenExpectation fulfill];
  570. }];
  571. XCTAssertNil([self.mockInstanceID token]);
  572. [self waitForExpectationsWithTimeout:10.0 handler:nil];
  573. [[NSNotificationCenter defaultCenter] removeObserver:self.tokenRefreshNotificationObserver];
  574. XCTAssertEqualObjects(notificationToken, kToken);
  575. // Fetch default handler again without any token changes
  576. XCTestExpectation *tokenCallback = [self expectationWithDescription:@"Callback was invoked."];
  577. [self.mockInstanceID defaultTokenWithHandler:^(NSString *token, NSError *error) {
  578. notificationToken = token;
  579. [tokenCallback fulfill];
  580. }];
  581. [self waitForExpectationsWithTimeout:10.0 handler:nil];
  582. XCTAssertEqualObjects(notificationToken, kToken);
  583. }
  584. /**
  585. * Test that when we fetch a new default token and cache it successfully we post a
  586. * tokenRefresh notification which allows to fetch the cached token.
  587. */
  588. - (void)testDefaultTokenFetch_returnValidToken {
  589. XCTestExpectation *defaultTokenExpectation =
  590. [self expectationWithDescription:@"Successfully got default token."];
  591. __block FIRInstanceIDTokenInfo *cachedTokenInfo = nil;
  592. [self stubInstallationsToReturnValidID];
  593. [self mockAuthServiceToAlwaysReturnValidCheckin];
  594. // Mock Token manager to always succeed the token fetch, and return
  595. // a particular cached value.
  596. // Return a dynamic cachedToken variable whenever the cached is checked.
  597. // This uses an invocation-based mock because the |cachedToken| pointer
  598. // will change. Normal stubbing will always return the initial pointer,
  599. // which in this case is 0x0 (nil).
  600. [[[self.mockTokenManager stub] andDo:^(NSInvocation *invocation) {
  601. __autoreleasing FIRInstanceIDTokenInfo *tokenInfo = cachedTokenInfo;
  602. [invocation setReturnValue:&tokenInfo];
  603. }] cachedTokenInfoWithAuthorizedEntity:kAuthorizedEntity scope:kFIRInstanceIDDefaultTokenScope];
  604. [[[self.mockTokenManager stub] andDo:^(NSInvocation *invocation) {
  605. self.newTokenCompletion(kToken, nil);
  606. }] fetchNewTokenWithAuthorizedEntity:kAuthorizedEntity
  607. scope:kFIRInstanceIDDefaultTokenScope
  608. instanceID:[OCMArg any]
  609. options:[OCMArg any]
  610. handler:[OCMArg checkWithBlock:^BOOL(id obj) {
  611. self.newTokenCompletion = obj;
  612. return obj != nil;
  613. }]];
  614. __block NSString *notificationToken = nil;
  615. NSString *notificationName = kFIRInstanceIDTokenRefreshNotification;
  616. self.tokenRefreshNotificationObserver = [[NSNotificationCenter defaultCenter]
  617. addObserverForName:notificationName
  618. object:nil
  619. queue:nil
  620. usingBlock:^(NSNotification *_Nonnull note) {
  621. // Should have saved token to cache
  622. cachedTokenInfo = sTokenInfo;
  623. notificationToken = [[self.instanceID token] copy];
  624. [defaultTokenExpectation fulfill];
  625. }];
  626. XCTAssertNil([self.mockInstanceID token]);
  627. [self waitForExpectationsWithTimeout:10.0 handler:nil];
  628. [[NSNotificationCenter defaultCenter] removeObserver:self.tokenRefreshNotificationObserver];
  629. XCTAssertEqualObjects(notificationToken, kToken);
  630. }
  631. /**
  632. * Tests that if we fail to fetch the token from the server for the first time we retry again
  633. * later with exponential backoff unless we succeed.
  634. */
  635. - (void)testDefaultTokenFetch_retryFetchToken {
  636. const int trialsBeforeSuccess = 3;
  637. __block int newTokenFetchCount = 0;
  638. __block int64_t lastFetchTimestampInSeconds;
  639. XCTestExpectation *defaultTokenExpectation =
  640. [self expectationWithDescription:@"Successfully got default token."];
  641. __block FIRInstanceIDTokenInfo *cachedTokenInfo = nil;
  642. [self stubInstallationsToReturnValidID];
  643. [self mockAuthServiceToAlwaysReturnValidCheckin];
  644. // Mock Token manager.
  645. // Return a dynamic cachedToken variable whenever the cached is checked.
  646. // This uses an invocation-based mock because the |cachedToken| pointer
  647. // will change. Normal stubbing will always return the initial pointer,
  648. // which in this case is 0x0 (nil).
  649. [[[self.mockTokenManager stub] andDo:^(NSInvocation *invocation) {
  650. __autoreleasing FIRInstanceIDTokenInfo *tokenInfo = cachedTokenInfo;
  651. [invocation setReturnValue:&tokenInfo];
  652. }] cachedTokenInfoWithAuthorizedEntity:kAuthorizedEntity scope:kFIRInstanceIDDefaultTokenScope];
  653. [[[self.mockTokenManager stub] andDo:^(NSInvocation *invocation) {
  654. newTokenFetchCount++;
  655. int64_t delaySinceLastFetchInSeconds =
  656. FIRInstanceIDCurrentTimestampInSeconds() - lastFetchTimestampInSeconds;
  657. // Test exponential backoff.
  658. if (newTokenFetchCount > 1) {
  659. XCTAssertLessThanOrEqual(1 << (newTokenFetchCount - 1), delaySinceLastFetchInSeconds);
  660. }
  661. lastFetchTimestampInSeconds = FIRInstanceIDCurrentTimestampInSeconds();
  662. if (newTokenFetchCount < trialsBeforeSuccess) {
  663. NSError *error = [NSError errorWithFIRInstanceIDErrorCode:kFIRInstanceIDErrorCodeTimeout];
  664. self.newTokenCompletion(nil, error);
  665. } else {
  666. self.newTokenCompletion(kToken, nil);
  667. }
  668. }] fetchNewTokenWithAuthorizedEntity:kAuthorizedEntity
  669. scope:kFIRInstanceIDDefaultTokenScope
  670. instanceID:[OCMArg any]
  671. options:[OCMArg any]
  672. handler:[OCMArg checkWithBlock:^BOOL(id obj) {
  673. self.newTokenCompletion = obj;
  674. return obj != nil;
  675. }]];
  676. __block int notificationPostCount = 0;
  677. __block NSString *notificationToken = nil;
  678. NSString *notificationName = kFIRInstanceIDTokenRefreshNotification;
  679. self.tokenRefreshNotificationObserver = [[NSNotificationCenter defaultCenter]
  680. addObserverForName:notificationName
  681. object:nil
  682. queue:nil
  683. usingBlock:^(NSNotification *_Nonnull note) {
  684. // Should have saved token to cache
  685. cachedTokenInfo = sTokenInfo;
  686. notificationPostCount++;
  687. notificationToken = [[self.instanceID token] copy];
  688. [defaultTokenExpectation fulfill];
  689. }];
  690. XCTAssertNil([self.mockInstanceID token]);
  691. [self waitForExpectationsWithTimeout:20.0 handler:nil];
  692. [[NSNotificationCenter defaultCenter] removeObserver:self.tokenRefreshNotificationObserver];
  693. XCTAssertEqualObjects(notificationToken, kToken);
  694. XCTAssertEqual(notificationPostCount, 1);
  695. XCTAssertEqual(newTokenFetchCount, trialsBeforeSuccess);
  696. }
  697. /**
  698. * Tests that when we don't have a cached default token multiple invocations to `getToken`
  699. * lead to a single networking call to fetch the token. Also verify that we post one unique
  700. * TokenRefresh notification for multiple invocations.
  701. */
  702. - (void)testDefaultToken_multipleInvocations {
  703. __block int newTokenFetchCount = 0;
  704. XCTestExpectation *defaultTokenExpectation =
  705. [self expectationWithDescription:@"Successfully got default token."];
  706. __block FIRInstanceIDTokenInfo *cachedTokenInfo = nil;
  707. [self stubInstallationsToReturnValidID];
  708. [self mockAuthServiceToAlwaysReturnValidCheckin];
  709. // Mock Token manager.
  710. // Return a dynamic cachedToken variable whenever the cached is checked.
  711. // This uses an invocation-based mock because the |cachedToken| pointer
  712. // will change. Normal stubbing will always return the initial pointer,
  713. // which in this case is 0x0 (nil).
  714. [[[self.mockTokenManager stub] andDo:^(NSInvocation *invocation) {
  715. __autoreleasing FIRInstanceIDTokenInfo *tokenInfo = cachedTokenInfo;
  716. [invocation setReturnValue:&tokenInfo];
  717. }] cachedTokenInfoWithAuthorizedEntity:kAuthorizedEntity scope:kFIRInstanceIDDefaultTokenScope];
  718. [[[self.mockTokenManager stub] andDo:^(NSInvocation *invocation) {
  719. // Invoke callback after some delay (network delay)
  720. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2 * NSEC_PER_SEC)),
  721. dispatch_get_main_queue(), ^{
  722. self.newTokenCompletion(kToken, nil);
  723. });
  724. newTokenFetchCount++;
  725. XCTAssertEqual(newTokenFetchCount, 1);
  726. }] fetchNewTokenWithAuthorizedEntity:kAuthorizedEntity
  727. scope:kFIRInstanceIDDefaultTokenScope
  728. instanceID:[OCMArg any]
  729. options:[OCMArg any]
  730. handler:[OCMArg checkWithBlock:^BOOL(id obj) {
  731. self.newTokenCompletion = obj;
  732. return obj != nil;
  733. }]];
  734. __block int notificationPostCount = 0;
  735. __block NSString *notificationToken = nil;
  736. NSString *notificationName = kFIRInstanceIDTokenRefreshNotification;
  737. self.tokenRefreshNotificationObserver = [[NSNotificationCenter defaultCenter]
  738. addObserverForName:notificationName
  739. object:nil
  740. queue:nil
  741. usingBlock:^(NSNotification *_Nonnull note) {
  742. // Should have saved token to cache
  743. cachedTokenInfo = sTokenInfo;
  744. notificationPostCount++;
  745. notificationToken = [[self.instanceID token] copy];
  746. [defaultTokenExpectation fulfill];
  747. }];
  748. XCTAssertNil([self.mockInstanceID token]);
  749. // Invoke get token again with some delay. Our initial request to getToken hasn't yet
  750. // returned from the server.
  751. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)),
  752. dispatch_get_main_queue(), ^{
  753. XCTAssertNil([self.mockInstanceID token]);
  754. });
  755. // Invoke again after further delay.
  756. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.5 * NSEC_PER_SEC)),
  757. dispatch_get_main_queue(), ^{
  758. XCTAssertNil([self.mockInstanceID token]);
  759. });
  760. [self waitForExpectationsWithTimeout:15.0 handler:nil];
  761. [[NSNotificationCenter defaultCenter] removeObserver:self.tokenRefreshNotificationObserver];
  762. XCTAssertEqualObjects(notificationToken, kToken);
  763. XCTAssertEqual(notificationPostCount, 1);
  764. XCTAssertEqual(newTokenFetchCount, 1);
  765. }
  766. - (void)testDefaultToken_maxRetries {
  767. __block int newTokenFetchCount = 0;
  768. XCTestExpectation *defaultTokenExpectation =
  769. [self expectationWithDescription:@"Did retry maximum times to fetch default token."];
  770. [self stubInstallationsToReturnValidID];
  771. [self mockAuthServiceToAlwaysReturnValidCheckin];
  772. // Mock Token manager.
  773. [[[self.mockTokenManager stub] andReturn:nil]
  774. cachedTokenInfoWithAuthorizedEntity:kAuthorizedEntity
  775. scope:kFIRInstanceIDDefaultTokenScope];
  776. [[[self.mockTokenManager stub] andDo:^(NSInvocation *invocation) {
  777. newTokenFetchCount++;
  778. NSError *error = [NSError errorWithFIRInstanceIDErrorCode:kFIRInstanceIDErrorCodeNetwork];
  779. self.newTokenCompletion(nil, error);
  780. if (newTokenFetchCount == [FIRInstanceID maxRetryCountForDefaultToken]) {
  781. [defaultTokenExpectation fulfill];
  782. }
  783. }] fetchNewTokenWithAuthorizedEntity:kAuthorizedEntity
  784. scope:kFIRInstanceIDDefaultTokenScope
  785. instanceID:[OCMArg any]
  786. options:[OCMArg any]
  787. handler:[OCMArg checkWithBlock:^BOOL(id obj) {
  788. self.newTokenCompletion = obj;
  789. return obj != nil;
  790. }]];
  791. // Mock Instance ID's retry interval to 0, to vastly speed up this test.
  792. [[[self.mockInstanceID stub] andReturnValue:@(0)] retryIntervalToFetchDefaultToken];
  793. // Try to fetch token once. It should set off retries since we mock failure.
  794. XCTAssertNil([self.mockInstanceID token]);
  795. [self waitForExpectationsWithTimeout:1.0 handler:nil];
  796. XCTAssertEqual(newTokenFetchCount, [FIRInstanceID maxRetryCountForDefaultToken]);
  797. }
  798. - (void)testInstanceIDWithHandler_WhileRequesting_Success {
  799. [self stubInstallationsToReturnValidID];
  800. [self mockAuthServiceToAlwaysReturnValidCheckin];
  801. // Expect `fetchNewTokenWithAuthorizedEntity` to be called once
  802. XCTestExpectation *fetchNewTokenExpectation =
  803. [self expectationWithDescription:@"fetchNewTokenExpectation"];
  804. __block FIRInstanceIDTokenHandler tokenHandler;
  805. [[[self.mockTokenManager stub] andDo:^(NSInvocation *invocation) {
  806. __unsafe_unretained FIRInstanceIDTokenHandler handler;
  807. [invocation getArgument:&handler atIndex:6];
  808. tokenHandler = handler;
  809. [fetchNewTokenExpectation fulfill];
  810. }] fetchNewTokenWithAuthorizedEntity:kAuthorizedEntity
  811. scope:kFIRInstanceIDDefaultTokenScope
  812. instanceID:[OCMArg any]
  813. options:[OCMArg any]
  814. handler:[OCMArg any]];
  815. // Make 1st call
  816. XCTestExpectation *handlerExpectation1 = [self expectationWithDescription:@"handlerExpectation1"];
  817. FIRInstanceIDResultHandler handler1 =
  818. ^(FIRInstanceIDResult *_Nullable result, NSError *_Nullable error) {
  819. [handlerExpectation1 fulfill];
  820. XCTAssertNotNil(result);
  821. XCTAssertEqual(result.token, kToken);
  822. XCTAssertNil(error);
  823. };
  824. [self.mockInstanceID instanceIDWithHandler:handler1];
  825. // Make 2nd call
  826. XCTestExpectation *handlerExpectation2 = [self expectationWithDescription:@"handlerExpectation1"];
  827. FIRInstanceIDResultHandler handler2 =
  828. ^(FIRInstanceIDResult *_Nullable result, NSError *_Nullable error) {
  829. [handlerExpectation2 fulfill];
  830. XCTAssertNotNil(result);
  831. XCTAssertEqual(result.token, kToken);
  832. XCTAssertNil(error);
  833. };
  834. [self.mockInstanceID instanceIDWithHandler:handler2];
  835. // Wait for `fetchNewTokenWithAuthorizedEntity` to be performed
  836. [self waitForExpectations:@[ fetchNewTokenExpectation ] timeout:1 enforceOrder:false];
  837. // Finish token fetch request
  838. tokenHandler(kToken, nil);
  839. // Wait for completion handlers for both calls to be performed
  840. [self waitForExpectationsWithTimeout:1 handler:NULL];
  841. }
  842. - (void)testInstanceIDWithHandler_WhileRequesting_RetrySuccess {
  843. [self stubInstallationsToReturnValidID];
  844. [self mockAuthServiceToAlwaysReturnValidCheckin];
  845. // Expect `fetchNewTokenWithAuthorizedEntity` to be called twice
  846. XCTestExpectation *fetchNewTokenExpectation1 =
  847. [self expectationWithDescription:@"fetchNewTokenExpectation1"];
  848. XCTestExpectation *fetchNewTokenExpectation2 =
  849. [self expectationWithDescription:@"fetchNewTokenExpectation2"];
  850. NSArray *fetchNewTokenExpectations = @[ fetchNewTokenExpectation1, fetchNewTokenExpectation2 ];
  851. __block NSInteger fetchNewTokenCallCount = 0;
  852. __block FIRInstanceIDTokenHandler tokenHandler;
  853. [[[self.mockTokenManager stub] andDo:^(NSInvocation *invocation) {
  854. __unsafe_unretained FIRInstanceIDTokenHandler handler;
  855. [invocation getArgument:&handler atIndex:6];
  856. tokenHandler = handler;
  857. [fetchNewTokenExpectations[fetchNewTokenCallCount] fulfill];
  858. fetchNewTokenCallCount += 1;
  859. }] fetchNewTokenWithAuthorizedEntity:kAuthorizedEntity
  860. scope:kFIRInstanceIDDefaultTokenScope
  861. instanceID:[OCMArg any]
  862. options:[OCMArg any]
  863. handler:[OCMArg any]];
  864. // Mock Instance ID's retry interval to 0, to vastly speed up this test.
  865. [[[self.mockInstanceID stub] andReturnValue:@(0)] retryIntervalToFetchDefaultToken];
  866. // Make 1st call
  867. XCTestExpectation *handlerExpectation1 = [self expectationWithDescription:@"handlerExpectation1"];
  868. FIRInstanceIDResultHandler handler1 =
  869. ^(FIRInstanceIDResult *_Nullable result, NSError *_Nullable error) {
  870. [handlerExpectation1 fulfill];
  871. XCTAssertNotNil(result);
  872. XCTAssertEqual(result.token, kToken);
  873. XCTAssertNil(error);
  874. };
  875. [self.mockInstanceID instanceIDWithHandler:handler1];
  876. // Make 2nd call
  877. XCTestExpectation *handlerExpectation2 = [self expectationWithDescription:@"handlerExpectation1"];
  878. FIRInstanceIDResultHandler handler2 =
  879. ^(FIRInstanceIDResult *_Nullable result, NSError *_Nullable error) {
  880. [handlerExpectation2 fulfill];
  881. XCTAssertNotNil(result);
  882. XCTAssertEqual(result.token, kToken);
  883. XCTAssertNil(error);
  884. };
  885. [self.mockInstanceID instanceIDWithHandler:handler2];
  886. // Wait for the 1st `fetchNewTokenWithAuthorizedEntity` to be performed
  887. [self waitForExpectations:@[ fetchNewTokenExpectation1 ] timeout:1 enforceOrder:false];
  888. // Fail for the 1st time
  889. tokenHandler(nil, [NSError errorWithFIRInstanceIDErrorCode:kFIRInstanceIDErrorCodeUnknown]);
  890. // Wait for the 2nd token feth
  891. [self waitForExpectations:@[ fetchNewTokenExpectation2 ] timeout:1 enforceOrder:false];
  892. // Finish with success
  893. tokenHandler(kToken, nil);
  894. // Wait for completion handlers for both calls to be performed
  895. [self waitForExpectationsWithTimeout:1 handler:NULL];
  896. }
  897. - (void)testInstanceIDWithHandler_WhileRequesting_RetryFailure {
  898. [self stubInstallationsToReturnValidID];
  899. [self mockAuthServiceToAlwaysReturnValidCheckin];
  900. // Expect `fetchNewTokenWithAuthorizedEntity` to be called once
  901. NSMutableArray<XCTestExpectation *> *fetchNewTokenExpectations = [NSMutableArray array];
  902. for (NSInteger i = 0; i < [[self.instanceID class] maxRetryCountForDefaultToken]; ++i) {
  903. NSString *name = [NSString stringWithFormat:@"fetchNewTokenExpectation-%ld", (long)i];
  904. [fetchNewTokenExpectations addObject:[self expectationWithDescription:name]];
  905. }
  906. __block NSInteger fetchNewTokenCallCount = 0;
  907. __block FIRInstanceIDTokenHandler tokenHandler;
  908. [[[self.mockTokenManager stub] andDo:^(NSInvocation *invocation) {
  909. __unsafe_unretained FIRInstanceIDTokenHandler handler;
  910. [invocation getArgument:&handler atIndex:6];
  911. tokenHandler = handler;
  912. [fetchNewTokenExpectations[fetchNewTokenCallCount] fulfill];
  913. fetchNewTokenCallCount += 1;
  914. }] fetchNewTokenWithAuthorizedEntity:kAuthorizedEntity
  915. scope:kFIRInstanceIDDefaultTokenScope
  916. instanceID:[OCMArg any]
  917. options:[OCMArg any]
  918. handler:[OCMArg any]];
  919. // Mock Instance ID's retry interval to 0, to vastly speed up this test.
  920. [[[self.mockInstanceID stub] andReturnValue:@(0)] retryIntervalToFetchDefaultToken];
  921. // Make 1st call
  922. XCTestExpectation *handlerExpectation1 = [self expectationWithDescription:@"handlerExpectation1"];
  923. FIRInstanceIDResultHandler handler1 =
  924. ^(FIRInstanceIDResult *_Nullable result, NSError *_Nullable error) {
  925. [handlerExpectation1 fulfill];
  926. XCTAssertNil(result);
  927. XCTAssertNotNil(error);
  928. };
  929. [self.mockInstanceID instanceIDWithHandler:handler1];
  930. // Make 2nd call
  931. XCTestExpectation *handlerExpectation2 = [self expectationWithDescription:@"handlerExpectation1"];
  932. FIRInstanceIDResultHandler handler2 =
  933. ^(FIRInstanceIDResult *_Nullable result, NSError *_Nullable error) {
  934. [handlerExpectation2 fulfill];
  935. XCTAssertNil(result);
  936. XCTAssertNotNil(error);
  937. };
  938. [self.mockInstanceID instanceIDWithHandler:handler2];
  939. for (NSInteger i = 0; i < [[self.instanceID class] maxRetryCountForDefaultToken]; ++i) {
  940. // Wait for the i `fetchNewTokenWithAuthorizedEntity` to be performed
  941. [self waitForExpectations:@[ fetchNewTokenExpectations[i] ] timeout:1 enforceOrder:false];
  942. // Fail for the i time
  943. tokenHandler(nil, [NSError errorWithFIRInstanceIDErrorCode:kFIRInstanceIDErrorCodeUnknown]);
  944. }
  945. // Wait for completion handlers for both calls to be performed
  946. [self waitForExpectationsWithTimeout:1 handler:NULL];
  947. }
  948. /**
  949. * Tests a Keychain read failure while we try to fetch a new InstanceID token. If the Keychain
  950. * read fails we won't be able to fetch the public key which is required while fetching a new
  951. * token. In such a case we should return KeyPair failure.
  952. */
  953. - (void)testNewTokenFetch_keyChainError {
  954. XCTestExpectation *tokenExpectation =
  955. [self expectationWithDescription:@"New token handler invoked."];
  956. [self mockAuthServiceToAlwaysReturnValidCheckin];
  957. // Simulate keypair fetch/generation failure.
  958. NSError *installationIDError = [NSError errorWithDomain:@"Test" code:-1 userInfo:nil];
  959. [self expectInstallationsInstallationIDWithFID:nil error:installationIDError];
  960. [[self.mockTokenManager reject] fetchNewTokenWithAuthorizedEntity:kAuthorizedEntity
  961. scope:kScope
  962. instanceID:[OCMArg any]
  963. options:[OCMArg any]
  964. handler:[OCMArg any]];
  965. [self.instanceID tokenWithAuthorizedEntity:kAuthorizedEntity
  966. scope:kScope
  967. options:nil
  968. handler:^(NSString *token, NSError *error) {
  969. XCTAssertNil(token);
  970. XCTAssertNotNil(error);
  971. [tokenExpectation fulfill];
  972. }];
  973. [self waitForExpectationsWithTimeout:1 handler:nil];
  974. OCMVerifyAll(self.mockTokenManager);
  975. }
  976. /**
  977. * If a token fetch includes in its options an "apns_token" object, but not a "apns_sandbox" key,
  978. * ensure that an "apns_sandbox" key is added to the token options (via automatic detection).
  979. */
  980. - (void)testTokenFetchAPNSServerTypeIsIncludedIfAPNSTokenProvided {
  981. XCTestExpectation *apnsServerTypeExpectation =
  982. [self expectationWithDescription:@"apns_sandbox key was included in token options"];
  983. [self stubInstallationsToReturnValidID];
  984. [self mockAuthServiceToAlwaysReturnValidCheckin];
  985. NSData *apnsToken = [kFakeAPNSToken dataUsingEncoding:NSUTF8StringEncoding];
  986. // Option is purposefully missing the apns_sandbox key
  987. NSDictionary *tokenOptions = @{kFIRInstanceIDTokenOptionsAPNSKey : apnsToken};
  988. [[[self.mockTokenManager stub] andDo:^(NSInvocation *invocation) {
  989. // Inspect
  990. __unsafe_unretained NSDictionary *options;
  991. [invocation getArgument:&options atIndex:5];
  992. if (options[kFIRInstanceIDTokenOptionsAPNSIsSandboxKey] != nil) {
  993. [apnsServerTypeExpectation fulfill];
  994. }
  995. self.newTokenCompletion(kToken, nil);
  996. }] fetchNewTokenWithAuthorizedEntity:kAuthorizedEntity
  997. scope:kScope
  998. instanceID:[OCMArg any]
  999. options:[OCMArg any]
  1000. handler:[OCMArg checkWithBlock:^BOOL(id obj) {
  1001. self.newTokenCompletion = obj;
  1002. return obj != nil;
  1003. }]];
  1004. [self.instanceID tokenWithAuthorizedEntity:kAuthorizedEntity
  1005. scope:kScope
  1006. options:tokenOptions
  1007. handler:^(NSString *token, NSError *error){
  1008. }];
  1009. [self waitForExpectationsWithTimeout:60.0
  1010. handler:^(NSError *error) {
  1011. XCTAssertNil(error);
  1012. }];
  1013. }
  1014. /**
  1015. * Tests that if a token was fetched, but during the fetch the APNs data was set, that a new
  1016. * token is fetched to associate the APNs data, and is not returned from the cache.
  1017. */
  1018. - (void)testTokenFetch_ignoresCacheIfAPNSInfoDifferent {
  1019. XCTestExpectation *tokenRequestExpectation =
  1020. [self expectationWithDescription:@"Token was fetched from the network"];
  1021. // Initialize a token in the cache *WITHOUT* APNSInfo
  1022. // This token is |kToken|, but we will simulate that a fetch will return another token
  1023. NSString *oldCachedToken = kToken;
  1024. NSString *fetchedToken = @"abcd123_newtoken";
  1025. [self stubInstallationsToReturnValidID];
  1026. [self mockAuthServiceToAlwaysReturnValidCheckin];
  1027. // During this test use the default scope ("*") to simulate the default token behavior.
  1028. // Return a dynamic cachedToken variable whenever the cached is checked.
  1029. // This uses an invocation-based mock because the |cachedToken| pointer
  1030. // will change. Normal stubbing will always return the initial pointer,
  1031. // which in this case is 0x0 (nil).
  1032. [[[self.mockTokenManager stub] andDo:^(NSInvocation *invocation) {
  1033. __autoreleasing FIRInstanceIDTokenInfo *tokenInfo =
  1034. [[FIRInstanceIDTokenInfo alloc] initWithAuthorizedEntity:kAuthorizedEntity
  1035. scope:kFIRInstanceIDDefaultTokenScope
  1036. token:oldCachedToken
  1037. appVersion:@"1.0"
  1038. firebaseAppID:@"firebaseAppID"];
  1039. [invocation setReturnValue:&tokenInfo];
  1040. }] cachedTokenInfoWithAuthorizedEntity:kAuthorizedEntity scope:kFIRInstanceIDDefaultTokenScope];
  1041. // Mock the network request to return |fetchedToken|, so we can clearly see if the token is
  1042. // is different than what was cached.
  1043. [[[self.mockTokenManager stub] andDo:^(NSInvocation *invocation) {
  1044. [tokenRequestExpectation fulfill];
  1045. self.newTokenCompletion(fetchedToken, nil);
  1046. }] fetchNewTokenWithAuthorizedEntity:kAuthorizedEntity
  1047. scope:kFIRInstanceIDDefaultTokenScope
  1048. instanceID:[OCMArg any]
  1049. options:[OCMArg any]
  1050. handler:[OCMArg checkWithBlock:^BOOL(id obj) {
  1051. self.newTokenCompletion = obj;
  1052. return obj != nil;
  1053. }]];
  1054. // Begin request
  1055. // Token options has APNS data, which is not associated with the cached token
  1056. NSDictionary *tokenOptions = @{
  1057. kFIRInstanceIDTokenOptionsAPNSKey : [@"apns" dataUsingEncoding:NSUTF8StringEncoding],
  1058. kFIRInstanceIDTokenOptionsAPNSIsSandboxKey : @(NO)
  1059. };
  1060. [self.instanceID
  1061. tokenWithAuthorizedEntity:kAuthorizedEntity
  1062. scope:kFIRInstanceIDDefaultTokenScope
  1063. options:tokenOptions
  1064. handler:^(NSString *_Nullable token, NSError *_Nullable error) {
  1065. XCTAssertEqualObjects(token, fetchedToken);
  1066. }];
  1067. [self waitForExpectationsWithTimeout:0.5 handler:nil];
  1068. }
  1069. /**
  1070. * Tests that if there is a keychain failure while fetching the InstanceID of the token we should
  1071. * return nil for the identity.
  1072. */
  1073. - (void)testInstanceIDFetch_keyChainError {
  1074. XCTestExpectation *tokenExpectation =
  1075. [self expectationWithDescription:@"InstanceID fetch handler invoked."];
  1076. // Simulate keypair fetch/generation failure.
  1077. NSError *error = [NSError errorWithFIRInstanceIDErrorCode:kFIRInstanceIDErrorCodeInvalidKeyPair];
  1078. [self expectInstallationsInstallationIDWithFID:nil error:error];
  1079. [self.instanceID getIDWithHandler:^(NSString *_Nullable identity, NSError *_Nullable error) {
  1080. XCTAssertNil(identity);
  1081. XCTAssertNotNil(error);
  1082. [tokenExpectation fulfill];
  1083. }];
  1084. [self waitForExpectationsWithTimeout:1 handler:nil];
  1085. }
  1086. - (void)testInstanceIDDeleteSuccess {
  1087. XCTestExpectation *tokenExpectation =
  1088. [self expectationWithDescription:@"InstanceID deleteID handler invoked."];
  1089. NSString *instanceID = @"validID";
  1090. [self expectInstallationsInstallationIDWithFID:instanceID error:nil];
  1091. [self expectTokenManagerDeleteAllTokensWithIID:instanceID completeWithError:nil];
  1092. [self expectTokenManagerDeleteAllTokensLocallyWithError:nil];
  1093. [self expectInstallationsDeleteWithError:nil];
  1094. [self expectAuthServiceResetCheckinWithError:nil];
  1095. [self.instanceID deleteIDWithHandler:^(NSError *_Nullable error) {
  1096. XCTAssertNil(error);
  1097. [tokenExpectation fulfill];
  1098. }];
  1099. [self waitForExpectationsWithTimeout:1 handler:nil];
  1100. OCMVerifyAll(self.mockInstallations);
  1101. OCMVerifyAll(self.mockTokenManager);
  1102. }
  1103. - (void)testInstanceIDDelete_keyChainError {
  1104. XCTestExpectation *tokenExpectation =
  1105. [self expectationWithDescription:@"InstanceID deleteID handler invoked."];
  1106. NSString *instanceID = @"validID";
  1107. [self expectInstallationsInstallationIDWithFID:instanceID error:nil];
  1108. [self expectTokenManagerDeleteAllTokensWithIID:instanceID completeWithError:nil];
  1109. [self expectTokenManagerDeleteAllTokensLocallyWithError:nil];
  1110. [self expectAuthServiceResetCheckinWithError:nil];
  1111. // Simulate keychain fetch/generation failure.
  1112. NSError *error = [NSError errorWithFIRInstanceIDErrorCode:kFIRInstanceIDErrorCodeInvalidKeyPair];
  1113. [self expectInstallationsDeleteWithError:error];
  1114. [self.instanceID deleteIDWithHandler:^(NSError *_Nullable error) {
  1115. XCTAssertNotNil(error);
  1116. [tokenExpectation fulfill];
  1117. }];
  1118. [self waitForExpectationsWithTimeout:1 handler:nil];
  1119. OCMVerifyAll(self.mockInstallations);
  1120. OCMVerifyAll(self.mockTokenManager);
  1121. }
  1122. - (void)testRefreshDifferentTokenFromMessaging {
  1123. _instanceID.defaultFCMToken = kToken;
  1124. XCTAssertEqualObjects(_instanceID.defaultFCMToken, kToken);
  1125. NSString *newTokenFromMessaging = @"a_new_token_from_messaging";
  1126. FIRInstanceIDTokenInfo *cachedTokenInfo =
  1127. [[FIRInstanceIDTokenInfo alloc] initWithAuthorizedEntity:kAuthorizedEntity
  1128. scope:kFIRInstanceIDDefaultTokenScope
  1129. token:kToken
  1130. appVersion:@""
  1131. firebaseAppID:kGoogleAppID];
  1132. OCMStub([self.mockTokenManager
  1133. cachedTokenInfoWithAuthorizedEntity:kAuthorizedEntity
  1134. scope:kFIRInstanceIDDefaultTokenScope])
  1135. .andReturn(cachedTokenInfo);
  1136. OCMExpect([self.mockTokenManager saveDefaultToken:newTokenFromMessaging
  1137. withOptions:[OCMArg any]]);
  1138. [[NSNotificationCenter defaultCenter]
  1139. postNotificationName:kFIRInstanceIDMessagingUpdateTokenNotification
  1140. object:newTokenFromMessaging];
  1141. OCMVerifyAll(self.mockTokenManager);
  1142. XCTAssertEqualObjects(_instanceID.defaultFCMToken, newTokenFromMessaging);
  1143. }
  1144. - (void)testRefreshTheSameTokenFromMessaging {
  1145. _instanceID.defaultFCMToken = kToken;
  1146. XCTAssertEqualObjects(_instanceID.defaultFCMToken, kToken);
  1147. NSString *newTokenFromMessaging = kToken;
  1148. FIRInstanceIDTokenInfo *cachedTokenInfo =
  1149. [[FIRInstanceIDTokenInfo alloc] initWithAuthorizedEntity:kAuthorizedEntity
  1150. scope:kFIRInstanceIDDefaultTokenScope
  1151. token:kToken
  1152. appVersion:@""
  1153. firebaseAppID:kGoogleAppID];
  1154. OCMStub([self.mockTokenManager
  1155. cachedTokenInfoWithAuthorizedEntity:kAuthorizedEntity
  1156. scope:kFIRInstanceIDDefaultTokenScope])
  1157. .andReturn(cachedTokenInfo);
  1158. OCMReject([self.mockTokenManager saveDefaultToken:newTokenFromMessaging
  1159. withOptions:[OCMArg any]]);
  1160. [[NSNotificationCenter defaultCenter]
  1161. postNotificationName:kFIRInstanceIDMessagingUpdateTokenNotification
  1162. object:newTokenFromMessaging];
  1163. OCMVerifyAll(self.mockTokenManager);
  1164. XCTAssertEqualObjects(_instanceID.defaultFCMToken, newTokenFromMessaging);
  1165. }
  1166. - (void)testRefreshDifferentTokenInInstanceIDStorage {
  1167. _instanceID.defaultFCMToken = kToken;
  1168. XCTAssertEqualObjects(_instanceID.defaultFCMToken, kToken);
  1169. // New token from messaging is the same as local cache in InstanceID
  1170. // But the token in InstanceID storage is different
  1171. NSString *newTokenFromMessaging = kToken;
  1172. FIRInstanceIDTokenInfo *cachedTokenInfo =
  1173. [[FIRInstanceIDTokenInfo alloc] initWithAuthorizedEntity:kAuthorizedEntity
  1174. scope:kFIRInstanceIDDefaultTokenScope
  1175. token:@"a_outdated_token_in_storage"
  1176. appVersion:@""
  1177. firebaseAppID:kGoogleAppID];
  1178. OCMStub([self.mockTokenManager
  1179. cachedTokenInfoWithAuthorizedEntity:kAuthorizedEntity
  1180. scope:kFIRInstanceIDDefaultTokenScope])
  1181. .andReturn(cachedTokenInfo);
  1182. OCMExpect([self.mockTokenManager saveDefaultToken:newTokenFromMessaging
  1183. withOptions:[OCMArg any]]);
  1184. [[NSNotificationCenter defaultCenter]
  1185. postNotificationName:kFIRInstanceIDMessagingUpdateTokenNotification
  1186. object:newTokenFromMessaging];
  1187. OCMVerifyAll(self.mockTokenManager);
  1188. XCTAssertEqualObjects(_instanceID.defaultFCMToken, newTokenFromMessaging);
  1189. }
  1190. - (void)testRefreshNullTokenFromMessaging {
  1191. _instanceID.defaultFCMToken = kToken;
  1192. XCTAssertEqualObjects(_instanceID.defaultFCMToken, kToken);
  1193. // New token from messaging is the same as local cache in InstanceID
  1194. // But the token in InstanceID storage is different
  1195. NSString *newTokenFromMessaging = nil;
  1196. FIRInstanceIDTokenInfo *cachedTokenInfo =
  1197. [[FIRInstanceIDTokenInfo alloc] initWithAuthorizedEntity:kAuthorizedEntity
  1198. scope:kFIRInstanceIDDefaultTokenScope
  1199. token:kToken
  1200. appVersion:@""
  1201. firebaseAppID:kGoogleAppID];
  1202. OCMStub([self.mockTokenManager
  1203. cachedTokenInfoWithAuthorizedEntity:kAuthorizedEntity
  1204. scope:kFIRInstanceIDDefaultTokenScope])
  1205. .andReturn(cachedTokenInfo);
  1206. OCMExpect([self.mockTokenManager saveDefaultToken:newTokenFromMessaging
  1207. withOptions:[OCMArg any]]);
  1208. [[NSNotificationCenter defaultCenter]
  1209. postNotificationName:kFIRInstanceIDMessagingUpdateTokenNotification
  1210. object:newTokenFromMessaging];
  1211. OCMVerifyAll(self.mockTokenManager);
  1212. XCTAssertEqualObjects(_instanceID.defaultFCMToken, newTokenFromMessaging);
  1213. }
  1214. #pragma mark - Private Helpers
  1215. - (void)stubInstallationsToReturnValidID {
  1216. OCMStub([self.mockInstallations
  1217. installationIDWithCompletion:[OCMArg
  1218. checkWithBlock:^BOOL(FIRInstallationsIDHandler completion) {
  1219. completion(@"validID", nil);
  1220. return YES;
  1221. }]]);
  1222. }
  1223. - (FIRInstanceIDCheckinPreferences *)validCheckinPreferences {
  1224. NSDictionary *gservicesData = @{
  1225. kFIRInstanceIDVersionInfoStringKey : kVersionInfo,
  1226. kFIRInstanceIDLastCheckinTimeKey : @(FIRInstanceIDCurrentTimestampInMilliseconds())
  1227. };
  1228. FIRInstanceIDCheckinPreferences *checkinPreferences =
  1229. [[FIRInstanceIDCheckinPreferences alloc] initWithDeviceID:kDeviceAuthId
  1230. secretToken:kSecretToken];
  1231. [checkinPreferences updateWithCheckinPlistContents:gservicesData];
  1232. return checkinPreferences;
  1233. }
  1234. - (void)mockAuthServiceToAlwaysReturnValidCheckin {
  1235. FIRInstanceIDCheckinPreferences *validCheckin = [self validCheckinPreferences];
  1236. __block FIRInstanceIDDeviceCheckinCompletion checkinHandler;
  1237. [[[self.mockAuthService stub] andDo:^(NSInvocation *invocation) {
  1238. if (checkinHandler) {
  1239. checkinHandler(validCheckin, nil);
  1240. }
  1241. }] fetchCheckinInfoWithHandler:[OCMArg checkWithBlock:^BOOL(id obj) {
  1242. return (checkinHandler = obj) != nil;
  1243. }]];
  1244. }
  1245. - (void)expectInstallationsInstallationIDWithFID:(nullable NSString *)FID
  1246. error:(nullable NSError *)error {
  1247. OCMExpect([self.mockInstallations
  1248. installationIDWithCompletion:[OCMArg
  1249. checkWithBlock:^BOOL(FIRInstallationsIDHandler completion) {
  1250. completion(FID, error);
  1251. return YES;
  1252. }]]);
  1253. }
  1254. - (void)expectInstallationsDeleteWithError:(nullable NSError *)deletionError {
  1255. OCMExpect([self.mockInstallations
  1256. deleteWithCompletion:[self errorCompletionOCMArgCompletingWithError:deletionError]]);
  1257. }
  1258. - (void)expectTokenManagerDeleteAllTokensWithIID:(NSString *)identifier
  1259. completeWithError:(nullable NSError *)error {
  1260. OCMExpect([self.mockTokenManager
  1261. deleteAllTokensWithInstanceID:identifier
  1262. handler:[self errorCompletionOCMArgCompletingWithError:error]]);
  1263. }
  1264. - (void)expectTokenManagerDeleteAllTokensLocallyWithError:(nullable NSError *)error {
  1265. OCMExpect([self.mockTokenManager
  1266. deleteAllTokensLocallyWithHandler:[self errorCompletionOCMArgCompletingWithError:error]]);
  1267. }
  1268. - (void)expectAuthServiceResetCheckinWithError:(NSError *)error {
  1269. OCMStub([self.mockAuthService
  1270. resetCheckinWithHandler:[self errorCompletionOCMArgCompletingWithError:error]]);
  1271. }
  1272. - (id)errorCompletionOCMArgCompletingWithError:(NSError *)errorToComplete {
  1273. return [OCMArg checkWithBlock:^BOOL(void (^completion)(NSError *)) {
  1274. completion(errorToComplete);
  1275. return YES;
  1276. }];
  1277. }
  1278. #pragma clang diagnostic pop
  1279. @end