FIRTraceTest.m 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753
  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/FPRAppActivityTracker.h"
  16. #import "FirebasePerformance/Sources/AppActivity/FPRSessionManager.h"
  17. #import "FirebasePerformance/Sources/Common/FPRConstants.h"
  18. #import "FirebasePerformance/Sources/Configurations/FPRConfigurations+Private.h"
  19. #import "FirebasePerformance/Sources/Configurations/FPRConfigurations.h"
  20. #import "FirebasePerformance/Sources/Configurations/FPRRemoteConfigFlags+Private.h"
  21. #import "FirebasePerformance/Sources/Configurations/FPRRemoteConfigFlags.h"
  22. #import "FirebasePerformance/Sources/FPRClient.h"
  23. #import "FirebasePerformance/Sources/Public/FirebasePerformance/FIRPerformance.h"
  24. #import "FirebasePerformance/Sources/Public/FirebasePerformance/FIRTrace.h"
  25. #import "FirebasePerformance/Sources/Timer/FIRTrace+Internal.h"
  26. #import "FirebasePerformance/Sources/Timer/FIRTrace+Private.h"
  27. #import "FirebasePerformance/Tests/Unit/Configurations/FPRFakeRemoteConfig.h"
  28. #import "FirebasePerformance/Tests/Unit/FPRTestCase.h"
  29. #import "FirebaseRemoteConfig/Sources/RCNConfigValue_Internal.h"
  30. #import <OCMock/OCMock.h>
  31. @interface FIRTraceTest : FPRTestCase
  32. @end
  33. @implementation FIRTraceTest
  34. - (void)setUp {
  35. [super setUp];
  36. FIRPerformance *performance = [FIRPerformance sharedInstance];
  37. [performance setDataCollectionEnabled:YES];
  38. [[FPRClient sharedInstance] disableInstrumentation];
  39. }
  40. - (void)tearDown {
  41. [super tearDown];
  42. FIRPerformance *performance = [FIRPerformance sharedInstance];
  43. [performance setDataCollectionEnabled:NO];
  44. [[FPRClient sharedInstance] disableInstrumentation];
  45. }
  46. /** Validates that init with a valid name returns a trace. */
  47. - (void)testInit {
  48. FIRTrace *trace = [[FIRTrace alloc] initWithName:@"Random"];
  49. XCTAssertNotNil(trace);
  50. }
  51. /** Validates that init with an empty name throws exception. */
  52. - (void)testInitWithEmptyName {
  53. XCTAssertThrows([[FIRTrace alloc] initWithName:@""]);
  54. }
  55. #pragma mark - Trace creation tests
  56. /** Validates if trace creation fails when SDK flag is disabled in remote config. */
  57. - (void)testTraceCreationWhenSDKFlagDisabled {
  58. FPRConfigurations *configurations = [FPRConfigurations sharedInstance];
  59. FPRFakeRemoteConfig *remoteConfig = [[FPRFakeRemoteConfig alloc] init];
  60. FPRRemoteConfigFlags *configFlags =
  61. [[FPRRemoteConfigFlags alloc] initWithRemoteConfig:(FIRRemoteConfig *)remoteConfig];
  62. configFlags.appStartConfigFetchDelayInSeconds = 0.0;
  63. configurations.remoteConfigFlags = configFlags;
  64. NSData *valueData = [@"false" dataUsingEncoding:NSUTF8StringEncoding];
  65. FIRRemoteConfigValue *value =
  66. [[FIRRemoteConfigValue alloc] initWithData:valueData source:FIRRemoteConfigSourceRemote];
  67. [remoteConfig.configValues setObject:value forKey:@"fpr_enabled"];
  68. // Trigger the RC config fetch
  69. remoteConfig.lastFetchTime = nil;
  70. configFlags.appStartConfigFetchDelayInSeconds = 0.0;
  71. [configFlags update];
  72. XCTAssertNil([[FIRTrace alloc] initWithName:@"Random"]);
  73. }
  74. /** Validates if trace creation succeeds when SDK flag is enabled in remote config. */
  75. - (void)testTraceCreationWhenSDKFlagEnabled {
  76. FPRConfigurations *configurations = [FPRConfigurations sharedInstance];
  77. FPRFakeRemoteConfig *remoteConfig = [[FPRFakeRemoteConfig alloc] init];
  78. FPRRemoteConfigFlags *configFlags =
  79. [[FPRRemoteConfigFlags alloc] initWithRemoteConfig:(FIRRemoteConfig *)remoteConfig];
  80. configurations.remoteConfigFlags = configFlags;
  81. NSUserDefaults *userDefaults = [[NSUserDefaults alloc] init];
  82. configFlags.userDefaults = userDefaults;
  83. NSString *configKey = [NSString stringWithFormat:@"%@.%@", kFPRConfigPrefix, @"fpr_enabled"];
  84. [userDefaults setObject:@(TRUE) forKey:configKey];
  85. XCTAssertNotNil([[FIRTrace alloc] initWithName:@"Random"]);
  86. }
  87. /** Validates if trace creation fails when SDK flag is enabled in remote config, but data collection
  88. * disabled. */
  89. - (void)testTraceCreationWhenSDKFlagEnabledWithDataCollectionDisabled {
  90. [[FIRPerformance sharedInstance] setDataCollectionEnabled:NO];
  91. FPRConfigurations *configurations = [FPRConfigurations sharedInstance];
  92. FPRFakeRemoteConfig *remoteConfig = [[FPRFakeRemoteConfig alloc] init];
  93. FPRRemoteConfigFlags *configFlags =
  94. [[FPRRemoteConfigFlags alloc] initWithRemoteConfig:(FIRRemoteConfig *)remoteConfig];
  95. configurations.remoteConfigFlags = configFlags;
  96. NSData *valueData = [@"true" dataUsingEncoding:NSUTF8StringEncoding];
  97. FIRRemoteConfigValue *value =
  98. [[FIRRemoteConfigValue alloc] initWithData:valueData source:FIRRemoteConfigSourceRemote];
  99. [remoteConfig.configValues setObject:value forKey:@"fpr_enabled"];
  100. XCTAssertNil([[FIRTrace alloc] initWithName:@"Random"]);
  101. }
  102. #pragma mark - Stages related testing
  103. /** Validates that stages are created. */
  104. - (void)testStaging {
  105. FIRTrace *trace = [[FIRTrace alloc] initWithName:@"Random"];
  106. [trace start];
  107. [trace startStageNamed:@"1"];
  108. [trace startStageNamed:@"2"];
  109. [trace stop];
  110. XCTAssertEqual(trace.stages.count, 2);
  111. }
  112. /** Validates that stages are not created without calling a start on the trace. */
  113. - (void)testStageWithoutStart {
  114. FIRTrace *trace = [[FIRTrace alloc] initWithName:@"Random"];
  115. [trace startStageNamed:@"1"];
  116. XCTAssertEqual(trace.stages.count, 0);
  117. }
  118. /** Validates that stages are not created without calling a start on the trace, but calling stop. */
  119. - (void)testStageWithoutStartWithStop {
  120. FIRTrace *trace = [[FIRTrace alloc] initWithName:@"Random"];
  121. [trace startStageNamed:@"1"];
  122. [trace stop];
  123. XCTAssertEqual(trace.stages.count, 0);
  124. }
  125. /** Validates that stages are not created after calling stop on the trace. */
  126. - (void)testStageAfterStop {
  127. FIRTrace *trace = [[FIRTrace alloc] initWithName:@"Random"];
  128. [trace start];
  129. [trace startStageNamed:@"1"];
  130. [trace startStageNamed:@"2"];
  131. [trace stop];
  132. [trace startStageNamed:@"3"];
  133. XCTAssertEqual(trace.stages.count, 2);
  134. }
  135. /** Validates that stopping a stage does not trigger an event being sent to Fll */
  136. - (void)testStageStopDoesNotTriggerEventSend {
  137. FIRTrace *trace = [[FIRTrace alloc] initWithName:@"Random"];
  138. id mock = [OCMockObject partialMockForObject:[FPRClient sharedInstance]];
  139. OCMStub([mock logTrace:[OCMArg any]]).andDo(nil);
  140. [trace start];
  141. [trace startStageNamed:@"1"];
  142. [[mock reject] logTrace:trace.activeStage];
  143. [trace startStageNamed:@"2"];
  144. [trace stop];
  145. }
  146. /** Validates that stopping a trace does trigger an event being sent to Fll. */
  147. - (void)testTraceStopDoesTriggerEventSend {
  148. FIRTrace *trace = [[FIRTrace alloc] initWithName:@"Random"];
  149. id mock = [OCMockObject partialMockForObject:[FPRClient sharedInstance]];
  150. OCMStub([mock logTrace:[OCMArg any]]).andDo(nil);
  151. [trace start];
  152. [trace startStageNamed:@"1"];
  153. [trace startStageNamed:@"2"];
  154. [trace stop];
  155. OCMVerify([mock logTrace:trace]);
  156. }
  157. /** Validates that the name of the trace is dropped if its length is above max admissible length. */
  158. - (void)testNameLengthMax {
  159. NSString *testName = [@"abc" stringByPaddingToLength:kFPRMaxNameLength + 1
  160. withString:@"-"
  161. startingAtIndex:0];
  162. XCTAssertThrows([[FIRTrace alloc] initWithName:testName]);
  163. }
  164. /** Validates that the name cannot have a prefix of underscore. */
  165. - (void)testNamePrefixSrtipped {
  166. NSString *testName = [NSString stringWithFormat:@"%@test", kFPRInternalNamePrefix];
  167. XCTAssertThrows([[FIRTrace alloc] initWithName:testName]);
  168. }
  169. #pragma mark - Metric related testing
  170. /** Validates that metric with greater than max length is not created on setMetric. */
  171. - (void)testSetMetricNameLengthMax {
  172. FIRTrace *trace = [[FIRTrace alloc] initWithName:@"Random"];
  173. NSString *testName = [@"abc" stringByPaddingToLength:kFPRMaxNameLength + 1
  174. withString:@"-"
  175. startingAtIndex:0];
  176. [trace start];
  177. [trace setIntValue:10 forMetric:testName];
  178. [trace stop];
  179. XCTAssertNil([trace.counters objectForKey:testName]);
  180. }
  181. /** Validates that metric with empty name is not created on setMetric. */
  182. - (void)testSetOrIncrementMetricNameLengthZero {
  183. FIRTrace *trace = [[FIRTrace alloc] initWithName:@"Random"];
  184. NSString *testName = @"";
  185. [trace start];
  186. [trace setIntValue:10 forMetric:testName];
  187. [trace incrementMetric:testName byInt:10];
  188. [trace stop];
  189. XCTAssertNil([trace.counters objectForKey:testName]);
  190. }
  191. /** Validates that metrics are not set when a trace is not started. */
  192. - (void)testSetOrIncrementMetricWithoutStart {
  193. FIRTrace *trace = [[FIRTrace alloc] initWithName:@"Random"];
  194. [trace setIntValue:10 forMetric:@"testing"];
  195. [trace incrementMetric:@"testing" byInt:10];
  196. [trace stop];
  197. XCTAssertNil([trace.counters objectForKey:@"testing"]);
  198. }
  199. /** Validates that calling get on a metric returns 0 if it hasnt been reviously set. */
  200. - (void)testGetMetricWhenSetHasntBeenCalledReturnsZero {
  201. FIRTrace *trace = [[FIRTrace alloc] initWithName:@"Random"];
  202. int64_t metricValue = [trace valueForIntMetric:@"testing"];
  203. [trace stop];
  204. XCTAssertEqual(metricValue, 0);
  205. }
  206. /** Validates that calling get on a metric without calling set doesn't create a new metric. */
  207. - (void)testGetMetricWhenSetHasntBeenCalledDoesntCreateMetric {
  208. FIRTrace *trace = [[FIRTrace alloc] initWithName:@"Random"];
  209. [trace valueForIntMetric:@"testing"];
  210. [trace stop];
  211. id metricValue = [trace.counters objectForKey:@"testing"];
  212. XCTAssertNil(metricValue);
  213. }
  214. /** Tests that calling set multiple times on a metric results in it holding just the last value. */
  215. - (void)testMultipleSetsOnAMetricResultInHoldingJustTheLastValue {
  216. FIRTrace *trace = [[FIRTrace alloc] initWithName:@"Random"];
  217. [trace start];
  218. [trace setIntValue:10 forMetric:@"testing"];
  219. [trace setIntValue:100 forMetric:@"testing"];
  220. [trace stop];
  221. int64_t metricValue = [trace valueForIntMetric:@"testing"];
  222. XCTAssertEqual(metricValue, 100);
  223. }
  224. /** Validates that incrementing a metric that has been previously set increments previous value. */
  225. - (void)testIncrementingAfterSettingMetric {
  226. FIRTrace *trace = [[FIRTrace alloc] initWithName:@"Random"];
  227. [trace start];
  228. [trace setIntValue:10 forMetric:@"testing"];
  229. [trace incrementMetric:@"testing" byInt:25];
  230. [trace stop];
  231. int64_t metricValue = [trace valueForIntMetric:@"testing"];
  232. XCTAssertEqual(metricValue, 35);
  233. }
  234. /** Validates that calling setMetric on a trace also sets it on the active stage. */
  235. - (void)testSetMetricCalledOnTraceAlsoSetsMetricOnStage {
  236. FIRTrace *trace = [[FIRTrace alloc] initWithName:@"Random"];
  237. [trace start];
  238. [trace startStageNamed:@"stage 1"];
  239. [trace setIntValue:35 forMetric:@"testing"];
  240. [trace startStageNamed:@"stage 2"];
  241. [trace setIntValue:40 forMetric:@"testing"];
  242. [trace stop];
  243. XCTAssertEqual([trace valueForIntMetric:@"testing"], 40);
  244. for (FIRTrace *stage in trace.stages) {
  245. if ([stage.name isEqualToString:@"stage 1"]) {
  246. XCTAssertEqual([stage valueForIntMetric:@"testing"], 35);
  247. } else if ([stage.name isEqualToString:@"stage 2"]) {
  248. XCTAssertEqual([stage valueForIntMetric:@"testing"], 40);
  249. }
  250. }
  251. }
  252. /** Validates that deleting a metric deletes it. */
  253. - (void)testDeleteMetricDeletesAMetric {
  254. FIRTrace *trace = [[FIRTrace alloc] initWithName:@"Random"];
  255. [trace start];
  256. [trace setIntValue:1 forMetric:@"testing"];
  257. [trace deleteMetric:@"testing"];
  258. [trace stop];
  259. XCTAssertNil(trace.counters[@"testing"]);
  260. }
  261. /** Validates that deleting a metric doesnt affect other metrics. */
  262. - (void)testDeleteMetricDoesntDeleteAnotherMetric {
  263. FIRTrace *trace = [[FIRTrace alloc] initWithName:@"Random"];
  264. [trace start];
  265. [trace setIntValue:1 forMetric:@"testing"];
  266. [trace setIntValue:1 forMetric:@"testing2"];
  267. [trace deleteMetric:@"testing"];
  268. [trace stop];
  269. XCTAssertNil(trace.counters[@"testing"]);
  270. XCTAssertEqual([trace valueForIntMetric:@"testing2"], 1);
  271. }
  272. /** Validates that trying to delete a non-existent metric doesnt affect anything. */
  273. - (void)testDeletingMetricThatDoesntExistDoesntDoAnything {
  274. FIRTrace *trace = [[FIRTrace alloc] initWithName:@"Random"];
  275. [trace start];
  276. [trace setIntValue:1 forMetric:@"testing"];
  277. [trace deleteMetric:@"testing2"];
  278. [trace stop];
  279. XCTAssertEqual([trace valueForIntMetric:@"testing"], 1);
  280. }
  281. /** Tests deleting a metric also deletes it from the active stage if it exists. */
  282. - (void)testDeleteMetricAlsoDeletesItFromActiveStage {
  283. FIRTrace *trace = [[FIRTrace alloc] initWithName:@"Random"];
  284. [trace start];
  285. [trace startStageNamed:@"stage 1"];
  286. FIRTrace *activeStage = trace.activeStage;
  287. [trace setIntValue:1 forMetric:@"testing"];
  288. [trace setIntValue:1 forMetric:@"testing2"];
  289. [trace deleteMetric:@"testing"];
  290. [trace stop];
  291. XCTAssertEqual([trace valueForIntMetric:@"testing2"], 1);
  292. XCTAssertEqual([activeStage valueForIntMetric:@"testing2"], 1);
  293. XCTAssertNil(trace.counters[@"testing"]);
  294. XCTAssertNil(activeStage.counters[@"testing"]);
  295. }
  296. /** Tests that deleteMetric has no effect after the trace has been stopped. */
  297. - (void)testDeleteMetricDoesNothingAfterTraceHasBeenStopped {
  298. FIRTrace *trace = [[FIRTrace alloc] initWithName:@"Random"];
  299. [trace start];
  300. [trace setIntValue:1 forMetric:@"testing"];
  301. [trace stop];
  302. [trace deleteMetric:@"testing"];
  303. XCTAssertEqual([trace valueForIntMetric:@"testing"], 1);
  304. }
  305. #pragma mark - Metrics related testing
  306. /** Validates that counters are incremented. */
  307. - (void)testMetricNameLengthMax {
  308. FIRTrace *trace = [[FIRTrace alloc] initWithName:@"Random"];
  309. NSString *testName = [@"abc" stringByPaddingToLength:kFPRMaxNameLength + 1
  310. withString:@"-"
  311. startingAtIndex:0];
  312. [trace start];
  313. [trace incrementMetric:testName byInt:5];
  314. [trace stop];
  315. XCTAssertNil([trace.counters objectForKey:testName]);
  316. }
  317. /** Validates that traces could start with a custom start time. */
  318. - (void)testStartTraceWithStartTimeAndStageDefined {
  319. NSDate *traceStartTime = [NSDate date];
  320. FIRTrace *trace = [[FIRTrace alloc] initWithName:@"testTrace"];
  321. [trace startWithStartTime:traceStartTime];
  322. XCTAssertEqual(trace.startTimeSinceEpoch, [traceStartTime timeIntervalSince1970]);
  323. [trace startStageNamed:@"testStage" startTime:traceStartTime];
  324. [trace stop];
  325. XCTAssertEqual(trace.stages.count, 1);
  326. FIRTrace *stage = trace.stages.lastObject;
  327. XCTAssertEqual(stage.startTimeSinceEpoch, [traceStartTime timeIntervalSince1970]);
  328. }
  329. - (void)testMetrics {
  330. FIRTrace *trace = [[FIRTrace alloc] initWithName:@"Random"];
  331. [trace start];
  332. [trace incrementMetric:@"testing" byInt:3];
  333. [trace incrementMetric:@"testing" byInt:2];
  334. [trace stop];
  335. NSUInteger metricValue = [[trace.counters objectForKey:@"testing"] integerValue];
  336. XCTAssertEqual(metricValue, 5);
  337. }
  338. /** Validates that metrics are not incremented when a trace is not started. */
  339. - (void)testMetricsWithoutStart {
  340. FIRTrace *trace = [[FIRTrace alloc] initWithName:@"Random"];
  341. [trace incrementMetric:@"testing" byInt:3];
  342. [trace incrementMetric:@"testing" byInt:2];
  343. [trace stop];
  344. NSUInteger metricValue = [[trace.counters objectForKey:@"testing"] integerValue];
  345. XCTAssertEqual(metricValue, 0);
  346. }
  347. /** Validates that trace without complete data is invalid. */
  348. - (void)testInvalidTraceValidationCheck {
  349. FIRTrace *trace = [[FIRTrace alloc] initWithName:@"Random"];
  350. [trace stop];
  351. XCTAssertFalse([trace isCompleteAndValid]);
  352. }
  353. /** Validates that valid traces with stages and metrics are marked as valid. */
  354. - (void)testValidTraceWithStageAndMetrics {
  355. FIRTrace *trace = [[FIRTrace alloc] initWithName:@"Random"];
  356. [trace start];
  357. [trace incrementMetric:@"counter 1" byInt:1];
  358. [trace incrementMetric:@"counter 2" byInt:1];
  359. [trace startStageNamed:@"1"];
  360. [trace incrementMetric:@"counter 1" byInt:1];
  361. [trace incrementMetric:@"counter 2" byInt:1];
  362. [trace startStageNamed:@"2"];
  363. [trace incrementMetric:@"counter 1" byInt:1];
  364. [trace incrementMetric:@"counter 2" byInt:1];
  365. [trace stop];
  366. XCTAssertTrue([trace isCompleteAndValid]);
  367. }
  368. /** Validates the value of background state when the app is backgrounded. */
  369. - (void)testValidTraceWithBackgrounding {
  370. NSNotificationCenter *defaultCenter = [NSNotificationCenter defaultCenter];
  371. FIRTrace *trace = [[FIRTrace alloc] initWithName:@"Random"];
  372. [trace start];
  373. [defaultCenter postNotificationName:UIApplicationDidEnterBackgroundNotification
  374. object:[UIApplication sharedApplication]];
  375. [defaultCenter postNotificationName:UIApplicationDidBecomeActiveNotification
  376. object:[UIApplication sharedApplication]];
  377. XCTAssertEqual(trace.backgroundTraceState, FPRTraceStateBackgroundAndForeground);
  378. [trace stop];
  379. }
  380. /** Validates the value of background state when trace is not started. */
  381. - (void)testValidTraceWithoutStart {
  382. NSNotificationCenter *defaultCenter = [NSNotificationCenter defaultCenter];
  383. FIRTrace *trace = [[FIRTrace alloc] initWithName:@"Random"];
  384. [defaultCenter postNotificationName:UIApplicationDidEnterBackgroundNotification
  385. object:[UIApplication sharedApplication]];
  386. [defaultCenter postNotificationName:UIApplicationDidBecomeActiveNotification
  387. object:[UIApplication sharedApplication]];
  388. [trace stop];
  389. XCTAssertEqual(trace.backgroundTraceState, FPRTraceStateUnknown);
  390. }
  391. /** Validates the value of background state is available after trace is stopped. */
  392. - (void)testBackgroundStateAfterTraceStop {
  393. NSNotificationCenter *defaultCenter = [NSNotificationCenter defaultCenter];
  394. FIRTrace *trace = [[FIRTrace alloc] initWithName:@"Random"];
  395. [trace start];
  396. [defaultCenter postNotificationName:UIApplicationDidEnterBackgroundNotification
  397. object:[UIApplication sharedApplication]];
  398. [defaultCenter postNotificationName:UIApplicationDidBecomeActiveNotification
  399. object:[UIApplication sharedApplication]];
  400. [trace stop];
  401. XCTAssertEqual(trace.backgroundTraceState, FPRTraceStateBackgroundAndForeground);
  402. }
  403. /** Validates that stages do not have any valid background state. */
  404. - (void)testValidTraceWithActiveStageHavingNoBackgroundState {
  405. NSNotificationCenter *defaultCenter = [NSNotificationCenter defaultCenter];
  406. FIRTrace *trace = [[FIRTrace alloc] initWithName:@"Random"];
  407. [trace start];
  408. [trace startStageNamed:@"RandomStage"];
  409. [defaultCenter postNotificationName:UIApplicationDidEnterBackgroundNotification
  410. object:[UIApplication sharedApplication]];
  411. [defaultCenter postNotificationName:UIApplicationDidBecomeActiveNotification
  412. object:[UIApplication sharedApplication]];
  413. [trace stop];
  414. XCTAssertEqual(trace.stages.count, 1);
  415. FIRTrace *activeStage = [trace.stages lastObject];
  416. XCTAssertEqual(activeStage.backgroundTraceState, FPRTraceStateUnknown);
  417. }
  418. /** Validates that internal trace names allow the reserved prefix value. */
  419. - (void)testInternalTraceCreationWithInternalPrefix {
  420. FIRTrace *trace = [[FIRTrace alloc] initInternalTraceWithName:@"_Random"];
  421. XCTAssertNotNil(trace);
  422. NSString *metricName = @"_counter";
  423. [trace start];
  424. [trace startStageNamed:@"_1"];
  425. [trace incrementMetric:metricName byInt:5];
  426. [trace stop];
  427. XCTAssertEqual(trace.stages.count, 1);
  428. FIRTrace *stage1 = [trace.stages lastObject];
  429. XCTAssertEqual(stage1.name, @"_1");
  430. NSUInteger metricValue = [[trace.counters objectForKey:metricName] integerValue];
  431. XCTAssertEqual(metricValue, 5);
  432. }
  433. /** Validates if the metric is incremented if a trace is started but not stopped. */
  434. - (void)testTraceStartedNotStoppedIncrementsAMetric {
  435. NSNotificationCenter *defaultCenter = [NSNotificationCenter defaultCenter];
  436. [defaultCenter postNotificationName:UIWindowDidBecomeVisibleNotification
  437. object:[UIApplication sharedApplication]];
  438. [defaultCenter postNotificationName:UIApplicationDidBecomeActiveNotification
  439. object:[UIApplication sharedApplication]];
  440. FIRTrace *activeTrace = [FPRAppActivityTracker sharedInstance].activeTrace;
  441. NSNumber *metric = [activeTrace.counters objectForKey:kFPRAppCounterNameTraceNotStopped];
  442. NSInteger metricValue = [metric integerValue];
  443. __weak FIRTrace *weakReferencedTrace;
  444. @autoreleasepool {
  445. FIRTrace *trace = [[FIRTrace alloc] initWithName:@"Random"];
  446. weakReferencedTrace = trace;
  447. [trace start];
  448. [trace startStageNamed:@"1"];
  449. }
  450. XCTestExpectation *expectation = [self expectationWithDescription:@"Expectation - Wait for 2s"];
  451. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.0 * NSEC_PER_SEC)),
  452. dispatch_get_main_queue(), ^{
  453. [expectation fulfill];
  454. XCTAssertNil(weakReferencedTrace);
  455. });
  456. [self waitForExpectationsWithTimeout:10.0 handler:nil];
  457. NSNumber *updatedMetric = [activeTrace.counters objectForKey:kFPRAppCounterNameTraceNotStopped];
  458. NSInteger updatedMetricValue = [updatedMetric integerValue];
  459. XCTAssertEqual(updatedMetricValue - metricValue, 1);
  460. [defaultCenter postNotificationName:UIApplicationWillResignActiveNotification
  461. object:[UIApplication sharedApplication]];
  462. }
  463. /** Validates if the metric is not incremented if a trace is started and stopped. */
  464. - (void)testTraceStartedAndStoppedDoesNotIncrementAMetric {
  465. FIRTrace *activeTrace = [FPRAppActivityTracker sharedInstance].activeTrace;
  466. NSNumber *metric = [activeTrace.counters objectForKey:kFPRAppCounterNameTraceNotStopped];
  467. NSInteger metricValue = [metric integerValue];
  468. __weak FIRTrace *weakReferencedTrace;
  469. @autoreleasepool {
  470. FIRTrace *trace = [[FIRTrace alloc] initWithName:@"Random"];
  471. weakReferencedTrace = trace;
  472. [trace start];
  473. [trace startStageNamed:@"1"];
  474. [trace stop];
  475. }
  476. NSNumber *updatedMetric = [activeTrace.counters objectForKey:kFPRAppCounterNameTraceNotStopped];
  477. NSInteger updatedMetricValue = [updatedMetric integerValue];
  478. XCTAssertEqual(updatedMetricValue - metricValue, 0);
  479. }
  480. #pragma mark - Custom attribute related testing
  481. /** Validates if setting a valid attribute before calling start works. */
  482. - (void)testSettingValidAttributeBeforeStart {
  483. FIRTrace *trace = [[FIRTrace alloc] initWithName:@"Random"];
  484. [trace setValue:@"bar" forAttribute:@"foo"];
  485. XCTAssertEqual([trace valueForAttribute:@"foo"], @"bar");
  486. }
  487. /** Validates if setting a valid attribute works between start/stop works. */
  488. - (void)testSettingValidAttributeBetweenStartAndStop {
  489. FIRTrace *trace = [[FIRTrace alloc] initWithName:@"Random"];
  490. [trace start];
  491. [trace setValue:@"bar" forAttribute:@"foo"];
  492. XCTAssertEqual([trace valueForAttribute:@"foo"], @"bar");
  493. [trace stop];
  494. }
  495. /** Validates if setting a valid attribute works after stop is a no-op. */
  496. - (void)testSettingValidAttributeBetweenAfterStop {
  497. FIRTrace *trace = [[FIRTrace alloc] initWithName:@"Random"];
  498. [trace start];
  499. [trace stop];
  500. [trace setValue:@"bar" forAttribute:@"foo"];
  501. XCTAssertNil([trace valueForAttribute:@"foo"]);
  502. }
  503. /** Validates if attributes property access works. */
  504. - (void)testReadingAttributesFromProperty {
  505. FIRTrace *trace = [[FIRTrace alloc] initWithName:@"Random"];
  506. XCTAssertNotNil(trace.attributes);
  507. XCTAssertEqual(trace.attributes.count, 0);
  508. [trace setValue:@"bar" forAttribute:@"foo"];
  509. NSDictionary<NSString *, NSString *> *attributes = trace.attributes;
  510. XCTAssertEqual(attributes.allKeys.count, 1);
  511. }
  512. /** Validates if attributes property is immutable. */
  513. - (void)testImmutablityOfAttributesProperty {
  514. FIRTrace *trace = [[FIRTrace alloc] initWithName:@"Random"];
  515. [trace setValue:@"bar" forAttribute:@"foo"];
  516. NSMutableDictionary<NSString *, NSString *> *attributes =
  517. (NSMutableDictionary<NSString *, NSString *> *)trace.attributes;
  518. XCTAssertThrows([attributes setValue:@"bar1" forKey:@"foo"]);
  519. }
  520. /** Validates if updating attribute value works. */
  521. - (void)testUpdatingAttributeValue {
  522. FIRTrace *trace = [[FIRTrace alloc] initWithName:@"Random"];
  523. [trace setValue:@"bar" forAttribute:@"foo"];
  524. [trace setValue:@"baz" forAttribute:@"foo"];
  525. XCTAssertEqual([trace valueForAttribute:@"foo"], @"baz");
  526. [trace setValue:@"qux" forAttribute:@"foo"];
  527. XCTAssertEqual([trace valueForAttribute:@"foo"], @"qux");
  528. }
  529. /** Validates if removing attributes work before call to start. */
  530. - (void)testRemovingAttributeBeforeStart {
  531. FIRTrace *trace = [[FIRTrace alloc] initWithName:@"Random"];
  532. [trace setValue:@"bar" forAttribute:@"foo"];
  533. [trace removeAttribute:@"foo"];
  534. XCTAssertNil([trace valueForAttribute:@"foo"]);
  535. [trace removeAttribute:@"foo"];
  536. XCTAssertNil([trace valueForAttribute:@"foo"]);
  537. }
  538. /** Validates if removing attributes work between start and stop calls. */
  539. - (void)testRemovingAttributeBetweenStartStop {
  540. FIRTrace *trace = [[FIRTrace alloc] initWithName:@"Random"];
  541. [trace setValue:@"bar" forAttribute:@"foo"];
  542. [trace start];
  543. [trace removeAttribute:@"foo"];
  544. [trace stop];
  545. XCTAssertNil([trace valueForAttribute:@"foo"]);
  546. }
  547. /** Validates if removing attributes is a no-op after stop. */
  548. - (void)testRemovingAttributeBetweenAfterStop {
  549. FIRTrace *trace = [[FIRTrace alloc] initWithName:@"Random"];
  550. [trace setValue:@"bar" forAttribute:@"foo"];
  551. [trace start];
  552. [trace stop];
  553. [trace removeAttribute:@"foo"];
  554. XCTAssertEqual([trace valueForAttribute:@"foo"], @"bar");
  555. }
  556. /** Validates if removing non-existing attributes works. */
  557. - (void)testRemovingNonExistingAttribute {
  558. FIRTrace *trace = [[FIRTrace alloc] initWithName:@"Random"];
  559. [trace removeAttribute:@"foo"];
  560. XCTAssertNil([trace valueForAttribute:@"foo"]);
  561. [trace removeAttribute:@"foo"];
  562. XCTAssertNil([trace valueForAttribute:@"foo"]);
  563. }
  564. /** Validates if using reserved prefix in attribute prefix will drop the attribute. */
  565. - (void)testAttributeNamePrefixSrtipped {
  566. NSArray<NSString *> *reservedPrefix = @[ @"firebase_", @"google_", @"ga_" ];
  567. [reservedPrefix enumerateObjectsUsingBlock:^(NSString *prefix, NSUInteger idx, BOOL *stop) {
  568. NSString *attributeName = [NSString stringWithFormat:@"%@name", prefix];
  569. NSString *attributeValue = @"value";
  570. FIRTrace *trace = [[FIRTrace alloc] initWithName:@"Random"];
  571. [trace setValue:attributeValue forAttribute:attributeName];
  572. XCTAssertNil([trace valueForAttribute:attributeName]);
  573. }];
  574. }
  575. /** Validates if long attribute names gets dropped. */
  576. - (void)testMaxLengthForAttributeName {
  577. NSString *testName = [@"abc" stringByPaddingToLength:kFPRMaxAttributeNameLength + 1
  578. withString:@"-"
  579. startingAtIndex:0];
  580. FIRTrace *trace = [[FIRTrace alloc] initWithName:@"Random"];
  581. [trace setValue:@"bar" forAttribute:testName];
  582. XCTAssertNil([trace valueForAttribute:testName]);
  583. }
  584. /** Validates if attribute names with illegal characters gets dropped. */
  585. - (void)testIllegalCharactersInAttributeName {
  586. FIRTrace *trace = [[FIRTrace alloc] initWithName:@"Random"];
  587. [trace setValue:@"bar" forAttribute:@"foo_"];
  588. XCTAssertEqual([trace valueForAttribute:@"foo_"], @"bar");
  589. [trace setValue:@"bar" forAttribute:@"foo_$"];
  590. XCTAssertNil([trace valueForAttribute:@"foo_$"]);
  591. [trace setValue:@"bar" forAttribute:@"FOO_$"];
  592. XCTAssertNil([trace valueForAttribute:@"FOO_$"]);
  593. [trace setValue:@"bar" forAttribute:@"FOO_"];
  594. XCTAssertEqual([trace valueForAttribute:@"FOO_"], @"bar");
  595. }
  596. /** Validates if long attribute values gets truncated. */
  597. - (void)testMaxLengthForAttributeValue {
  598. NSString *testValue = [@"abc" stringByPaddingToLength:kFPRMaxAttributeValueLength + 1
  599. withString:@"-"
  600. startingAtIndex:0];
  601. FIRTrace *trace = [[FIRTrace alloc] initWithName:@"Random"];
  602. [trace setValue:testValue forAttribute:@"foo"];
  603. XCTAssertNil([trace valueForAttribute:@"foo"]);
  604. }
  605. /** Validates if empty name or value of the attributes are getting dropped. */
  606. - (void)testAttributesWithEmptyValues {
  607. FIRTrace *trace = [[FIRTrace alloc] initWithName:@"Random"];
  608. [trace setValue:@"" forAttribute:@"foo"];
  609. XCTAssertNil([trace valueForAttribute:@"foo"]);
  610. [trace setValue:@"bar" forAttribute:@""];
  611. XCTAssertNil([trace valueForAttribute:@""]);
  612. }
  613. /** Validates if the limit the maximum number of attributes work. */
  614. - (void)testMaximumNumberOfAttributes {
  615. FIRTrace *trace = [[FIRTrace alloc] initWithName:@"Random"];
  616. for (int i = 0; i < kFPRMaxGlobalCustomAttributesCount; i++) {
  617. NSString *attributeName = [NSString stringWithFormat:@"dim%d", i];
  618. [trace setValue:@"bar" forAttribute:attributeName];
  619. XCTAssertEqual([trace valueForAttribute:attributeName], @"bar");
  620. }
  621. [trace setValue:@"bar" forAttribute:@"foo"];
  622. XCTAssertNil([trace valueForAttribute:@"foo"]);
  623. }
  624. /** Validates if removing old attributes and adding new attributes work. */
  625. - (void)testRemovingAndAddingAttributes {
  626. FIRTrace *trace = [[FIRTrace alloc] initWithName:@"Random"];
  627. for (int i = 0; i < kFPRMaxGlobalCustomAttributesCount; i++) {
  628. NSString *attributeName = [NSString stringWithFormat:@"dim%d", i];
  629. [trace setValue:@"bar" forAttribute:attributeName];
  630. XCTAssertEqual([trace valueForAttribute:attributeName], @"bar");
  631. }
  632. [trace removeAttribute:@"dim1"];
  633. [trace setValue:@"bar" forAttribute:@"foo"];
  634. XCTAssertEqual([trace valueForAttribute:@"foo"], @"bar");
  635. }
  636. /** Validates if every trace contains a session Id. */
  637. - (void)testSessionId {
  638. [[FPRSessionManager sharedInstance] updateSessionId:@"testSessionId"];
  639. FIRTrace *trace = [[FIRTrace alloc] initWithName:@"Random"];
  640. [trace start];
  641. [trace stop];
  642. XCTAssertNotNil(trace.sessions);
  643. XCTAssertTrue(trace.sessions.count > 0);
  644. }
  645. /** Validates if every trace contains multiple session Ids on changing app state. */
  646. - (void)testMultipleSessionIds {
  647. [[FPRSessionManager sharedInstance] updateSessionId:@"testSessionId"];
  648. FIRTrace *trace = [[FIRTrace alloc] initWithName:@"Random"];
  649. [trace start];
  650. [[FPRSessionManager sharedInstance] updateSessionId:@"testSessionId2"];
  651. [[FPRSessionManager sharedInstance] updateSessionId:@"testSessionId3"];
  652. XCTestExpectation *expectation = [self expectationWithDescription:@"Expectation - Wait for 2s"];
  653. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.0 * NSEC_PER_SEC)),
  654. dispatch_get_main_queue(), ^{
  655. [expectation fulfill];
  656. [trace stop];
  657. XCTAssertNotNil(trace.sessions);
  658. XCTAssertTrue(trace.sessions.count >= 2);
  659. });
  660. [self waitForExpectationsWithTimeout:10.0 handler:nil];
  661. }
  662. @end