4 // Stolen from Mark Pauley / CDEntitledTestRunner who stole it from Drew Terry / MobileContainerManager
5 // Copyright 2016-2018 Apple. All rights reserved.
8 #import <Foundation/Foundation.h>
10 #import <XCTest/XCTest.h>
12 @interface TestRunner : NSObject <XCTestObservation> {
14 XCTestSuite *_testSuite;
17 - (instancetype)initWithBundlePath:(NSString *)path andTestNames:(NSArray *)names;
18 - (NSUInteger)runUnitTestSuite;
19 - (void)testLogWithFormat:(NSString *)format, ... NS_FORMAT_FUNCTION(1, 2);
20 - (void)testLogWithFormat:(NSString *)format arguments:(va_list)arguments NS_FORMAT_FUNCTION(1,0);
23 @implementation TestRunner
24 - (instancetype)initWithBundlePath:(NSString *)path andTestNames:(NSArray *)names
26 if ((self = [super init])) {
29 _bundle = [NSBundle bundleWithPath:path];
31 [self testLogWithFormat:@"No bundle at location %@ (%s)\n", path, strerror(errno)];
34 if (![_bundle loadAndReturnError:&error]) {
35 [self testLogWithFormat:@"Test Bundle at %@ didn't load: %@\n", path, error];
40 XCTestSuite* testSuite = [[XCTestSuite alloc] initWithName:[[path lastPathComponent] stringByDeletingPathExtension]];
41 XCTestSuite* loadedSuite = [XCTestSuite testSuiteForBundlePath:path];
42 // Filter out only the tests that were named.
43 [loadedSuite.tests enumerateObjectsUsingBlock:^(__kindof XCTest * _Nonnull test, NSUInteger __unused idx, BOOL * __unused _Nonnull stop) {
44 [self testLogWithFormat:@"Checking test %@\n", test.name];
45 if([names containsObject:test.name]) {
46 [testSuite addTest:test];
49 _testSuite = testSuite;
52 _testSuite = [XCTestSuite testSuiteForBundlePath:path];
58 - (NSUInteger)runUnitTestSuite
60 [[XCTestObservationCenter sharedTestObservationCenter] addTestObserver:self];
64 XCTestRun *testRun = [_testSuite testRun];
66 return testRun.totalFailureCount;
69 - (NSFileHandle *)logFileHandle
71 return [NSFileHandle fileHandleWithStandardOutput];
74 - (void)testLogWithFormat:(NSString *)format, ...
78 [self testLogWithFormat:format arguments:ap];
82 - (void)testLogWithFormat:(NSString *)format arguments:(va_list)arguments
84 NSString *message = [[NSString alloc] initWithFormat:format arguments:arguments];
85 [self.logFileHandle writeData:[message dataUsingEncoding:NSUTF8StringEncoding]];
88 - (NSDateFormatter *)dateFormatter
90 static NSDateFormatter *dateFormatter;
91 static dispatch_once_t onceToken;
92 dispatch_once(&onceToken, ^{
93 dateFormatter = [NSDateFormatter new];
94 dateFormatter.dateFormat = @"yyyy-MM-dd HH:mm:ss.SSS";
99 /* -testBundleWillStart: // exactly once per test bundle
100 * -testSuiteWillStart: // exactly once per test suite
101 * -testCaseWillStart: // exactly once per test case
102 * -testCase:didFailWithDescription:... // zero or more times per test case, any time between test case start and finish
103 * -testCaseDidFinish: // exactly once per test case
104 * -testSuite:didFailWithDescription:... // zero or more times per test suite, any time between test suite start and finish
105 * -testSuiteDidFinish: // exactly once per test suite
106 * -testBundleDidFinish: // exactly once per test bundle
109 - (void)testSuiteWillStart:(XCTestSuite *)testSuite
111 [self testLogWithFormat:@"Test Suite '%@' started at %@\n", testSuite.name, [self.dateFormatter stringFromDate:testSuite.testRun.startDate]];
114 - (void)testSuite:(XCTestSuite *)testSuite didRecordIssue:(XCTIssue *)issue
116 NSString *filePath = [issue.sourceCodeContext.location.fileURL absoluteString];
117 NSInteger lineNumber = issue.sourceCodeContext.location.lineNumber;
118 NSString *description = issue.description;
119 [self testLogWithFormat:@"%@:%lu: error: %@ : %@\n", ((nil != filePath) ? filePath : @"<unknown>"), ((unsigned long)((nil != filePath) ? lineNumber : 0)), testSuite.name, description];
122 - (void)testSuiteDidFinish:(XCTestSuite *)testSuite
124 XCTestRun *testRun = testSuite.testRun;
125 [self testLogWithFormat:@"Test Suite '%@' %s at %@.\n\t Executed %lu test%s, with %lu failure%s (%lu unexpected) in %.3f (%.3f) seconds\n",
127 (testRun.hasSucceeded ? "passed" : "failed"),
128 [self.dateFormatter stringFromDate:testRun.stopDate],
129 ((unsigned long)testRun.executionCount), (testRun.executionCount != 1 ? "s" : ""),
130 ((unsigned long)testRun.totalFailureCount), (testRun.totalFailureCount != 1 ? "s" : ""),
131 ((unsigned long)testRun.unexpectedExceptionCount),
132 testRun.testDuration,
133 testRun.totalDuration];
136 - (void)testCaseWillStart:(XCTestCase *)testCase
138 [self testLogWithFormat:@"Test Case '%@' started.\n", testCase.name];
141 - (void)testCase:(XCTestCase *)testCase didRecordIssue:(XCTIssue *)issue
143 NSString *filePath = [issue.sourceCodeContext.location.fileURL absoluteString];
144 NSInteger lineNumber = issue.sourceCodeContext.location.lineNumber;
145 NSString *description = issue.description;
146 [self testLogWithFormat:@"%@:%lu: error: %@ : %@\n", ((nil != filePath) ? filePath : @"<unknown>"), ((unsigned long)((nil != filePath) ? lineNumber : 0)), testCase.name, description];
149 - (void)testCaseDidFinish:(XCTestCase *)testCase
151 [self testLogWithFormat:@"Test Case '%@' %s (%.3f seconds).\n", testCase.name, (testCase.testRun.hasSucceeded ? "passed" : "failed"), testCase.testRun.totalDuration];
159 static char* gTestBundleDir = "/AppleInternal/XCTests/com.apple.security/";
160 static char* gTestBundleName = "TrustTests";
162 static NSMutableArray* gTestCaseNames = nil;
164 static const char* opt_str = "d:t:c:h";
166 static void usage(char*const binName, bool longUsage) {
167 fprintf(stderr, "Usage: %s [-d <test_dir>] -t test_bundle_name [(-c test_case_name)*]\n", binName);
169 fprintf(stderr, "-d: argument = path to directory where test bundles live\n");
170 fprintf(stderr, "-t: argument = name of test bundle to be run (without extension)\n");
171 fprintf(stderr, "-c: argument = name of test case to be run (multiple)\n");
175 static void getOptions(int argc, char *const *argv) {
177 while ( (ch = getopt(argc, argv, opt_str)) != -1 ) {
181 gTestBundleDir = optarg;
184 gTestBundleName = optarg;
187 if(!gTestCaseNames) {
188 gTestCaseNames = [NSMutableArray new];
190 [gTestCaseNames addObject:@(optarg)];
195 usage(argv[0], true);
202 int main (int argc, const char * argv[])
205 getOptions(argc, (char*const*)argv);
206 NSString *testBundleDir = [NSString stringWithCString:gTestBundleDir encoding:NSUTF8StringEncoding];
207 NSString *testBundleName = [NSString stringWithCString:gTestBundleName encoding:NSUTF8StringEncoding];
208 NSString *testBundlePath = [[testBundleDir stringByAppendingPathComponent:testBundleName] stringByAppendingPathExtension:@"xctest"];
210 printf("Running unit tests %s at: %s\n", gTestCaseNames?gTestCaseNames.description.UTF8String:"[All]", testBundlePath.UTF8String);
212 TestRunner *unitTest = [[TestRunner alloc] initWithBundlePath:testBundlePath andTestNames:gTestCaseNames];
214 fprintf(stderr, "Failed to load unit test runner at: %s\n", testBundlePath.UTF8String);
218 //runUnitTestSuite returns the number of failures. 0 = success, non-zero means failure. This complies with BATS testing standards.
219 return (int)[unitTest runUnitTestSuite];