FIRInstallationsAPIServiceTests.m 26 KB

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