widget_tester_test.dart 29.5 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:io';
7

8
import 'package:flutter/cupertino.dart';
9
import 'package:flutter/foundation.dart';
10
import 'package:flutter/gestures.dart';
11
import 'package:flutter/material.dart';
12
import 'package:flutter/rendering.dart';
13
import 'package:flutter/scheduler.dart';
14
import 'package:flutter_test/flutter_test.dart';
15
import 'package:test_api/src/expect/async_matcher.dart'; // ignore: implementation_imports
16
// ignore: deprecated_member_use
17
import 'package:test_api/test_api.dart' as test_package;
18

19 20 21
const List<Widget> fooBarTexts = <Text>[
  Text('foo', textDirection: TextDirection.ltr),
  Text('bar', textDirection: TextDirection.ltr),
Ian Hickson's avatar
Ian Hickson committed
22 23
];

24
void main() {
25 26
  group('expectLater', () {
    testWidgets('completes when matcher completes', (WidgetTester tester) async {
27 28
      final Completer<void> completer = Completer<void>();
      final Future<void> future = expectLater(null, FakeMatcher(completer));
29
      String? result;
30 31
      future.then<void>((void value) {
        result = '123';
32
      });
33
      test_package.expect(result, isNull);
34
      completer.complete();
35
      test_package.expect(result, isNull);
36 37
      await future;
      await tester.pump();
38
      test_package.expect(result, '123');
39
    });
40 41

    testWidgets('respects the skip flag', (WidgetTester tester) async {
42
      final Completer<void> completer = Completer<void>();
43
      final Future<void> future = expectLater(null, FakeMatcher(completer), skip: 'testing skip'); // [intended] API testing
44
      bool completed = false;
45
      future.then<void>((_) {
46 47 48 49 50
        completed = true;
      });
      test_package.expect(completed, isFalse);
      await future;
      test_package.expect(completed, isTrue);
51
    });
52 53
  });

54 55 56 57
  group('respects the group skip flag', () {
    testWidgets('should be skipped', (WidgetTester tester) async {
      expect(false, true);
    });
58
  }, skip: true); // [intended] API testing
59

60
  group('findsOneWidget', () {
61
    testWidgets('finds exactly one widget', (WidgetTester tester) async {
Ian Hickson's avatar
Ian Hickson committed
62
      await tester.pumpWidget(const Text('foo', textDirection: TextDirection.ltr));
63
      expect(find.text('foo'), findsOneWidget);
64 65
    });

66
    testWidgets('fails with a descriptive message', (WidgetTester tester) async {
67
      late TestFailure failure;
68
      try {
69
        expect(find.text('foo', skipOffstage: false), findsOneWidget);
70
      } on TestFailure catch (e) {
71 72 73 74
        failure = e;
      }

      expect(failure, isNotNull);
75
      final String? message = failure.message;
76
      expect(message, contains('Expected: exactly one matching node in the widget tree\n'));
77
      expect(message, contains('Actual: _TextFinder:<zero widgets with text "foo">\n'));
78
      expect(message, contains('Which: means none were found but one was expected\n'));
79 80 81
    });
  });

82
  group('findsNothing', () {
83
    testWidgets('finds no widgets', (WidgetTester tester) async {
84
      expect(find.text('foo'), findsNothing);
85 86
    });

87
    testWidgets('fails with a descriptive message', (WidgetTester tester) async {
Ian Hickson's avatar
Ian Hickson committed
88
      await tester.pumpWidget(const Text('foo', textDirection: TextDirection.ltr));
89

90
      late TestFailure failure;
91
      try {
92
        expect(find.text('foo', skipOffstage: false), findsNothing);
93
      } on TestFailure catch (e) {
94 95 96 97
        failure = e;
      }

      expect(failure, isNotNull);
98
      final String? message = failure.message;
99 100

      expect(message, contains('Expected: no matching nodes in the widget tree\n'));
101
      expect(message, contains('Actual: _TextFinder:<exactly one widget with text "foo": Text("foo", textDirection: ltr)>\n'));
102
      expect(message, contains('Which: means one was found but none were expected\n'));
103
    });
104 105

    testWidgets('fails with a descriptive message when skipping', (WidgetTester tester) async {
Ian Hickson's avatar
Ian Hickson committed
106
      await tester.pumpWidget(const Text('foo', textDirection: TextDirection.ltr));
107

108
      late TestFailure failure;
109 110
      try {
        expect(find.text('foo'), findsNothing);
111
      } on TestFailure catch (e) {
112 113 114 115
        failure = e;
      }

      expect(failure, isNotNull);
116
      final String? message = failure.message;
117 118

      expect(message, contains('Expected: no matching nodes in the widget tree\n'));
119
      expect(message, contains('Actual: _TextFinder:<exactly one widget with text "foo" (ignoring offstage widgets): Text("foo", textDirection: ltr)>\n'));
120 121
      expect(message, contains('Which: means one was found but none were expected\n'));
    });
122
  });
123

124
  group('pumping', () {
125
    testWidgets('pumping', (WidgetTester tester) async {
Ian Hickson's avatar
Ian Hickson committed
126
      await tester.pumpWidget(const Text('foo', textDirection: TextDirection.ltr));
127 128
      int count;

129
      final AnimationController test = AnimationController(
130 131 132
        duration: const Duration(milliseconds: 5100),
        vsync: tester,
      );
133 134
      count = await tester.pumpAndSettle(const Duration(seconds: 1));
      expect(count, 1); // it always pumps at least one frame
135 136

      test.forward(from: 0.0);
137
      count = await tester.pumpAndSettle(const Duration(seconds: 1));
138 139 140 141 142 143 144 145 146 147 148
      // 1 frame at t=0, starting the animation
      // 1 frame at t=1
      // 1 frame at t=2
      // 1 frame at t=3
      // 1 frame at t=4
      // 1 frame at t=5
      // 1 frame at t=6, ending the animation
      expect(count, 7);

      test.forward(from: 0.0);
      await tester.pump(); // starts the animation
149
      count = await tester.pumpAndSettle(const Duration(seconds: 1));
150 151 152 153 154
      expect(count, 6);

      test.forward(from: 0.0);
      await tester.pump(); // starts the animation
      await tester.pump(); // has no effect
155
      count = await tester.pumpAndSettle(const Duration(seconds: 1));
156 157
      expect(count, 6);
    });
158 159 160

    testWidgets('pumpFrames', (WidgetTester tester) async {
      final List<int> logPaints = <int>[];
161
      int? initial;
162 163 164

      final Widget target = _AlwaysAnimating(
        onPaint: () {
165
          final int current = SchedulerBinding.instance.currentFrameTimeStamp.inMicroseconds;
166
          initial ??= current;
167
          logPaints.add(current - initial!);
168 169 170 171 172 173 174 175 176 177 178 179
        },
      );

      await tester.pumpFrames(target, const Duration(milliseconds: 55));

      expect(logPaints, <int>[0, 17000, 34000, 50000]);
      logPaints.clear();

      await tester.pumpFrames(target, const Duration(milliseconds: 30), const Duration(milliseconds: 10));

      expect(logPaints, <int>[60000, 70000, 80000]);
    });
180
  });
181

182 183
  group('find.byElementPredicate', () {
    testWidgets('fails with a custom description in the message', (WidgetTester tester) async {
Ian Hickson's avatar
Ian Hickson committed
184
      await tester.pumpWidget(const Text('foo', textDirection: TextDirection.ltr));
185

186
      const String customDescription = 'custom description';
187
      late TestFailure failure;
188 189
      try {
        expect(find.byElementPredicate((_) => false, description: customDescription), findsOneWidget);
190
      } on TestFailure catch (e) {
191 192 193 194
        failure = e;
      }

      expect(failure, isNotNull);
195
      expect(failure.message, contains('Actual: _ElementPredicateFinder:<zero widgets with $customDescription'));
196 197 198 199 200
    });
  });

  group('find.byWidgetPredicate', () {
    testWidgets('fails with a custom description in the message', (WidgetTester tester) async {
Ian Hickson's avatar
Ian Hickson committed
201
      await tester.pumpWidget(const Text('foo', textDirection: TextDirection.ltr));
202

203
      const String customDescription = 'custom description';
204
      late TestFailure failure;
205 206
      try {
        expect(find.byWidgetPredicate((_) => false, description: customDescription), findsOneWidget);
207
      } on TestFailure catch (e) {
208 209 210 211
        failure = e;
      }

      expect(failure, isNotNull);
212
      expect(failure.message, contains('Actual: _WidgetPredicateFinder:<zero widgets with $customDescription'));
213 214
    });
  });
215 216 217

  group('find.descendant', () {
    testWidgets('finds one descendant', (WidgetTester tester) async {
218
      await tester.pumpWidget(Row(
219 220
        textDirection: TextDirection.ltr,
        children: <Widget>[
221
          Column(children: fooBarTexts),
222 223
        ],
      ));
224 225 226

      expect(find.descendant(
        of: find.widgetWithText(Row, 'foo'),
227
        matching: find.text('bar'),
228 229 230 231
      ), findsOneWidget);
    });

    testWidgets('finds two descendants with different ancestors', (WidgetTester tester) async {
232
      await tester.pumpWidget(Row(
233 234
        textDirection: TextDirection.ltr,
        children: <Widget>[
235 236
          Column(children: fooBarTexts),
          Column(children: fooBarTexts),
237 238
        ],
      ));
239 240 241

      expect(find.descendant(
        of: find.widgetWithText(Column, 'foo'),
242
        matching: find.text('bar'),
243 244 245 246
      ), findsNWidgets(2));
    });

    testWidgets('fails with a descriptive message', (WidgetTester tester) async {
247
      await tester.pumpWidget(Row(
248 249
        textDirection: TextDirection.ltr,
        children: <Widget>[
250
          Column(children: const <Text>[Text('foo', textDirection: TextDirection.ltr)]),
Ian Hickson's avatar
Ian Hickson committed
251
          const Text('bar', textDirection: TextDirection.ltr),
252 253
        ],
      ));
254

255
      late TestFailure failure;
256 257 258
      try {
        expect(find.descendant(
          of: find.widgetWithText(Column, 'foo'),
259
          matching: find.text('bar'),
260
        ), findsOneWidget);
261
      } on TestFailure catch (e) {
262 263 264 265 266
        failure = e;
      }

      expect(failure, isNotNull);
      expect(
267
        failure.message,
268
        contains(
269
          'Actual: _DescendantFinder:<zero widgets with text "bar" that has ancestor(s) with type "Column" which is an ancestor of text "foo"',
270
        ),
271
      );
272
    });
273
  });
274

275 276
  group('find.ancestor', () {
    testWidgets('finds one ancestor', (WidgetTester tester) async {
277
      await tester.pumpWidget(Row(
278 279
        textDirection: TextDirection.ltr,
        children: <Widget>[
280
          Column(children: fooBarTexts),
281 282
        ],
      ));
283

284 285 286 287 288 289 290 291
      expect(find.ancestor(
        of: find.text('bar'),
        matching: find.widgetWithText(Row, 'foo'),
      ), findsOneWidget);
    });

    testWidgets('finds two matching ancestors, one descendant', (WidgetTester tester) async {
      await tester.pumpWidget(
292
        Directionality(
293
          textDirection: TextDirection.ltr,
294
          child: Row(
295
            children: <Widget>[
296
              Row(children: fooBarTexts),
297 298 299 300 301 302 303
            ],
          ),
        ),
      );

      expect(find.ancestor(
        of: find.text('bar'),
304
        matching: find.byType(Row),
305 306 307 308
      ), findsNWidgets(2));
    });

    testWidgets('fails with a descriptive message', (WidgetTester tester) async {
309
      await tester.pumpWidget(Row(
310 311
        textDirection: TextDirection.ltr,
        children: <Widget>[
312
          Column(children: const <Text>[Text('foo', textDirection: TextDirection.ltr)]),
313 314 315 316
          const Text('bar', textDirection: TextDirection.ltr),
        ],
      ));

317
      late TestFailure failure;
318 319 320 321 322
      try {
        expect(find.ancestor(
          of: find.text('bar'),
          matching: find.widgetWithText(Column, 'foo'),
        ), findsOneWidget);
323
      } on TestFailure catch (e) {
324 325 326 327 328 329
        failure = e;
      }

      expect(failure, isNotNull);
      expect(
        failure.message,
330
        contains(
331
          'Actual: _AncestorFinder:<zero widgets with type "Column" which is an ancestor of text "foo" which is an ancestor of text "bar"',
332
        ),
333 334 335 336
      );
    });

    testWidgets('Root not matched by default', (WidgetTester tester) async {
337
      await tester.pumpWidget(Row(
338 339
        textDirection: TextDirection.ltr,
        children: <Widget>[
340
          Column(children: fooBarTexts),
341 342 343 344 345 346
        ],
      ));

      expect(find.ancestor(
        of: find.byType(Column),
        matching: find.widgetWithText(Column, 'foo'),
347 348 349 350
      ), findsNothing);
    });

    testWidgets('Match the root', (WidgetTester tester) async {
351
      await tester.pumpWidget(Row(
352 353
        textDirection: TextDirection.ltr,
        children: <Widget>[
354
          Column(children: fooBarTexts),
355 356
        ],
      ));
357 358

      expect(find.descendant(
359 360
        of: find.byType(Column),
        matching: find.widgetWithText(Column, 'foo'),
361 362 363
        matchRoot: true,
      ), findsOneWidget);
    });
364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387

    testWidgets('is fast in deep tree', (WidgetTester tester) async {
      await tester.pumpWidget(
        Directionality(
          textDirection: TextDirection.ltr,
          child: _deepWidgetTree(
            depth: 1000,
            child: Row(
              children: <Widget>[
                _deepWidgetTree(
                  depth: 1000,
                  child: Column(children: fooBarTexts),
                ),
              ],
            ),
          ),
        ),
      );

      expect(find.ancestor(
        of: find.text('bar'),
        matching: find.byType(Row),
      ), findsOneWidget);
    });
388
  });
389

390
  group('pageBack', () {
391
    testWidgets('fails when there are no back buttons', (WidgetTester tester) async {
392
      await tester.pumpWidget(Container());
393 394 395

      expect(
        expectAsync0(tester.pageBack),
Dan Field's avatar
Dan Field committed
396
        throwsA(isA<TestFailure>()),
397 398 399 400 401
      );
    });

    testWidgets('successfully taps material back buttons', (WidgetTester tester) async {
      await tester.pumpWidget(
402 403 404
        MaterialApp(
          home: Center(
            child: Builder(
405
              builder: (BuildContext context) {
406
                return ElevatedButton(
407 408
                  child: const Text('Next'),
                  onPressed: () {
409
                    Navigator.push<void>(context, MaterialPageRoute<void>(
410
                      builder: (BuildContext context) {
411 412
                        return Scaffold(
                          appBar: AppBar(
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
                            title: const Text('Page 2'),
                          ),
                        );
                      },
                    ));
                  },
                );
              } ,
            ),
          ),
        ),
      );

      await tester.tap(find.text('Next'));
      await tester.pump();
      await tester.pump(const Duration(milliseconds: 400));

      await tester.pageBack();
      await tester.pump();
      await tester.pump(const Duration(milliseconds: 400));

      expect(find.text('Next'), findsOneWidget);
      expect(find.text('Page 2'), findsNothing);
    });

    testWidgets('successfully taps cupertino back buttons', (WidgetTester tester) async {
      await tester.pumpWidget(
440 441 442
        MaterialApp(
          home: Center(
            child: Builder(
443
              builder: (BuildContext context) {
444
                return CupertinoButton(
445 446
                  child: const Text('Next'),
                  onPressed: () {
447
                    Navigator.push<void>(context, CupertinoPageRoute<void>(
448
                      builder: (BuildContext context) {
449
                        return CupertinoPageScaffold(
450
                          navigationBar: const CupertinoNavigationBar(
451
                            middle: Text('Page 2'),
452
                          ),
453
                          child: Container(),
454 455 456 457 458 459 460 461 462 463 464 465 466
                        );
                      },
                    ));
                  },
                );
              } ,
            ),
          ),
        ),
      );

      await tester.tap(find.text('Next'));
      await tester.pump();
467
      await tester.pump(const Duration(milliseconds: 400));
468 469 470

      await tester.pageBack();
      await tester.pump();
471
      await tester.pumpAndSettle();
472 473 474 475 476 477

      expect(find.text('Next'), findsOneWidget);
      expect(find.text('Page 2'), findsNothing);
    });
  });

478
  testWidgets('hasRunningAnimations control test', (WidgetTester tester) async {
479
    final AnimationController controller = AnimationController(
480
      duration: const Duration(seconds: 1),
481
      vsync: const TestVSync(),
482 483 484 485 486 487 488 489 490 491 492
    );
    expect(tester.hasRunningAnimations, isFalse);
    controller.forward();
    expect(tester.hasRunningAnimations, isTrue);
    controller.stop();
    expect(tester.hasRunningAnimations, isFalse);
    controller.forward();
    expect(tester.hasRunningAnimations, isTrue);
    await tester.pumpAndSettle();
    expect(tester.hasRunningAnimations, isFalse);
  });
493 494

  testWidgets('pumpAndSettle control test', (WidgetTester tester) async {
495
    final AnimationController controller = AnimationController(
496
      duration: const Duration(minutes: 525600),
497
      vsync: const TestVSync(),
498 499 500
    );
    expect(await tester.pumpAndSettle(), 1);
    controller.forward();
501 502 503 504 505 506 507 508 509 510
    try {
      await tester.pumpAndSettle();
      expect(true, isFalse);
    } catch (e) {
      expect(e, isFlutterError);
    }
    controller.stop();
    expect(await tester.pumpAndSettle(), 1);
    controller.duration = const Duration(seconds: 1);
    controller.forward();
511 512
    expect(await tester.pumpAndSettle(const Duration(milliseconds: 300)), 5); // 0, 300, 600, 900, 1200ms
  });
513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552

  testWidgets('Input event array', (WidgetTester tester) async {
      final List<String> logs = <String>[];

      await tester.pumpWidget(
        Directionality(
          textDirection: TextDirection.ltr,
          child: Listener(
            onPointerDown: (PointerDownEvent event) => logs.add('down ${event.buttons}'),
            onPointerMove: (PointerMoveEvent event) => logs.add('move ${event.buttons}'),
            onPointerUp: (PointerUpEvent event) => logs.add('up ${event.buttons}'),
            child: const Text('test'),
          ),
        ),
      );

      final Offset location = tester.getCenter(find.text('test'));
      final List<PointerEventRecord> records = <PointerEventRecord>[
        PointerEventRecord(Duration.zero, <PointerEvent>[
          // Typically PointerAddedEvent is not used in testers, but for records
          // captured on a device it is usually what start a gesture.
          PointerAddedEvent(
            position: location,
          ),
          PointerDownEvent(
            position: location,
            buttons: kSecondaryMouseButton,
            pointer: 1,
          ),
        ]),
        ...<PointerEventRecord>[
          for (Duration t = const Duration(milliseconds: 5);
               t < const Duration(milliseconds: 80);
               t += const Duration(milliseconds: 16))
            PointerEventRecord(t, <PointerEvent>[
              PointerMoveEvent(
                timeStamp: t - const Duration(milliseconds: 1),
                position: location,
                buttons: kSecondaryMouseButton,
                pointer: 1,
553 554
              ),
            ]),
555 556 557 558 559 560 561
        ],
        PointerEventRecord(const Duration(milliseconds: 80), <PointerEvent>[
          PointerUpEvent(
            timeStamp: const Duration(milliseconds: 79),
            position: location,
            buttons: kSecondaryMouseButton,
            pointer: 1,
562 563
          ),
        ]),
564 565 566 567 568 569 570 571 572 573 574 575 576 577
      ];
      final List<Duration> timeDiffs = await tester.handlePointerEventRecord(records);
      expect(timeDiffs.length, records.length);
      for (final Duration diff in timeDiffs) {
        expect(diff, Duration.zero);
      }

      const String b = '$kSecondaryMouseButton';
      expect(logs.first, 'down $b');
      for (int i = 1; i < logs.length - 1; i++) {
        expect(logs[i], 'move $b');
      }
      expect(logs.last, 'up $b');
  });
578 579 580

  group('runAsync', () {
    testWidgets('works with no async calls', (WidgetTester tester) async {
581
      String? value;
582 583 584 585 586 587 588
      await tester.runAsync(() async {
        value = '123';
      });
      expect(value, '123');
    });

    testWidgets('works with real async calls', (WidgetTester tester) async {
589
      final StringBuffer buf = StringBuffer('1');
590 591
      await tester.runAsync(() async {
        buf.write('2');
592
        //ignore: avoid_slow_async_io
593 594 595 596 597 598 599 600
        await Directory.current.stat();
        buf.write('3');
      });
      buf.write('4');
      expect(buf.toString(), '1234');
    });

    testWidgets('propagates return values', (WidgetTester tester) async {
601
      final String? value = await tester.runAsync<String>(() async {
602 603 604 605 606 607
        return '123';
      });
      expect(value, '123');
    });

    testWidgets('reports errors via framework', (WidgetTester tester) async {
608
      final String? value = await tester.runAsync<String>(() async {
609
        throw ArgumentError();
610 611 612 613 614 615
      });
      expect(value, isNull);
      expect(tester.takeException(), isArgumentError);
    });

    testWidgets('disallows re-entry', (WidgetTester tester) async {
616
      final Completer<void> completer = Completer<void>();
617
      tester.runAsync<void>(() => completer.future);
Dan Field's avatar
Dan Field committed
618
      expect(() => tester.runAsync(() async { }), throwsA(isA<TestFailure>()));
619 620
      completer.complete();
    });
621 622

    testWidgets('maintains existing zone values', (WidgetTester tester) async {
623
      final Object key = Object();
624
      await runZoned<Future<void>>(() {
625
        expect(Zone.current[key], 'abczed');
626
        return tester.runAsync<void>(() async {
627 628 629 630 631 632
          expect(Zone.current[key], 'abczed');
        });
      }, zoneValues: <dynamic, dynamic>{
        key: 'abczed',
      });
    });
633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649

    testWidgets('control test (return value)', (WidgetTester tester) async {
      final String? result = await tester.binding.runAsync<String>(() async => 'Judy Turner');
      expect(result, 'Judy Turner');
    });

    testWidgets('async throw', (WidgetTester tester) async {
      final String? result = await tester.binding.runAsync<Never>(() async => throw Exception('Lois Dilettente'));
      expect(result, isNull);
      expect(tester.takeException(), isNotNull);
    });

    testWidgets('sync throw', (WidgetTester tester) async {
      final String? result = await tester.binding.runAsync<Never>(() => throw Exception('Butch Barton'));
      expect(result, isNull);
      expect(tester.takeException(), isNotNull);
    });
650
  });
651

652 653 654 655 656 657 658 659
  group('showKeyboard', () {
    testWidgets('can be called twice', (WidgetTester tester) async {
      await tester.pumpWidget(
        MaterialApp(
          home: Material(
            child: Center(
              child: TextFormField(),
            ),
660 661
          ),
        ),
662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687
      );
      await tester.showKeyboard(find.byType(TextField));
      await tester.testTextInput.receiveAction(TextInputAction.done);
      await tester.pump();
      await tester.showKeyboard(find.byType(TextField));
      await tester.testTextInput.receiveAction(TextInputAction.done);
      await tester.pump();
      await tester.showKeyboard(find.byType(TextField));
      await tester.showKeyboard(find.byType(TextField));
      await tester.pump();
    });

    testWidgets(
      'can focus on offstage text input field if finder says not to skip offstage nodes',
      (WidgetTester tester) async {
        await tester.pumpWidget(
          MaterialApp(
            home: Material(
              child: Offstage(
                child: TextFormField(),
              ),
            ),
          ),
        );
        await tester.showKeyboard(find.byType(TextField, skipOffstage: false));
      });
688
  });
689

690
  testWidgets('verifyTickersWereDisposed control test', (WidgetTester tester) async {
691
    late FlutterError error;
692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707
    final Ticker ticker = tester.createTicker((Duration duration) {});
    ticker.start();
    try {
      tester.verifyTickersWereDisposed('');
    } on FlutterError catch (e) {
      error = e;
    } finally {
      expect(error, isNotNull);
      expect(error.diagnostics.length, 4);
      expect(error.diagnostics[2].level, DiagnosticLevel.hint);
      expect(
        error.diagnostics[2].toStringDeep(),
        'Tickers used by AnimationControllers should be disposed by\n'
        'calling dispose() on the AnimationController itself. Otherwise,\n'
        'the ticker will leak.\n',
      );
Dan Field's avatar
Dan Field committed
708
      expect(error.diagnostics.last, isA<DiagnosticsProperty<Ticker>>());
709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738
      expect(error.diagnostics.last.value, ticker);
      expect(error.toStringDeep(), startsWith(
        'FlutterError\n'
        '   A Ticker was active .\n'
        '   All Tickers must be disposed.\n'
        '   Tickers used by AnimationControllers should be disposed by\n'
        '   calling dispose() on the AnimationController itself. Otherwise,\n'
        '   the ticker will leak.\n'
        '   The offending ticker was:\n'
        '     _TestTicker()\n',
      ));
    }
    ticker.stop();
  });

  group('testWidgets variants work', () {
    int numberOfVariationsRun = 0;

    testWidgets('variant tests run all values provided', (WidgetTester tester) async {
      if (debugDefaultTargetPlatformOverride == null) {
        expect(numberOfVariationsRun, equals(TargetPlatform.values.length));
      } else {
        numberOfVariationsRun += 1;
      }
    }, variant: TargetPlatformVariant(TargetPlatform.values.toSet()));

    testWidgets('variant tests have descriptions with details', (WidgetTester tester) async {
      if (debugDefaultTargetPlatformOverride == null) {
        expect(tester.testDescription, equals('variant tests have descriptions with details'));
      } else {
739 740 741 742
        expect(
          tester.testDescription,
          equals('variant tests have descriptions with details (variant: $debugDefaultTargetPlatformOverride)'),
        );
743 744 745 746 747 748
      }
    }, variant: TargetPlatformVariant(TargetPlatform.values.toSet()));
  });

  group('TargetPlatformVariant', () {
    int numberOfVariationsRun = 0;
749
    TargetPlatform? origTargetPlatform;
750

751
    setUpAll(() {
752 753 754
      origTargetPlatform = debugDefaultTargetPlatformOverride;
    });

755
    tearDownAll(() {
756 757 758 759 760 761 762 763
      expect(debugDefaultTargetPlatformOverride, equals(origTargetPlatform));
    });

    testWidgets('TargetPlatformVariant.only tests given value', (WidgetTester tester) async {
      expect(debugDefaultTargetPlatformOverride, equals(TargetPlatform.iOS));
      expect(defaultTargetPlatform, equals(TargetPlatform.iOS));
    }, variant: TargetPlatformVariant.only(TargetPlatform.iOS));

764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786
    group('all', () {
      testWidgets('TargetPlatformVariant.all tests run all variants', (WidgetTester tester) async {
        if (debugDefaultTargetPlatformOverride == null) {
          expect(numberOfVariationsRun, equals(TargetPlatform.values.length));
        } else {
          numberOfVariationsRun += 1;
        }
      }, variant: TargetPlatformVariant.all());

      const Set<TargetPlatform> excludePlatforms = <TargetPlatform>{ TargetPlatform.android, TargetPlatform.linux };
      testWidgets('TargetPlatformVariant.all, excluding runs an all variants except those provided in excluding', (WidgetTester tester) async {
        if (debugDefaultTargetPlatformOverride == null) {
          expect(numberOfVariationsRun, equals(TargetPlatform.values.length - excludePlatforms.length));
          expect(
            excludePlatforms,
            isNot(contains(debugDefaultTargetPlatformOverride)),
            reason: 'this test should not run on any platform in excludePlatforms'
          );
        } else {
          numberOfVariationsRun += 1;
        }
      }, variant: TargetPlatformVariant.all(excluding: excludePlatforms));
    });
787 788 789 790 791 792 793

    testWidgets('TargetPlatformVariant.desktop + mobile contains all TargetPlatform values', (WidgetTester tester) async {
      final TargetPlatformVariant all = TargetPlatformVariant.all();
      final TargetPlatformVariant desktop = TargetPlatformVariant.all();
      final TargetPlatformVariant mobile = TargetPlatformVariant.all();
      expect(desktop.values.union(mobile.values), equals(all.values));
    });
794
  });
795 796

  group('Pending timer', () {
797
    late TestExceptionReporter currentExceptionReporter;
798 799 800 801 802 803 804 805 806
    setUp(() {
      currentExceptionReporter = reportTestException;
    });

    tearDown(() {
      reportTestException = currentExceptionReporter;
    });

    test('Throws assertion message without code', () async {
807
      late FlutterErrorDetails flutterErrorDetails;
808 809 810 811
      reportTestException = (FlutterErrorDetails details, String testDescription) {
        flutterErrorDetails = details;
      };

812
      final TestWidgetsFlutterBinding binding = TestWidgetsFlutterBinding.ensureInitialized();
813 814 815 816 817
      await binding.runTest(() async {
        final Timer timer = Timer(const Duration(seconds: 1), () {});
        expect(timer.isActive, true);
      }, () {});

818
      expect(flutterErrorDetails.exception, isA<AssertionError>());
819
      expect((flutterErrorDetails.exception as AssertionError).message, 'A Timer is still pending even after the widget tree was disposed.');
820 821
      expect(binding.inTest, true);
      binding.postTest();
822 823
    });
  });
824
}
825 826 827 828 829 830 831

class FakeMatcher extends AsyncMatcher {
  FakeMatcher(this.completer);

  final Completer<void> completer;

  @override
832 833
  Future<String?> matchAsync(dynamic object) {
    return completer.future.then<String?>((void value) {
834 835 836 837 838 839 840
      return object?.toString();
    });
  }

  @override
  Description describe(Description description) => description.add('--fake--');
}
841

842 843
class _AlwaysAnimating extends StatefulWidget {
  const _AlwaysAnimating({
844
    required this.onPaint,
845 846 847 848 849 850 851 852 853
  });

  final VoidCallback onPaint;

  @override
  State<StatefulWidget> createState() => _AlwaysAnimatingState();
}

class _AlwaysAnimatingState extends State<_AlwaysAnimating> with SingleTickerProviderStateMixin {
854
  late AnimationController _controller;
855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875

  @override
  void initState() {
    super.initState();
    _controller = AnimationController(
      duration: const Duration(milliseconds: 100),
      vsync: this,
    );
    _controller.repeat();
  }

  @override
  void dispose() {
    _controller.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return AnimatedBuilder(
      animation: _controller.view,
876
      builder: (BuildContext context, Widget? child) {
877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897
        return CustomPaint(
          painter: _AlwaysRepaint(widget.onPaint),
        );
      },
    );
  }
}

class _AlwaysRepaint extends CustomPainter {
  _AlwaysRepaint(this.onPaint);

  final VoidCallback onPaint;

  @override
  bool shouldRepaint(CustomPainter oldDelegate) => true;

  @override
  void paint(Canvas canvas, Size size) {
    onPaint();
  }
}
898 899 900 901 902 903 904 905 906

/// Wraps [child] in [depth] layers of [SizedBox]
Widget _deepWidgetTree({required int depth, required Widget child}) {
  Widget tree = child;
  for (int i = 0; i < depth; i += 1) {
    tree = SizedBox(child: tree);
  }
  return tree;
}