fake_process_manager.dart 14.8 KB
Newer Older
Ian Hickson's avatar
Ian Hickson committed
1
// Copyright 2014 The Flutter Authors. All rights reserved.
2 3 4
// 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
import 'dart:io' as io show Process, ProcessResult, ProcessSignal, ProcessStartMode, systemEncoding;
8

9
import 'package:file/file.dart';
10
import 'package:meta/meta.dart';
11
import 'package:process/process.dart';
12 13

import 'test_wrapper.dart';
14 15

export 'package:process/process.dart' show ProcessManager;
16

17 18
typedef VoidCallback = void Function();

19 20 21 22
/// A command for [FakeProcessManager].
@immutable
class FakeCommand {
  const FakeCommand({
23
    required this.command,
24 25
    this.workingDirectory,
    this.environment,
26
    this.encoding,
27
    this.duration = Duration.zero,
28 29 30 31
    this.onRun,
    this.exitCode = 0,
    this.stdout = '',
    this.stderr = '',
32
    this.completer,
33
    this.stdin,
34
    this.exception,
35
    this.outputFollowsExit = false,
36
  });
37 38

  /// The exact commands that must be matched for this [FakeCommand] to be
39
  /// considered correct.
40
  final List<Pattern> command;
41 42

  /// The exact working directory that must be matched for this [FakeCommand] to
43
  /// be considered correct.
44
  ///
45
  /// If this is null, the working directory is ignored.
46
  final String? workingDirectory;
47

48
  /// The environment that must be matched for this [FakeCommand] to be considered correct.
49
  ///
50
  /// If this is null, then the environment is ignored.
51 52 53
  ///
  /// Otherwise, each key in this environment must be present and must have a
  /// value that matches the one given here for the [FakeCommand] to match.
54
  final Map<String, String>? environment;
55

56 57 58 59
  /// The stdout and stderr encoding that must be matched for this [FakeCommand]
  /// to be considered correct.
  ///
  /// If this is null, then the encodings are ignored.
60
  final Encoding? encoding;
61

62 63 64 65 66 67 68
  /// The time to allow to elapse before returning the [exitCode], if this command
  /// is "executed".
  ///
  /// If you set this to a non-zero time, you should use a [FakeAsync] zone,
  /// otherwise the test will be artificially slow.
  final Duration duration;

69 70
  /// A callback that is run after [duration] expires but before the [exitCode]
  /// (and output) are passed back.
71
  final VoidCallback? onRun;
72

73 74
  /// The process' exit code.
  ///
75
  /// To simulate a never-ending process, set [duration] to a value greater than
76 77 78 79 80 81 82 83 84 85 86 87 88 89
  /// 15 minutes (the timeout for our tests).
  ///
  /// To simulate a crash, subtract the crash signal number from 256. For example,
  /// SIGPIPE (-13) is 243.
  final int exitCode;

  /// The output to simulate on stdout. This will be encoded as UTF-8 and
  /// returned in one go.
  final String stdout;

  /// The output to simulate on stderr. This will be encoded as UTF-8 and
  /// returned in one go.
  final String stderr;

90 91
  /// If provided, allows the command completion to be blocked until the future
  /// resolves.
92
  final Completer<void>? completer;
93

94 95
  /// An optional stdin sink that will be exposed through the resulting
  /// [FakeProcess].
96
  final IOSink? stdin;
97

98
  /// If provided, this exception will be thrown when the fake command is run.
99
  final Object? exception;
100

101 102
  /// When true, stdout and stderr will only be emitted after the `exitCode`
  /// [Future] on [io.Process] completes.
103 104
  final bool outputFollowsExit;

105 106
  void _matches(
    List<String> command,
107 108
    String? workingDirectory,
    Map<String, String>? environment,
109
    Encoding? encoding,
110
  ) {
111 112
    final List<dynamic> matchers = this.command.map((Pattern x) => x is String ? x : matches(x)).toList();
    expect(command, matchers);
113 114
    if (this.workingDirectory != null) {
      expect(this.workingDirectory, workingDirectory);
115 116
    }
    if (this.environment != null) {
117
      expect(this.environment, environment);
118
    }
119 120 121
    if (this.encoding != null) {
      expect(this.encoding, encoding);
    }
122 123 124
  }
}

125 126 127 128 129 130 131 132 133 134 135 136 137 138
/// A fake process for use with [FakeProcessManager].
///
/// The process delays exit until both [duration] (if specified) has elapsed
/// and [completer] (if specified) has completed.
///
/// When [outputFollowsExit] is specified, bytes are streamed to [stderr] and
/// [stdout] after the process exits.
@visibleForTesting
class FakeProcess implements io.Process {
  FakeProcess({
    int exitCode = 0,
    Duration duration = Duration.zero,
    this.pid = 1234,
    List<int> stderr = const <int>[],
139
    IOSink? stdin,
140 141 142 143 144 145 146 147 148 149 150 151 152 153
    List<int> stdout = const <int>[],
    Completer<void>? completer,
    bool outputFollowsExit = false,
  }) : _exitCode = exitCode,
       exitCode = Future<void>.delayed(duration).then((void value) {
         if (completer != null) {
           return completer.future.then((void _) => exitCode);
         }
         return exitCode;
       }),
      _stderr = stderr,
      stdin = stdin ?? IOSink(StreamController<List<int>>().sink),
      _stdout = stdout,
      _completer = completer
154
  {
155
    if (_stderr.isEmpty) {
156
      this.stderr = const Stream<List<int>>.empty();
157
    } else if (outputFollowsExit) {
158
      // Wait for the process to exit before emitting stderr.
159
      this.stderr = Stream<List<int>>.fromFuture(this.exitCode.then((_) {
160 161
        // Return a Future so stderr isn't immediately available to those who
        // await exitCode, but is available asynchronously later.
162
        return Future<List<int>>(() => _stderr);
163 164
      }));
    } else {
165
      this.stderr = Stream<List<int>>.value(_stderr);
166 167
    }

168
    if (_stdout.isEmpty) {
169
      this.stdout = const Stream<List<int>>.empty();
170
    } else if (outputFollowsExit) {
171
      // Wait for the process to exit before emitting stdout.
172
      this.stdout = Stream<List<int>>.fromFuture(this.exitCode.then((_) {
173 174
        // Return a Future so stdout isn't immediately available to those who
        // await exitCode, but is available asynchronously later.
175
        return Future<List<int>>(() => _stdout);
176 177
      }));
    } else {
178
      this.stdout = Stream<List<int>>.value(_stdout);
179 180
    }
  }
181

182
  /// The process exit code.
183
  final int _exitCode;
184 185

  /// When specified, blocks process exit until completed.
186
  final Completer<void>? _completer;
187 188 189 190 191 192 193

  @override
  final Future<int> exitCode;

  @override
  final int pid;

194
  /// The raw byte content of stderr.
195
  final List<int> _stderr;
196 197

  @override
198
  late final Stream<List<int>> stderr;
199 200 201 202 203

  @override
  final IOSink stdin;

  @override
204
  late final Stream<List<int>> stdout;
205

206
  /// The raw byte content of stdout.
207
  final List<int> _stdout;
208 209 210

  @override
  bool kill([io.ProcessSignal signal = io.ProcessSignal.sigterm]) {
211
    // Killing a fake process has no effect.
212 213 214 215
    return false;
  }
}

216 217 218 219
abstract class FakeProcessManager implements ProcessManager {
  /// A fake [ProcessManager] which responds to all commands as if they had run
  /// instantaneously with an exit code of 0 and no output.
  factory FakeProcessManager.any() = _FakeAnyProcessManager;
220

221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236
  /// A fake [ProcessManager] which responds to particular commands with
  /// particular results.
  ///
  /// On creation, pass in a list of [FakeCommand] objects. When the
  /// [ProcessManager] methods such as [start] are invoked, the next
  /// [FakeCommand] must match (otherwise the test fails); its settings are used
  /// to simulate the result of running that command.
  ///
  /// If no command is found, then one is implied which immediately returns exit
  /// code 0 with no output.
  ///
  /// There is no logic to ensure that all the listed commands are run. Use
  /// [FakeCommand.onRun] to set a flag, or specify a sentinel command as your
  /// last command and verify its execution is successful, to ensure that all
  /// the specified commands are actually called.
  factory FakeProcessManager.list(List<FakeCommand> commands) = _SequenceProcessManager;
237
  factory FakeProcessManager.empty() => _SequenceProcessManager(<FakeCommand>[]);
238

239 240
  FakeProcessManager._();

241 242 243 244 245 246 247 248
  /// Adds a new [FakeCommand] to the current process manager.
  ///
  /// This can be used to configure test expectations after the [ProcessManager] has been
  /// provided to another interface.
  ///
  /// This is a no-op on [FakeProcessManager.any].
  void addCommand(FakeCommand command);

249 250 251 252 253
  /// Add multiple [FakeCommand] to the current process manager.
  void addCommands(Iterable<FakeCommand> commands) {
    commands.forEach(addCommand);
  }

254
  final Map<int, FakeProcess> _fakeRunningProcesses = <int, FakeProcess>{};
255

256 257 258 259 260
  /// Whether this fake has more [FakeCommand]s that are expected to run.
  ///
  /// This is always `true` for [FakeProcessManager.any].
  bool get hasRemainingExpectations;

261 262 263
  /// The expected [FakeCommand]s that have not yet run.
  List<FakeCommand> get _remainingExpectations;

264
  @protected
265 266
  FakeCommand findCommand(
    List<String> command,
267 268
    String? workingDirectory,
    Map<String, String>? environment,
269
    Encoding? encoding,
270
  );
271 272 273

  int _pid = 9999;

274
  FakeProcess _runCommand(
275
    List<String> command,
276 277
    String? workingDirectory,
    Map<String, String>? environment,
278
    Encoding? encoding,
279
  ) {
280
    _pid += 1;
281
    final FakeCommand fakeCommand = findCommand(command, workingDirectory, environment, encoding);
282
    if (fakeCommand.exception != null) {
283 284
      assert(fakeCommand.exception is Exception || fakeCommand.exception is Error);
      throw fakeCommand.exception!; // ignore: only_throw_errors
285
    }
286
    if (fakeCommand.onRun != null) {
287
      fakeCommand.onRun!();
288
    }
289 290 291 292 293 294 295 296 297
    return FakeProcess(
      duration: fakeCommand.duration,
      exitCode: fakeCommand.exitCode,
      pid: _pid,
      stderr: encoding?.encode(fakeCommand.stderr) ?? fakeCommand.stderr.codeUnits,
      stdin: fakeCommand.stdin,
      stdout: encoding?.encode(fakeCommand.stdout) ?? fakeCommand.stdout.codeUnits,
      completer: fakeCommand.completer,
      outputFollowsExit: fakeCommand.outputFollowsExit,
298 299 300 301
    );
  }

  @override
302
  Future<io.Process> start(
303
    List<dynamic> command, {
304 305
    String? workingDirectory,
    Map<String, String>? environment,
306 307
    bool includeParentEnvironment = true, // ignored
    bool runInShell = false, // ignored
308
    io.ProcessStartMode mode = io.ProcessStartMode.normal, // ignored
309
  }) {
310
    final FakeProcess process = _runCommand(command.cast<String>(), workingDirectory, environment, io.systemEncoding);
311 312 313 314 315 316
    if (process._completer != null) {
      _fakeRunningProcesses[process.pid] = process;
      process.exitCode.whenComplete(() {
        _fakeRunningProcesses.remove(process.pid);
      });
    }
317
    return Future<io.Process>.value(process);
318
  }
319 320

  @override
321
  Future<io.ProcessResult> run(
322
    List<dynamic> command, {
323 324
    String? workingDirectory,
    Map<String, String>? environment,
325 326
    bool includeParentEnvironment = true, // ignored
    bool runInShell = false, // ignored
327 328
    Encoding? stdoutEncoding = io.systemEncoding,
    Encoding? stderrEncoding = io.systemEncoding,
329
  }) async {
330
    final FakeProcess process = _runCommand(command.cast<String>(), workingDirectory, environment, stdoutEncoding);
331
    await process.exitCode;
332
    return io.ProcessResult(
333 334
      process.pid,
      process._exitCode,
335 336
      stdoutEncoding == null ? process._stdout : await stdoutEncoding.decodeStream(process.stdout),
      stderrEncoding == null ? process._stderr : await stderrEncoding.decodeStream(process.stderr),
337 338 339 340
    );
  }

  @override
341
  io.ProcessResult runSync(
342
    List<dynamic> command, {
343 344
    String? workingDirectory,
    Map<String, String>? environment,
345 346
    bool includeParentEnvironment = true, // ignored
    bool runInShell = false, // ignored
347 348
    Encoding? stdoutEncoding = io.systemEncoding,
    Encoding? stderrEncoding = io.systemEncoding,
349
  }) {
350
    final FakeProcess process = _runCommand(command.cast<String>(), workingDirectory, environment, stdoutEncoding);
351
    return io.ProcessResult(
352 353
      process.pid,
      process._exitCode,
354 355
      stdoutEncoding == null ? process._stdout : stdoutEncoding.decode(process._stdout),
      stderrEncoding == null ? process._stderr : stderrEncoding.decode(process._stderr),
356 357 358
    );
  }

359
  /// Returns false if executable in [excludedExecutables].
360
  @override
361
  bool canRun(dynamic executable, {String? workingDirectory}) => !excludedExecutables.contains(executable);
362 363

  Set<String> excludedExecutables = <String>{};
364 365

  @override
366
  bool killPid(int pid, [io.ProcessSignal signal = io.ProcessSignal.sigterm]) {
367
    // Killing a fake process has no effect unless it has an attached completer.
368
    final FakeProcess? fakeProcess = _fakeRunningProcesses[pid];
369 370 371
    if (fakeProcess == null) {
      return false;
    }
372 373 374
    if (fakeProcess._completer != null) {
      fakeProcess._completer!.complete();
    }
375
    return true;
376 377
  }
}
378 379 380 381 382

class _FakeAnyProcessManager extends FakeProcessManager {
  _FakeAnyProcessManager() : super._();

  @override
383 384
  FakeCommand findCommand(
    List<String> command,
385 386
    String? workingDirectory,
    Map<String, String>? environment,
387
    Encoding? encoding,
388
  ) {
389 390 391 392
    return FakeCommand(
      command: command,
      workingDirectory: workingDirectory,
      environment: environment,
393
      encoding: encoding,
394 395
    );
  }
396 397 398

  @override
  void addCommand(FakeCommand command) { }
399 400 401

  @override
  bool get hasRemainingExpectations => true;
402 403 404

  @override
  List<FakeCommand> get _remainingExpectations => <FakeCommand>[];
405 406 407 408 409 410 411 412
}

class _SequenceProcessManager extends FakeProcessManager {
  _SequenceProcessManager(this._commands) : super._();

  final List<FakeCommand> _commands;

  @override
413 414
  FakeCommand findCommand(
    List<String> command,
415 416
    String? workingDirectory,
    Map<String, String>? environment,
417
    Encoding? encoding,
418
  ) {
419 420 421 422
    expect(_commands, isNotEmpty,
      reason: 'ProcessManager was told to execute $command (in $workingDirectory) '
              'but the FakeProcessManager.list expected no more processes.'
    );
423
    _commands.first._matches(command, workingDirectory, environment, encoding);
424 425
    return _commands.removeAt(0);
  }
426 427 428 429 430

  @override
  void addCommand(FakeCommand command) {
    _commands.add(command);
  }
431 432 433

  @override
  bool get hasRemainingExpectations => _commands.isNotEmpty;
434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464

  @override
  List<FakeCommand> get _remainingExpectations => _commands;
}

/// Matcher that successfully matches against a [FakeProcessManager] with
/// no remaining expectations ([item.hasRemainingExpectations] returns false).
const Matcher hasNoRemainingExpectations = _HasNoRemainingExpectations();

class _HasNoRemainingExpectations extends Matcher {
  const _HasNoRemainingExpectations();

  @override
  bool matches(dynamic item, Map<dynamic, dynamic> matchState) =>
      item is FakeProcessManager && !item.hasRemainingExpectations;

  @override
  Description describe(Description description) =>
      description.add('a fake process manager with no remaining expectations');

  @override
  Description describeMismatch(
      dynamic item,
      Description description,
      Map<dynamic, dynamic> matchState,
      bool verbose,
      ) {
    final FakeProcessManager fakeProcessManager = item as FakeProcessManager;
    return description.add(
        'has remaining expectations:\n${fakeProcessManager._remainingExpectations.map((FakeCommand command) => command.command).join('\n')}');
  }
465
}