ios_deploy_test.dart 21.1 KB
Newer Older
1 2 3 4
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

5
import 'dart:async';
6
import 'dart:convert';
7

8 9
import 'package:file/memory.dart';
import 'package:file_testing/file_testing.dart';
10
import 'package:flutter_tools/src/artifacts.dart';
11
import 'package:flutter_tools/src/base/file_system.dart';
12
import 'package:flutter_tools/src/base/logger.dart';
13
import 'package:flutter_tools/src/base/platform.dart';
14 15
import 'package:flutter_tools/src/cache.dart';
import 'package:flutter_tools/src/ios/ios_deploy.dart';
16
import 'package:flutter_tools/src/ios/iproxy.dart';
17 18

import '../../src/common.dart';
19
import '../../src/fake_process_manager.dart';
20
import '../../src/fakes.dart';
21 22

void main () {
23 24 25
  late Artifacts artifacts;
  late String iosDeployPath;
  late FileSystem fileSystem;
26 27 28

  setUp(() {
    artifacts = Artifacts.test();
29
    iosDeployPath = artifacts.getHostArtifact(HostArtifact.iosDeploy).path;
30
    fileSystem = MemoryFileSystem.test();
31 32
  });

33 34 35
  testWithoutContext('IOSDeploy.iosDeployEnv returns path with /usr/bin first', () {
    final IOSDeploy iosDeploy = setUpIOSDeploy(FakeProcessManager.any());
    final Map<String, String> environment = iosDeploy.iosDeployEnv;
36

37 38
    expect(environment['PATH'], startsWith('/usr/bin'));
  });
39

40 41 42 43 44 45 46 47 48
  group('IOSDeploy.prepareDebuggerForLaunch', () {
    testWithoutContext('calls ios-deploy with correct arguments and returns when debugger attaches', () async {
      final FakeProcessManager processManager = FakeProcessManager.list(<FakeCommand>[
        FakeCommand(
          command: <String>[
            'script',
            '-t',
            '0',
            '/dev/null',
49
            iosDeployPath,
50 51 52 53
            '--id',
            '123',
            '--bundle',
            '/',
54 55
            '--app_deltas',
            'app-delta',
56
            '--uninstall',
57 58 59 60 61 62 63
            '--debug',
            '--args',
            <String>[
              '--enable-dart-profiling',
            ].join(' '),
          ], environment: const <String, String>{
            'PATH': '/usr/bin:/usr/local/bin:/usr/bin',
64
            'DYLD_LIBRARY_PATH': '/path/to/libraries',
65 66 67 68
          },
          stdout: '(lldb)     run\nsuccess\nDid finish launching.',
        ),
      ]);
69
      final Directory appDeltaDirectory = fileSystem.directory('app-delta');
70
      final IOSDeploy iosDeploy = setUpIOSDeploy(processManager, artifacts: artifacts);
71 72 73
      final IOSDeployDebugger iosDeployDebugger = iosDeploy.prepareDebuggerForLaunch(
        deviceId: '123',
        bundlePath: '/',
74
        appDeltaDirectory: appDeltaDirectory,
75
        launchArguments: <String>['--enable-dart-profiling'],
76
        interfaceType: IOSDeviceConnectionInterface.network,
77
        uninstallFirst: true,
78 79
      );

80
      expect(iosDeployDebugger.logLines, emits('Did finish launching.'));
81
      expect(await iosDeployDebugger.launchAndAttach(), isTrue);
82
      await iosDeployDebugger.logLines.drain();
83
      expect(processManager, hasNoRemainingExpectations);
84
      expect(appDeltaDirectory, exists);
85 86 87 88 89
    });
  });

  group('IOSDeployDebugger', () {
    group('launch', () {
90
      late BufferLogger logger;
91 92 93 94 95

      setUp(() {
        logger = BufferLogger.test();
      });

96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111
      testWithoutContext('custom lldb prompt', () async {
        final StreamController<List<int>> stdin = StreamController<List<int>>();
        final FakeProcessManager processManager = FakeProcessManager.list(<FakeCommand>[
          FakeCommand(
            command: const <String>['ios-deploy'],
            stdout: "(mylldb)    platform select remote-'ios' --sysroot\r\n(mylldb)     run\r\nsuccess\r\n",
            stdin: IOSink(stdin.sink),
          ),
        ]);
        final IOSDeployDebugger iosDeployDebugger = IOSDeployDebugger.test(
          processManager: processManager,
          logger: logger,
        );
        expect(await iosDeployDebugger.launchAndAttach(), isTrue);
      });

112 113
      testWithoutContext('debugger attached and stopped', () async {
        final StreamController<List<int>> stdin = StreamController<List<int>>();
114
        final FakeProcessManager processManager = FakeProcessManager.list(<FakeCommand>[
115 116 117 118
          FakeCommand(
            command: const <String>['ios-deploy'],
            stdout: "(lldb)     run\r\nsuccess\r\nsuccess\r\nLog on attach1\r\n\r\nLog on attach2\r\n\r\n\r\n\r\nPROCESS_STOPPED\r\nLog after process stop\r\nthread backtrace all\r\n* thread #1, queue = 'com.apple.main-thread', stop reason = signal SIGSTOP",
            stdin: IOSink(stdin.sink),
119 120 121 122 123 124 125 126 127 128
          ),
        ]);
        final IOSDeployDebugger iosDeployDebugger = IOSDeployDebugger.test(
          processManager: processManager,
          logger: logger,
        );
        final List<String> receivedLogLines = <String>[];
        final Stream<String> logLines = iosDeployDebugger.logLines
          ..listen(receivedLogLines.add);

129
        expect(iosDeployDebugger.logLines, emitsInOrder(<String>[
130 131 132
          'success', // ignore first "success" from lldb, but log subsequent ones from real logging.
          'Log on attach1',
          'Log on attach2',
133 134
          '',
          '',
135
          'Log after process stop',
136 137
        ]));
        expect(stdin.stream.transform<String>(const Utf8Decoder()), emitsInOrder(<String>[
138 139 140
          'thread backtrace all',
          '\n',
          'process detach',
141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160
        ]));
        expect(await iosDeployDebugger.launchAndAttach(), isTrue);
        await logLines.drain();

        expect(logger.traceText, contains('PROCESS_STOPPED'));
        expect(logger.traceText, contains('thread backtrace all'));
        expect(logger.traceText, contains('* thread #1'));
      });

      testWithoutContext('handle processing logging after process exit', () async {
        final StreamController<List<int>> stdin = StreamController<List<int>>();
        // Make sure we don't hit a race where logging processed after the process exits
        // causes listeners to receive logging on the closed logLines stream.
        final FakeProcessManager processManager = FakeProcessManager.list(<FakeCommand>[
          FakeCommand(
            command: const <String>['ios-deploy'],
            stdout: 'stdout: "(lldb)     run\r\nsuccess\r\n',
            stdin: IOSink(stdin.sink),
            outputFollowsExit: true,
          ),
161
        ]);
162 163 164 165 166 167 168 169
        final IOSDeployDebugger iosDeployDebugger = IOSDeployDebugger.test(
          processManager: processManager,
          logger: logger,
        );

        expect(iosDeployDebugger.logLines, emitsDone);
        expect(await iosDeployDebugger.launchAndAttach(), isFalse);
        await iosDeployDebugger.logLines.drain();
170 171 172 173 174 175
      });

      testWithoutContext('app exit', () async {
        final FakeProcessManager processManager = FakeProcessManager.list(<FakeCommand>[
          const FakeCommand(
            command: <String>['ios-deploy'],
176
            stdout: '(lldb)     run\r\nsuccess\r\nLog on attach\r\nProcess 100 exited with status = 0\r\nLog after process exit',
177 178 179 180 181 182
          ),
        ]);
        final IOSDeployDebugger iosDeployDebugger = IOSDeployDebugger.test(
          processManager: processManager,
          logger: logger,
        );
183
        expect(iosDeployDebugger.logLines, emitsInOrder(<String>[
184 185
          'Log on attach',
          'Log after process exit',
186 187 188 189
        ]));

        expect(await iosDeployDebugger.launchAndAttach(), isTrue);
        await iosDeployDebugger.logLines.drain();
190 191 192
      });

      testWithoutContext('app crash', () async {
193
        final StreamController<List<int>> stdin = StreamController<List<int>>();
194
        final FakeProcessManager processManager = FakeProcessManager.list(<FakeCommand>[
195 196
          FakeCommand(
            command: const <String>['ios-deploy'],
197
            stdout:
198 199
                '(lldb)     run\r\nsuccess\r\nLog on attach\r\n(lldb) Process 6156 stopped\r\n* thread #1, stop reason = Assertion failed:\r\nthread backtrace all\r\n* thread #1, stop reason = Assertion failed:',
            stdin: IOSink(stdin.sink),
200 201 202 203 204 205 206
          ),
        ]);
        final IOSDeployDebugger iosDeployDebugger = IOSDeployDebugger.test(
          processManager: processManager,
          logger: logger,
        );

207
        expect(iosDeployDebugger.logLines, emitsInOrder(<String>[
208 209
          'Log on attach',
          '* thread #1, stop reason = Assertion failed:',
210 211 212
        ]));

        expect(stdin.stream.transform<String>(const Utf8Decoder()), emitsInOrder(<String>[
213 214 215
          'thread backtrace all',
          '\n',
          'process detach',
216 217 218 219 220 221 222 223
        ]));

        expect(await iosDeployDebugger.launchAndAttach(), isTrue);
        await iosDeployDebugger.logLines.drain();

        expect(logger.traceText, contains('Process 6156 stopped'));
        expect(logger.traceText, contains('thread backtrace all'));
        expect(logger.traceText, contains('* thread #1'));
224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239
      });

      testWithoutContext('attach failed', () async {
        final FakeProcessManager processManager = FakeProcessManager.list(<FakeCommand>[
          const FakeCommand(
            command: <String>['ios-deploy'],
            // A success after an error should never happen, but test that we're handling random "successes" anyway.
            stdout: '(lldb)     run\r\nerror: process launch failed\r\nsuccess\r\nLog on attach1',
          ),
        ]);
        final IOSDeployDebugger iosDeployDebugger = IOSDeployDebugger.test(
          processManager: processManager,
          logger: logger,
        );
        // Debugger lines are double spaced, separated by an extra \r\n. Skip the extra lines.
        // Still include empty lines other than the extra added newlines.
240 241 242 243
        expect(iosDeployDebugger.logLines, emitsDone);

        expect(await iosDeployDebugger.launchAndAttach(), isFalse);
        await iosDeployDebugger.logLines.drain();
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
      });

      testWithoutContext('no provisioning profile 1, stdout', () async {
        final FakeProcessManager processManager = FakeProcessManager.list(<FakeCommand>[
          const FakeCommand(
            command: <String>['ios-deploy'],
            stdout: 'Error 0xe8008015',
          ),
        ]);
        final IOSDeployDebugger iosDeployDebugger = IOSDeployDebugger.test(
          processManager: processManager,
          logger: logger,
        );

        await iosDeployDebugger.launchAndAttach();
        expect(logger.errorText, contains('No Provisioning Profile was found'));
      });

      testWithoutContext('no provisioning profile 2, stderr', () async {
        final FakeProcessManager processManager = FakeProcessManager.list(<FakeCommand>[
          const FakeCommand(
            command: <String>['ios-deploy'],
            stderr: 'Error 0xe8000067',
          ),
        ]);
        final IOSDeployDebugger iosDeployDebugger = IOSDeployDebugger.test(
          processManager: processManager,
          logger: logger,
        );
        await iosDeployDebugger.launchAndAttach();
        expect(logger.errorText, contains('No Provisioning Profile was found'));
      });

277
      testWithoutContext('device locked code', () async {
278 279 280 281 282 283 284 285 286 287 288 289 290 291
        final FakeProcessManager processManager = FakeProcessManager.list(<FakeCommand>[
          const FakeCommand(
            command: <String>['ios-deploy'],
            stdout: 'e80000e2',
          ),
        ]);
        final IOSDeployDebugger iosDeployDebugger = IOSDeployDebugger.test(
          processManager: processManager,
          logger: logger,
        );
        await iosDeployDebugger.launchAndAttach();
        expect(logger.errorText, contains('Your device is locked.'));
      });

292 293 294 295 296 297 298 299 300 301 302 303 304 305 306
      testWithoutContext('device locked message', () async {
        final FakeProcessManager processManager = FakeProcessManager.list(<FakeCommand>[
          const FakeCommand(
            command: <String>['ios-deploy'],
            stdout: '[  +95 ms] error: The operation couldn’t be completed. Unable to launch io.flutter.examples.gallery because the device was not, or could not be, unlocked.',
          ),
        ]);
        final IOSDeployDebugger iosDeployDebugger = IOSDeployDebugger.test(
          processManager: processManager,
          logger: logger,
        );
        await iosDeployDebugger.launchAndAttach();
        expect(logger.errorText, contains('Your device is locked.'));
      });

307
      testWithoutContext('unknown app launch error', () async {
308 309 310 311 312 313 314 315 316 317 318 319 320
        final FakeProcessManager processManager = FakeProcessManager.list(<FakeCommand>[
          const FakeCommand(
            command: <String>['ios-deploy'],
            stdout: 'Error 0xe8000022',
          ),
        ]);
        final IOSDeployDebugger iosDeployDebugger = IOSDeployDebugger.test(
          processManager: processManager,
          logger: logger,
        );
        await iosDeployDebugger.launchAndAttach();
        expect(logger.errorText, contains('Try launching from within Xcode'));
      });
321
    });
322

323 324 325 326 327 328 329 330 331 332 333 334 335 336
    testWithoutContext('detach', () async {
      final StreamController<List<int>> stdin = StreamController<List<int>>();
      final FakeProcessManager processManager = FakeProcessManager.list(<FakeCommand>[
        FakeCommand(
          command: const <String>[
            'ios-deploy',
          ],
          stdout: '(lldb)     run\nsuccess',
          stdin: IOSink(stdin.sink),
        ),
      ]);
      final IOSDeployDebugger iosDeployDebugger = IOSDeployDebugger.test(
        processManager: processManager,
      );
337
      expect(stdin.stream.transform<String>(const Utf8Decoder()), emits('process detach'));
338 339
      await iosDeployDebugger.launchAndAttach();
      iosDeployDebugger.detach();
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

    testWithoutContext('stop with backtrace', () async {
      final StreamController<List<int>> stdin = StreamController<List<int>>();
      final Stream<String> stdinStream = stdin.stream.transform<String>(const Utf8Decoder());
      final FakeProcessManager processManager = FakeProcessManager.list(<FakeCommand>[
        FakeCommand(
          command: const <String>[
            'ios-deploy',
          ],
          stdout:
          '(lldb)     run\nsuccess\nLog on attach\n(lldb) Process 6156 stopped\n* thread #1, stop reason = Assertion failed:\n(lldb) Process 6156 detached',
          stdin: IOSink(stdin.sink),
        ),
      ]);
      final IOSDeployDebugger iosDeployDebugger = IOSDeployDebugger.test(
        processManager: processManager,
      );
      await iosDeployDebugger.launchAndAttach();
      await iosDeployDebugger.stopAndDumpBacktrace();
      expect(await stdinStream.take(3).toList(), <String>[
        'thread backtrace all',
        '\n',
        'process detach',
      ]);
    });
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

    testWithoutContext('pause with backtrace', () async {
      final StreamController<List<int>> stdin = StreamController<List<int>>();
      final Stream<String> stdinStream = stdin.stream.transform<String>(const Utf8Decoder());
      const String stdout = '''
(lldb)     run
success
Log on attach
(lldb) Process 6156 stopped
* thread #1, stop reason = Assertion failed:
thread backtrace all
process continue
* thread #1, stop reason = signal SIGSTOP
  * frame #0: 0x0000000102eaee80 dyld`dyld3::MachOFile::read_uleb128(Diagnostics&, unsigned char const*&, unsigned char const*) + 36
    frame #1: 0x0000000102eabbd4 dyld`dyld3::MachOLoaded::trieWalk(Diagnostics&, unsigned char const*, unsigned char const*, char const*) + 332
    frame #2: 0x0000000102eaa078 dyld`DyldSharedCache::hasImagePath(char const*, unsigned int&) const + 144
    frame #3: 0x0000000102eaa13c dyld`DyldSharedCache::hasNonOverridablePath(char const*) const + 44
    frame #4: 0x0000000102ebc404 dyld`dyld3::closure::ClosureBuilder::findImage(char const*, dyld3::closure::ClosureBuilder::LoadedImageChain const&, dyld3::closure::ClosureBuilder::BuilderLoadedImage*&, dyld3::closure::ClosureBuilder::LinkageType, unsigned int, bool) +

    frame #5: 0x0000000102ebd974 dyld`invocation function for block in dyld3::closure::ClosureBuilder::recursiveLoadDependents(dyld3::closure::ClosureBuilder::LoadedImageChain&, bool) + 136
    frame #6: 0x0000000102eae1b0 dyld`invocation function for block in dyld3::MachOFile::forEachDependentDylib(void (char const*, bool, bool, bool, unsigned int, unsigned int, bool&) block_pointer) const + 136
    frame #7: 0x0000000102eadc38 dyld`dyld3::MachOFile::forEachLoadCommand(Diagnostics&, void (load_command const*, bool&) block_pointer) const + 168
    frame #8: 0x0000000102eae108 dyld`dyld3::MachOFile::forEachDependentDylib(void (char const*, bool, bool, bool, unsigned int, unsigned int, bool&) block_pointer) const + 116
    frame #9: 0x0000000102ebd80c dyld`dyld3::closure::ClosureBuilder::recursiveLoadDependents(dyld3::closure::ClosureBuilder::LoadedImageChain&, bool) + 164
    frame #10: 0x0000000102ebd8a8 dyld`dyld3::closure::ClosureBuilder::recursiveLoadDependents(dyld3::closure::ClosureBuilder::LoadedImageChain&, bool) + 320
    frame #11: 0x0000000102ebd8a8 dyld`dyld3::closure::ClosureBuilder::recursiveLoadDependents(dyld3::closure::ClosureBuilder::LoadedImageChain&, bool) + 320
    frame #12: 0x0000000102ebd8a8 dyld`dyld3::closure::ClosureBuilder::recursiveLoadDependents(dyld3::closure::ClosureBuilder::LoadedImageChain&, bool) + 320
    frame #13: 0x0000000102ebd8a8 dyld`dyld3::closure::ClosureBuilder::recursiveLoadDependents(dyld3::closure::ClosureBuilder::LoadedImageChain&, bool) + 320
    frame #14: 0x0000000102ebd8a8 dyld`dyld3::closure::ClosureBuilder::recursiveLoadDependents(dyld3::closure::ClosureBuilder::LoadedImageChain&, bool) + 320
    frame #15: 0x0000000102ebd8a8 dyld`dyld3::closure::ClosureBuilder::recursiveLoadDependents(dyld3::closure::ClosureBuilder::LoadedImageChain&, bool) + 320
    frame #16: 0x0000000102ec7638 dyld`dyld3::closure::ClosureBuilder::makeLaunchClosure(dyld3::closure::LoadedFileInfo const&, bool) + 752
    frame #17: 0x0000000102e8fcf0 dyld`dyld::buildLaunchClosure(unsigned char const*, dyld3::closure::LoadedFileInfo const&, char const**) + 344
    frame #18: 0x0000000102e8e938 dyld`dyld::_main(macho_header const*, unsigned long, int, char const**, char const**, char const**, unsigned long*) + 2876
    frame #19: 0x0000000102e8922c dyld`dyldbootstrap::start(dyld3::MachOLoaded const*, int, char const**, dyld3::MachOLoaded const*, unsigned long*) + 432
    frame #20: 0x0000000102e89038 dyld`_dyld_start + 56
''';
      final BufferLogger logger = BufferLogger.test();
      final FakeProcessManager processManager = FakeProcessManager.list(<FakeCommand>[
        FakeCommand(
          command: const <String>[
            'ios-deploy',
          ],
          stdout: stdout,
          stdin: IOSink(stdin.sink),
        ),
      ]);
      final IOSDeployDebugger iosDeployDebugger = IOSDeployDebugger.test(
        processManager: processManager,
        logger: logger,
      );
      await iosDeployDebugger.launchAndAttach();
      await iosDeployDebugger.pauseDumpBacktraceResume();
      // verify stacktrace was logged to trace
      expect(
        logger.traceText,
        contains(
          'frame #0: 0x0000000102eaee80 dyld`dyld3::MachOFile::read_uleb128(Diagnostics&, unsigned char const*&, unsigned char const*) + 36',
        ),
      );
      expect(await stdinStream.take(3).toList(), <String>[
        'thread backtrace all',
        '\n',
        'process detach',
      ]);
    });
431
  });
432

433 434 435 436 437
  group('IOSDeploy.uninstallApp', () {
    testWithoutContext('calls ios-deploy with correct arguments and returns 0 on success', () async {
      const String deviceId = '123';
      const String bundleId = 'com.example.app';
      final FakeProcessManager processManager = FakeProcessManager.list(<FakeCommand>[
438 439
        FakeCommand(command: <String>[
          iosDeployPath,
440 441 442 443 444
          '--id',
          deviceId,
          '--uninstall_only',
          '--bundle_id',
          bundleId,
445
        ]),
446
      ]);
447
      final IOSDeploy iosDeploy = setUpIOSDeploy(processManager, artifacts: artifacts);
448 449 450 451 452 453
      final int exitCode = await iosDeploy.uninstallApp(
        deviceId: deviceId,
        bundleId: bundleId,
      );

      expect(exitCode, 0);
454
      expect(processManager, hasNoRemainingExpectations);
455 456 457 458 459 460
    });

    testWithoutContext('returns non-zero exit code when ios-deploy does the same', () async {
      const String deviceId = '123';
      const String bundleId = 'com.example.app';
      final FakeProcessManager processManager = FakeProcessManager.list(<FakeCommand>[
461 462
        FakeCommand(command: <String>[
          iosDeployPath,
463 464 465 466 467
          '--id',
          deviceId,
          '--uninstall_only',
          '--bundle_id',
          bundleId,
468
        ], exitCode: 1),
469
      ]);
470
      final IOSDeploy iosDeploy = setUpIOSDeploy(processManager, artifacts: artifacts);
471 472 473 474 475 476
      final int exitCode = await iosDeploy.uninstallApp(
        deviceId: deviceId,
        bundleId: bundleId,
      );

      expect(exitCode, 1);
477
      expect(processManager, hasNoRemainingExpectations);
478
    });
479 480
  });
}
481

482
IOSDeploy setUpIOSDeploy(ProcessManager processManager, {
483
    Artifacts? artifacts,
484
  }) {
485 486 487
  final FakePlatform macPlatform = FakePlatform(
    operatingSystem: 'macos',
    environment: <String, String>{
488
      'PATH': '/usr/local/bin:/usr/bin',
489 490
    }
  );
491 492 493 494 495
  final Cache cache = Cache.test(
    platform: macPlatform,
    artifacts: <ArtifactSet>[
      FakeDyldEnvironmentArtifact(),
    ],
496
    processManager: FakeProcessManager.any(),
497
  );
498 499 500 501 502

  return IOSDeploy(
    logger: BufferLogger.test(),
    platform: macPlatform,
    processManager: processManager,
503
    artifacts: artifacts ?? Artifacts.test(),
504 505 506
    cache: cache,
  );
}