FPRNetworkTraceTest.m 22 KB

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