elapseUntil<T> method

Future<T> elapseUntil<T>(
  1. Future<T> future, {
  2. Duration step = const Duration(milliseconds: 10),
  3. Duration within = const Duration(seconds: 1),
})

future, once the clock has moved on until it completed, step at a time as elapse moves it: what code run in the clock's zone ends with — an app's run, an answer to a prompt — once the timers it waits on have fired, however long the machine takes to run them. A future that completes without the clock moving is returned with the clock where it was. A TestFailure once the clock has moved on by within and future has not completed, saying how many timers wait.

The future is returned as it completed: awaited, it throws the error it completed with.

final clock = FakeClock();
final answer = clock.run(
  () => Future<int>.delayed(const Duration(milliseconds: 250), () => 42),
);
expect(await clock.elapseUntil(answer), 42);
expect(clock.elapsed, const Duration(milliseconds: 250));

An app run by hand, on a terminal that neither testTwk nor its tester makes: the terminal and the binding made in the clock's zone, the binding reading the clock, its run awaited until it has ended.

final clock = FakeClock();
final term = clock.run(() => HeadlessTerminal(width: 20, height: 2));
final done = clock.run(
  () => AppBinding(term, clock: clock.stopwatch).run(const Text('hi')),
);
await clock.elapse(const Duration(milliseconds: 30));
term.type('\x03');
await clock.elapseUntil(done);
expect(term.closed, isTrue);

Implementation

Future<T> elapseUntil<T>(
  Future<T> future, {
  Duration step = const Duration(milliseconds: 10),
  Duration within = const Duration(seconds: 1),
}) async {
  if (step <= Duration.zero) {
    throw ArgumentError.value(step, 'step', 'is not positive');
  }
  var done = false;
  unawaited(
    future.then<void>((_) => done = true, onError: (Object _) => done = true),
  );
  final end = _now + within.inMicroseconds;
  await flushMicrotasks();
  while (!done) {
    final left = end - _now;
    if (left <= 0) {
      final timers = switch (pendingTimers) {
        0 => 'no timer waits',
        1 => '1 timer waits',
        final n => '$n timers wait',
      };
      throw TestFailure(
        'elapseUntil: the future has not completed '
        '${_seconds(within)} on the clock, and $timers'
        '${pendingTimers == 0 ? '' : ':\n${describeTimers()}'}',
      );
    }
    final micros = step.inMicroseconds;
    await elapse(Duration(microseconds: left < micros ? left : micros));
  }
  return future;
}