2 * Copyright (c) 2017 Apple Inc. All Rights Reserved.
4 * @APPLE_LICENSE_HEADER_START@
6 * This file contains Original Code and/or Modifications of Original Code
7 * as defined in and that are subject to the Apple Public Source License
8 * Version 2.0 (the 'License'). You may not use this file except in
9 * compliance with the License. Please obtain a copy of the License at
10 * http://www.opensource.apple.com/apsl/ and read it before using this
13 * The Original Code and all software distributed under the License are
14 * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
15 * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
16 * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
17 * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
18 * Please see the License for the specific language governing rights and
19 * limitations under the License.
21 * @APPLE_LICENSE_HEADER_END@
24 #import <XCTest/XCTest.h>
25 #import <Security/SFAnalytics.h>
26 #import "SFAnalytics+Internal.h"
27 #import "SFAnalyticsDefines.h"
28 #import "SFAnalyticsSQLiteStore.h"
29 #import "NSDate+SFAnalytics.h"
31 #import <Prequelite/Prequelite.h>
32 #import <CoreFoundation/CFPriv.h>
34 #import "keychain/analytics/TestResourceUsage.h"
36 @interface UnitTestAnalytics : SFAnalytics
37 + (NSString*)databasePath;
38 + (void)setDatabasePath:(NSString*)path;
41 // MARK: SFAnalytics subclass for custom DB
43 @implementation UnitTestAnalytics
44 static NSString* _utapath;
46 + (NSString*)databasePath
51 + (void)setDatabasePath:(NSString*)path
58 @interface SFAnalyticsTests : XCTestCase
61 @implementation SFAnalyticsTests
63 UnitTestAnalytics* _analytics;
68 static NSString* _path;
69 static NSInteger _testnum;
70 static NSString* build = NULL;
71 static NSString* product = NULL;
72 static NSString* modelID = nil;
74 // MARK: Test helper methods
76 - (void)assertNoSuccessEvents
78 XCTAssertFalse([[_db fetch:@"select * from success_count"] next]);
81 - (void)assertNoHardFailures
83 XCTAssertFalse([[_db fetch:@"select * from hard_failures"] next]);
86 - (void)assertNoSoftFailures
88 XCTAssertFalse([[_db fetch:@"select * from soft_failures"] next]);
93 XCTAssertFalse([[_db fetch:@"select * from notes"] next]);
96 - (void)assertNoSamples
98 XCTAssertFalse([[_db fetch:@"select * from samples"] next]);
101 - (void)assertNoEventsAnywhere
103 [self assertNoNotes];
104 [self assertNoSuccessEvents];
105 [self assertNoHardFailures];
106 [self assertNoSoftFailures];
107 [self assertNoSamples];
110 - (void)recentTimeStamp:(NSTimeInterval)timestamp timestampBucket:(SFAnalyticsTimestampBucket)bucket
112 NSTimeInterval roundedTimestamp = [[NSDate date] timeIntervalSince1970WithBucket:bucket];
113 XCTAssertEqualWithAccuracy(roundedTimestamp, timestamp, 5, @"Timestamp is pretty recent (%f ~? %f)", timestamp, roundedTimestamp);
116 - (void)properEventLogged:(PQLResultSet*)result eventType:(NSString*)eventType class:(SFAnalyticsEventClass)class attributes:(NSDictionary*)attrs
118 [self _properEventLogged:result eventType:eventType class:class];
120 NSDictionary* rowdata = [NSPropertyListSerialization propertyListWithData:[result dataAtIndex:2] options:NSPropertyListImmutable format:nil error:nil];
121 for (NSString* key in [attrs allKeys]) {
122 XCTAssert([attrs[key] isEqualToString:rowdata[key]], @"Attribute \"%@\" value \"%@\" matches expected \"%@\"", key, rowdata[key], attrs[key]);
124 XCTAssertFalse([result next], @"only one row returned");
127 - (void)properEventLogged:(PQLResultSet*)result eventType:(NSString*)eventType class:(SFAnalyticsEventClass)class
129 [self _properEventLogged:result eventType:eventType class:class];
130 XCTAssertFalse([result next], @"only one row returned");
133 - (void)properEventLogged:(PQLResultSet*)result eventType:(NSString*)eventType class:(SFAnalyticsEventClass)class timestampBucket:(SFAnalyticsTimestampBucket)bucket
135 [self _properEventLogged:result eventType:eventType class:class timestampBucket:bucket];
136 XCTAssertFalse([result next], @"only one row returned");
139 - (void)_properEventLogged:(PQLResultSet*)result eventType:(NSString*)eventType class:(SFAnalyticsEventClass)class
141 [self _properEventLogged:result eventType:eventType class:class timestampBucket:SFAnalyticsTimestampBucketSecond];
144 - (void)_properEventLogged:(PQLResultSet*)result eventType:(NSString*)eventType class:(SFAnalyticsEventClass)class timestampBucket:(SFAnalyticsTimestampBucket)bucket
146 XCTAssert([result next], @"result found after adding an event");
147 NSError* error = nil;
148 [result doubleAtIndex:1];
149 NSDictionary* rowdata = [NSPropertyListSerialization propertyListWithData:[result dataAtIndex:2] options:NSPropertyListImmutable format:nil error:&error];
150 XCTAssertNotNil(rowdata, @"able to deserialize db data, %@", error);
151 NSNumber *timestamp = rowdata[SFAnalyticsEventTime];
152 XCTAssert([timestamp isKindOfClass:[NSNumber class]], @"Timestamp is an NSNumber");
153 [self recentTimeStamp:([timestamp doubleValue] / 1000) timestampBucket:bucket]; // We need to convert to seconds, as its stored in milliseconds
154 XCTAssertTrue([rowdata[SFAnalyticsEventType] isKindOfClass:[NSString class]] && [rowdata[SFAnalyticsEventType] isEqualToString:eventType], @"found eventType \"%@\" in db", eventType);
155 XCTAssertTrue([rowdata[SFAnalyticsEventClassKey] isKindOfClass:[NSNumber class]] && [rowdata[SFAnalyticsEventClassKey] intValue] == class, @"eventClass is %ld", (long)class);
156 XCTAssertTrue([rowdata[@"build"] isEqualToString:build], @"event row includes build");
157 XCTAssertTrue([rowdata[@"product"] isEqualToString:product], @"event row includes product");
158 XCTAssertTrue([rowdata[@"modelid"] isEqualToString:modelID], @"event row includes modelid");
159 XCTAssertTrue(rowdata[@"internal"], @"event row includes internal");
162 - (void)checkSuccessCountsForEvent:(NSString*)eventType success:(int)success hard:(int)hard soft:(int)soft
164 PQLResultSet* result = [_db fetch:@"select * from success_count where event_type = %@", eventType];
165 XCTAssert([result next]);
166 XCTAssertTrue([[result stringAtIndex:0] isEqualToString:eventType], @"event name \"%@\", expected \"%@\"", [result stringAtIndex:0], eventType);
167 XCTAssertEqual([result intAtIndex:1], success, @"correct count of successes: %d / %d", [result intAtIndex:1], success);
168 XCTAssertEqual([result intAtIndex:2], hard, @"correct count of successes: %d / %d", [result intAtIndex:2], hard);
169 XCTAssertEqual([result intAtIndex:3], soft, @"correct count of successes: %d / %d", [result intAtIndex:3], soft);
170 XCTAssertFalse([result next], @"no more than one row returned");
173 - (void)checkSamples:(NSArray*)samples name:(NSString*)samplerName totalSamples:(NSUInteger)total accuracy:(double)accuracy
175 NSUInteger samplescount = 0, targetcount = 0;
176 NSMutableArray* samplesfound = [NSMutableArray array];
177 PQLResultSet* result = [_db fetch:@"select * from samples"];
178 while ([result next]) {
180 [self recentTimeStamp:[[result numberAtIndex:1] doubleValue] timestampBucket:SFAnalyticsTimestampBucketSecond];
181 if ([[result stringAtIndex:2] isEqual:samplerName]) {
183 [samplesfound addObject:[result numberAtIndex:3]];
187 XCTAssertEqual([samples count], targetcount);
188 XCTAssertEqual(samplescount, total);
190 [samplesfound sortUsingSelector:@selector(compare:)];
191 NSArray* sortedInput = [samples sortedArrayUsingSelector:@selector(compare:)];
192 for (NSUInteger idx = 0; idx < [samples count]; ++idx) {
193 XCTAssertEqualWithAccuracy([samplesfound[idx] doubleValue], [sortedInput[idx] doubleValue], accuracy);
197 - (void)waitForSamplerWork:(double)interval
199 dispatch_semaphore_t sema = dispatch_semaphore_create(0);
200 dispatch_after(dispatch_time(DISPATCH_TIME_NOW, NSEC_PER_SEC * interval), dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^{
201 dispatch_semaphore_signal(sema);
203 dispatch_semaphore_wait(sema, DISPATCH_TIME_FOREVER);
206 // MARK: Test administration
211 _path = [NSTemporaryDirectory() stringByAppendingPathComponent:[NSString stringWithFormat:@"%@/", [[NSUUID UUID] UUIDString]]];
212 [[NSFileManager defaultManager] createDirectoryAtPath:_path
213 withIntermediateDirectories:YES
216 // No XCTAssert in class method
218 NSLog(@"Could not make directory at %@", _path);
220 NSDictionary *version = CFBridgingRelease(_CFCopySystemVersionDictionary());
222 build = version[(__bridge NSString *)_kCFSystemVersionBuildVersionKey];
223 product = version[(__bridge NSString *)_kCFSystemVersionProductNameKey];
225 NSLog(@"could not get build version/product, tests should fail");
228 modelID = [SFAnalytics hwModelID];
230 [TestResourceUsage monitorTestResourceUsage];
236 self.continueAfterFailure = NO;
237 NSError* error = nil;
238 _dbpath = [_path stringByAppendingFormat:@"/test_%ld.db", (long)++_testnum];
239 NSLog(@"sqlite3 %@", _dbpath);
240 [UnitTestAnalytics setDatabasePath:_dbpath];
241 _analytics = [UnitTestAnalytics logger];
242 _db = [PQLConnection new];
244 XCTAssertTrue([_db openAtURL:[NSURL URLWithString:_dbpath] sharedCache:NO error:&error]);
245 XCTAssertNil(error, @"could open db");
246 XCTAssertNotNil(_db);
251 NSError *error = nil;
252 XCTAssertTrue([_db close:&error], @"could close db");
253 XCTAssertNil(error, @"No error from closing db");
254 [_analytics removeState];
260 [[NSFileManager defaultManager] removeItemAtPath:_path error:nil];
263 // MARK: SFAnalytics Tests
265 - (void)testDbIsEmptyAtStartup
267 [self assertNoEventsAnywhere];
270 - (void)testDontCrashWithEmptyDBPath
272 NSString* schema = @"CREATE TABLE IF NOT EXISTS test (id INTEGER PRIMARY KEY AUTOINCREMENT,data BLOB);";
273 NSString* path = [NSString stringWithFormat:@"%@/empty", _path];
275 XCTAssertNil([SFAnalyticsSQLiteStore storeWithPath:nil schema:schema]);
276 XCTAssertNil([SFAnalyticsSQLiteStore storeWithPath:@"" schema:schema]);
277 XCTAssertNil([SFAnalyticsSQLiteStore storeWithPath:path schema:nil]);
278 XCTAssertNil([SFAnalyticsSQLiteStore storeWithPath:path schema:@""]);
280 XCTAssertNil([[SFSQLite alloc] initWithPath:nil schema:schema]);
281 XCTAssertNil([[SFSQLite alloc] initWithPath:@"" schema:schema]);
282 XCTAssertNil([[SFSQLite alloc] initWithPath:path schema:nil]);
283 XCTAssertNil([[SFSQLite alloc] initWithPath:path schema:@""]);
286 - (void)testAddingEventsWithNilName
288 #pragma clang diagnostic push
289 #pragma clang diagnostic ignored "-Wnonnull"
290 [_analytics logSuccessForEventNamed:nil];
291 [self assertNoEventsAnywhere];
293 [_analytics logHardFailureForEventNamed:nil withAttributes:nil];
294 [self assertNoEventsAnywhere];
296 [_analytics logSoftFailureForEventNamed:nil withAttributes:nil];
297 [self assertNoEventsAnywhere];
299 [_analytics noteEventNamed:nil];
300 [self assertNoEventsAnywhere];
301 #pragma clang diagnostic pop
304 - (void)testLogSuccess
306 [_analytics logSuccessForEventNamed:@"unittestevent"];
307 [self assertNoHardFailures];
308 [self assertNoSoftFailures];
310 PQLResultSet* result = [_db fetch:@"select success_count from success_count"];
311 XCTAssert([result next], @"a row was found after adding an event");
312 XCTAssertEqual([result intAtIndex:0], 1, @"success count is 1 after adding an event");
313 XCTAssertFalse([result next], @"only one row found in success_count after inserting a single event");
314 [self assertNoNotes];
315 [self assertNoHardFailures];
316 [self assertNoSoftFailures];
319 - (void)testLogWithRoundedTimestamp
321 SFAnalyticsTimestampBucket bucket = SFAnalyticsTimestampBucketMinute;
323 [_analytics logSoftFailureForEventNamed:@"unittestevent" withAttributes:nil timestampBucket:bucket];
324 [self assertNoHardFailures];
326 // First check success_count has logged a soft failure
327 [self checkSuccessCountsForEvent:@"unittestevent" success:0 hard:0 soft:1];
329 // then check soft_failures itself
330 PQLResultSet* result = [_db fetch:@"select * from soft_failures"];
331 [self properEventLogged:result eventType:@"unittestevent" class:SFAnalyticsEventClassSoftFailure timestampBucket:bucket];
332 [self assertNoNotes];
333 [self assertNoHardFailures];
336 - (void)testLogRecoverableFailure
338 [_analytics logSoftFailureForEventNamed:@"unittestevent" withAttributes:nil];
339 [self assertNoHardFailures];
341 // First check success_count has logged a soft failure
342 [self checkSuccessCountsForEvent:@"unittestevent" success:0 hard:0 soft:1];
344 // then check soft_failures itself
345 PQLResultSet* result = [_db fetch:@"select * from soft_failures"];
346 [self properEventLogged:result eventType:@"unittestevent" class:SFAnalyticsEventClassSoftFailure];
347 [self assertNoNotes];
348 [self assertNoHardFailures];
351 - (void)testLogRecoverablyFailureWithAttributes
353 NSDictionary* attrs = @{@"attr1" : @"value1", @"attr2" : @"value2"};
354 [_analytics logSoftFailureForEventNamed:@"unittestevent" withAttributes:attrs];
355 [self assertNoHardFailures];
357 [self checkSuccessCountsForEvent:@"unittestevent" success:0 hard:0 soft:1];
359 // then check soft_failures itself
360 PQLResultSet* result = [_db fetch:@"select * from soft_failures"];
361 [self properEventLogged:result eventType:@"unittestevent" class:SFAnalyticsEventClassSoftFailure attributes:attrs];
362 [self assertNoNotes];
363 [self assertNoHardFailures];
366 - (void)testLogUnrecoverableFailure
368 [_analytics logHardFailureForEventNamed:@"unittestevent" withAttributes:nil];
369 [self assertNoSoftFailures];
371 // First check success_count has logged a hard failure
372 [self checkSuccessCountsForEvent:@"unittestevent" success:0 hard:1 soft:0];
374 // then check hard_failures itself
375 PQLResultSet* result = [_db fetch:@"select * from hard_failures"];
376 [self properEventLogged:result eventType:@"unittestevent" class:SFAnalyticsEventClassHardFailure];
377 [self assertNoNotes];
378 [self assertNoSoftFailures];
381 - (void)testLogUnrecoverableFailureWithAttributes
383 NSDictionary* attrs = @{@"attr1" : @"value1", @"attr2" : @"value2"};
384 [_analytics logHardFailureForEventNamed:@"unittestevent" withAttributes:attrs];
385 [self assertNoSoftFailures];
387 // First check success_count has logged a hard failure
388 [self checkSuccessCountsForEvent:@"unittestevent" success:0 hard:1 soft:0];
390 // then check hard_failures itself
391 PQLResultSet* result = [_db fetch:@"select * from hard_failures"];
392 [self properEventLogged:result eventType:@"unittestevent" class:SFAnalyticsEventClassHardFailure attributes:attrs];
393 [self assertNoNotes];
394 [self assertNoSoftFailures];
397 - (void)testLogSeveralEvents
399 NSDictionary* attrs = @{@"attr1" : @"value1", @"attr2" : @"value2"};
400 int iterations = 100;
401 for (int idx = 0; idx < iterations; ++idx) {
402 [_analytics logHardFailureForEventNamed:@"unittesthardfailure" withAttributes:attrs];
403 [_analytics logSoftFailureForEventNamed:@"unittestsoftfailure" withAttributes:attrs];
404 [_analytics logSuccessForEventNamed:@"unittestsuccess"];
405 [_analytics logHardFailureForEventNamed:@"unittestcombined" withAttributes:attrs];
406 [_analytics logSoftFailureForEventNamed:@"unittestcombined" withAttributes:attrs];
407 [_analytics logSuccessForEventNamed:@"unittestcombined"];
410 [self checkSuccessCountsForEvent:@"unittesthardfailure" success:0 hard:iterations soft:0];
411 [self checkSuccessCountsForEvent:@"unittestsoftfailure" success:0 hard:0 soft:iterations];
412 [self checkSuccessCountsForEvent:@"unittestsuccess" success:iterations hard:0 soft:0];
413 [self checkSuccessCountsForEvent:@"unittestcombined" success:iterations hard:iterations soft:iterations];
416 - (void)testNoteEvent
418 [_analytics noteEventNamed:@"unittestevent"];
419 [self assertNoSoftFailures];
420 [self assertNoHardFailures];
422 // First check success_count has logged a success
423 [self checkSuccessCountsForEvent:@"unittestevent" success:1 hard:0 soft:0];
425 PQLResultSet* result = [_db fetch:@"select * from notes"];
426 [self properEventLogged:result eventType:@"unittestevent" class:SFAnalyticsEventClassNote];
429 // MARK: SFAnalyticsSampler Tests
431 - (void)testSamplerSimple
433 NSString* samplerName = [NSString stringWithFormat:@"UnitTestSamplerSimple_%li", (long)_testnum];
435 // This block should be set immediately and fire in 1000ms. Give it a little slack in checking though
436 XCTestExpectation* exp = [self expectationWithDescription:@"waiting for sampler to fire"];
437 [_analytics addMetricSamplerForName:samplerName withTimeInterval:1.0f block:^NSNumber *{
441 [self waitForExpectations:@[exp] timeout:1.2f];
442 [_analytics removeMetricSamplerForName:samplerName];
444 // The expectation is fulfilled before returning and after returning some more work needs to happen. Let it settle down.
445 [self waitForSamplerWork:0.2f];
447 [self checkSamples:@[@15.3] name:samplerName totalSamples:1 accuracy:0.01f];
450 // Test state removal mostly
451 - (void)testSamplerSimpleLoop
454 for (int idx = 0; idx < 3; ++idx) {
457 [self testSamplerSimple];
464 - (void)testSamplerDoesNotFirePrematurely
466 NSString* samplerName = [NSString stringWithFormat:@"UnitTestSamplerDoesNotFirePrematurely_%li", (long)_testnum];
467 __block BOOL run = NO;
468 [_analytics addMetricSamplerForName:samplerName withTimeInterval:1.0f block:^NSNumber *{
473 [self waitForSamplerWork:0.5f];
474 XCTAssertFalse(run, @"sample did not fire prematurely");
475 [_analytics removeMetricSamplerForName:samplerName];
478 - (void)testSamplerRemove
480 NSString* samplerName = [NSString stringWithFormat:@"UnitTestSamplerRemove_%li", (long)_testnum];
481 __block BOOL run = NO;
482 [_analytics addMetricSamplerForName:samplerName withTimeInterval:1.0f block:^NSNumber *{
486 XCTAssertNotNil([_analytics existingMetricSamplerForName:samplerName], @"SFAnalytics held onto the sampler we setup");
487 [_analytics removeMetricSamplerForName:samplerName];
488 XCTAssertNil([_analytics existingMetricSamplerForName:samplerName], @"SFAnalytics got rid of our sampler");
490 [self waitForSamplerWork:2.0f];
491 XCTAssertFalse(run, @"sampler did not run after removal");
494 - (void)testSamplerRepeatedSampling
496 NSString* samplerName = [NSString stringWithFormat:@"UnitTestSamplerRepeatedSampling_%li", (long)_testnum];
498 [_analytics addMetricSamplerForName:samplerName withTimeInterval:1.0f block:^NSNumber *{
503 [self waitForSamplerWork:3.5f];
504 [_analytics removeMetricSamplerForName:samplerName];
505 XCTAssertEqual(run, 3, @"sampler ran correct number of times");
506 [self checkSamples:@[@1.5, @1.5, @1.5] name:samplerName totalSamples:3 accuracy:0.01f];
509 - (void)testSamplerDisable
511 NSString* samplerName = [NSString stringWithFormat:@"UnitTestSamplerDisable_%li", (long)_testnum];
513 [_analytics addMetricSamplerForName:samplerName withTimeInterval:1.0f block:^NSNumber *{
518 [[_analytics existingMetricSamplerForName:samplerName] pauseSampling];
519 [self waitForSamplerWork:2.0f];
520 XCTAssertEqual(run, 0, @"sampler did not run while disabled");
522 [[_analytics existingMetricSamplerForName:samplerName] resumeSampling];
523 [self waitForSamplerWork:1.3f];
524 XCTAssertEqual(run, 1, @"sampler ran after resuming");
526 [self checkSamples:@[@44.9] name:samplerName totalSamples:1 accuracy:0.01f];
529 - (void)testSamplerWithBadData
531 #pragma clang diagnostic push
532 #pragma clang diagnostic ignored "-Wnonnull"
533 NSString* samplerName = [NSString stringWithFormat:@"UnitTestSamplerWithBadData_%li", (long)_testnum];
536 XCTAssertNil([_analytics addMetricSamplerForName:nil withTimeInterval:3.0f block:^NSNumber *{
541 XCTAssertNil([_analytics addMetricSamplerForName:samplerName withTimeInterval:0.0f block:^NSNumber *{
545 XCTAssertNil([_analytics addMetricSamplerForName:samplerName withTimeInterval:2.0f block:nil]);
546 #pragma clang diagnostic pop
549 - (void)testSamplerOncePerReport
551 NSString* samplerName = [NSString stringWithFormat:@"UnitTestSamplerOncePerReport_%li", (long)_testnum];
553 [_analytics addMetricSamplerForName:samplerName withTimeInterval:SFAnalyticsSamplerIntervalOncePerReport block:^NSNumber *{
558 // There's no point in waiting, it could have been set to some arbitrarily long timer instead
560 notify_post(SFAnalyticsFireSamplersNotification);
561 [self waitForSamplerWork:0.5f];
562 XCTAssertEqual(run, 1, @"once-per-report sampler fired once in response to notification");
563 [self checkSamples:@[@74.1] name:samplerName totalSamples:1 accuracy:0.01f];
566 - (void)testSamplerOncePerReportEnsuresSingleSampleInDatabase
568 NSString* samplerName = [NSString stringWithFormat:@"UnitTestSamplerSetTimeInterval_%li", (long)_testnum];
569 [_analytics addMetricSamplerForName:samplerName withTimeInterval:SFAnalyticsSamplerIntervalOncePerReport block:^NSNumber *{
572 notify_post(SFAnalyticsFireSamplersNotification);
573 [self waitForSamplerWork:0.5f];
574 notify_post(SFAnalyticsFireSamplersNotification);
575 [self waitForSamplerWork:0.5f];
576 [self checkSamples:@[@57.6] name:samplerName totalSamples:1 accuracy:0.01f];
579 - (void)testSamplerAddSamplerTwice
581 NSString* samplerName = [NSString stringWithFormat:@"UnitTestSamplerDisable_%li", (long)_testnum];
582 XCTAssertNotNil([_analytics addMetricSamplerForName:samplerName withTimeInterval:3.0f block:^NSNumber *{
584 }], @"adding first sampler works okay");
586 XCTAssertNil([_analytics addMetricSamplerForName:samplerName withTimeInterval:3.0f block:^NSNumber *{
588 }], @"adding duplicate sampler did not work");
591 - (void)testSamplerLogBadSample
593 #pragma clang diagnostic push
594 #pragma clang diagnostic ignored "-Wnonnull"
595 [_analytics logMetric:nil withName:@"testsampler"];
596 [self checkSamples:@[] name:@"testsampler" totalSamples:0 accuracy:0.01f];
597 #pragma clang diagnostic pop
599 id badobj = [NSString stringWithUTF8String:"yolo!"];
600 [_analytics logMetric:badobj withName:@"testSampler"];
601 [self checkSamples:@[] name:@"testsampler" totalSamples:0 accuracy:0.01f];
604 - (void)testSamplerSetTimeInterval
606 NSString* samplerName = [NSString stringWithFormat:@"UnitTestSamplerSetTimeInterval_%li", (long)_testnum];
607 __block NSUInteger run = 0;
609 [_analytics addMetricSamplerForName:samplerName withTimeInterval:1.0f block:^NSNumber *{
613 [self waitForSamplerWork:1.2f];
614 [_analytics existingMetricSamplerForName:samplerName].samplingInterval = 1.5f;
615 [self waitForSamplerWork:2.5f];
616 XCTAssertEqual(run, 2ul);
617 [self checkSamples:@[@23.8, @23.8] name:samplerName totalSamples:2 accuracy:0.01f];
620 // MARK: SFAnalyticsMultiSampler Tests
622 - (void)testMultiSamplerSimple
624 NSString* samplerName = [NSString stringWithFormat:@"UnitTestMultiSamplerSimple_%li", (long)_testnum];
626 XCTestExpectation* exp = [self expectationWithDescription:@"waiting for sampler to fire"];
627 [_analytics AddMultiSamplerForName:samplerName withTimeInterval:1.0f block:^NSDictionary<NSString *,NSNumber *> *{
629 return @{@"val1" : @89.4f, @"val2" : @11.2f};
631 [self waitForExpectations:@[exp] timeout:1.3f];
632 [_analytics removeMultiSamplerForName:samplerName];
634 // The expectation is fulfilled before returning and after returning some more work needs to happen. Let it settle down.
635 [self waitForSamplerWork:0.2f];
637 [self checkSamples:@[@89.4f] name:@"val1" totalSamples:2 accuracy:0.01f];
638 [self checkSamples:@[@11.2f] name:@"val2" totalSamples:2 accuracy:0.01f];
641 - (void)testMultiSamplerOncePerReport
643 NSString* samplerName = [NSString stringWithFormat:@"UnitTestMultiSamplerOncePerReport_%li", (long)_testnum];
645 [_analytics AddMultiSamplerForName:samplerName withTimeInterval:SFAnalyticsSamplerIntervalOncePerReport block:^NSDictionary<NSString *,NSNumber *> *{
647 return @{@"val1" : @33.8f, @"val2" : @54.6f};
650 // There's no point in waiting, it could have been set to some arbitrarily long timer instead
652 notify_post(SFAnalyticsFireSamplersNotification);
653 [self waitForSamplerWork:1.0f];
654 XCTAssertEqual(run, 1, @"once-per-report sampler fired once in response to notification");
655 [self checkSamples:@[@33.8f] name:@"val1" totalSamples:2 accuracy:0.01f];
656 [self checkSamples:@[@54.6f] name:@"val2" totalSamples:2 accuracy:0.01f];
659 - (void)testMultiSamplerSetTimeInterval
661 NSString* samplerName = [NSString stringWithFormat:@"UnitTestMultiSamplerSetTimeInterval_%li", (long)_testnum];
662 __block NSUInteger run = 0;
663 [_analytics AddMultiSamplerForName:samplerName withTimeInterval:1.0f block:^NSDictionary<NSString *,NSNumber *> *{
665 return @{@"val1" : @29.3f, @"val2" : @19.3f};
667 [self waitForSamplerWork:1.2f];
668 [_analytics existingMultiSamplerForName:samplerName].samplingInterval = 1.5f;
669 [self waitForSamplerWork:2.5f];
670 XCTAssertEqual(run, 2ul);
671 [self checkSamples:@[@29.3f, @29.3f] name:@"val1" totalSamples:4 accuracy:0.01f];
672 [self checkSamples:@[@19.3f, @19.3f] name:@"val2" totalSamples:4 accuracy:0.01f];
676 // MARK: SFAnalyticsActivityTracker Tests
678 - (void)testTrackerSimple
680 NSString* trackerName = @"UnitTestTrackerSimple";
682 [_analytics logSystemMetricsForActivityNamed:trackerName withAction:^{
683 [NSThread sleepForTimeInterval:0.3f];
688 [self checkSamples:@[@(0.3f * NSEC_PER_SEC)] name:trackerName totalSamples:1 accuracy:(0.05f * NSEC_PER_SEC)];
691 - (void)testTrackerMultipleBlocks
693 NSString* trackerName = @"UnitTestTrackerMultipleBlocks";
695 SFAnalyticsActivityTracker* tracker = [_analytics logSystemMetricsForActivityNamed:trackerName withAction:^{
696 [NSThread sleepForTimeInterval:0.3f];
699 [tracker performAction:^{
700 [NSThread sleepForTimeInterval:0.2f];
704 [self checkSamples:@[@(0.5f * NSEC_PER_SEC)] name:trackerName totalSamples:1 accuracy:(0.1f * NSEC_PER_SEC)];
707 - (void)testTrackerAction
709 NSString* trackerName = @"UnitTestTrackerOneBlock";
711 SFAnalyticsActivityTracker* tracker = [_analytics logSystemMetricsForActivityNamed:trackerName withAction:NULL];
712 [tracker performAction:^{
713 [NSThread sleepForTimeInterval:0.2f];
717 [self checkSamples:@[@(0.2f * NSEC_PER_SEC)] name:trackerName totalSamples:1 accuracy:(0.1f * NSEC_PER_SEC)];
720 - (void)testTrackerStartStop {
722 NSString* trackerName = @"UnitTestTrackerStartStop";
724 SFAnalyticsActivityTracker* tracker = [_analytics logSystemMetricsForActivityNamed:trackerName withAction:NULL];
726 [NSThread sleepForTimeInterval:0.2f];
730 [self checkSamples:@[@(0.2f * NSEC_PER_SEC)] name:trackerName totalSamples:1 accuracy:(0.1f * NSEC_PER_SEC)];
733 - (void)testTrackerCancel
735 NSString* trackerName = @"UnitTestTrackerCancel";
737 [[_analytics logSystemMetricsForActivityNamed:trackerName withAction:^{
738 [NSThread sleepForTimeInterval:0.3f];
742 [self assertNoEventsAnywhere];
747 - (void)testTrackerBadData
749 #pragma clang diagnostic push
750 #pragma clang diagnostic ignored "-Wnonnull"
751 // Inspect database to find out it's empty
752 [_analytics logMetric:nil withName:@"fake"];
753 [_analytics logMetric:@3.0 withName:nil];
755 // get object back so inspect that, too
756 XCTAssertNil([_analytics logSystemMetricsForActivityNamed:nil withAction:^{return;}]);
758 [self assertNoEventsAnywhere];
759 #pragma clang diagnostic pop
762 // MARK: Miscellaneous
764 - (void)testInstantiateBaseClass
766 XCTAssertNil([SFAnalytics logger]);
769 - (void)testFuzzyDaysSinceDate
771 NSInteger secondsPerDay = 60 * 60 * 24;
772 XCTAssertEqual([SFAnalytics fuzzyDaysSinceDate:[NSDate date]], 0);
773 XCTAssertEqual([SFAnalytics fuzzyDaysSinceDate:[NSDate dateWithTimeIntervalSinceNow:secondsPerDay * -3]], 1);
774 XCTAssertEqual([SFAnalytics fuzzyDaysSinceDate:[NSDate dateWithTimeIntervalSinceNow:secondsPerDay * -18]], 7);
775 XCTAssertEqual([SFAnalytics fuzzyDaysSinceDate:[NSDate dateWithTimeIntervalSinceNow:secondsPerDay * -77]], 30);
776 XCTAssertEqual([SFAnalytics fuzzyDaysSinceDate:[NSDate dateWithTimeIntervalSinceNow:secondsPerDay * -370]], 365);
777 XCTAssertEqual([SFAnalytics fuzzyDaysSinceDate:[NSDate distantPast]], 1000);
778 #pragma clang diagnostic push
779 #pragma clang diagnostic ignored "-Wnonnull"
780 XCTAssertEqual([SFAnalytics fuzzyDaysSinceDate:nil], -1);
781 #pragma clang diagnostic pop
784 - (void)testRingBuffer {
785 [self assertNoEventsAnywhere];
786 for (unsigned idx = 0; idx < (SFAnalyticsMaxEventsToReport + 50); ++idx) {
787 [_analytics logHardFailureForEventNamed:@"ringbufferevent" withAttributes:nil];
790 PQLResultSet* result = [_db fetch:@"select count(*) from hard_failures"];
791 XCTAssertTrue([result next], @"Got a count from hard_failures");
792 XCTAssertLessThanOrEqual([result unsignedIntAtIndex:0], SFAnalyticsMaxEventsToReport, @"Ring buffer contains a sane number of events");
795 - (void)testRaceToCreateLoggers
797 dispatch_semaphore_t semaphore = dispatch_semaphore_create(0);
798 for (NSInteger idx = 0; idx < 500; ++idx) {
799 dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
800 UnitTestAnalytics* logger = [UnitTestAnalytics logger];
801 [logger logSuccessForEventNamed:@"testevent"];
802 dispatch_semaphore_signal(semaphore);
806 for (NSInteger idx = 0; idx < 500; ++idx) {
807 dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);
811 - (void)testDateProperty
813 NSString* propertyKey = @"testDataPropertyKey";
814 XCTAssertNil([_analytics datePropertyForKey:propertyKey]);
815 NSDate* test = [NSDate date];
816 [_analytics setDateProperty:test forKey:propertyKey];
817 NSDate* retrieved = [_analytics datePropertyForKey:propertyKey];
818 XCTAssertNotNil(retrieved);
819 // Storing in SQLite as string loses subsecond resolution, so we need some slack
820 XCTAssertEqualWithAccuracy([test timeIntervalSinceDate:retrieved], 0, 1);
822 [_analytics setDateProperty:nil forKey:propertyKey];
823 XCTAssertNil([_analytics datePropertyForKey:propertyKey]);