FIRInstallationsAPIServiceTests.m 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661
  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 <OCMock/OCMock.h>
  18. #import "FBLPromise+Testing.h"
  19. #import "FirebaseInstallations/Source/Tests/Utils/FIRInstallationsItem+Tests.h"
  20. #import "FirebaseInstallations/Source/Library/Errors/FIRInstallationsErrorUtil.h"
  21. #import "FirebaseInstallations/Source/Library/Errors/FIRInstallationsHTTPError.h"
  22. #import "FirebaseInstallations/Source/Library/InstallationsAPI/FIRInstallationsAPIService.h"
  23. #import "FirebaseInstallations/Source/Library/InstallationsStore/FIRInstallationsStoredAuthToken.h"
  24. #import "FirebaseInstallations/Source/Library/Public/FirebaseInstallations/FIRInstallationsVersion.h"
  25. #import "FirebaseCore/Sources/Private/FirebaseCoreInternal.h"
  26. typedef FBLPromise * (^FIRInstallationsAPIServiceTask)(void);
  27. @interface FIRInstallationsAPIService (Tests)
  28. - (instancetype)initWithURLSession:(NSURLSession *)URLSession
  29. APIKey:(NSString *)APIKey
  30. projectID:(NSString *)projectID;
  31. @end
  32. @interface FIRInstallationsAPIServiceTests : XCTestCase
  33. @property(nonatomic) FIRInstallationsAPIService *service;
  34. @property(nonatomic) id mockURLSession;
  35. @property(nonatomic) NSString *APIKey;
  36. @property(nonatomic) NSString *projectID;
  37. @property(nonatomic) id heartbeatMock;
  38. @end
  39. @implementation FIRInstallationsAPIServiceTests
  40. - (void)setUp {
  41. self.APIKey = @"api-key";
  42. self.projectID = @"project-id";
  43. self.mockURLSession = OCMClassMock([NSURLSession class]);
  44. self.service = [[FIRInstallationsAPIService alloc] initWithURLSession:self.mockURLSession
  45. APIKey:self.APIKey
  46. projectID:self.projectID];
  47. self.heartbeatMock = OCMClassMock([FIRHeartbeatInfo class]);
  48. OCMStub([self.heartbeatMock heartbeatCodeForTag:@"fire-installations"])
  49. .andDo(^(NSInvocation *invocation) {
  50. XCTAssertFalse([NSThread isMainThread]);
  51. })
  52. .andReturn(FIRHeartbeatInfoCodeCombined);
  53. }
  54. - (void)tearDown {
  55. self.service = nil;
  56. self.mockURLSession = nil;
  57. self.projectID = nil;
  58. self.APIKey = nil;
  59. self.heartbeatMock = nil;
  60. // Wait for any pending promises to complete.
  61. XCTAssert(FBLWaitForPromisesWithTimeout(2));
  62. }
  63. - (void)testRegisterInstallationSuccess {
  64. NSString *fixtureName = @"APIRegisterInstallationResponseSuccess.json";
  65. [self assertRegisterInstallationSuccessWithResponseFixtureName:fixtureName
  66. responseCode:201
  67. expectedFIDOverride:@"aaaaaaaaaaaaaaaaaaaaaa"];
  68. }
  69. - (void)testRegisterInstallationSuccess_NoFIDInResponse {
  70. NSString *fixtureName = @"APIRegisterInstallationResponseSuccessNoFID.json";
  71. [self assertRegisterInstallationSuccessWithResponseFixtureName:fixtureName
  72. responseCode:201
  73. expectedFIDOverride:nil];
  74. }
  75. - (void)testRegisterInstallationSuccess_InvalidInstallation {
  76. FIRInstallationsItem *installation = [FIRInstallationsItem createUnregisteredInstallationItem];
  77. installation.firebaseInstallationID = nil;
  78. __auto_type promise = [self.service registerInstallation:installation];
  79. XCTAssert(FBLWaitForPromisesWithTimeout(0.5));
  80. XCTAssertTrue(promise.isRejected);
  81. XCTAssertNil(promise.value);
  82. XCTAssertNotNil(promise.error);
  83. }
  84. - (void)testRefreshAuthTokenSuccess {
  85. FIRInstallationsItem *installation = [FIRInstallationsItem createRegisteredInstallationItem];
  86. installation.firebaseInstallationID = @"qwertyuiopasdfghjklzxcvbnm";
  87. // 1. Stub URL session:
  88. // 1.1. URL request validation.
  89. id URLRequestValidation = [self refreshTokenRequestValidationArgWithInstallation:installation];
  90. // 1.2. Capture completion to call it later.
  91. __block void (^taskCompletion)(NSData *, NSURLResponse *, NSError *);
  92. id completionArg = [OCMArg checkWithBlock:^BOOL(id obj) {
  93. taskCompletion = obj;
  94. return YES;
  95. }];
  96. // 1.3. Create a data task mock.
  97. id mockDataTask = OCMClassMock([NSURLSessionDataTask class]);
  98. OCMExpect([(NSURLSessionDataTask *)mockDataTask resume]);
  99. // 1.4. Expect `dataTaskWithRequest` to be called.
  100. OCMExpect([self.mockURLSession dataTaskWithRequest:URLRequestValidation
  101. completionHandler:completionArg])
  102. .andReturn(mockDataTask);
  103. // 1.5. Prepare server response data.
  104. NSData *successResponseData = [self loadFixtureNamed:@"APIGenerateTokenResponseSuccess.json"];
  105. // 2. Call
  106. FBLPromise<FIRInstallationsItem *> *promise =
  107. [self.service refreshAuthTokenForInstallation:installation];
  108. // 3. Wait for `[NSURLSession dataTaskWithRequest...]` to be called
  109. OCMVerifyAllWithDelay(self.mockURLSession, 0.5);
  110. // 4. Wait for the data task `resume` to be called.
  111. OCMVerifyAllWithDelay(mockDataTask, 0.5);
  112. // 5. Call the data task completion.
  113. taskCompletion(successResponseData, [self responseWithStatusCode:200], nil);
  114. // 6. Check result.
  115. XCTAssert(FBLWaitForPromisesWithTimeout(0.5));
  116. XCTAssertNil(promise.error);
  117. XCTAssertNotNil(promise.value);
  118. XCTAssertNotEqual(promise.value, installation);
  119. XCTAssertEqualObjects(promise.value.appID, installation.appID);
  120. XCTAssertEqualObjects(promise.value.firebaseAppName, installation.firebaseAppName);
  121. XCTAssertEqualObjects(promise.value.firebaseInstallationID, installation.firebaseInstallationID);
  122. XCTAssertEqualObjects(promise.value.refreshToken, installation.refreshToken);
  123. XCTAssertEqualObjects(promise.value.authToken.token,
  124. @"aaaaaaaaaaaaaa.bbbbbbbbbbbbbbbbb.cccccccccccccccccccccccc");
  125. [self assertDate:promise.value.authToken.expirationDate
  126. isApproximatelyEqualCurrentPlusTimeInterval:3987465];
  127. }
  128. - (void)testRefreshAuthTokenAPIError {
  129. FIRInstallationsItem *installation = [FIRInstallationsItem createRegisteredInstallationItem];
  130. installation.firebaseInstallationID = @"qwertyuiopasdfghjklzxcvbnm";
  131. // 1. Stub URL session:
  132. // 1.1. URL request validation.
  133. id URLRequestValidation = [self refreshTokenRequestValidationArgWithInstallation:installation];
  134. // 1.2. Capture completion to call it later.
  135. __block void (^taskCompletion)(NSData *, NSURLResponse *, NSError *);
  136. id completionArg = [OCMArg checkWithBlock:^BOOL(id obj) {
  137. taskCompletion = obj;
  138. return YES;
  139. }];
  140. // 1.3. Create a data task mock.
  141. id mockDataTask = OCMClassMock([NSURLSessionDataTask class]);
  142. OCMExpect([(NSURLSessionDataTask *)mockDataTask resume]);
  143. // 1.4. Expect `dataTaskWithRequest` to be called.
  144. OCMExpect([self.mockURLSession dataTaskWithRequest:URLRequestValidation
  145. completionHandler:completionArg])
  146. .andReturn(mockDataTask);
  147. // 1.5. Prepare server response data.
  148. NSData *errorResponseData =
  149. [self loadFixtureNamed:@"APIGenerateTokenResponseInvalidRefreshToken.json"];
  150. // 2. Call
  151. FBLPromise<FIRInstallationsItem *> *promise =
  152. [self.service refreshAuthTokenForInstallation:installation];
  153. // 3. Wait for `[NSURLSession dataTaskWithRequest...]` to be called
  154. OCMVerifyAllWithDelay(self.mockURLSession, 0.5);
  155. // 4. Wait for the data task `resume` to be called.
  156. OCMVerifyAllWithDelay(mockDataTask, 0.5);
  157. // 5. Call the data task completion.
  158. taskCompletion(errorResponseData, [self responseWithStatusCode:401], nil);
  159. // 6. Check result.
  160. XCTAssert(FBLWaitForPromisesWithTimeout(0.5));
  161. XCTAssertTrue([FIRInstallationsErrorUtil isAPIError:promise.error withHTTPCode:401]);
  162. XCTAssertNil(promise.value);
  163. }
  164. - (void)testRefreshAuthToken_WhenAPIError500_ThenRetriesOnce {
  165. FIRInstallationsItem *installation = [FIRInstallationsItem createRegisteredInstallationItem];
  166. installation.firebaseInstallationID = @"qwertyuiopasdfghjklzxcvbnm";
  167. // 1. Stub URL session:
  168. // 1.1. URL request validation.
  169. id URLRequestValidation = [self refreshTokenRequestValidationArgWithInstallation:installation];
  170. // 1.2. Capture completion to call it later.
  171. __block void (^taskCompletion)(NSData *, NSURLResponse *, NSError *);
  172. id completionArg = [OCMArg checkWithBlock:^BOOL(id obj) {
  173. taskCompletion = obj;
  174. return YES;
  175. }];
  176. // 1.3. Create a data task mock.
  177. id mockDataTask1 = OCMClassMock([NSURLSessionDataTask class]);
  178. OCMExpect([(NSURLSessionDataTask *)mockDataTask1 resume]);
  179. // 1.4. Expect `dataTaskWithRequest` to be called.
  180. OCMExpect([self.mockURLSession dataTaskWithRequest:URLRequestValidation
  181. completionHandler:completionArg])
  182. .andReturn(mockDataTask1);
  183. // 1.5. Prepare server response data.
  184. NSData *errorResponseData =
  185. [self loadFixtureNamed:@"APIGenerateTokenResponseInvalidRefreshToken.json"];
  186. // 2. Call
  187. FBLPromise<FIRInstallationsItem *> *promise =
  188. [self.service refreshAuthTokenForInstallation:installation];
  189. // 3. Wait for `[NSURLSession dataTaskWithRequest...]` to be called
  190. OCMVerifyAllWithDelay(self.mockURLSession, 0.5);
  191. // 4. Wait for the data task `resume` to be called.
  192. OCMVerifyAllWithDelay(mockDataTask1, 0.5);
  193. // 5. Call the data task completion.
  194. taskCompletion(errorResponseData,
  195. [self responseWithStatusCode:FIRInstallationsHTTPCodesServerInternalError], nil);
  196. // 6. Retry:
  197. // 6.1. Expect another API request to be sent.
  198. id mockDataTask2 = OCMClassMock([NSURLSessionDataTask class]);
  199. OCMExpect([(NSURLSessionDataTask *)mockDataTask2 resume]);
  200. OCMExpect([self.mockURLSession dataTaskWithRequest:URLRequestValidation
  201. completionHandler:completionArg])
  202. .andReturn(mockDataTask2);
  203. OCMVerifyAllWithDelay(self.mockURLSession, 1.5);
  204. OCMVerifyAllWithDelay(mockDataTask2, 1.5);
  205. // 6.2. Send the API response again.
  206. taskCompletion(errorResponseData,
  207. [self responseWithStatusCode:FIRInstallationsHTTPCodesServerInternalError], nil);
  208. // 6. Check result.
  209. XCTAssert(FBLWaitForPromisesWithTimeout(0.5));
  210. XCTAssertTrue([FIRInstallationsErrorUtil
  211. isAPIError:promise.error
  212. withHTTPCode:FIRInstallationsHTTPCodesServerInternalError]);
  213. XCTAssertNil(promise.value);
  214. }
  215. - (void)testRefreshAuthTokenDataNil {
  216. FIRInstallationsItem *installation = [FIRInstallationsItem createRegisteredInstallationItem];
  217. installation.firebaseInstallationID = @"qwertyuiopasdfghjklzxcvbnm";
  218. // 1. Stub URL session:
  219. // 1.1. URL request validation.
  220. id URLRequestValidation = [self refreshTokenRequestValidationArgWithInstallation:installation];
  221. // 1.2. Capture completion to call it later.
  222. __block void (^taskCompletion)(NSData *, NSURLResponse *, NSError *);
  223. id completionArg = [OCMArg checkWithBlock:^BOOL(id obj) {
  224. taskCompletion = obj;
  225. return YES;
  226. }];
  227. // 1.3. Create a data task mock.
  228. id mockDataTask = OCMClassMock([NSURLSessionDataTask class]);
  229. OCMExpect([(NSURLSessionDataTask *)mockDataTask resume]);
  230. // 1.4. Expect `dataTaskWithRequest` to be called.
  231. OCMExpect([self.mockURLSession dataTaskWithRequest:URLRequestValidation
  232. completionHandler:completionArg])
  233. .andReturn(mockDataTask);
  234. // 2. Call
  235. FBLPromise<FIRInstallationsItem *> *promise =
  236. [self.service refreshAuthTokenForInstallation:installation];
  237. // 3. Wait for `[NSURLSession dataTaskWithRequest...]` to be called
  238. OCMVerifyAllWithDelay(self.mockURLSession, 0.5);
  239. // 4. Wait for the data task `resume` to be called.
  240. OCMVerifyAllWithDelay(mockDataTask, 0.5);
  241. // 5. Call the data task completion.
  242. // HTTP 200 but no data (a potential server failure).
  243. taskCompletion(nil, [self responseWithStatusCode:200], nil);
  244. // 6. Check result.
  245. XCTAssert(FBLWaitForPromisesWithTimeout(0.5));
  246. XCTAssertEqualObjects(promise.error.userInfo[NSLocalizedFailureReasonErrorKey],
  247. @"Failed to serialize JSON data.");
  248. XCTAssertNil(promise.value);
  249. }
  250. - (void)testDeleteInstallationSuccess {
  251. FIRInstallationsItem *installation = [FIRInstallationsItem createRegisteredInstallationItem];
  252. // 1. Stub URL session:
  253. // 1.1. URL request validation.
  254. id URLRequestValidation = [self deleteInstallationRequestValidationWithInstallation:installation];
  255. // 1.2. Capture completion to call it later.
  256. __block void (^taskCompletion)(NSData *, NSURLResponse *, NSError *);
  257. id completionArg = [OCMArg checkWithBlock:^BOOL(id obj) {
  258. taskCompletion = obj;
  259. return YES;
  260. }];
  261. // 1.3. Create a data task mock.
  262. id mockDataTask = OCMClassMock([NSURLSessionDataTask class]);
  263. OCMExpect([(NSURLSessionDataTask *)mockDataTask resume]);
  264. // 1.4. Expect `dataTaskWithRequest` to be called.
  265. OCMExpect([self.mockURLSession dataTaskWithRequest:URLRequestValidation
  266. completionHandler:completionArg])
  267. .andReturn(mockDataTask);
  268. // 2. Call
  269. FBLPromise<FIRInstallationsItem *> *promise = [self.service deleteInstallation:installation];
  270. // 3. Wait for `[NSURLSession dataTaskWithRequest...]` to be called
  271. OCMVerifyAllWithDelay(self.mockURLSession, 0.5);
  272. // 4. Wait for the data task `resume` to be called.
  273. OCMVerifyAllWithDelay(mockDataTask, 0.5);
  274. // 5. Call the data task completion.
  275. // HTTP 200 but no data (a potential server failure).
  276. NSData *successResponseData = [@"{}" dataUsingEncoding:NSUTF8StringEncoding];
  277. taskCompletion(successResponseData, [self responseWithStatusCode:200], nil);
  278. // 6. Check result.
  279. XCTAssert(FBLWaitForPromisesWithTimeout(0.5));
  280. XCTAssertNil(promise.error);
  281. XCTAssertEqual(promise.value, installation);
  282. }
  283. - (void)testDeleteInstallationErrorNotFound {
  284. FIRInstallationsItem *installation = [FIRInstallationsItem createRegisteredInstallationItem];
  285. // 1. Stub URL session:
  286. // 1.1. URL request validation.
  287. id URLRequestValidation = [self deleteInstallationRequestValidationWithInstallation:installation];
  288. // 1.2. Capture completion to call it later.
  289. __block void (^taskCompletion)(NSData *, NSURLResponse *, NSError *);
  290. id completionArg = [OCMArg checkWithBlock:^BOOL(id obj) {
  291. taskCompletion = obj;
  292. return YES;
  293. }];
  294. // 1.3. Create a data task mock.
  295. id mockDataTask = OCMClassMock([NSURLSessionDataTask class]);
  296. OCMExpect([(NSURLSessionDataTask *)mockDataTask resume]);
  297. // 1.4. Expect `dataTaskWithRequest` to be called.
  298. OCMExpect([self.mockURLSession dataTaskWithRequest:URLRequestValidation
  299. completionHandler:completionArg])
  300. .andReturn(mockDataTask);
  301. // 2. Call
  302. FBLPromise<FIRInstallationsItem *> *promise = [self.service deleteInstallation:installation];
  303. // 3. Wait for `[NSURLSession dataTaskWithRequest...]` to be called
  304. OCMVerifyAllWithDelay(self.mockURLSession, 0.5);
  305. // 4. Wait for the data task `resume` to be called.
  306. OCMVerifyAllWithDelay(mockDataTask, 0.5);
  307. // 5. Call the data task completion.
  308. // HTTP 200 but no data (a potential server failure).
  309. taskCompletion(nil, [self responseWithStatusCode:404], nil);
  310. // 6. Check result.
  311. XCTAssert(FBLWaitForPromisesWithTimeout(0.5));
  312. XCTAssertTrue([FIRInstallationsErrorUtil isAPIError:promise.error withHTTPCode:404]);
  313. XCTAssertNil(promise.value);
  314. }
  315. - (void)testDeleteInstallation_WhenAPIError500_ThenRetriesOnce {
  316. FIRInstallationsItem *installation = [FIRInstallationsItem createRegisteredInstallationItem];
  317. // 1. Stub URL session:
  318. // 1.1. URL request validation.
  319. id URLRequestValidation = [self deleteInstallationRequestValidationWithInstallation:installation];
  320. // 1.2. Capture completion to call it later.
  321. __block void (^taskCompletion)(NSData *, NSURLResponse *, NSError *);
  322. id completionArg = [OCMArg checkWithBlock:^BOOL(id obj) {
  323. taskCompletion = obj;
  324. return YES;
  325. }];
  326. // 1.3. Create a data task mock.
  327. id mockDataTask1 = OCMClassMock([NSURLSessionDataTask class]);
  328. OCMExpect([(NSURLSessionDataTask *)mockDataTask1 resume]);
  329. // 1.4. Expect `dataTaskWithRequest` to be called.
  330. OCMExpect([self.mockURLSession dataTaskWithRequest:URLRequestValidation
  331. completionHandler:completionArg])
  332. .andReturn(mockDataTask1);
  333. // 2. Call
  334. FBLPromise<FIRInstallationsItem *> *promise = [self.service deleteInstallation:installation];
  335. // 3. Wait for `[NSURLSession dataTaskWithRequest...]` to be called
  336. OCMVerifyAllWithDelay(self.mockURLSession, 0.5);
  337. // 4. Wait for the data task `resume` to be called.
  338. OCMVerifyAllWithDelay(mockDataTask1, 0.5);
  339. // 5. Call the data task completion.
  340. // HTTP 200 but no data (a potential server failure).
  341. taskCompletion(nil, [self responseWithStatusCode:FIRInstallationsHTTPCodesServerInternalError],
  342. nil);
  343. // 6. Retry:
  344. // 6.1. Wait for the API request to be sent again.
  345. id mockDataTask2 = OCMClassMock([NSURLSessionDataTask class]);
  346. OCMExpect([(NSURLSessionDataTask *)mockDataTask2 resume]);
  347. OCMExpect([self.mockURLSession dataTaskWithRequest:URLRequestValidation
  348. completionHandler:completionArg])
  349. .andReturn(mockDataTask2);
  350. OCMVerifyAllWithDelay(self.mockURLSession, 1.5);
  351. OCMVerifyAllWithDelay(mockDataTask1, 1.5);
  352. // 6.1. Send another response.
  353. taskCompletion(nil, [self responseWithStatusCode:FIRInstallationsHTTPCodesServerInternalError],
  354. nil);
  355. // 7. Check result.
  356. XCTAssert(FBLWaitForPromisesWithTimeout(0.5));
  357. XCTAssertTrue([FIRInstallationsErrorUtil
  358. isAPIError:promise.error
  359. withHTTPCode:FIRInstallationsHTTPCodesServerInternalError]);
  360. XCTAssertNil(promise.value);
  361. }
  362. #pragma mark - Helpers
  363. - (NSData *)loadFixtureNamed:(NSString *)fileName {
  364. NSURL *fileURL = [[NSBundle bundleForClass:[self class]] URLForResource:fileName
  365. withExtension:nil];
  366. XCTAssertNotNil(fileURL);
  367. NSError *error;
  368. NSData *data = [NSData dataWithContentsOfURL:fileURL options:0 error:&error];
  369. XCTAssertNotNil(data, @"File name: %@ Error: %@", fileName, error);
  370. return data;
  371. }
  372. - (NSURLResponse *)responseWithStatusCode:(NSUInteger)statusCode {
  373. NSHTTPURLResponse *response = [[NSHTTPURLResponse alloc] initWithURL:[NSURL fileURLWithPath:@"/"]
  374. statusCode:statusCode
  375. HTTPVersion:nil
  376. headerFields:nil];
  377. return response;
  378. }
  379. - (void)assertDate:(NSDate *)date
  380. isApproximatelyEqualCurrentPlusTimeInterval:(NSTimeInterval)timeInterval {
  381. NSDate *expectedDate = [NSDate dateWithTimeIntervalSinceNow:timeInterval];
  382. NSTimeInterval precision = 10;
  383. XCTAssert(ABS([date timeIntervalSinceDate:expectedDate]) <= precision,
  384. @"date: %@ is not equal to expected %@ with precision %f - %@", date, expectedDate,
  385. precision, self.name);
  386. }
  387. - (id)refreshTokenRequestValidationArgWithInstallation:(FIRInstallationsItem *)installation {
  388. return [OCMArg checkWithBlock:^BOOL(NSURLRequest *request) {
  389. XCTAssertEqualObjects(request.HTTPMethod, @"POST");
  390. XCTAssertEqualObjects(request.URL.absoluteString,
  391. @"https://firebaseinstallations.googleapis.com/v1/projects/project-id/"
  392. @"installations/qwertyuiopasdfghjklzxcvbnm/authTokens:generate");
  393. XCTAssertEqualObjects([request valueForHTTPHeaderField:@"Content-Type"], @"application/json",
  394. @"%@", self.name);
  395. XCTAssertEqualObjects([request valueForHTTPHeaderField:@"X-Goog-Api-Key"], self.APIKey, @"%@",
  396. self.name);
  397. XCTAssertEqualObjects([request valueForHTTPHeaderField:kFIRInstallationsUserAgentKey],
  398. [FIRApp firebaseUserAgent]);
  399. XCTAssertEqualObjects([request valueForHTTPHeaderField:kFIRInstallationsHeartbeatKey], @"3");
  400. NSString *expectedAuthHeader =
  401. [NSString stringWithFormat:@"FIS_v2 %@", installation.refreshToken];
  402. XCTAssertEqualObjects(request.allHTTPHeaderFields[@"Authorization"], expectedAuthHeader, @"%@",
  403. self.name);
  404. NSError *error;
  405. NSDictionary *body = [NSJSONSerialization JSONObjectWithData:request.HTTPBody
  406. options:0
  407. error:&error];
  408. XCTAssertNotNil(body, @"Error: %@, test: %@", error, self.name);
  409. XCTAssertEqualObjects(
  410. body,
  411. @{@"installation" : @{@"sdkVersion" : [self SDKVersion]}}, @"%@", self.name);
  412. return YES;
  413. }];
  414. }
  415. - (id)deleteInstallationRequestValidationWithInstallation:(FIRInstallationsItem *)installation {
  416. return [OCMArg checkWithBlock:^BOOL(NSURLRequest *request) {
  417. XCTAssert([request isKindOfClass:[NSURLRequest class]], @"Unexpected class: %@",
  418. [request class]);
  419. XCTAssertEqualObjects(request.HTTPMethod, @"DELETE");
  420. NSString *expectedURL = [NSString
  421. stringWithFormat:
  422. @"https://firebaseinstallations.googleapis.com/v1/projects/%@/installations/%@/",
  423. self.projectID, installation.firebaseInstallationID];
  424. XCTAssertEqualObjects(request.URL.absoluteString, expectedURL);
  425. XCTAssertEqualObjects(request.allHTTPHeaderFields[@"Content-Type"], @"application/json");
  426. XCTAssertEqualObjects(request.allHTTPHeaderFields[@"X-Goog-Api-Key"], self.APIKey);
  427. NSString *expectedAuthHeader =
  428. [NSString stringWithFormat:@"FIS_v2 %@", installation.refreshToken];
  429. XCTAssertEqualObjects(request.allHTTPHeaderFields[@"Authorization"], expectedAuthHeader, @"%@",
  430. self.name);
  431. NSError *error;
  432. NSDictionary *JSONBody = [NSJSONSerialization JSONObjectWithData:request.HTTPBody
  433. options:0
  434. error:&error];
  435. XCTAssertNotNil(JSONBody, @"Error: %@", error);
  436. XCTAssertEqualObjects(JSONBody, @{});
  437. return YES;
  438. }];
  439. }
  440. - (void)assertRegisterInstallationSuccessWithResponseFixtureName:(NSString *)fixtureName
  441. responseCode:(NSInteger)responseCode
  442. expectedFIDOverride:(nullable NSString *)overrideFID {
  443. FIRInstallationsItem *installation = [FIRInstallationsItem createUnregisteredInstallationItem];
  444. installation.IIDDefaultToken = @"iid-auth-token";
  445. NSString *expectedFID = overrideFID ?: installation.firebaseInstallationID;
  446. // 1. Stub URL session:
  447. // 1.1. URL request validation.
  448. id URLRequestValidation = [OCMArg checkWithBlock:^BOOL(NSURLRequest *request) {
  449. XCTAssertEqualObjects(request.HTTPMethod, @"POST");
  450. XCTAssertEqualObjects(
  451. request.URL.absoluteString,
  452. @"https://firebaseinstallations.googleapis.com/v1/projects/project-id/installations/");
  453. XCTAssertEqualObjects([request valueForHTTPHeaderField:@"Content-Type"], @"application/json");
  454. XCTAssertEqualObjects([request valueForHTTPHeaderField:@"X-Goog-Api-Key"], self.APIKey);
  455. XCTAssertEqualObjects([request valueForHTTPHeaderField:@"X-Ios-Bundle-Identifier"],
  456. [[NSBundle mainBundle] bundleIdentifier]);
  457. XCTAssertEqualObjects([request valueForHTTPHeaderField:kFIRInstallationsUserAgentKey],
  458. [FIRApp firebaseUserAgent]);
  459. XCTAssertEqualObjects([request valueForHTTPHeaderField:kFIRInstallationsHeartbeatKey], @"3");
  460. NSString *expectedIIDMigrationHeader = installation.IIDDefaultToken;
  461. XCTAssertEqualObjects([request valueForHTTPHeaderField:@"x-goog-fis-ios-iid-migration-auth"],
  462. expectedIIDMigrationHeader);
  463. NSError *error;
  464. NSDictionary *body = [NSJSONSerialization JSONObjectWithData:request.HTTPBody
  465. options:0
  466. error:&error];
  467. XCTAssertNotNil(body, @"Error: %@", error);
  468. XCTAssertEqualObjects(body[@"fid"], installation.firebaseInstallationID);
  469. XCTAssertEqualObjects(body[@"authVersion"], @"FIS_v2");
  470. XCTAssertEqualObjects(body[@"appId"], installation.appID);
  471. XCTAssertEqualObjects(body[@"sdkVersion"], [self SDKVersion]);
  472. return YES;
  473. }];
  474. // 1.2. Capture completion to call it later.
  475. __block void (^taskCompletion)(NSData *, NSURLResponse *, NSError *);
  476. id completionArg = [OCMArg checkWithBlock:^BOOL(id obj) {
  477. taskCompletion = obj;
  478. return YES;
  479. }];
  480. // 1.3. Create a data task mock.
  481. id mockDataTask = OCMClassMock([NSURLSessionDataTask class]);
  482. OCMExpect([(NSURLSessionDataTask *)mockDataTask resume]);
  483. // 1.4. Expect `dataTaskWithRequest` to be called.
  484. OCMExpect([self.mockURLSession dataTaskWithRequest:URLRequestValidation
  485. completionHandler:completionArg])
  486. .andReturn(mockDataTask);
  487. // 2. Call
  488. FBLPromise<FIRInstallationsItem *> *promise = [self.service registerInstallation:installation];
  489. // 3. Wait for `[NSURLSession dataTaskWithRequest...]` to be called
  490. OCMVerifyAllWithDelay(self.mockURLSession, 0.5);
  491. // 4. Wait for the data task `resume` to be called.
  492. OCMVerifyAllWithDelay(mockDataTask, 0.5);
  493. // 5. Call the data task completion.
  494. NSData *responseData = [self loadFixtureNamed:fixtureName];
  495. taskCompletion(responseData, [self responseWithStatusCode:responseCode], nil);
  496. // 6. Check result.
  497. XCTAssert(FBLWaitForPromisesWithTimeout(0.5));
  498. XCTAssertNil(promise.error);
  499. XCTAssertNotNil(promise.value);
  500. XCTAssertNotEqual(promise.value, installation);
  501. XCTAssertEqualObjects(promise.value.appID, installation.appID);
  502. XCTAssertEqualObjects(promise.value.firebaseAppName, installation.firebaseAppName);
  503. // Server may respond with a different FID if the sent FID cannot be accepted.
  504. XCTAssertEqualObjects(promise.value.firebaseInstallationID, expectedFID);
  505. XCTAssertEqualObjects(promise.value.refreshToken, @"aaaaaaabbbbbbbbcccccccccdddddddd00000000");
  506. XCTAssertEqualObjects(promise.value.authToken.token,
  507. @"aaaaaaaaaaaaaa.bbbbbbbbbbbbbbbbb.cccccccccccccccccccccccc");
  508. [self assertDate:promise.value.authToken.expirationDate
  509. isApproximatelyEqualCurrentPlusTimeInterval:604800];
  510. }
  511. - (NSString *)SDKVersion {
  512. return [NSString stringWithFormat:@"i:%s", FIRInstallationsVersionStr];
  513. }
  514. @end