widget_tester.dart 43.3 KB
Newer Older
Ian Hickson's avatar
Ian Hickson committed
1
// Copyright 2014 The Flutter Authors. All rights reserved.
Hixie's avatar
Hixie committed
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 'package:flutter/cupertino.dart';
6
import 'package:flutter/foundation.dart';
7
import 'package:flutter/gestures.dart';
8
import 'package:flutter/material.dart' show Tooltip;
9
import 'package:flutter/rendering.dart';
10
import 'package:flutter/scheduler.dart';
11
import 'package:flutter/services.dart';
12
import 'package:meta/meta.dart';
13

14
// The test_api package is not for general use... it's literally for our use.
15
// ignore: deprecated_member_use
16
import 'package:test_api/test_api.dart' as test_package;
17

18
import 'all_elements.dart';
19
import 'binding.dart';
20
import 'controller.dart';
21
import 'finders.dart';
22
import 'matchers.dart';
23
import 'restoration.dart';
24
import 'test_async_utils.dart';
25
import 'test_compat.dart';
26
import 'test_pointer.dart';
27
import 'test_text_input.dart';
28

29
// Keep users from needing multiple imports to test semantics.
30 31
export 'package:flutter/rendering.dart' show SemanticsHandle;

32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47
// We re-export the test package minus some features that we reimplement.
//
// Specifically:
//
//  - test, group, setUpAll, tearDownAll, setUp, tearDown, and expect would
//    conflict with our own implementations in test_compat.dart. This handles
//    setting up a declarer when one is not defined, which can happen when a
//    test is executed via `flutter run`.
//
//  - expect is reimplemented below, to catch incorrect async usage.
//
//  - isInstanceOf is reimplemented in matchers.dart because we don't want to
//    mark it as deprecated (ours is just a method, not a class).
//
// The test_api package has a deprecation warning to discourage direct use but
// that doesn't apply here.
48
// ignore: deprecated_member_use
49
export 'package:test_api/test_api.dart' hide
50
  expect,
51
  group,
52
  isInstanceOf,
53
  setUp,
54
  setUpAll,
55
  tearDown,
56 57
  tearDownAll,
  test;
58

59
/// Signature for callback to [testWidgets] and [benchmarkWidgets].
60
typedef WidgetTesterCallback = Future<void> Function(WidgetTester widgetTester);
61

62
// Return the last element that satisfies `test`, or return null if not found.
63 64 65 66 67 68 69 70 71
E? _lastWhereOrNull<E>(Iterable<E> list, bool Function(E) test) {
  late E result;
  bool foundMatching = false;
  for (final E element in list) {
    if (test(element)) {
      result = element;
      foundMatching = true;
    }
  }
72
  if (foundMatching) {
73
    return result;
74
  }
75 76 77
  return null;
}

78 79 80 81 82
/// Runs the [callback] inside the Flutter test environment.
///
/// Use this function for testing custom [StatelessWidget]s and
/// [StatefulWidget]s.
///
83 84
/// The callback can be asynchronous (using `async`/`await` or
/// using explicit [Future]s).
85
///
86 87 88 89 90 91 92
/// The `timeout` argument specifies the backstop timeout implemented by the
/// `test` package. If set, it should be relatively large (minutes). It defaults
/// to ten minutes for tests run by `flutter test`, and is unlimited for tests
/// run by `flutter run`; specifically, it defaults to
/// [TestWidgetsFlutterBinding.defaultTestTimeout]. (The `initialTimeout`
/// parameter has no effect. It was previously used with
/// [TestWidgetsFlutterBinding.addTime] but that feature was removed.)
93
///
94
/// If the `semanticsEnabled` parameter is set to `true`,
95 96
/// [WidgetTester.ensureSemantics] will have been called before the tester is
/// passed to the `callback`, and that handle will automatically be disposed
97
/// after the callback is finished. It defaults to true.
98
///
99 100 101 102 103 104
/// This function uses the [test] function in the test package to
/// register the given callback as a test. The callback, when run,
/// will be given a new instance of [WidgetTester]. The [find] object
/// provides convenient widget [Finder]s for use with the
/// [WidgetTester].
///
105 106 107 108
/// When the [variant] argument is set, [testWidgets] will run the test once for
/// each value of the [TestVariant.values]. If [variant] is not set, the test
/// will be run once using the base test environment.
///
109 110 111
/// If the [tags] are passed, they declare user-defined tags that are implemented by
/// the `test` package.
///
112 113 114
/// See also:
///
///  * [AutomatedTestWidgetsFlutterBinding.addTime] to learn more about
115
///    timeout and how to manually increase timeouts.
116
///
117
/// ## Sample code
118
///
119
/// ```dart
120
/// testWidgets('MyWidget', (WidgetTester tester) async {
Anas35's avatar
Anas35 committed
121
///   await tester.pumpWidget(MyWidget());
122 123 124
///   await tester.tap(find.text('Save'));
///   expect(find.text('Success'), findsOneWidget);
/// });
125
/// ```
126
@isTest
127 128 129
void testWidgets(
  String description,
  WidgetTesterCallback callback, {
130
  bool? skip,
131
  test_package.Timeout? timeout,
132 133 134 135
  @Deprecated(
    'This parameter has no effect. Use `timeout` instead. '
    'This feature was deprecated after v2.6.0-1.0.pre.'
  )
136
  Duration? initialTimeout,
137
  bool semanticsEnabled = true,
138
  TestVariant<Object?> variant = const DefaultTestVariant(),
139
  dynamic tags,
140
}) {
141
  assert(variant != null);
142
  assert(variant.values.isNotEmpty, 'There must be at least one value to test in the testing variant.');
143
  final TestWidgetsFlutterBinding binding = TestWidgetsFlutterBinding.ensureInitialized();
144
  final WidgetTester tester = WidgetTester._(binding);
145
  for (final dynamic value in variant.values) {
146
    final String variationDescription = variant.describeValue(value);
147 148 149 150 151 152 153
    // IDEs may make assumptions about the format of this suffix in order to
    // support running tests directly from the editor (where they may have
    // access to only the test name, provided by the analysis server).
    // See https://github.com/flutter/flutter/issues/86659.
    final String combinedDescription = variationDescription.isNotEmpty
        ? '$description (variant: $variationDescription)'
        : description;
154 155 156 157
    test(
      combinedDescription,
      () {
        tester._testDescription = combinedDescription;
158
        SemanticsHandle? semanticsHandle;
159 160 161 162 163 164 165
        if (semanticsEnabled == true) {
          semanticsHandle = tester.ensureSemantics();
        }
        tester._recordNumberOfSemanticsHandles();
        test_package.addTearDown(binding.postTest);
        return binding.runTest(
          () async {
166
            binding.reset(); // TODO(ianh): the binding should just do this itself in _runTest
167
            debugResetSemanticsIdCounter();
168
            Object? memento;
169 170 171 172 173 174 175 176 177
            try {
              memento = await variant.setUp(value);
              await callback(tester);
            } finally {
              await variant.tearDown(value, memento);
            }
            semanticsHandle?.dispose();
          },
          tester._endOfTestVerifications,
178
          description: combinedDescription,
179 180 181
          timeout: initialTimeout,
        );
      },
182
      skip: skip,
183
      timeout: timeout ?? binding.defaultTestTimeout,
184
      tags: tags,
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
    );
  }
}

/// An abstract base class for describing test environment variants.
///
/// These serve as elements of the `variants` argument to [testWidgets].
///
/// Use care when adding more testing variants: it multiplies the number of
/// tests which run. This can drastically increase the time it takes to run all
/// the tests.
abstract class TestVariant<T> {
  /// A const constructor so that subclasses can be const.
  const TestVariant();

  /// Returns an iterable of the variations that this test dimension represents.
  ///
  /// The variations returned should be unique so that the same variation isn't
  /// needlessly run twice.
  Iterable<T> get values;

  /// Returns the string that will be used to both add to the test description, and
  /// be printed when a test fails for this variation.
  String describeValue(T value);

  /// A function that will be called before each value is tested, with the
  /// value that will be tested.
  ///
  /// This function should preserve any state needed to restore the testing
  /// environment back to its base state when [tearDown] is called in the
  /// `Object` that is returned. The returned object will then be passed to
  /// [tearDown] as a `memento` when the test is complete.
217
  Future<Object?> setUp(T value);
218 219 220 221 222 223 224

  /// A function that is guaranteed to be called after a value is tested, even
  /// if it throws an exception.
  ///
  /// Calling this function must return the testing environment back to the base
  /// state it was in before [setUp] was called. The [memento] is the object
  /// returned from [setUp] when it was called.
225
  Future<void> tearDown(T value, covariant Object? memento);
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
}

/// The [TestVariant] that represents the "default" test that is run if no
/// `variants` iterable is specified for [testWidgets].
///
/// This variant can be added into a list of other test variants to provide
/// a "control" test where nothing is changed from the base test environment.
class DefaultTestVariant extends TestVariant<void> {
  /// A const constructor for a [DefaultTestVariant].
  const DefaultTestVariant();

  @override
  Iterable<void> get values => const <void>[null];

  @override
  String describeValue(void value) => '';

  @override
  Future<void> setUp(void value) async {}

  @override
  Future<void> tearDown(void value, void memento) async {}
}

/// A [TestVariant] that runs tests with [debugDefaultTargetPlatformOverride]
/// set to different values of [TargetPlatform].
class TargetPlatformVariant extends TestVariant<TargetPlatform> {
  /// Creates a [TargetPlatformVariant] that tests the given [values].
  const TargetPlatformVariant(this.values);

  /// Creates a [TargetPlatformVariant] that tests all values from
257 258 259 260 261
  /// the [TargetPlatform] enum. If [excluding] is provided, will test all platforms
  /// except those in [excluding].
  TargetPlatformVariant.all({
    Set<TargetPlatform> excluding = const <TargetPlatform>{},
  }) : values = TargetPlatform.values.toSet()..removeAll(excluding);
262

263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278
  /// Creates a [TargetPlatformVariant] that includes platforms that are
  /// considered desktop platforms.
  TargetPlatformVariant.desktop() : values = <TargetPlatform>{
    TargetPlatform.linux,
    TargetPlatform.macOS,
    TargetPlatform.windows,
  };

  /// Creates a [TargetPlatformVariant] that includes platforms that are
  /// considered mobile platforms.
  TargetPlatformVariant.mobile() : values = <TargetPlatform>{
    TargetPlatform.android,
    TargetPlatform.iOS,
    TargetPlatform.fuchsia,
  };

279 280 281 282 283 284 285 286 287 288 289
  /// Creates a [TargetPlatformVariant] that tests only the given value of
  /// [TargetPlatform].
  TargetPlatformVariant.only(TargetPlatform platform) : values = <TargetPlatform>{platform};

  @override
  final Set<TargetPlatform> values;

  @override
  String describeValue(TargetPlatform value) => value.toString();

  @override
290 291
  Future<TargetPlatform?> setUp(TargetPlatform value) async {
    final TargetPlatform? previousTargetPlatform = debugDefaultTargetPlatformOverride;
292 293 294 295 296
    debugDefaultTargetPlatformOverride = value;
    return previousTargetPlatform;
  }

  @override
297
  Future<void> tearDown(TargetPlatform value, TargetPlatform? memento) async {
298 299
    debugDefaultTargetPlatformOverride = memento;
  }
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
/// A [TestVariant] that runs separate tests with each of the given values.
///
/// To use this variant, define it before the test, and then access
/// [currentValue] inside the test.
///
/// The values are typically enums, but they don't have to be. The `toString`
/// for the given value will be used to describe the variant. Values will have
/// their type name stripped from their `toString` output, so that enum values
/// will only print the value, not the type.
///
/// {@tool snippet}
/// This example shows how to set up the test to access the [currentValue]. In
/// this example, two tests will be run, one with `value1`, and one with
/// `value2`. The test with `value2` will fail. The names of the tests will be:
///
///   - `Test handling of TestScenario (value1)`
///   - `Test handling of TestScenario (value2)`
///
/// ```dart
/// enum TestScenario {
///   value1,
///   value2,
///   value3,
/// }
///
/// final ValueVariant<TestScenario> variants = ValueVariant<TestScenario>(
///   <TestScenario>{value1, value2},
/// );
///
/// testWidgets('Test handling of TestScenario', (WidgetTester tester) {
///   expect(variants.currentValue, equals(value1));
/// }, variant: variants);
/// ```
/// {@end-tool}
class ValueVariant<T> extends TestVariant<T> {
  /// Creates a [ValueVariant] that tests the given [values].
  ValueVariant(this.values);

  /// Returns the value currently under test.
341 342
  T? get currentValue => _currentValue;
  T? _currentValue;
343 344 345 346 347 348 349 350 351 352 353 354 355 356

  @override
  final Set<T> values;

  @override
  String describeValue(T value) => value.toString().replaceFirst('$T.', '');

  @override
  Future<T> setUp(T value) async => _currentValue = value;

  @override
  Future<void> tearDown(T value, T memento) async {}
}

357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372
/// The warning message to show when a benchmark is performed with assert on.
const String kDebugWarning = '''
┏╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍┓
┇ ⚠    THIS BENCHMARK IS BEING RUN IN DEBUG MODE     ⚠  ┇
┡╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍┦
│                                                       │
│  Numbers obtained from a benchmark while asserts are  │
│  enabled will not accurately reflect the performance  │
│  that will be experienced by end users using release  ╎
│  builds. Benchmarks should be run using this command  ╎
│  line:  "flutter run --profile test.dart" or          ┊
│  or "flutter drive --profile -t test.dart".           ┊
│                                                       ┊
└─────────────────────────────────────────────────╌┄┈  🐢
''';

373 374 375 376 377 378 379 380 381 382 383
/// Runs the [callback] inside the Flutter benchmark environment.
///
/// Use this function for benchmarking custom [StatelessWidget]s and
/// [StatefulWidget]s when you want to be able to use features from
/// [TestWidgetsFlutterBinding]. The callback, when run, will be given
/// a new instance of [WidgetTester]. The [find] object provides
/// convenient widget [Finder]s for use with the [WidgetTester].
///
/// The callback can be asynchronous (using `async`/`await` or using
/// explicit [Future]s). If it is, then [benchmarkWidgets] will return
/// a [Future] that completes when the callback's does. Otherwise, it
384 385 386 387
/// will return a Future that is always complete.
///
/// If the callback is asynchronous, make sure you `await` the call
/// to [benchmarkWidgets], otherwise it won't run!
388
///
389 390 391 392 393
/// If the `semanticsEnabled` parameter is set to `true`,
/// [WidgetTester.ensureSemantics] will have been called before the tester is
/// passed to the `callback`, and that handle will automatically be disposed
/// after the callback is finished.
///
394
/// Benchmarks must not be run in debug mode, because the performance is not
395
/// representative. To avoid this, this function will print a big message if it
396
/// is run in debug mode. Unit tests of this method pass `mayRunWithAsserts`,
397
/// but it should not be used for actual benchmarking.
398 399 400 401
///
/// Example:
///
///     main() async {
402
///       assert(false); // fail in debug mode
403
///       await benchmarkWidgets((WidgetTester tester) async {
Anas35's avatar
Anas35 committed
404 405
///         await tester.pumpWidget(MyWidget());
///         final Stopwatch timer = Stopwatch()..start();
406
///         for (int index = 0; index < 10000; index += 1) {
407 408
///           await tester.tap(find.text('Tap me'));
///           await tester.pump();
409 410
///         }
///         timer.stop();
411
///         debugPrint('Time taken: ${timer.elapsedMilliseconds}ms');
412 413 414
///       });
///       exit(0);
///     }
415 416 417
Future<void> benchmarkWidgets(
  WidgetTesterCallback callback, {
  bool mayRunWithAsserts = false,
418
  bool semanticsEnabled = false,
419
}) {
420
  assert(() {
421
    if (mayRunWithAsserts) {
422
      return true;
423
    }
424
    debugPrint(kDebugWarning);
425
    return true;
426
  }());
427
  final TestWidgetsFlutterBinding binding = TestWidgetsFlutterBinding.ensureInitialized();
428
  assert(binding is! AutomatedTestWidgetsFlutterBinding);
429
  final WidgetTester tester = WidgetTester._(binding);
430
  SemanticsHandle? semanticsHandle;
431 432 433
  if (semanticsEnabled == true) {
    semanticsHandle = tester.ensureSemantics();
  }
434
  tester._recordNumberOfSemanticsHandles();
435
  return binding.runTest(
436 437 438 439
    () async {
      await callback(tester);
      semanticsHandle?.dispose();
    },
440
    tester._endOfTestVerifications,
441
  );
442
}
443

444 445 446 447 448
/// Assert that `actual` matches `matcher`.
///
/// See [test_package.expect] for details. This is a variant of that function
/// that additionally verifies that there are no asynchronous APIs
/// that have not yet resolved.
449 450 451 452
///
/// See also:
///
///  * [expectLater] for use with asynchronous matchers.
453 454 455
void expect(
  dynamic actual,
  dynamic matcher, {
456
  String? reason,
Ian Hickson's avatar
Ian Hickson committed
457
  dynamic skip, // true or a String
458 459
}) {
  TestAsyncUtils.guardSync();
Ian Hickson's avatar
Ian Hickson committed
460
  test_package.expect(actual, matcher, reason: reason, skip: skip);
461 462 463 464 465 466 467 468 469 470 471
}

/// Assert that `actual` matches `matcher`.
///
/// See [test_package.expect] for details. This variant will _not_ check that
/// there are no outstanding asynchronous API requests. As such, it can be
/// called from, e.g., callbacks that are run during build or layout, or in the
/// completion handlers of futures that execute in response to user input.
///
/// Generally, it is better to use [expect], which does include checks to ensure
/// that asynchronous APIs are not being called.
472 473 474
void expectSync(
  dynamic actual,
  dynamic matcher, {
475
  String? reason,
476
}) {
477
  test_package.expect(actual, matcher, reason: reason);
478 479
}

480 481 482 483 484 485 486 487
/// Just like [expect], but returns a [Future] that completes when the matcher
/// has finished matching.
///
/// See [test_package.expectLater] for details.
///
/// If the matcher fails asynchronously, that failure is piped to the returned
/// future where it can be handled by user code. If it is not handled by user
/// code, the test will fail.
488 489 490
Future<void> expectLater(
  dynamic actual,
  dynamic matcher, {
491
  String? reason,
492 493
  dynamic skip, // true or a String
}) {
494 495 496
  // We can't wrap the delegate in a guard, or we'll hit async barriers in
  // [TestWidgetsFlutterBinding] while we're waiting for the matcher to complete
  TestAsyncUtils.guardSync();
497 498
  return test_package.expectLater(actual, matcher, reason: reason, skip: skip)
           .then<void>((dynamic value) => null);
499 500
}

501
/// Class that programmatically interacts with widgets and the test environment.
502 503
///
/// For convenience, instances of this class (such as the one provided by
504
/// `testWidgets`) can be used as the `vsync` for `AnimationController` objects.
505 506 507 508
///
/// When the binding is [LiveTestWidgetsFlutterBinding], events from
/// [LiveTestWidgetsFlutterBinding.deviceEventDispatcher] will be handled in
/// [dispatchEvent].
509
class WidgetTester extends WidgetController implements HitTestDispatcher, TickerProvider {
510
  WidgetTester._(super.binding) {
511
    if (binding is LiveTestWidgetsFlutterBinding) {
512
      (binding as LiveTestWidgetsFlutterBinding).deviceEventDispatcher = this;
513
    }
514
  }
515

516 517 518 519
  /// The description string of the test currently being run.
  String get testDescription => _testDescription;
  String _testDescription = '';

520 521
  /// The binding instance used by the testing framework.
  @override
522
  TestWidgetsFlutterBinding get binding => super.binding as TestWidgetsFlutterBinding;
523 524 525

  /// Renders the UI from the given [widget].
  ///
526 527 528 529
  /// Calls [runApp] with the given widget, then triggers a frame and flushes
  /// microtasks, by calling [pump] with the same `duration` (if any). The
  /// supplied [EnginePhase] is the final phase reached during the pump pass; if
  /// not supplied, the whole pass is executed.
530 531 532 533
  ///
  /// Subsequent calls to this is different from [pump] in that it forces a full
  /// rebuild of the tree, even if [widget] is the same as the previous call.
  /// [pump] will only rebuild the widgets that have changed.
534
  ///
535 536 537 538
  /// This method should not be used as the first parameter to an [expect] or
  /// [expectLater] call to test that a widget throws an exception. Instead, use
  /// [TestWidgetsFlutterBinding.takeException].
  ///
539
  /// {@tool snippet}
540 541 542 543 544 545 546 547
  /// ```dart
  /// testWidgets('MyWidget asserts invalid bounds', (WidgetTester tester) async {
  ///   await tester.pumpWidget(MyWidget(-1));
  ///   expect(tester.takeException(), isAssertionError); // or isNull, as appropriate.
  /// });
  /// ```
  /// {@end-tool}
  ///
548 549
  /// See also [LiveTestWidgetsFlutterBindingFramePolicy], which affects how
  /// this method works when the test is run with `flutter run`.
550 551
  Future<void> pumpWidget(
    Widget widget, [
552
    Duration? duration,
553
    EnginePhase phase = EnginePhase.sendSemanticsUpdate,
554
  ]) {
555
    return TestAsyncUtils.guard<void>(() {
556 557 558 559 560
      return _pumpWidget(
        binding.wrapWithDefaultView(widget),
        duration,
        phase,
      );
561
    });
562 563
  }

564 565 566 567 568 569 570 571 572 573
  Future<void> _pumpWidget(
    Widget widget, [
    Duration? duration,
    EnginePhase phase = EnginePhase.sendSemanticsUpdate,
  ]) {
    binding.attachRootWidget(widget);
    binding.scheduleFrame();
    return binding.pump(duration, phase);
  }

574
  @override
575
  Future<List<Duration>> handlePointerEventRecord(Iterable<PointerEventRecord> records) {
576 577 578 579
    assert(records != null);
    assert(records.isNotEmpty);
    return TestAsyncUtils.guard<List<Duration>>(() async {
      final List<Duration> handleTimeStampDiff = <Duration>[];
580
      DateTime? startTime;
581 582 583 584 585 586 587
      for (final PointerEventRecord record in records) {
        final DateTime now = binding.clock.now();
        startTime ??= now;
        // So that the first event is promised to receive a zero timeDiff
        final Duration timeDiff = record.timeDelay - now.difference(startTime);
        if (timeDiff.isNegative) {
          // Flush all past events
588
          handleTimeStampDiff.add(-timeDiff);
589
          for (final PointerEvent event in record.events) {
590
            binding.handlePointerEventForSource(event, source: TestBindingEventSource.test);
591 592 593 594 595
          }
        } else {
          await binding.pump();
          await binding.delayed(timeDiff);
          handleTimeStampDiff.add(
596
            binding.clock.now().difference(startTime) - record.timeDelay,
597 598
          );
          for (final PointerEvent event in record.events) {
599
            binding.handlePointerEventForSource(event, source: TestBindingEventSource.test);
600 601 602 603 604 605 606 607 608 609
          }
        }
      }
      await binding.pump();
      // This makes sure that a gesture is completed, with no more pointers
      // active.
      return handleTimeStampDiff;
    });
  }

610 611 612
  /// Triggers a frame after `duration` amount of time.
  ///
  /// This makes the framework act as if the application had janked (missed
613
  /// frames) for `duration` amount of time, and then received a "Vsync" signal
614
  /// to paint the application.
615
  ///
616 617 618 619
  /// For a [FakeAsync] environment (typically in `flutter test`), this advances
  /// time and timeout counting; for a live environment this delays `duration`
  /// time.
  ///
620 621
  /// This is a convenience function that just calls
  /// [TestWidgetsFlutterBinding.pump].
622 623 624
  ///
  /// See also [LiveTestWidgetsFlutterBindingFramePolicy], which affects how
  /// this method works when the test is run with `flutter run`.
625
  @override
626
  Future<void> pump([
627
    Duration? duration,
628
    EnginePhase phase = EnginePhase.sendSemanticsUpdate,
629
  ]) {
630
    return TestAsyncUtils.guard<void>(() => binding.pump(duration, phase));
631
  }
632

633 634 635 636 637 638 639 640 641 642
  /// Triggers a frame after `duration` amount of time, return as soon as the frame is drawn.
  ///
  /// This enables driving an artificially high CPU load by rendering frames in
  /// a tight loop. It must be used with the frame policy set to
  /// [LiveTestWidgetsFlutterBindingFramePolicy.benchmark].
  ///
  /// Similarly to [pump], this doesn't actually wait for `duration`, just
  /// advances the clock.
  Future<void> pumpBenchmark(Duration duration) async {
    assert(() {
643 644
      final TestWidgetsFlutterBinding widgetsBinding = binding;
      return widgetsBinding is LiveTestWidgetsFlutterBinding &&
645
             widgetsBinding.framePolicy == LiveTestWidgetsFlutterBindingFramePolicy.benchmark;
646 647 648 649 650
    }());

    dynamic caughtException;
    void handleError(dynamic error, StackTrace stackTrace) => caughtException ??= error;

651
    await Future<void>.microtask(() { binding.handleBeginFrame(duration); }).catchError(handleError);
652
    await idle();
653
    await Future<void>.microtask(() { binding.handleDrawFrame(); }).catchError(handleError);
654 655 656
    await idle();

    if (caughtException != null) {
657
      throw caughtException as Object; // ignore: only_throw_errors, rethrowing caught exception.
658 659 660
    }
  }

661
  @override
662
  Future<int> pumpAndSettle([
663 664
    Duration duration = const Duration(milliseconds: 100),
    EnginePhase phase = EnginePhase.sendSemanticsUpdate,
665
    Duration timeout = const Duration(minutes: 10),
666
  ]) {
667
    assert(duration != null);
668
    assert(duration > Duration.zero);
669 670
    assert(timeout != null);
    assert(timeout > Duration.zero);
671 672 673 674
    assert(() {
      final WidgetsBinding binding = this.binding;
      if (binding is LiveTestWidgetsFlutterBinding &&
          binding.framePolicy == LiveTestWidgetsFlutterBindingFramePolicy.benchmark) {
675 676 677 678 679 680
        test_package.fail(
          'When using LiveTestWidgetsFlutterBindingFramePolicy.benchmark, '
          'hasScheduledFrame is never set to true. This means that pumpAndSettle() '
          'cannot be used, because it has no way to know if the application has '
          'stopped registering new frames.',
        );
681 682 683
      }
      return true;
    }());
684
    return TestAsyncUtils.guard<int>(() async {
685
      final DateTime endTime = binding.clock.fromNowBy(timeout);
686
      int count = 0;
687
      do {
688
        if (binding.clock.now().isAfter(endTime)) {
689
          throw FlutterError('pumpAndSettle timed out');
690
        }
691 692
        await binding.pump(duration, phase);
        count += 1;
693
      } while (binding.hasScheduledFrame);
694 695
      return count;
    });
696 697
  }

698 699 700 701 702 703 704 705 706 707 708 709 710 711
  /// Repeatedly pump frames that render the `target` widget with a fixed time
  /// `interval` as many as `maxDuration` allows.
  ///
  /// The `maxDuration` argument is required. The `interval` argument defaults to
  /// 16.683 milliseconds (59.94 FPS).
  Future<void> pumpFrames(
    Widget target,
    Duration maxDuration, [
    Duration interval = const Duration(milliseconds: 16, microseconds: 683),
  ]) {
    assert(maxDuration != null);
    // The interval following the last frame doesn't have to be within the fullDuration.
    Duration elapsed = Duration.zero;
    return TestAsyncUtils.guard<void>(() async {
712
      binding.attachRootWidget(binding.wrapWithDefaultView(target));
713 714 715 716 717 718 719 720
      binding.scheduleFrame();
      while (elapsed < maxDuration) {
        await binding.pump(interval);
        elapsed += interval;
      }
    });
  }

721 722 723 724 725 726 727 728 729 730 731 732 733 734
  /// Simulates restoring the state of the widget tree after the application
  /// is restarted.
  ///
  /// The method grabs the current serialized restoration data from the
  /// [RestorationManager], takes down the widget tree to destroy all in-memory
  /// state, and then restores the widget tree from the serialized restoration
  /// data.
  Future<void> restartAndRestore() async {
    assert(
      binding.restorationManager.debugRootBucketAccessed,
      'The current widget tree did not inject the root bucket of the RestorationManager and '
      'therefore no restoration data has been collected to restore from. Did you forget to wrap '
      'your widget tree in a RootRestorationScope?',
    );
735 736 737 738 739 740 741 742
    return TestAsyncUtils.guard<void>(() async {
      final Widget widget = ((binding.renderViewElement! as RenderObjectToWidgetElement<RenderObject>).widget as RenderObjectToWidgetAdapter<RenderObject>).child!;
      final TestRestorationData restorationData = binding.restorationManager.restorationData;
      runApp(Container(key: UniqueKey()));
      await pump();
      binding.restorationManager.restoreFrom(restorationData);
      return _pumpWidget(widget);
    });
743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769
  }

  /// Retrieves the current restoration data from the [RestorationManager].
  ///
  /// The returned [TestRestorationData] describes the current state of the
  /// widget tree under test and can be provided to [restoreFrom] to restore
  /// the widget tree to the state described by this data.
  Future<TestRestorationData> getRestorationData() async {
    assert(
      binding.restorationManager.debugRootBucketAccessed,
      'The current widget tree did not inject the root bucket of the RestorationManager and '
      'therefore no restoration data has been collected. Did you forget to wrap your widget tree '
      'in a RootRestorationScope?',
    );
    return binding.restorationManager.restorationData;
  }

  /// Restores the widget tree under test to the state described by the
  /// provided [TestRestorationData].
  ///
  /// The data provided to this method is usually obtained from
  /// [getRestorationData].
  Future<void> restoreFrom(TestRestorationData data) {
    binding.restorationManager.restoreFrom(data);
    return pump();
  }

770 771 772 773 774 775 776 777 778 779 780 781 782 783
  /// Runs a [callback] that performs real asynchronous work.
  ///
  /// This is intended for callers who need to call asynchronous methods where
  /// the methods spawn isolates or OS threads and thus cannot be executed
  /// synchronously by calling [pump].
  ///
  /// If callers were to run these types of asynchronous tasks directly in
  /// their test methods, they run the possibility of encountering deadlocks.
  ///
  /// If [callback] completes successfully, this will return the future
  /// returned by [callback].
  ///
  /// If [callback] completes with an error, the error will be caught by the
  /// Flutter framework and made available via [takeException], and this method
784
  /// will return a future that completes with `null`.
785 786 787 788 789
  ///
  /// Re-entrant calls to this method are not allowed; callers of this method
  /// are required to wait for the returned future to complete before calling
  /// this method again. Attempts to do otherwise will result in a
  /// [TestFailure] error being thrown.
790 791 792 793 794 795 796 797 798 799 800 801
  ///
  /// If your widget test hangs and you are using [runAsync], chances are your
  /// code depends on the result of a task that did not complete. Fake async
  /// environment is unable to resolve a future that was created in [runAsync].
  /// If you observe such behavior or flakiness, you have a number of options:
  ///
  /// * Consider restructuring your code so you do not need [runAsync]. This is
  ///   the optimal solution as widget tests are designed to run in fake async
  ///   environment.
  ///
  /// * Expose a [Future] in your application code that signals the readiness of
  ///   your widget tree, then await that future inside [callback].
802
  Future<T?> runAsync<T>(
803
    Future<T> Function() callback, {
804
    Duration additionalTime = const Duration(milliseconds: 1000),
805
  }) => binding.runAsync<T?>(callback, additionalTime: additionalTime);
806

nt4f04uNd's avatar
nt4f04uNd committed
807
  /// Whether there are any transient callbacks scheduled.
808 809
  ///
  /// This essentially checks whether all animations have completed.
810 811 812 813 814 815 816 817 818 819 820
  ///
  /// See also:
  ///
  ///  * [pumpAndSettle], which essentially calls [pump] until there are no
  ///    scheduled frames.
  ///  * [SchedulerBinding.transientCallbackCount], which is the value on which
  ///    this is based.
  ///  * [SchedulerBinding.hasScheduledFrame], which is true whenever a frame is
  ///    pending. [SchedulerBinding.hasScheduledFrame] is made true when a
  ///    widget calls [State.setState], even if there are no transient callbacks
  ///    scheduled. This is what [pumpAndSettle] uses.
821 822
  bool get hasRunningAnimations => binding.transientCallbackCount > 0;

823
  @override
824
  HitTestResult hitTestOnBinding(Offset location) {
825
    assert(location != null);
826 827 828 829
    location = binding.localToGlobal(location);
    return super.hitTestOnBinding(location);
  }

830
  @override
831
  Future<void> sendEventToBinding(PointerEvent event) {
832
    return TestAsyncUtils.guard<void>(() async {
833
      binding.handlePointerEventForSource(event, source: TestBindingEventSource.test);
834 835 836
    });
  }

837
  /// Handler for device events caught by the binding in live test mode.
838 839 840 841
  ///
  /// [PointerDownEvent]s received here will only print a diagnostic message
  /// showing possible [Finder]s that can be used to interact with the widget at
  /// the location of [result].
842 843 844
  @override
  void dispatchEvent(PointerEvent event, HitTestResult result) {
    if (event is PointerDownEvent) {
845 846 847 848
      final RenderObject innerTarget = result.path
        .map((HitTestEntry candidate) => candidate.target)
        .whereType<RenderObject>()
        .first;
849 850 851
      final Element? innerTargetElement = _lastWhereOrNull(
        collectAllElementsFrom(binding.renderViewElement!, skipOffstage: true),
        (Element element) => element.renderObject == innerTarget,
852 853
      );
      if (innerTargetElement == null) {
854
        printToConsole('No widgets found at ${event.position}.');
855 856
        return;
      }
857 858 859 860 861 862
      final List<Element> candidates = <Element>[];
      innerTargetElement.visitAncestorElements((Element element) {
        candidates.add(element);
        return true;
      });
      assert(candidates.isNotEmpty);
863
      String? descendantText;
864 865 866
      int numberOfWithTexts = 0;
      int numberOfTypes = 0;
      int totalNumber = 0;
867
      printToConsole('Some possible finders for the widgets at ${event.position}:');
868
      for (final Element element in candidates) {
869
        if (totalNumber > 13) {
870
          break;
871
        }
872 873
        totalNumber += 1; // optimistically assume we'll be able to describe it

874 875
        final Widget widget = element.widget;
        if (widget is Tooltip) {
876 877
          final String message = widget.message ?? widget.richMessage!.toPlainText();
          final Iterable<Element> matches = find.byTooltip(message).evaluate();
878
          if (matches.length == 1) {
879
            printToConsole("  find.byTooltip('$message')");
880 881 882
            continue;
          }
        }
883

884
        if (widget is Text) {
885
          assert(descendantText == null);
886 887 888
          assert(widget.data != null || widget.textSpan != null);
          final String text = widget.data ?? widget.textSpan!.toPlainText();
          final Iterable<Element> matches = find.text(text).evaluate();
889 890
          descendantText = widget.data;
          if (matches.length == 1) {
891
            printToConsole("  find.text('$text')");
892 893 894 895
            continue;
          }
        }

896
        final Key? key = widget.key;
897
        if (key is ValueKey<dynamic>) {
898
          String? keyLabel;
899 900 901
          if (key is ValueKey<int> ||
              key is ValueKey<double> ||
              key is ValueKey<bool>) {
902
            keyLabel = 'const ${key.runtimeType}(${key.value})';
903
          } else if (key is ValueKey<String>) {
904
            keyLabel = "const Key('${key.value}')";
905 906 907 908
          }
          if (keyLabel != null) {
            final Iterable<Element> matches = find.byKey(key).evaluate();
            if (matches.length == 1) {
909
              printToConsole('  find.byKey($keyLabel)');
910 911 912 913 914
              continue;
            }
          }
        }

915
        if (!_isPrivate(widget.runtimeType)) {
916
          if (numberOfTypes < 5) {
917
            final Iterable<Element> matches = find.byType(widget.runtimeType).evaluate();
918
            if (matches.length == 1) {
919
              printToConsole('  find.byType(${widget.runtimeType})');
920 921 922 923 924 925
              numberOfTypes += 1;
              continue;
            }
          }

          if (descendantText != null && numberOfWithTexts < 5) {
926
            final Iterable<Element> matches = find.widgetWithText(widget.runtimeType, descendantText).evaluate();
927
            if (matches.length == 1) {
928
              printToConsole("  find.widgetWithText(${widget.runtimeType}, '$descendantText')");
929 930 931 932 933 934 935 936 937
              numberOfWithTexts += 1;
              continue;
            }
          }
        }

        if (!_isPrivate(element.runtimeType)) {
          final Iterable<Element> matches = find.byElementType(element.runtimeType).evaluate();
          if (matches.length == 1) {
938
            printToConsole('  find.byElementType(${element.runtimeType})');
939 940 941 942 943 944
            continue;
          }
        }

        totalNumber -= 1; // if we got here, we didn't actually find something to say about it
      }
945
      if (totalNumber == 0) {
946
        printToConsole('  <could not come up with any unique finders>');
947
      }
948 949 950 951
    }
  }

  bool _isPrivate(Type type) {
952
    // used above so that we don't suggest matchers for private types
953 954 955
    return '_'.matchAsPrefix(type.toString()) != null;
  }

956 957
  /// Returns the exception most recently caught by the Flutter framework.
  ///
958
  /// See [TestWidgetsFlutterBinding.takeException] for details.
959
  dynamic takeException() {
960
    return binding.takeException();
961 962
  }

963 964 965 966 967 968 969
  /// {@macro flutter.flutter_test.TakeAccessibilityAnnouncements}
  ///
  /// See [TestWidgetsFlutterBinding.takeAnnouncements] for details.
  List<CapturedAccessibilityAnnouncement> takeAnnouncements() {
    return binding.takeAnnouncements();
  }

970 971
  /// Acts as if the application went idle.
  ///
972
  /// Runs all remaining microtasks, including those scheduled as a result of
973 974
  /// running them, until there are no more microtasks scheduled. Then, runs any
  /// previously scheduled timers with zero time, and completes the returned future.
975
  ///
976 977 978
  /// May result in an infinite loop or run out of memory if microtasks continue
  /// to recursively schedule new microtasks. Will not run any timers scheduled
  /// after this method was invoked, even if they are zero-time timers.
979 980
  Future<void> idle() {
    return TestAsyncUtils.guard<void>(() => binding.idle());
981
  }
982

983
  Set<Ticker>? _tickers;
984 985 986

  @override
  Ticker createTicker(TickerCallback onTick) {
987
    _tickers ??= <_TestTicker>{};
988
    final _TestTicker result = _TestTicker(onTick, _removeTicker);
989
    _tickers!.add(result);
990 991 992 993 994
    return result;
  }

  void _removeTicker(_TestTicker ticker) {
    assert(_tickers != null);
995 996
    assert(_tickers!.contains(ticker));
    _tickers!.remove(ticker);
997 998 999 1000 1001 1002 1003 1004 1005 1006 1007
  }

  /// Throws an exception if any tickers created by the [WidgetTester] are still
  /// active when the method is called.
  ///
  /// An argument can be specified to provide a string that will be used in the
  /// error message. It should be an adverbial phrase describing the current
  /// situation, such as "at the end of the test".
  void verifyTickersWereDisposed([ String when = 'when none should have been' ]) {
    assert(when != null);
    if (_tickers != null) {
1008
      for (final Ticker ticker in _tickers!) {
1009
        if (ticker.isActive) {
1010 1011 1012 1013 1014 1015 1016 1017
          throw FlutterError.fromParts(<DiagnosticsNode>[
            ErrorSummary('A Ticker was active $when.'),
            ErrorDescription('All Tickers must be disposed.'),
            ErrorHint(
              'Tickers used by AnimationControllers '
              'should be disposed by calling dispose() on the AnimationController itself. '
              'Otherwise, the ticker will leak.'
            ),
1018
            ticker.describeForError('The offending ticker was'),
1019
          ]);
1020 1021 1022 1023 1024 1025 1026
        }
      }
    }
  }

  void _endOfTestVerifications() {
    verifyTickersWereDisposed('at the end of the test');
1027 1028 1029 1030
    _verifySemanticsHandlesWereDisposed();
  }

  void _verifySemanticsHandlesWereDisposed() {
1031
    assert(_lastRecordedSemanticsHandles != null);
1032
    if (binding.pipelineOwner.debugOutstandingSemanticsHandles > _lastRecordedSemanticsHandles!) {
1033 1034 1035 1036 1037 1038 1039 1040 1041 1042
      throw FlutterError.fromParts(<DiagnosticsNode>[
        ErrorSummary('A SemanticsHandle was active at the end of the test.'),
        ErrorDescription(
          'All SemanticsHandle instances must be disposed by calling dispose() on '
          'the SemanticsHandle.'
        ),
        ErrorHint(
          'If your test uses SemanticsTester, it is '
          'sufficient to call dispose() on SemanticsTester. Otherwise, the '
          'existing handle will leak into another test and alter its behavior.'
1043
        ),
1044
      ]);
1045
    }
1046 1047 1048
    _lastRecordedSemanticsHandles = null;
  }

1049
  int? _lastRecordedSemanticsHandles;
1050 1051 1052

  void _recordNumberOfSemanticsHandles() {
    _lastRecordedSemanticsHandles = binding.pipelineOwner.debugOutstandingSemanticsHandles;
1053
  }
1054 1055 1056 1057

  /// Returns the TestTextInput singleton.
  ///
  /// Typical app tests will not need to use this value. To add text to widgets
1058
  /// like [TextField] or [TextFormField], call [enterText].
1059
  ///
1060 1061 1062 1063 1064 1065
  /// Some of the properties and methods on this value are only valid if the
  /// binding's [TestWidgetsFlutterBinding.registerTestTextInput] flag is set to
  /// true as a test is starting (meaning that the keyboard is to be simulated
  /// by the test framework). If those members are accessed when using a binding
  /// that sets this flag to false, they will throw.
  TestTextInput get testTextInput => binding.testTextInput;
1066

1067
  /// Give the text input widget specified by [finder] the focus, as if the
1068 1069
  /// onscreen keyboard had appeared.
  ///
1070 1071
  /// Implies a call to [pump].
  ///
1072 1073
  /// The widget specified by [finder] must be an [EditableText] or have
  /// an [EditableText] descendant. For example `find.byType(TextField)`
1074
  /// or `find.byType(TextFormField)`, or `find.byType(EditableText)`.
1075 1076
  ///
  /// Tests that just need to add text to widgets like [TextField]
1077
  /// or [TextFormField] only need to call [enterText].
1078 1079
  Future<void> showKeyboard(Finder finder) async {
    return TestAsyncUtils.guard<void>(() async {
1080
      final EditableTextState editable = state<EditableTextState>(
1081 1082
        find.descendant(
          of: finder,
1083
          matching: find.byType(EditableText, skipOffstage: finder.skipOffstage),
1084 1085 1086
          matchRoot: true,
        ),
      );
1087 1088 1089
      // Setting focusedEditable causes the binding to call requestKeyboard()
      // on the EditableTextState, which itself eventually calls TextInput.attach
      // to establish the connection.
1090 1091
      binding.focusedEditable = editable;
      await pump();
1092
    });
1093 1094
  }

1095 1096
  /// Give the text input widget specified by [finder] the focus and replace its
  /// content with [text], as if it had been provided by the onscreen keyboard.
1097 1098 1099
  ///
  /// The widget specified by [finder] must be an [EditableText] or have
  /// an [EditableText] descendant. For example `find.byType(TextField)`
1100
  /// or `find.byType(TextFormField)`, or `find.byType(EditableText)`.
1101
  ///
1102 1103 1104
  /// When the returned future completes, the text input widget's text will be
  /// exactly `text`, and the caret will be placed at the end of `text`.
  ///
1105 1106
  /// To just give [finder] the focus without entering any text,
  /// see [showKeyboard].
1107 1108 1109 1110 1111 1112
  ///
  /// To enter text into other widgets (e.g. a custom widget that maintains a
  /// TextInputConnection the way that a [EditableText] does), first ensure that
  /// that widget has an open connection (e.g. by using [tap] to to focus it),
  /// then call `testTextInput.enterText` directly (see
  /// [TestTextInput.enterText]).
1113 1114
  Future<void> enterText(Finder finder, String text) async {
    return TestAsyncUtils.guard<void>(() async {
1115 1116 1117 1118
      await showKeyboard(finder);
      testTextInput.enterText(text);
      await idle();
    });
1119
  }
1120 1121 1122 1123 1124 1125

  /// Makes an effort to dismiss the current page with a Material [Scaffold] or
  /// a [CupertinoPageScaffold].
  ///
  /// Will throw an error if there is no back button in the page.
  Future<void> pageBack() async {
1126
    return TestAsyncUtils.guard<void>(() async {
1127 1128
      Finder backButton = find.byTooltip('Back');
      if (backButton.evaluate().isEmpty) {
1129
        backButton = find.byType(CupertinoNavigationBarBackButton);
1130
      }
1131

1132
      expectSync(backButton, findsOneWidget, reason: 'One back button expected on screen');
1133

1134 1135
      await tap(backButton);
    });
1136
  }
1137 1138 1139 1140 1141

  @override
  void printToConsole(String message) {
    binding.debugPrintOverride(message);
  }
1142 1143
}

1144
typedef _TickerDisposeCallback = void Function(_TestTicker ticker);
1145 1146

class _TestTicker extends Ticker {
1147
  _TestTicker(super.onTick, this._onDispose);
1148

1149
  final _TickerDisposeCallback _onDispose;
1150 1151 1152

  @override
  void dispose() {
1153
    _onDispose(this);
1154 1155
    super.dispose();
  }
1156
}