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
30 _bundle = [NSBundle bundleWithPath:path];
32 [self testLogWithFormat:@"No bundle at location %@ (%s)\n", path, strerror(errno)];
35 if (![_bundle loadAndReturnError:&error]) {
36 [self testLogWithFormat:@"Test Bundle at %@ didn't load: %@\n", path, error];
41 XCTestSuite* testSuite = [[XCTestSuite alloc] initWithName:[[path lastPathComponent] stringByDeletingPathExtension]];
42 XCTestSuite* loadedSuite = [XCTestSuite testSuiteForBundlePath:path];
43 // Filter out only the tests that were named.
44 [loadedSuite.tests enumerateObjectsUsingBlock:^(__kindof XCTest * _Nonnull test, NSUInteger __unused idx, BOOL * __unused _Nonnull stop) {
45 [self testLogWithFormat:@"Checking test %@\n", test.name];
46 if([names containsObject:test.name]) {
47 [testSuite addTest:test];
50 _testSuite = testSuite;
53 _testSuite = [XCTestSuite testSuiteForBundlePath:path];
59 - (NSUInteger)runUnitTestSuite
61 [[XCTestObservationCenter sharedTestObservationCenter] addTestObserver:self];
65 XCTestRun *testRun = [_testSuite testRun];
67 return testRun.totalFailureCount;
70 - (NSFileHandle *)logFileHandle
72 return [NSFileHandle fileHandleWithStandardOutput];
75 - (void)testLogWithFormat:(NSString *)format, ...
79 [self testLogWithFormat:format arguments:ap];
83 - (void)testLogWithFormat:(NSString *)format arguments:(va_list)arguments
85 NSString *message = [[NSString alloc] initWithFormat:format arguments:arguments];
86 [self.logFileHandle writeData:[message dataUsingEncoding:NSUTF8StringEncoding]];
89 - (NSDateFormatter *)dateFormatter
91 static NSDateFormatter *dateFormatter;
92 static dispatch_once_t onceToken;
93 dispatch_once(&onceToken, ^{
94 dateFormatter = [NSDateFormatter new];
95 dateFormatter.dateFormat = @"yyyy-MM-dd HH:mm:ss.SSS";
100 /* -testBundleWillStart: // exactly once per test bundle
101 * -testSuiteWillStart: // exactly once per test suite
102 * -testCaseWillStart: // exactly once per test case
103 * -testCase:didFailWithDescription:... // zero or more times per test case, any time between test case start and finish
104 * -testCaseDidFinish: // exactly once per test case
105 * -testSuite:didFailWithDescription:... // zero or more times per test suite, any time between test suite start and finish
106 * -testSuiteDidFinish: // exactly once per test suite
107 * -testBundleDidFinish: // exactly once per test bundle
110 - (void)testSuiteWillStart:(XCTestSuite *)testSuite
112 [self testLogWithFormat:@"Test Suite '%@' started at %@\n", testSuite.name, [self.dateFormatter stringFromDate:testSuite.testRun.startDate]];
115 - (void)testSuite:(XCTestSuite *)testSuite didFailWithDescription:(NSString *)description inFile:(nullable NSString *)filePath atLine:(NSUInteger)lineNumber
117 [self testLogWithFormat:@"%@:%lu: error: %@ : %@\n", ((nil != filePath) ? filePath : @"<unknown>"), ((unsigned long)((nil != filePath) ? lineNumber : 0)), testSuite.name, description];
120 - (void)testSuiteDidFinish:(XCTestSuite *)testSuite
122 XCTestRun *testRun = testSuite.testRun;
123 [self testLogWithFormat:@"Test Suite '%@' %s at %@.\n\t Executed %lu test%s, with %lu failure%s (%lu unexpected) in %.3f (%.3f) seconds\n",
125 (testRun.hasSucceeded ? "passed" : "failed"),
126 [self.dateFormatter stringFromDate:testRun.stopDate],
127 ((unsigned long)testRun.executionCount), (testRun.executionCount != 1 ? "s" : ""),
128 ((unsigned long)testRun.totalFailureCount), (testRun.totalFailureCount != 1 ? "s" : ""),
129 ((unsigned long)testRun.unexpectedExceptionCount),
130 testRun.testDuration,
131 testRun.totalDuration];
134 - (void)testCaseWillStart:(XCTestCase *)testCase
136 [self testLogWithFormat:@"Test Case '%@' started.\n", testCase.name];
139 - (void)testCase:(XCTestCase *)testCase didFailWithDescription:(NSString *)description inFile:(nullable NSString *)filePath atLine:(NSUInteger)lineNumber
141 [self testLogWithFormat:@"%@:%lu: error: %@ : %@\n", ((nil != filePath) ? filePath : @"<unknown>"), ((unsigned long)((nil != filePath) ? lineNumber : 0)), testCase.name, description];
144 - (void)testCaseDidFinish:(XCTestCase *)testCase
146 [self testLogWithFormat:@"Test Case '%@' %s (%.3f seconds).\n", testCase.name, (testCase.testRun.hasSucceeded ? "passed" : "failed"), testCase.testRun.totalDuration];
154 static char* gTestBundleDir = "/AppleInternal/XCTests/com.apple.security/";
155 static char* gTestBundleName = "TrustTests";
157 static NSMutableArray* gTestCaseNames = nil;
159 static const char* opt_str = "d:t:c:h";
161 static void usage(char*const binName, bool longUsage) {
162 fprintf(stderr, "Usage: %s [-d <test_dir>] -t test_bundle_name [(-c test_case_name)*]\n", binName);
164 fprintf(stderr, "-d: argument = path to directory where test bundles live\n");
165 fprintf(stderr, "-t: argument = name of test bundle to be run (without extension)\n");
166 fprintf(stderr, "-c: argument = name of test case to be run (multiple)\n");
170 static void getOptions(int argc, char *const *argv) {
172 while ( (ch = getopt(argc, argv, opt_str)) != -1 ) {
176 gTestBundleDir = optarg;
179 gTestBundleName = optarg;
182 if(!gTestCaseNames) {
183 gTestCaseNames = [NSMutableArray new];
185 [gTestCaseNames addObject:@(optarg)];
190 usage(argv[0], true);
197 int main (int argc, const char * argv[])
200 getOptions(argc, (char*const*)argv);
201 NSString *testBundleDir = [NSString stringWithCString:gTestBundleDir encoding:NSUTF8StringEncoding];
202 NSString *testBundleName = [NSString stringWithCString:gTestBundleName encoding:NSUTF8StringEncoding];
203 NSString *testBundlePath = [[testBundleDir stringByAppendingPathComponent:testBundleName] stringByAppendingPathExtension:@"xctest"];
205 printf("Running unit tests %s at: %s\n", gTestCaseNames?gTestCaseNames.description.UTF8String:"[All]", testBundlePath.UTF8String);
207 TestRunner *unitTest = [[TestRunner alloc] initWithBundlePath:testBundlePath andTestNames:gTestCaseNames];
209 fprintf(stderr, "Failed to load unit test runner at: %s\n", testBundlePath.UTF8String);
213 //runUnitTestSuite returns the number of failures. 0 = success, non-zero means failure. This complies with BATS testing standards.
214 return (int)[unitTest runUnitTestSuite];