FIRTraceTest.m 31 KB

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