FPRNetworkTraceTest.m 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494
  1. // Copyright 2020 Google LLC
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. #import <XCTest/XCTest.h>
  15. #import "FirebasePerformance/Sources/AppActivity/FPRSessionManager.h"
  16. #import "FirebasePerformance/Sources/Common/FPRConstants.h"
  17. #import "FirebasePerformance/Sources/Configurations/FPRConfigurations+Private.h"
  18. #import "FirebasePerformance/Sources/Configurations/FPRConfigurations.h"
  19. #import "FirebasePerformance/Sources/Configurations/FPRRemoteConfigFlags+Private.h"
  20. #import "FirebasePerformance/Sources/Configurations/FPRRemoteConfigFlags.h"
  21. #import "FirebasePerformance/Sources/Instrumentation/FPRNetworkTrace+Private.h"
  22. #import "FirebasePerformance/Sources/Instrumentation/FPRNetworkTrace.h"
  23. #import "FirebasePerformance/Sources/Public/FirebasePerformance/FIRPerformance.h"
  24. #import "FirebasePerformance/Tests/Unit/Configurations/FPRFakeRemoteConfig.h"
  25. #import "FirebasePerformance/Tests/Unit/FPRTestCase.h"
  26. #import "FirebasePerformance/Tests/Unit/FPRTestUtils.h"
  27. #import <OCMock/OCMock.h>
  28. @interface FPRNetworkTraceTest : FPRTestCase
  29. @property(nonatomic) NSURLRequest *testURLRequest;
  30. @end
  31. @implementation FPRNetworkTraceTest
  32. - (void)setUp {
  33. [super setUp];
  34. NSURL *URL = [NSURL URLWithString:@"https://abc.com"];
  35. _testURLRequest = [NSURLRequest requestWithURL:URL];
  36. FIRPerformance *performance = [FIRPerformance sharedInstance];
  37. [performance setDataCollectionEnabled:YES];
  38. }
  39. - (void)tearDown {
  40. [super tearDown];
  41. FIRPerformance *performance = [FIRPerformance sharedInstance];
  42. [performance setDataCollectionEnabled:NO];
  43. }
  44. - (void)testInit {
  45. FPRNetworkTrace *trace = [[FPRNetworkTrace alloc] initWithURLRequest:self.testURLRequest];
  46. XCTAssertNotNil(trace);
  47. }
  48. /**
  49. * Validates that the object creation fails for invalid URLs.
  50. */
  51. - (void)testInitWithNonHttpURL {
  52. NSURL *URL = [NSURL URLWithString:@"ftp://abc.com"];
  53. NSURLRequest *sampleURLRequest = [NSURLRequest requestWithURL:URL];
  54. FPRNetworkTrace *trace = [[FPRNetworkTrace alloc] initWithURLRequest:sampleURLRequest];
  55. XCTAssertNil(trace);
  56. }
  57. /**
  58. * Validates that the object creation fails for malformed URLs.
  59. */
  60. - (void)testMalformedURL {
  61. NSURL *URL = [NSURL URLWithString:@"htp://abc.com"];
  62. NSURLRequest *sampleURLRequest = [NSURLRequest requestWithURL:URL];
  63. FPRNetworkTrace *trace = [[FPRNetworkTrace alloc] initWithURLRequest:sampleURLRequest];
  64. XCTAssertNil(trace);
  65. }
  66. /**
  67. * Validates that the object creation fails for a non URL.
  68. */
  69. - (void)testNonURL {
  70. NSURL *URL = [NSURL URLWithString:@"Iamtheherooftheuniverse"];
  71. NSURLRequest *sampleURLRequest = [NSURLRequest requestWithURL:URL];
  72. FPRNetworkTrace *trace = [[FPRNetworkTrace alloc] initWithURLRequest:sampleURLRequest];
  73. XCTAssertNil(trace);
  74. }
  75. /**
  76. * Validates that the object creation fails for nil URLs.
  77. */
  78. - (void)testNilURL {
  79. NSString *URLString = nil;
  80. NSURL *URL = [NSURL URLWithString:URLString];
  81. NSURLRequest *sampleURLRequest = [NSURLRequest requestWithURL:URL];
  82. FPRNetworkTrace *trace = [[FPRNetworkTrace alloc] initWithURLRequest:sampleURLRequest];
  83. XCTAssertNil(trace);
  84. }
  85. /**
  86. * Validates that the object creation fails for empty URLs.
  87. */
  88. - (void)testEmptyURL {
  89. NSURL *URL = [NSURL URLWithString:@""];
  90. NSURLRequest *sampleURLRequest = [NSURLRequest requestWithURL:URL];
  91. FPRNetworkTrace *trace = [[FPRNetworkTrace alloc] initWithURLRequest:sampleURLRequest];
  92. XCTAssertNil(trace);
  93. }
  94. #pragma mark - Network Trace creation tests.
  95. /** Validates if trace creation fails when SDK flag is disabled in remote config. */
  96. - (void)testTraceCreationWhenSDKFlagDisabled {
  97. FPRConfigurations *configurations = [FPRConfigurations sharedInstance];
  98. FPRFakeRemoteConfig *remoteConfig = [[FPRFakeRemoteConfig alloc] init];
  99. FPRRemoteConfigFlags *configFlags =
  100. [[FPRRemoteConfigFlags alloc] initWithRemoteConfig:(FIRRemoteConfig *)remoteConfig];
  101. configurations.remoteConfigFlags = configFlags;
  102. NSData *valueData = [@"false" dataUsingEncoding:NSUTF8StringEncoding];
  103. FIRRemoteConfigValue *value =
  104. [[FIRRemoteConfigValue alloc] initWithData:valueData source:FIRRemoteConfigSourceRemote];
  105. [remoteConfig.configValues setObject:value forKey:@"fpr_enabled"];
  106. // Trigger the RC config fetch
  107. remoteConfig.lastFetchTime = nil;
  108. configFlags.appStartConfigFetchDelayInSeconds = 0.0;
  109. [configFlags update];
  110. XCTAssertNil([[FPRNetworkTrace alloc] initWithURLRequest:self.testURLRequest]);
  111. }
  112. /** Validates if trace creation succeeds when SDK flag is enabled in remote config. */
  113. - (void)testTraceCreationWhenSDKFlagEnabled {
  114. FPRConfigurations *configurations = [FPRConfigurations sharedInstance];
  115. FPRFakeRemoteConfig *remoteConfig = [[FPRFakeRemoteConfig alloc] init];
  116. FPRRemoteConfigFlags *configFlags =
  117. [[FPRRemoteConfigFlags alloc] initWithRemoteConfig:(FIRRemoteConfig *)remoteConfig];
  118. configurations.remoteConfigFlags = configFlags;
  119. NSUserDefaults *userDefaults = [[NSUserDefaults alloc] init];
  120. configFlags.userDefaults = userDefaults;
  121. NSString *configKey = [NSString stringWithFormat:@"%@.%@", kFPRConfigPrefix, @"fpr_enabled"];
  122. [userDefaults setObject:@(TRUE) forKey:configKey];
  123. XCTAssertNotNil([[FPRNetworkTrace alloc] initWithURLRequest:self.testURLRequest]);
  124. }
  125. /** Validates if trace creation fails when SDK flag is enabled in remote config, but data collection
  126. * disabled. */
  127. - (void)testTraceCreationWhenSDKFlagEnabledWithDataCollectionDisabled {
  128. [[FIRPerformance sharedInstance] setDataCollectionEnabled:NO];
  129. FPRConfigurations *configurations = [FPRConfigurations sharedInstance];
  130. FPRFakeRemoteConfig *remoteConfig = [[FPRFakeRemoteConfig alloc] init];
  131. FPRRemoteConfigFlags *configFlags =
  132. [[FPRRemoteConfigFlags alloc] initWithRemoteConfig:(FIRRemoteConfig *)remoteConfig];
  133. configurations.remoteConfigFlags = configFlags;
  134. NSData *valueData = [@"true" dataUsingEncoding:NSUTF8StringEncoding];
  135. FIRRemoteConfigValue *value =
  136. [[FIRRemoteConfigValue alloc] initWithData:valueData source:FIRRemoteConfigSourceRemote];
  137. [remoteConfig.configValues setObject:value forKey:@"fpr_enabled"];
  138. XCTAssertNil([[FPRNetworkTrace alloc] initWithURLRequest:self.testURLRequest]);
  139. }
  140. #pragma mark - Other Network Trace related tests.
  141. /**
  142. * Validates that the object creation succeeds for long URLs and returns a valid trimmed URL.
  143. */
  144. - (void)testInitWithVeryLongURL {
  145. NSString *domainString = @"https://thelongesturlusedtotestifitisgettingdropped.com";
  146. NSString *appendString = @"/thelongesturlusedtotestifitisgettingdroppedpath";
  147. NSString *URLString = domainString;
  148. NSInteger numberOfAppends = 0;
  149. // Create a long URL which exceed the limit.
  150. while (URLString.length < kFPRMaxURLLength) {
  151. URLString = [URLString stringByAppendingString:appendString];
  152. ++numberOfAppends;
  153. }
  154. URLString = [URLString stringByAppendingString:@"?param=value"];
  155. NSURLRequest *sampleURLRequest = [NSURLRequest requestWithURL:[NSURL URLWithString:URLString]];
  156. FPRNetworkTrace *trace = [[FPRNetworkTrace alloc] initWithURLRequest:sampleURLRequest];
  157. XCTAssertNotNil(trace);
  158. // Expected length of the URL should be the domainLength, number of times path was appended which
  159. // does not make the length go beyond the max limit.
  160. NSInteger expectedLength = domainString.length + (numberOfAppends - 1) * appendString.length;
  161. XCTAssertEqual(trace.trimmedURLString.length, expectedLength);
  162. }
  163. /**
  164. * Validates the process of checkpointing and the time that is stored for a checkpoint.
  165. */
  166. - (void)testCheckpointStates {
  167. FPRNetworkTrace *trace = [[FPRNetworkTrace alloc] initWithURLRequest:self.testURLRequest];
  168. [trace start];
  169. [trace checkpointState:FPRNetworkTraceCheckpointStateInitiated];
  170. NSDictionary<NSString *, NSNumber *> *states = [trace checkpointStates];
  171. XCTAssertEqual(states.count, 1);
  172. NSString *key = [@(FPRNetworkTraceCheckpointStateInitiated) stringValue];
  173. NSNumber *value = [states objectForKey:key];
  174. NSTimeInterval now = [[NSDate date] timeIntervalSince1970];
  175. // Validate if the event had occurred less than a millisecond ago.
  176. XCTAssertLessThan(now - [value doubleValue], .001);
  177. }
  178. /**
  179. * Validates if checkpointing of the same state is not honored.
  180. */
  181. - (void)testCheckpointingAgain {
  182. FPRNetworkTrace *trace = [[FPRNetworkTrace alloc] initWithURLRequest:self.testURLRequest];
  183. [trace start];
  184. [trace checkpointState:FPRNetworkTraceCheckpointStateInitiated];
  185. NSTimeInterval firstCheckpointTime = [[NSDate date] timeIntervalSince1970];
  186. NSString *key = [@(FPRNetworkTraceCheckpointStateInitiated) stringValue];
  187. NSDictionary<NSString *, NSNumber *> *statesAfterFirstCheckpoint = [trace checkpointStates];
  188. NSNumber *firstValue = [statesAfterFirstCheckpoint objectForKey:key];
  189. NSTimeInterval firstInitiatedTime = [firstValue doubleValue];
  190. [trace checkpointState:FPRNetworkTraceCheckpointStateInitiated];
  191. NSTimeInterval secondCheckpointTime = [[NSDate date] timeIntervalSince1970];
  192. NSDictionary<NSString *, NSNumber *> *statesAfterSecondCheckpoint = [trace checkpointStates];
  193. NSNumber *secondValue = [statesAfterSecondCheckpoint objectForKey:key];
  194. NSTimeInterval secondInitiatedTime = [secondValue doubleValue];
  195. NSDictionary<NSString *, NSNumber *> *states = [trace checkpointStates];
  196. XCTAssertEqual(states.count, 1);
  197. // Validate if the first checkpoint occurred before the second checkpoint time.
  198. XCTAssertLessThan(firstCheckpointTime, secondCheckpointTime);
  199. // Validate if the time has not changed even after rec checkpointing.
  200. XCTAssertEqual(firstInitiatedTime, secondInitiatedTime);
  201. }
  202. - (void)testCheckpointStatesBeforeStarting {
  203. FPRNetworkTrace *trace = [[FPRNetworkTrace alloc] initWithURLRequest:self.testURLRequest];
  204. [trace checkpointState:FPRNetworkTraceCheckpointStateInitiated];
  205. NSDictionary<NSString *, NSNumber *> *states = [trace checkpointStates];
  206. XCTAssertEqual(states.count, 0);
  207. }
  208. /**
  209. * Validates a successfully completed request for its checkpoints and data fetched out of the
  210. * response.
  211. */
  212. - (void)testDidCompleteRequestWithValidResponse {
  213. FPRNetworkTrace *trace = [[FPRNetworkTrace alloc] initWithURLRequest:self.testURLRequest];
  214. [trace start];
  215. [trace checkpointState:FPRNetworkTraceCheckpointStateInitiated];
  216. [trace checkpointState:FPRNetworkTraceCheckpointStateResponseReceived];
  217. NSDictionary<NSString *, NSString *> *headerFields = @{@"Content-Type" : @"text/json"};
  218. NSHTTPURLResponse *response = [[NSHTTPURLResponse alloc] initWithURL:self.testURLRequest.URL
  219. statusCode:200
  220. HTTPVersion:@"HTTP/1.1"
  221. headerFields:headerFields];
  222. NSString *string = @"Successful response";
  223. NSData *data = [string dataUsingEncoding:NSUTF8StringEncoding];
  224. [trace didReceiveData:data];
  225. [trace didCompleteRequestWithResponse:response error:nil];
  226. NSDictionary<NSString *, NSNumber *> *states = [trace checkpointStates];
  227. XCTAssertEqual(states.count, 3);
  228. XCTAssertEqual(trace.responseCode, 200);
  229. XCTAssertEqual(trace.responseSize, string.length);
  230. XCTAssertEqualObjects(trace.responseContentType, @"text/json");
  231. NSString *key = [@(FPRNetworkTraceCheckpointStateResponseCompleted) stringValue];
  232. NSNumber *value = [states objectForKey:key];
  233. XCTAssertNotNil(value);
  234. }
  235. /**
  236. * Validates a failed network request for its checkpoints and data fetched out of the response.
  237. */
  238. - (void)testDidCompleteRequestWithErrorResponse {
  239. FPRNetworkTrace *trace = [[FPRNetworkTrace alloc] initWithURLRequest:self.testURLRequest];
  240. [trace start];
  241. [trace checkpointState:FPRNetworkTraceCheckpointStateInitiated];
  242. [trace checkpointState:FPRNetworkTraceCheckpointStateResponseReceived];
  243. NSDictionary<NSString *, NSString *> *headerFields = @{@"Content-Type" : @"text/json"};
  244. NSHTTPURLResponse *response = [[NSHTTPURLResponse alloc] initWithURL:self.testURLRequest.URL
  245. statusCode:404
  246. HTTPVersion:@"HTTP/1.1"
  247. headerFields:headerFields];
  248. NSError *error = [NSError errorWithDomain:NSURLErrorDomain code:-200 userInfo:nil];
  249. [trace didReceiveData:[NSData data]];
  250. [trace didCompleteRequestWithResponse:response error:error];
  251. NSDictionary<NSString *, NSNumber *> *states = [trace checkpointStates];
  252. XCTAssertEqual(states.count, 3);
  253. XCTAssertEqual(trace.responseCode, 404);
  254. XCTAssertEqual(trace.responseSize, 0);
  255. XCTAssertEqualObjects(trace.responseContentType, @"text/json");
  256. NSString *key = [@(FPRNetworkTraceCheckpointStateResponseCompleted) stringValue];
  257. NSNumber *value = [states objectForKey:key];
  258. XCTAssertNotNil(value);
  259. }
  260. /**
  261. * Validates that the uploaded file size correctly reflect in the NetworkTrace.
  262. */
  263. - (void)testDidUploadFile {
  264. NSBundle *bundle = [FPRTestUtils getBundle];
  265. NSURL *fileURL = [bundle URLForResource:@"smallDownloadFile" withExtension:@""];
  266. FPRNetworkTrace *trace = [[FPRNetworkTrace alloc] initWithURLRequest:self.testURLRequest];
  267. [trace start];
  268. [trace checkpointState:FPRNetworkTraceCheckpointStateInitiated];
  269. [trace checkpointState:FPRNetworkTraceCheckpointStateResponseReceived];
  270. [trace didUploadFileWithURL:fileURL];
  271. XCTAssertEqual(trace.requestSize, 26);
  272. XCTAssertEqual(trace.responseSize, 0);
  273. [[NSFileManager defaultManager] removeItemAtURL:fileURL error:nil];
  274. }
  275. - (void)testCompletedRequest {
  276. FPRNetworkTrace *trace = [[FPRNetworkTrace alloc] initWithURLRequest:self.testURLRequest];
  277. [trace start];
  278. [trace checkpointState:FPRNetworkTraceCheckpointStateInitiated];
  279. [trace checkpointState:FPRNetworkTraceCheckpointStateResponseReceived];
  280. [trace didCompleteRequestWithResponse:nil error:nil];
  281. NSDictionary<NSString *, NSNumber *> *states = [trace checkpointStates];
  282. XCTAssertEqual(states.count, 3);
  283. NSString *key = [@(FPRNetworkTraceCheckpointStateResponseCompleted) stringValue];
  284. NSNumber *value = [states objectForKey:key];
  285. XCTAssertNotNil(value);
  286. }
  287. /**
  288. * Validates checkpointing for edge state - Checkpointing after a network request is completed.
  289. */
  290. - (void)testCheckpointAfterCompletedRequest {
  291. FPRNetworkTrace *trace = [[FPRNetworkTrace alloc] initWithURLRequest:self.testURLRequest];
  292. [trace start];
  293. [trace checkpointState:FPRNetworkTraceCheckpointStateInitiated];
  294. [trace didCompleteRequestWithResponse:nil error:nil];
  295. [trace checkpointState:FPRNetworkTraceCheckpointStateResponseReceived];
  296. NSDictionary<NSString *, NSNumber *> *states = [trace checkpointStates];
  297. XCTAssertEqual(states.count, 2);
  298. }
  299. - (void)testTimeIntervalBetweenValidStates {
  300. FPRNetworkTrace *trace = [[FPRNetworkTrace alloc] initWithURLRequest:self.testURLRequest];
  301. [trace start];
  302. [trace checkpointState:FPRNetworkTraceCheckpointStateInitiated];
  303. sleep(2);
  304. [trace checkpointState:FPRNetworkTraceCheckpointStateResponseReceived];
  305. NSTimeInterval timeDifference =
  306. [trace timeIntervalBetweenCheckpointState:FPRNetworkTraceCheckpointStateInitiated
  307. andState:FPRNetworkTraceCheckpointStateResponseReceived];
  308. XCTAssertLessThan(fabs(timeDifference - 2), 0.2);
  309. }
  310. - (void)testURLTrimmingWithQuery {
  311. NSURL *URL = [NSURL URLWithString:@"https://accounts.google.com/ServiceLogin?service=mail"];
  312. NSURLRequest *URLRequest = [NSURLRequest requestWithURL:URL];
  313. FPRNetworkTrace *networkTrace = [[FPRNetworkTrace alloc] initWithURLRequest:URLRequest];
  314. XCTAssertEqualObjects(networkTrace.trimmedURLString, @"https://accounts.google.com/ServiceLogin");
  315. }
  316. - (void)testURLTrimmingWithUserNamePasswordAndPort {
  317. NSURL *URL = [NSURL URLWithString:@"https://a:b@ab.com:1000/ServiceLogin?service=mail"];
  318. NSURLRequest *URLRequest = [NSURLRequest requestWithURL:URL];
  319. FPRNetworkTrace *networkTrace = [[FPRNetworkTrace alloc] initWithURLRequest:URLRequest];
  320. XCTAssertEqualObjects(networkTrace.trimmedURLString, @"https://ab.com:1000/ServiceLogin");
  321. }
  322. - (void)testURLTrimmingWithDeepPath {
  323. NSURL *URL = [NSURL URLWithString:@"https://a:b@ab.com:1000/x/y/z?service=1&really=2"];
  324. NSURLRequest *URLRequest = [NSURLRequest requestWithURL:URL];
  325. FPRNetworkTrace *networkTrace = [[FPRNetworkTrace alloc] initWithURLRequest:URLRequest];
  326. XCTAssertEqualObjects(networkTrace.trimmedURLString, @"https://ab.com:1000/x/y/z");
  327. }
  328. - (void)testURLTrimmingWithFragments {
  329. NSURL *URL = [NSURL URLWithString:@"https://a:b@ab.com:1000/x#really?service=1&really=2"];
  330. NSURLRequest *URLRequest = [NSURLRequest requestWithURL:URL];
  331. FPRNetworkTrace *networkTrace = [[FPRNetworkTrace alloc] initWithURLRequest:URLRequest];
  332. XCTAssertEqualObjects(networkTrace.trimmedURLString, @"https://ab.com:1000/x");
  333. }
  334. /** Validate if the trace creation fails when the domain name is beyond max length. */
  335. - (void)testURLMaxLength {
  336. NSString *longString = [@"abd" stringByPaddingToLength:kFPRMaxURLLength + 1
  337. withString:@"-"
  338. startingAtIndex:0];
  339. NSString *urlString = [NSString stringWithFormat:@"https://%@.com", longString];
  340. NSURL *URL = [NSURL URLWithString:urlString];
  341. NSURLRequest *URLRequest = [NSURLRequest requestWithURL:URL];
  342. XCTAssertNil([[FPRNetworkTrace alloc] initWithURLRequest:URLRequest]);
  343. }
  344. /** Validate if the trimmed URL drops only few sub paths from the URL when the length goes beyond
  345. * the limit.
  346. */
  347. - (void)testURLMaxLengthWithQuerypath {
  348. NSString *longString = [@"abd" stringByPaddingToLength:kFPRMaxURLLength - 20
  349. withString:@"-"
  350. startingAtIndex:0];
  351. NSString *urlString = [NSString stringWithFormat:@"https://%@.com/abcd/efgh/ijkl", longString];
  352. NSURL *URL = [NSURL URLWithString:urlString];
  353. NSURLRequest *URLRequest = [NSURLRequest requestWithURL:URL];
  354. FPRNetworkTrace *networkTrace = [[FPRNetworkTrace alloc] initWithURLRequest:URLRequest];
  355. XCTAssertNotNil(networkTrace);
  356. XCTAssertEqual(networkTrace.trimmedURLString.length, 1997);
  357. }
  358. /** Validate if the trimmed URL is equal to the URL provided when the length is less than the limit.
  359. */
  360. - (void)testTrimmedURLForShortLengthURLs {
  361. NSString *urlString = @"https://helloworld.com/abcd/efgh/ijkl";
  362. NSURL *URL = [NSURL URLWithString:urlString];
  363. NSURLRequest *URLRequest = [NSURLRequest requestWithURL:URL];
  364. FPRNetworkTrace *networkTrace = [[FPRNetworkTrace alloc] initWithURLRequest:URLRequest];
  365. XCTAssertNotNil(networkTrace);
  366. XCTAssertEqualObjects(networkTrace.URLRequest.URL.absoluteString, urlString);
  367. }
  368. /** Validates that every trace contains a session Id. */
  369. - (void)testSessionId {
  370. [[FPRSessionManager sharedInstance] updateSessionId:@"testSessionId"];
  371. FPRNetworkTrace *trace = [[FPRNetworkTrace alloc] initWithURLRequest:self.testURLRequest];
  372. [trace start];
  373. [trace checkpointState:FPRNetworkTraceCheckpointStateInitiated];
  374. [trace checkpointState:FPRNetworkTraceCheckpointStateResponseReceived];
  375. NSDictionary<NSString *, NSString *> *headerFields = @{@"Content-Type" : @"text/json"};
  376. NSHTTPURLResponse *response = [[NSHTTPURLResponse alloc] initWithURL:self.testURLRequest.URL
  377. statusCode:200
  378. HTTPVersion:@"HTTP/1.1"
  379. headerFields:headerFields];
  380. NSString *string = @"Successful response";
  381. NSData *data = [string dataUsingEncoding:NSUTF8StringEncoding];
  382. [trace didReceiveData:data];
  383. [trace didCompleteRequestWithResponse:response error:nil];
  384. XCTAssertNotNil(trace.sessions);
  385. XCTAssertTrue(trace.sessions.count > 0);
  386. }
  387. /** Validates if a trace contains multiple session Ids on changing app state. */
  388. - (void)testMultipleSessionIds {
  389. [[FPRSessionManager sharedInstance] updateSessionId:@"testSessionId"];
  390. FPRNetworkTrace *trace = [[FPRNetworkTrace alloc] initWithURLRequest:self.testURLRequest];
  391. [trace start];
  392. [trace checkpointState:FPRNetworkTraceCheckpointStateInitiated];
  393. [trace checkpointState:FPRNetworkTraceCheckpointStateResponseReceived];
  394. [[FPRSessionManager sharedInstance] updateSessionId:@"testSessionId2"];
  395. [[FPRSessionManager sharedInstance] updateSessionId:@"testSessionId3"];
  396. NSDictionary<NSString *, NSString *> *headerFields = @{@"Content-Type" : @"text/json"};
  397. NSHTTPURLResponse *response = [[NSHTTPURLResponse alloc] initWithURL:self.testURLRequest.URL
  398. statusCode:200
  399. HTTPVersion:@"HTTP/1.1"
  400. headerFields:headerFields];
  401. NSString *string = @"Successful response";
  402. NSData *data = [string dataUsingEncoding:NSUTF8StringEncoding];
  403. [trace didReceiveData:data];
  404. [trace didCompleteRequestWithResponse:response error:nil];
  405. XCTestExpectation *expectation = [self expectationWithDescription:@"Dummy expectation"];
  406. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.0 * NSEC_PER_SEC)),
  407. dispatch_get_main_queue(), ^{
  408. [expectation fulfill];
  409. XCTAssertNotNil(trace.sessions);
  410. XCTAssertTrue(trace.sessions.count >= 2);
  411. });
  412. [self waitForExpectationsWithTimeout:10.0 handler:nil];
  413. }
  414. @end