FIRInstanceIDTest.m 62 KB

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