1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
|
// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#import <Foundation/Foundation.h>
#include <getopt.h>
#include <string>
namespace {
void PrintUsage() {
fprintf(
stderr,
"Usage: iossim [-d device] [-s sdk_version] <app_path> <xctest_path>\n"
" where <app_path> is the path to the .app directory and <xctest_path> "
"is the path to an optional xctest bundle.\n"
"Options:\n"
" -d Specifies the device (must be one of the values from the iOS "
"Simulator's Hardware -> Device menu. Defaults to 'iPhone 6s'.\n"
" -w Wipe the device's contents and settings before running the "
"test.\n"
" -e Specifies an environment key=value pair that will be"
" set in the simulated application's environment.\n"
" -t Specifies a test or test suite that should be included in the"
"test run. All other tests will be excluded from this run.\n"
" -c Specifies command line flags to pass to application.\n"
" -p Print the device's home directory, does not run a test.\n"
" -s Specifies the SDK version to use (e.g '9.3'). Will use system "
"default if not specified.\n");
}
// Exit status codes.
const int kExitSuccess = EXIT_SUCCESS;
const int kExitInvalidArguments = 2;
void LogError(NSString* format, ...) {
va_list list;
va_start(list, format);
NSString* message =
[[[NSString alloc] initWithFormat:format arguments:list] autorelease];
fprintf(stderr, "iossim: ERROR: %s\n", [message UTF8String]);
fflush(stderr);
va_end(list);
}
}
// Wrap boiler plate calls to xcrun NSTasks.
@interface XCRunTask : NSObject {
NSTask* _task;
}
- (instancetype)initWithArguments:(NSArray*)arguments;
- (void)run;
- (void)setStandardOutput:(id)output;
- (void)setStandardError:(id)error;
@end
@implementation XCRunTask
- (instancetype)initWithArguments:(NSArray*)arguments {
self = [super init];
if (self) {
_task = [[NSTask alloc] init];
SEL selector = @selector(setStartsNewProcessGroup:);
if ([_task respondsToSelector:selector])
[_task performSelector:selector withObject:nil];
[_task setLaunchPath:@"/usr/bin/xcrun"];
[_task setArguments:arguments];
}
return self;
}
- (void)dealloc {
[_task release];
[super dealloc];
}
- (void)setStandardOutput:(id)output {
[_task setStandardOutput:output];
}
- (void)setStandardError:(id)error {
[_task setStandardError:error];
}
- (void)run {
[_task launch];
[_task waitUntilExit];
}
- (void)launch {
[_task launch];
}
- (void)waitUntilExit {
[_task waitUntilExit];
}
@end
// Return array of available iOS runtime dictionaries. Unavailable (old Xcode
// versions) or other runtimes (tvOS, watchOS) are removed.
NSArray* Runtimes(NSDictionary* simctl_list) {
NSMutableArray* runtimes =
[[simctl_list[@"runtimes"] mutableCopy] autorelease];
for (NSDictionary* runtime in simctl_list[@"runtimes"]) {
if (![runtime[@"identifier"]
hasPrefix:@"com.apple.CoreSimulator.SimRuntime.iOS"] ||
![runtime[@"availability"] isEqualToString:@"(available)"]) {
[runtimes removeObject:runtime];
}
}
return runtimes;
}
// Return array of device dictionaries.
NSArray* Devices(NSDictionary* simctl_list) {
NSMutableArray* devicetypes =
[[simctl_list[@"devicetypes"] mutableCopy] autorelease];
for (NSDictionary* devicetype in simctl_list[@"devicetypes"]) {
if (![devicetype[@"identifier"]
hasPrefix:@"com.apple.CoreSimulator.SimDeviceType.iPad"] &&
![devicetype[@"identifier"]
hasPrefix:@"com.apple.CoreSimulator.SimDeviceType.iPhone"]) {
[devicetypes removeObject:devicetype];
}
}
return devicetypes;
}
// Get list of devices, runtimes, etc from sim_ctl.
NSDictionary* GetSimulatorList() {
XCRunTask* task = [[[XCRunTask alloc]
initWithArguments:@[ @"simctl", @"list", @"-j" ]] autorelease];
NSPipe* out = [NSPipe pipe];
[task setStandardOutput:out];
// In the rest of the this file we read from the pipe after -waitUntilExit
// (We normally wrap -launch and -waitUntilExit in one -run method). However,
// on some swarming slaves this led to a hang on simctl's pipe. Since the
// output of simctl is so instant, reading it before exit seems to work, and
// seems to avoid the hang.
[task launch];
NSData* data = [[out fileHandleForReading] readDataToEndOfFile];
[task waitUntilExit];
NSError* error = nil;
return [NSJSONSerialization JSONObjectWithData:data
options:kNilOptions
error:&error];
}
// List supported runtimes and devices.
void PrintSupportedDevices(NSDictionary* simctl_list) {
printf("\niOS devices:\n");
for (NSDictionary* type in Devices(simctl_list)) {
printf("%s\n", [type[@"name"] UTF8String]);
}
printf("\nruntimes:\n");
for (NSDictionary* runtime in Runtimes(simctl_list)) {
printf("%s\n", [runtime[@"version"] UTF8String]);
}
}
// Expand path to absolute path.
NSString* ResolvePath(NSString* path) {
path = [path stringByExpandingTildeInPath];
path = [path stringByStandardizingPath];
const char* cpath = [path cStringUsingEncoding:NSUTF8StringEncoding];
char* resolved_name = NULL;
char* abs_path = realpath(cpath, resolved_name);
if (abs_path == NULL) {
return nil;
}
return [NSString stringWithCString:abs_path encoding:NSUTF8StringEncoding];
}
// Search |simctl_list| for a udid matching |device_name| and |sdk_version|.
NSString* GetDeviceBySDKAndName(NSDictionary* simctl_list,
NSString* device_name,
NSString* sdk_version) {
NSString* sdk = [@"iOS " stringByAppendingString:sdk_version];
NSArray* devices = [simctl_list[@"devices"] objectForKey:sdk];
for (NSDictionary* device in devices) {
if ([device[@"name"] isEqualToString:device_name]) {
return device[@"udid"];
}
}
return nil;
}
// Prints the HOME environment variable for a device. Used by the bots to
// package up all the test data.
void PrintDeviceHome(NSString* udid) {
XCRunTask* task = [[[XCRunTask alloc]
initWithArguments:@[ @"simctl", @"getenv", udid, @"HOME" ]] autorelease];
[task run];
}
// Erase a device, used by the bots before a clean test run.
void WipeDevice(NSString* udid) {
XCRunTask* shutdown = [[[XCRunTask alloc]
initWithArguments:@[ @"simctl", @"shutdown", udid ]] autorelease];
[shutdown setStandardOutput:nil];
[shutdown setStandardError:nil];
[shutdown run];
XCRunTask* erase = [[[XCRunTask alloc]
initWithArguments:@[ @"simctl", @"erase", udid ]] autorelease];
[erase run];
}
void KillSimulator() {
XCRunTask* task = [[[XCRunTask alloc]
initWithArguments:@[ @"killall", @"Simulator" ]] autorelease];
[task setStandardOutput:nil];
[task setStandardError:nil];
[task run];
}
void RunApplication(NSString* app_path,
NSString* xctest_path,
NSString* udid,
NSMutableDictionary* app_env,
NSString* cmd_args,
NSMutableArray* tests_filter) {
NSString* tempFilePath = [NSTemporaryDirectory()
stringByAppendingPathComponent:[[NSUUID UUID] UUIDString]];
[[NSFileManager defaultManager] createFileAtPath:tempFilePath
contents:nil
attributes:nil];
NSMutableDictionary* xctestrun = [NSMutableDictionary dictionary];
NSMutableDictionary* testTargetName = [NSMutableDictionary dictionary];
NSMutableDictionary* testingEnvironmentVariables =
[NSMutableDictionary dictionary];
[testingEnvironmentVariables setValue:[app_path lastPathComponent]
forKey:@"IDEiPhoneInternalTestBundleName"];
NSString* frameworkPath =
@"__PLATFORMS__/iPhoneSimulator.platform/Developer/Library/Frameworks";
[testingEnvironmentVariables setValue:frameworkPath
forKey:@"DYLD_FRAMEWORK_PATH"];
NSString* libraryPath =
@"__PLATFORMS__/iPhoneSimulator.platform/Developer/Library";
[testingEnvironmentVariables setValue:libraryPath
forKey:@"DYLD_LIBRARY_PATH"];
if (xctest_path) {
[testTargetName setValue:xctest_path forKey:@"TestBundlePath"];
NSString* inject =
@"__PLATFORMS__/iPhoneSimulator.platform/Developer/Library/"
"PrivateFrameworks/IDEBundleInjection.framework/IDEBundleInjection";
[testingEnvironmentVariables setValue:inject
forKey:@"DYLD_INSERT_LIBRARIES"];
} else {
[testTargetName setValue:app_path forKey:@"TestBundlePath"];
}
[testTargetName setValue:app_path forKey:@"TestHostPath"];
if ([app_env count]) {
[testTargetName setObject:app_env forKey:@"EnvironmentVariables"];
}
if (cmd_args) {
[testTargetName setObject:@[ cmd_args ] forKey:@"CommandLineArguments"];
}
if ([tests_filter count] > 0) {
[testTargetName setObject:tests_filter forKey:@"OnlyTestIdentifiers"];
}
[testTargetName setObject:testingEnvironmentVariables
forKey:@"TestingEnvironmentVariables"];
[xctestrun setObject:testTargetName forKey:@"TestTargetName"];
NSString* error;
NSData* data = [NSPropertyListSerialization
dataFromPropertyList:xctestrun
format:NSPropertyListXMLFormat_v1_0
errorDescription:&error];
[data writeToFile:tempFilePath atomically:YES];
XCRunTask* task = [[[XCRunTask alloc] initWithArguments:@[
@"xcodebuild", @"-xctestrun", tempFilePath, @"-destination",
[@"platform=iOS Simulator,id=" stringByAppendingString:udid],
@"test-without-building"
]] autorelease];
if (!xctest_path) {
// The following stderr messages are meaningless on iossim when not running
// xctests and can be safely stripped.
NSArray* ignore_strings = @[
@"IDETestOperationsObserverErrorDomain", @"** TEST EXECUTE FAILED **"
];
NSPipe* stderr_pipe = [NSPipe pipe];
stderr_pipe.fileHandleForReading.readabilityHandler =
^(NSFileHandle* handle) {
NSString* log = [[[NSString alloc] initWithData:handle.availableData
encoding:NSUTF8StringEncoding]
autorelease];
for (NSString* ignore_string in ignore_strings) {
if ([log rangeOfString:ignore_string].location != NSNotFound) {
return;
}
}
printf("%s", [log UTF8String]);
};
[task setStandardError:stderr_pipe];
}
[task run];
}
int main(int argc, char* const argv[]) {
// When the last running simulator is from Xcode 7, an Xcode 8 run will yeild
// a failure to "unload a stale CoreSimulatorService job" message. Sending a
// hidden simctl to do something simple (list devices) helpfully works around
// this issue.
XCRunTask* workaround_task = [[[XCRunTask alloc]
initWithArguments:@[ @"simctl", @"list", @"-j" ]] autorelease];
[workaround_task setStandardOutput:nil];
[workaround_task setStandardError:nil];
[workaround_task run];
NSString* app_path = nil;
NSString* xctest_path = nil;
NSString* cmd_args = nil;
NSString* device_name = @"iPhone 6s";
bool wants_wipe = false;
bool wants_print_home = false;
NSDictionary* simctl_list = GetSimulatorList();
float sdk = 0;
for (NSDictionary* runtime in Runtimes(simctl_list)) {
sdk = fmax(sdk, [runtime[@"version"] floatValue]);
}
NSString* sdk_version = [NSString stringWithFormat:@"%0.1f", sdk];
NSMutableDictionary* app_env = [NSMutableDictionary dictionary];
NSMutableArray* tests_filter = [NSMutableArray array];
int c;
while ((c = getopt(argc, argv, "hs:d:u:t:e:c:pwl")) != -1) {
switch (c) {
case 's':
sdk_version = [NSString stringWithUTF8String:optarg];
break;
case 'd':
device_name = [NSString stringWithUTF8String:optarg];
break;
case 'w':
wants_wipe = true;
break;
case 'c':
cmd_args = [NSString stringWithUTF8String:optarg];
break;
case 't': {
NSString* test = [NSString stringWithUTF8String:optarg];
[tests_filter addObject:test];
} break;
case 'e': {
NSString* envLine = [NSString stringWithUTF8String:optarg];
NSRange range = [envLine rangeOfString:@"="];
if (range.location == NSNotFound) {
LogError(@"Invalid key=value argument for -e.");
PrintUsage();
exit(kExitInvalidArguments);
}
NSString* key = [envLine substringToIndex:range.location];
NSString* value = [envLine substringFromIndex:(range.location + 1)];
[app_env setObject:value forKey:key];
} break;
case 'p':
wants_print_home = true;
break;
case 'l':
PrintSupportedDevices(simctl_list);
exit(kExitSuccess);
break;
case 'h':
PrintUsage();
exit(kExitSuccess);
break;
default:
PrintUsage();
exit(kExitInvalidArguments);
}
}
NSString* udid = GetDeviceBySDKAndName(simctl_list, device_name, sdk_version);
if (udid == nil) {
LogError(@"Unable to find a device %@ with SDK %@.", device_name,
sdk_version);
PrintSupportedDevices(simctl_list);
exit(kExitInvalidArguments);
}
if (wants_print_home) {
PrintDeviceHome(udid);
exit(kExitSuccess);
}
KillSimulator();
if (wants_wipe) {
WipeDevice(udid);
printf("Device wiped.\n");
exit(kExitSuccess);
}
// There should be at least one arg left, specifying the app path. Any
// additional args are passed as arguments to the app.
if (optind < argc) {
NSString* unresolved_path = [[NSFileManager defaultManager]
stringWithFileSystemRepresentation:argv[optind]
length:strlen(argv[optind])];
app_path = ResolvePath(unresolved_path);
if (!app_path) {
LogError(@"Unable to resolve app_path %@", unresolved_path);
exit(kExitInvalidArguments);
}
if (++optind < argc) {
NSString* unresolved_path = [[NSFileManager defaultManager]
stringWithFileSystemRepresentation:argv[optind]
length:strlen(argv[optind])];
xctest_path = ResolvePath(unresolved_path);
if (!xctest_path) {
LogError(@"Unable to resolve xctest_path %@", unresolved_path);
exit(kExitInvalidArguments);
}
}
} else {
LogError(@"Unable to parse command line arguments.");
PrintUsage();
exit(kExitInvalidArguments);
}
RunApplication(app_path, xctest_path, udid, app_env, cmd_args, tests_filter);
KillSimulator();
return kExitSuccess;
}
|