FIRTraceTest.m 31 KB

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