/
binding.dart
1809 lines (1644 loc) · 68.1 KB
/
binding.dart
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
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
217
218
219
220
221
222
223
224
225
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
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
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
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
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
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
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
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
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
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
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
739
740
741
742
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
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'dart:async';
import 'dart:ui' as ui;
import 'package:clock/clock.dart';
import 'package:fake_async/fake_async.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/gestures.dart';
import 'package:flutter/rendering.dart';
import 'package:flutter/scheduler.dart';
import 'package:flutter/services.dart';
import 'package:flutter/widgets.dart';
import 'package:flutter_test/flutter_test.dart' show TestWindow;
import 'package:stack_trace/stack_trace.dart' as stack_trace;
import 'package:test_api/test_api.dart' as test_package; // ignore: deprecated_member_use
import 'package:vector_math/vector_math_64.dart';
import '_binding_io.dart' if (dart.library.html) '_binding_web.dart' as binding;
import 'goldens.dart';
import 'platform.dart';
import 'restoration.dart';
import 'stack_manipulation.dart';
import 'test_async_utils.dart';
import 'test_default_binary_messenger.dart';
import 'test_exception_reporter.dart';
import 'test_text_input.dart';
/// Phases that can be reached by [WidgetTester.pumpWidget] and
/// [TestWidgetsFlutterBinding.pump].
///
/// See [WidgetsBinding.drawFrame] for a more detailed description of some of
/// these phases.
enum EnginePhase {
/// The build phase in the widgets library. See [BuildOwner.buildScope].
build,
/// The layout phase in the rendering library. See [PipelineOwner.flushLayout].
layout,
/// The compositing bits update phase in the rendering library. See
/// [PipelineOwner.flushCompositingBits].
compositingBits,
/// The paint phase in the rendering library. See [PipelineOwner.flushPaint].
paint,
/// The compositing phase in the rendering library. See
/// [RenderView.compositeFrame]. This is the phase in which data is sent to
/// the GPU. If semantics are not enabled, then this is the last phase.
composite,
/// The semantics building phase in the rendering library. See
/// [PipelineOwner.flushSemantics].
flushSemantics,
/// The final phase in the rendering library, wherein semantics information is
/// sent to the embedder. See [SemanticsOwner.sendSemanticsUpdate].
sendSemanticsUpdate,
}
/// Parts of the system that can generate pointer events that reach the test
/// binding.
///
/// This is used to identify how to handle events in the
/// [LiveTestWidgetsFlutterBinding]. See
/// [TestWidgetsFlutterBinding.dispatchEvent].
enum TestBindingEventSource {
/// The pointer event came from the test framework itself, e.g. from a
/// [TestGesture] created by [WidgetTester.startGesture].
test,
/// The pointer event came from the system, presumably as a result of the user
/// interactive directly with the device while the test was running.
device,
}
const Size _kDefaultTestViewportSize = Size(800.0, 600.0);
/// Overrides the [ServicesBinding]'s binary messenger logic to use
/// [TestDefaultBinaryMessenger].
///
/// Test bindings that are used by tests that mock message handlers for plugins
/// should mix in this binding to enable the use of the
/// [TestDefaultBinaryMessenger] APIs.
mixin TestDefaultBinaryMessengerBinding on BindingBase, ServicesBinding {
@override
void initInstances() {
super.initInstances();
_instance = this;
}
/// The current [TestDefaultBinaryMessengerBinding], if one has been created.
static TestDefaultBinaryMessengerBinding? get instance => _instance;
static TestDefaultBinaryMessengerBinding? _instance;
@override
TestDefaultBinaryMessenger get defaultBinaryMessenger => super.defaultBinaryMessenger as TestDefaultBinaryMessenger;
@override
TestDefaultBinaryMessenger createBinaryMessenger() {
return TestDefaultBinaryMessenger(super.createBinaryMessenger());
}
}
/// Base class for bindings used by widgets library tests.
///
/// The [ensureInitialized] method creates (if necessary) and returns
/// an instance of the appropriate subclass.
///
/// When using these bindings, certain features are disabled. For
/// example, [timeDilation] is reset to 1.0 on initialization.
///
/// In non-browser tests, the binding overrides `HttpClient` creation with a
/// fake client that always returns a status code of 400. This is to prevent
/// tests from making network calls, which could introduce flakiness. A test
/// that actually needs to make a network call should provide its own
/// `HttpClient` to the code making the call, so that it can appropriately mock
/// or fake responses.
abstract class TestWidgetsFlutterBinding extends BindingBase
with SchedulerBinding,
ServicesBinding,
GestureBinding,
SemanticsBinding,
RendererBinding,
PaintingBinding,
WidgetsBinding,
TestDefaultBinaryMessengerBinding {
/// Constructor for [TestWidgetsFlutterBinding].
///
/// This constructor overrides the [debugPrint] global hook to point to
/// [debugPrintOverride], which can be overridden by subclasses.
TestWidgetsFlutterBinding() : _window = TestWindow(window: ui.window) {
debugPrint = debugPrintOverride;
debugDisableShadows = disableShadows;
}
@override
TestWindow get window => _window;
final TestWindow _window;
@override
TestRestorationManager get restorationManager {
_restorationManager ??= createRestorationManager();
return _restorationManager!;
}
TestRestorationManager? _restorationManager;
/// Called by the test framework at the beginning of a widget test to
/// prepare the binding for the next test.
///
/// If [registerTestTextInput] returns true when this method is called,
/// the [testTextInput] is configured to simulate the keyboard.
void reset() {
_restorationManager = null;
resetGestureBinding();
testTextInput.reset();
if (registerTestTextInput)
_testTextInput.register();
}
@override
TestRestorationManager createRestorationManager() {
return TestRestorationManager();
}
/// The value to set [debugPrint] to while tests are running.
///
/// This can be used to redirect console output from the framework, or to
/// change the behavior of [debugPrint]. For example,
/// [AutomatedTestWidgetsFlutterBinding] uses it to make [debugPrint]
/// synchronous, disabling its normal throttling behavior.
///
/// It is also used by some other parts of the test framework (e.g.
/// [WidgetTester.printToConsole]) to ensure that messages from the
/// test framework are displayed to the developer rather than logged
/// by whatever code is overriding [debugPrint].
DebugPrintCallback get debugPrintOverride => debugPrint;
/// The value to set [debugDisableShadows] to while tests are running.
///
/// This can be used to reduce the likelihood of golden file tests being
/// flaky, because shadow rendering is not always deterministic. The
/// [AutomatedTestWidgetsFlutterBinding] sets this to true, so that all tests
/// always run with shadows disabled.
@protected
bool get disableShadows => false;
/// Determines whether the Dart [HttpClient] class should be overridden to
/// always return a failure response.
///
/// By default, this value is true, so that unit tests will not become flaky
/// due to intermittent network errors. The value may be overridden by a
/// binding intended for use in integration tests that do end to end
/// application testing, including working with real network responses.
@protected
bool get overrideHttpClient => true;
/// Determines whether the binding automatically registers [testTextInput] as
/// a fake keyboard implementation.
///
/// Unit tests make use of this to mock out text input communication for
/// widgets. An integration test would set this to false, to test real IME
/// or keyboard input.
///
/// [TestTextInput.isRegistered] reports whether the text input mock is
/// registered or not.
///
/// Some of the properties and methods on [testTextInput] are only valid if
/// [registerTestTextInput] returns true when a test starts. If those
/// members are accessed when using a binding that sets this flag to false,
/// they will throw.
///
/// If this property returns true when a test ends, the [testTextInput] is
/// unregistered.
///
/// This property should not change the value it returns during the lifetime
/// of the binding. Changing the value of this property risks very confusing
/// behavior as the [TestTextInput] may be inconsistently registered or
/// unregistered.
@protected
bool get registerTestTextInput => true;
/// Increase the timeout for the current test by the given duration.
///
/// This only matters if the test has an `initialTimeout` set on
/// [testWidgets], and the test is running via `flutter test`. By default,
/// tests do not have such a timeout. Tests run using `flutter run` never time
/// out even if one is specified.
///
/// This method has no effect on the timeout specified via `timeout` on
/// [testWidgets]. That timeout is implemented by the `test` package.
///
/// By default, each [pump] and [WidgetTester.pumpWidget] call increases the
/// timeout by a hundred milliseconds, and each [matchesGoldenFile]
/// expectation increases it by a minute. If there is no timeout in the first
/// place, this has no effect.
///
/// The granularity of timeouts is coarse: the time is checked once per
/// second, and only when the test is not executing. It is therefore possible
/// for a timeout to be exceeded by hundreds of milliseconds and for the test
/// to still succeed. If precise timing is required, it should be implemented
/// as a part of the test rather than relying on this mechanism.
///
/// See also:
///
/// * [testWidgets], on which a timeout can be set using the `timeout`
/// argument.
/// * [defaultTestTimeout], the maximum that the timeout can reach.
/// (That timeout is implemented by the `test` package.)
// See AutomatedTestWidgetsFlutterBinding.addTime for an actual implementation.
void addTime(Duration duration);
/// Delay for `duration` of time.
///
/// In the automated test environment ([AutomatedTestWidgetsFlutterBinding],
/// typically used in `flutter test`), this advances the fake [clock] for the
/// period and also increases timeout (see [addTime]).
///
/// In the live test environment ([LiveTestWidgetsFlutterBinding], typically
/// used for `flutter run` and for [e2e](https://pub.dev/packages/e2e)), it is
/// equivalent as [Future.delayed].
Future<void> delayed(Duration duration);
/// Creates and initializes the binding. This function is
/// idempotent; calling it a second time will just return the
/// previously-created instance.
///
/// This function will use [AutomatedTestWidgetsFlutterBinding] if
/// the test was run using `flutter test`, and
/// [LiveTestWidgetsFlutterBinding] otherwise (e.g. if it was run
/// using `flutter run`). This is determined by looking at the
/// environment variables for a variable called `FLUTTER_TEST`.
///
/// If `FLUTTER_TEST` is set with a value of 'true', then this test was
/// invoked by `flutter test`. If `FLUTTER_TEST` is not set, or if it is set
/// to 'false', then this test was invoked by `flutter run`.
///
/// Browser environments do not currently support the
/// [LiveTestWidgetsFlutterBinding], so this function will always set up an
/// [AutomatedTestWidgetsFlutterBinding] when run in a web browser.
///
/// The parameter `environment` is exposed to test different environment
/// variable values, and should not be used.
static WidgetsBinding ensureInitialized([@visibleForTesting Map<String, String>? environment]) => binding.ensureInitialized(environment);
@override
void initInstances() {
super.initInstances();
timeDilation = 1.0; // just in case the developer has artificially changed it for development
if (overrideHttpClient) {
binding.setupHttpOverrides();
}
_testTextInput = TestTextInput(onCleared: _resetFocusedEditable);
}
@override
// ignore: MUST_CALL_SUPER
void initLicenses() {
// Do not include any licenses, because we're a test, and the LICENSE file
// doesn't get generated for tests.
}
/// Whether there is currently a test executing.
bool get inTest;
/// The number of outstanding microtasks in the queue.
int get microtaskCount;
/// The default maximum test timeout for tests when using this binding.
///
/// This controls the default for the `timeout` argument on `testWidgets`. It
/// is 10 minutes for [AutomatedTestWidgetsFlutterBinding] (tests running
/// using `flutter test`), and unlimited for tests using
/// [LiveTestWidgetsFlutterBinding] (tests running using `flutter run`).
///
/// This is the maximum that the timeout controlled by `initialTimeout` on
/// [testWidgets] can reach when augmented using [addTime].
test_package.Timeout get defaultTestTimeout;
/// The current time.
///
/// In the automated test environment (`flutter test`), this is a fake clock
/// that begins in January 2015 at the start of the test and advances each
/// time [pump] is called with a non-zero duration.
///
/// In the live testing environment (`flutter run`), this object shows the
/// actual current wall-clock time.
Clock get clock;
/// Triggers a frame sequence (build/layout/paint/etc),
/// then flushes microtasks.
///
/// If duration is set, then advances the clock by that much first.
/// Doing this flushes microtasks.
///
/// The supplied EnginePhase is the final phase reached during the pump pass;
/// if not supplied, the whole pass is executed.
///
/// See also [LiveTestWidgetsFlutterBindingFramePolicy], which affects how
/// this method works when the test is run with `flutter run`.
Future<void> pump([ Duration? duration, EnginePhase newPhase = EnginePhase.sendSemanticsUpdate ]);
/// 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].
///
/// The `callback` must return a [Future] that completes to a value of type
/// `T`.
///
/// 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
/// will return a future that completes with `null`.
///
/// 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.
///
/// The `additionalTime` argument is used by the
/// [AutomatedTestWidgetsFlutterBinding] implementation to increase the
/// current timeout, if any. See [AutomatedTestWidgetsFlutterBinding.addTime]
/// for details.
Future<T?> runAsync<T>(
Future<T> Function() callback, {
Duration additionalTime = const Duration(milliseconds: 1000),
});
/// Artificially calls dispatchLocalesChanged on the Widget binding,
/// then flushes microtasks.
///
/// Passes only one single Locale. Use [setLocales] to pass a full preferred
/// locales list.
Future<void> setLocale(String languageCode, String countryCode) {
return TestAsyncUtils.guard<void>(() async {
assert(inTest);
final Locale locale = Locale(languageCode, countryCode == '' ? null : countryCode);
dispatchLocalesChanged(<Locale>[locale]);
});
}
/// Artificially calls dispatchLocalesChanged on the Widget binding,
/// then flushes microtasks.
Future<void> setLocales(List<Locale> locales) {
return TestAsyncUtils.guard<void>(() async {
assert(inTest);
dispatchLocalesChanged(locales);
});
}
/// Re-attempts the initialization of the lifecycle state after providing
/// test values in [TestWindow.initialLifecycleStateTestValue].
void readTestInitialLifecycleStateFromNativeWindow() {
readInitialLifecycleStateFromNativeWindow();
}
Size? _surfaceSize;
/// Artificially changes the surface size to `size` on the Widget binding,
/// then flushes microtasks.
///
/// Set to null to use the default surface size.
Future<void> setSurfaceSize(Size? size) {
return TestAsyncUtils.guard<void>(() async {
assert(inTest);
if (_surfaceSize == size)
return;
_surfaceSize = size;
handleMetricsChanged();
});
}
@override
ViewConfiguration createViewConfiguration() {
final double devicePixelRatio = window.devicePixelRatio;
final Size size = _surfaceSize ?? window.physicalSize / devicePixelRatio;
return ViewConfiguration(
size: size,
devicePixelRatio: devicePixelRatio,
);
}
/// Acts as if the application went idle.
///
/// Runs all remaining microtasks, including those scheduled as a result of
/// running them, until there are no more microtasks scheduled. Then, runs any
/// previously scheduled timers with zero time, and completes the returned future.
///
/// 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.
Future<void> idle() {
return TestAsyncUtils.guard<void>(() {
final Completer<void> completer = Completer<void>();
Timer.run(() {
completer.complete();
});
return completer.future;
});
}
/// Convert the given point from the global coordinate system (as used by
/// pointer events from the device) to the coordinate system used by the
/// tests (an 800 by 600 window).
Offset globalToLocal(Offset point) => point;
/// Convert the given point from the coordinate system used by the tests (an
/// 800 by 600 window) to the global coordinate system (as used by pointer
/// events from the device).
Offset localToGlobal(Offset point) => point;
// The source of the current pointer event.
//
// The [pointerEventSource] is set as the `source` parameter of
// [handlePointerEvent] and can be used in the immediate enclosing
// [dispatchEvent].
TestBindingEventSource _pointerEventSource = TestBindingEventSource.device;
@override
void handlePointerEvent(
PointerEvent event, {
TestBindingEventSource source = TestBindingEventSource.device,
}) {
final TestBindingEventSource previousSource = source;
_pointerEventSource = source;
try {
super.handlePointerEvent(event);
} finally {
_pointerEventSource = previousSource;
}
}
/// A stub for the system's onscreen keyboard. Callers must set the
/// [focusedEditable] before using this value.
TestTextInput get testTextInput => _testTextInput;
late TestTextInput _testTextInput;
/// The [State] of the current [EditableText] client of the onscreen keyboard.
///
/// Setting this property to a new value causes the given [EditableTextState]
/// to focus itself and request the keyboard to establish a
/// [TextInputConnection].
///
/// Callers must pump an additional frame after setting this property to
/// complete the focus change.
///
/// Instead of setting this directly, consider using
/// [WidgetTester.showKeyboard].
//
// TODO(ianh): We should just remove this property and move the call to
// requestKeyboard to the WidgetTester.showKeyboard method.
EditableTextState? get focusedEditable => _focusedEditable;
EditableTextState? _focusedEditable;
set focusedEditable(EditableTextState? value) {
if (_focusedEditable != value) {
_focusedEditable = value;
value?.requestKeyboard();
}
}
void _resetFocusedEditable() {
_focusedEditable = null;
}
/// Returns the exception most recently caught by the Flutter framework.
///
/// Call this if you expect an exception during a test. If an exception is
/// thrown and this is not called, then the exception is rethrown when
/// the [testWidgets] call completes.
///
/// If two exceptions are thrown in a row without the first one being
/// acknowledged with a call to this method, then when the second exception is
/// thrown, they are both dumped to the console and then the second is
/// rethrown from the exception handler. This will likely result in the
/// framework entering a highly unstable state and everything collapsing.
///
/// It's safe to call this when there's no pending exception; it will return
/// null in that case.
dynamic takeException() {
assert(inTest);
final dynamic result = _pendingExceptionDetails?.exception;
_pendingExceptionDetails = null;
return result;
}
FlutterExceptionHandler? _oldExceptionHandler;
late StackTraceDemangler _oldStackTraceDemangler;
FlutterErrorDetails? _pendingExceptionDetails;
static const TextStyle _messageStyle = TextStyle(
color: Color(0xFF917FFF),
fontSize: 40.0,
);
static const Widget _preTestMessage = Center(
child: Text(
'Test starting...',
style: _messageStyle,
textDirection: TextDirection.ltr,
),
);
static const Widget _postTestMessage = Center(
child: Text(
'Test finished.',
style: _messageStyle,
textDirection: TextDirection.ltr,
),
);
/// Whether to include the output of debugDumpApp() when reporting
/// test failures.
bool showAppDumpInErrors = false;
/// Call the testBody inside a [FakeAsync] scope on which [pump] can
/// advance time.
///
/// Returns a future which completes when the test has run.
///
/// Called by the [testWidgets] and [benchmarkWidgets] functions to
/// run a test.
///
/// The `invariantTester` argument is called after the `testBody`'s [Future]
/// completes. If it throws, then the test is marked as failed.
///
/// The `description` is used by the [LiveTestWidgetsFlutterBinding] to
/// show a label on the screen during the test. The description comes from
/// the value passed to [testWidgets]. It must not be null.
///
/// The `timeout` argument sets the initial timeout, if any. It can
/// be increased with [addTime]. By default there is no timeout.
Future<void> runTest(Future<void> Function() testBody, VoidCallback invariantTester, { String description = '', Duration? timeout });
/// This is called during test execution before and after the body has been
/// executed.
///
/// It's used by [AutomatedTestWidgetsFlutterBinding] to drain the microtasks
/// before the final [pump] that happens during test cleanup.
void asyncBarrier() {
TestAsyncUtils.verifyAllScopesClosed();
}
Zone? _parentZone;
VoidCallback _createTestCompletionHandler(String testDescription, Completer<void> completer) {
return () {
// This can get called twice, in the case of a Future without listeners failing, and then
// our main future completing.
assert(Zone.current == _parentZone);
if (_pendingExceptionDetails != null) {
debugPrint = debugPrintOverride; // just in case the test overrides it -- otherwise we won't see the error!
reportTestException(_pendingExceptionDetails!, testDescription);
_pendingExceptionDetails = null;
}
if (!completer.isCompleted)
completer.complete();
};
}
/// Called when the framework catches an exception, even if that exception is
/// being handled by [takeException].
///
/// This is called when there is no pending exception; if multiple exceptions
/// are thrown and [takeException] isn't used, then subsequent exceptions are
/// logged to the console regardless (and the test will fail).
@protected
void reportExceptionNoticed(FlutterErrorDetails exception) {
// By default we do nothing.
// The LiveTestWidgetsFlutterBinding overrides this to report the exception to the console.
}
Future<void> _runTest(
Future<void> Function() testBody,
VoidCallback invariantTester,
String description, {
Future<void>? timeout,
}) {
assert(description != null);
assert(inTest);
_oldExceptionHandler = FlutterError.onError;
_oldStackTraceDemangler = FlutterError.demangleStackTrace;
int _exceptionCount = 0; // number of un-taken exceptions
FlutterError.onError = (FlutterErrorDetails details) {
if (_pendingExceptionDetails != null) {
debugPrint = debugPrintOverride; // just in case the test overrides it -- otherwise we won't see the errors!
if (_exceptionCount == 0) {
_exceptionCount = 2;
FlutterError.dumpErrorToConsole(_pendingExceptionDetails!, forceReport: true);
} else {
_exceptionCount += 1;
}
FlutterError.dumpErrorToConsole(details, forceReport: true);
_pendingExceptionDetails = FlutterErrorDetails(
exception: 'Multiple exceptions ($_exceptionCount) were detected during the running of the current test, and at least one was unexpected.',
library: 'Flutter test framework',
);
} else {
reportExceptionNoticed(details); // mostly this is just a hook for the LiveTestWidgetsFlutterBinding
_pendingExceptionDetails = details;
}
};
FlutterError.demangleStackTrace = (StackTrace stack) {
// package:stack_trace uses ZoneSpecification.errorCallback to add useful
// information to stack traces, in this case the Trace and Chain classes
// can be present. Because these StackTrace implementations do not follow
// the format the framework expects, we covert them to a vm trace here.
if (stack is stack_trace.Trace)
return stack.vmTrace;
if (stack is stack_trace.Chain)
return stack.toTrace().vmTrace;
return stack;
};
final Completer<void> testCompleter = Completer<void>();
final VoidCallback testCompletionHandler = _createTestCompletionHandler(description, testCompleter);
void handleUncaughtError(Object exception, StackTrace stack) {
if (testCompleter.isCompleted) {
// Well this is not a good sign.
// Ideally, once the test has failed we would stop getting errors from the test.
// However, if someone tries hard enough they could get in a state where this happens.
// If we silently dropped these errors on the ground, nobody would ever know. So instead
// we report them to the console. They don't cause test failures, but hopefully someone
// will see them in the logs at some point.
debugPrint = debugPrintOverride; // just in case the test overrides it -- otherwise we won't see the error!
FlutterError.dumpErrorToConsole(FlutterErrorDetails(
exception: exception,
stack: stack,
context: ErrorDescription('running a test (but after the test had completed)'),
library: 'Flutter test framework',
), forceReport: true);
return;
}
// This is where test failures, e.g. those in expect(), will end up.
// Specifically, runUnaryGuarded() will call this synchronously and
// return our return value if _runTestBody fails synchronously (which it
// won't, so this never happens), and Future will call this when the
// Future completes with an error and it would otherwise call listeners
// if the listener is in a different zone (which it would be for the
// `whenComplete` handler below), or if the Future completes with an
// error and the future has no listeners at all.
//
// This handler further calls the onError handler above, which sets
// _pendingExceptionDetails. Nothing gets printed as a result of that
// call unless we already had an exception pending, because in general
// we want people to be able to cause the framework to report exceptions
// and then use takeException to verify that they were really caught.
// Now, if we actually get here, this isn't going to be one of those
// cases. We only get here if the test has actually failed. So, once
// we've carefully reported it, we then immediately end the test by
// calling the testCompletionHandler in the _parentZone.
//
// We have to manually call testCompletionHandler because if the Future
// library calls us, it is maybe _instead_ of calling a registered
// listener from a different zone. In our case, that would be instead of
// calling the whenComplete() listener below.
//
// We have to call it in the parent zone because if we called it in
// _this_ zone, the test framework would find this zone was the current
// zone and helpfully throw the error in this zone, causing us to be
// directly called again.
DiagnosticsNode treeDump;
try {
treeDump = renderViewElement?.toDiagnosticsNode() ?? DiagnosticsNode.message('<no tree>');
// TODO(jacobr): this is a hack to make sure the tree can safely be fully dumped.
// Potentially everything is good enough without this case.
treeDump.toStringDeep();
} catch (exception) {
treeDump = DiagnosticsNode.message('<additional error caught while dumping tree: $exception>', level: DiagnosticLevel.error);
}
final List<DiagnosticsNode> omittedFrames = <DiagnosticsNode>[];
final int stackLinesToOmit = reportExpectCall(stack, omittedFrames);
FlutterError.reportError(FlutterErrorDetails(
exception: exception,
stack: stack,
context: ErrorDescription('running a test'),
library: 'Flutter test framework',
stackFilter: (Iterable<String> frames) {
return FlutterError.defaultStackFilter(frames.skip(stackLinesToOmit));
},
informationCollector: () sync* {
if (stackLinesToOmit > 0)
yield* omittedFrames;
if (showAppDumpInErrors) {
yield DiagnosticsProperty<DiagnosticsNode>('At the time of the failure, the widget tree looked as follows', treeDump, linePrefix: '# ', style: DiagnosticsTreeStyle.flat);
}
if (description.isNotEmpty)
yield DiagnosticsProperty<String>('The test description was', description, style: DiagnosticsTreeStyle.errorProperty);
},
));
assert(_parentZone != null);
assert(_pendingExceptionDetails != null, 'A test overrode FlutterError.onError but either failed to return it to its original state, or had unexpected additional errors that it could not handle. Typically, this is caused by using expect() before restoring FlutterError.onError.');
_parentZone!.run<void>(testCompletionHandler);
}
final ZoneSpecification errorHandlingZoneSpecification = ZoneSpecification(
handleUncaughtError: (Zone self, ZoneDelegate parent, Zone zone, Object exception, StackTrace stack) {
handleUncaughtError(exception, stack);
}
);
_parentZone = Zone.current;
final Zone testZone = _parentZone!.fork(specification: errorHandlingZoneSpecification);
testZone.runBinary<Future<void>, Future<void> Function(), VoidCallback>(_runTestBody, testBody, invariantTester)
.whenComplete(testCompletionHandler);
timeout?.catchError(handleUncaughtError);
return testCompleter.future;
}
Future<void> _runTestBody(Future<void> Function() testBody, VoidCallback invariantTester) async {
assert(inTest);
// So that we can assert that it remains the same after the test finishes.
_beforeTestCheckIntrinsicSizes = debugCheckIntrinsicSizes;
runApp(Container(key: UniqueKey(), child: _preTestMessage)); // Reset the tree to a known state.
await pump();
// Pretend that the first frame produced in the test body is the first frame
// sent to the engine.
resetFirstFrameSent();
final bool autoUpdateGoldensBeforeTest = autoUpdateGoldenFiles && !isBrowser;
final TestExceptionReporter reportTestExceptionBeforeTest = reportTestException;
final ErrorWidgetBuilder errorWidgetBuilderBeforeTest = ErrorWidget.builder;
// run the test
await testBody();
asyncBarrier(); // drains the microtasks in `flutter test` mode (when using AutomatedTestWidgetsFlutterBinding)
if (_pendingExceptionDetails == null) {
// We only try to clean up and verify invariants if we didn't already
// fail. If we got an exception already, then we instead leave everything
// alone so that we don't cause more spurious errors.
runApp(Container(key: UniqueKey(), child: _postTestMessage)); // Unmount any remaining widgets.
await pump();
if (registerTestTextInput)
_testTextInput.unregister();
invariantTester();
_verifyAutoUpdateGoldensUnset(autoUpdateGoldensBeforeTest && !isBrowser);
_verifyReportTestExceptionUnset(reportTestExceptionBeforeTest);
_verifyErrorWidgetBuilderUnset(errorWidgetBuilderBeforeTest);
_verifyInvariants();
}
assert(inTest);
asyncBarrier(); // When using AutomatedTestWidgetsFlutterBinding, this flushes the microtasks.
}
late bool _beforeTestCheckIntrinsicSizes;
void _verifyInvariants() {
assert(debugAssertNoTransientCallbacks(
'An animation is still running even after the widget tree was disposed.'
));
assert(debugAssertAllFoundationVarsUnset(
'The value of a foundation debug variable was changed by the test.',
debugPrintOverride: debugPrintOverride,
));
assert(debugAssertAllGesturesVarsUnset(
'The value of a gestures debug variable was changed by the test.',
));
assert(debugAssertAllPaintingVarsUnset(
'The value of a painting debug variable was changed by the test.',
debugDisableShadowsOverride: disableShadows,
));
assert(debugAssertAllRenderVarsUnset(
'The value of a rendering debug variable was changed by the test.',
debugCheckIntrinsicSizesOverride: _beforeTestCheckIntrinsicSizes,
));
assert(debugAssertAllWidgetVarsUnset(
'The value of a widget debug variable was changed by the test.',
));
assert(debugAssertAllSchedulerVarsUnset(
'The value of a scheduler debug variable was changed by the test.',
));
}
void _verifyAutoUpdateGoldensUnset(bool valueBeforeTest) {
assert(() {
if (autoUpdateGoldenFiles != valueBeforeTest) {
FlutterError.reportError(FlutterErrorDetails(
exception: FlutterError(
'The value of autoUpdateGoldenFiles was changed by the test.',
),
stack: StackTrace.current,
library: 'Flutter test framework',
));
}
return true;
}());
}
void _verifyReportTestExceptionUnset(TestExceptionReporter valueBeforeTest) {
assert(() {
if (reportTestException != valueBeforeTest) {
// We can't report this error to their modified reporter because we
// can't be guaranteed that their reporter will cause the test to fail.
// So we reset the error reporter to its initial value and then report
// this error.
reportTestException = valueBeforeTest;
FlutterError.reportError(FlutterErrorDetails(
exception: FlutterError(
'The value of reportTestException was changed by the test.',
),
stack: StackTrace.current,
library: 'Flutter test framework',
));
}
return true;
}());
}
void _verifyErrorWidgetBuilderUnset(ErrorWidgetBuilder valueBeforeTest) {
assert(() {
if (ErrorWidget.builder != valueBeforeTest) {
FlutterError.reportError(FlutterErrorDetails(
exception: FlutterError(
'The value of ErrorWidget.builder was changed by the test.',
),
stack: StackTrace.current,
library: 'Flutter test framework',
));
}
return true;
}());
}
/// Called by the [testWidgets] function after a test is executed.
void postTest() {
assert(inTest);
FlutterError.onError = _oldExceptionHandler;
FlutterError.demangleStackTrace = _oldStackTraceDemangler;
_pendingExceptionDetails = null;
_parentZone = null;
buildOwner!.focusManager.dispose();
buildOwner!.focusManager = FocusManager()..registerGlobalHandlers();
// Disabling the warning because @visibleForTesting doesn't take the testing
// framework itself into account, but we don't want it visible outside of
// tests.
// ignore: invalid_use_of_visible_for_testing_member
RawKeyboard.instance.clearKeysPressed();
assert(!RendererBinding.instance!.mouseTracker.mouseIsConnected,
'The MouseTracker thinks that there is still a mouse connected, which indicates that a '
'test has not removed the mouse pointer which it added. Call removePointer on the '
'active mouse gesture to remove the mouse pointer.');
// ignore: invalid_use_of_visible_for_testing_member
RendererBinding.instance!.initMouseTracker();
}
}
/// A variant of [TestWidgetsFlutterBinding] for executing tests in
/// the `flutter test` environment.
///
/// This binding controls time, allowing tests to verify long
/// animation sequences without having to execute them in real time.
///
/// This class assumes it is always run in checked mode (since tests are always
/// run in checked mode).
class AutomatedTestWidgetsFlutterBinding extends TestWidgetsFlutterBinding {
@override
void initInstances() {
super.initInstances();
binding.mockFlutterAssets();
}
FakeAsync? _currentFakeAsync; // set in runTest; cleared in postTest
Completer<void>? _pendingAsyncTasks;
@override
Clock get clock {
assert(inTest);
return _clock!;
}
Clock? _clock;
@override
DebugPrintCallback get debugPrintOverride => debugPrintSynchronously;
@override
bool get disableShadows => true;
/// The value of [defaultTestTimeout] can be set to `None` to enable debugging flutter tests where
/// we would not want to timeout the test. This is expected to be used by test tooling which
/// can detect debug mode.
@override
test_package.Timeout defaultTestTimeout = const test_package.Timeout(Duration(minutes: 10));
@override
bool get inTest => _currentFakeAsync != null;
@override
int get microtaskCount => _currentFakeAsync!.microtaskCount;
@override
Future<void> pump([ Duration? duration, EnginePhase newPhase = EnginePhase.sendSemanticsUpdate ]) {
return TestAsyncUtils.guard<void>(() {
assert(inTest);
assert(_clock != null);
if (duration != null)
_currentFakeAsync!.elapse(duration);
_phase = newPhase;
if (hasScheduledFrame) {
addTime(const Duration(milliseconds: 500));
_currentFakeAsync!.flushMicrotasks();
handleBeginFrame(Duration(
milliseconds: _clock!.now().millisecondsSinceEpoch,
));
_currentFakeAsync!.flushMicrotasks();
handleDrawFrame();
}
_currentFakeAsync!.flushMicrotasks();
return Future<void>.value();
});
}
@override
Future<T?> runAsync<T>(
Future<T> Function() callback, {
Duration additionalTime = const Duration(milliseconds: 1000),
}) {
assert(additionalTime != null);
assert(() {
if (_pendingAsyncTasks == null)
return true;
throw test_package.TestFailure(
'Reentrant call to runAsync() denied.\n'
'runAsync() was called, then before its future completed, it '
'was called again. You must wait for the first returned future '
'to complete before calling runAsync() again.'
);
}());
final Zone realAsyncZone = Zone.current.fork(
specification: ZoneSpecification(
scheduleMicrotask: (Zone self, ZoneDelegate parent, Zone zone, void Function() f) {
Zone.root.scheduleMicrotask(f);
},
createTimer: (Zone self, ZoneDelegate parent, Zone zone, Duration duration, void Function() f) {
return Zone.root.createTimer(duration, f);
},
createPeriodicTimer: (Zone self, ZoneDelegate parent, Zone zone, Duration period, void Function(Timer timer) f) {
return Zone.root.createPeriodicTimer(period, f);
},
),
);
addTime(additionalTime);
return realAsyncZone.run<Future<T?>>(() async {
_pendingAsyncTasks = Completer<void>();
T? result;
try {
result = await callback();
} catch (exception, stack) {
FlutterError.reportError(FlutterErrorDetails(
exception: exception,
stack: stack,
library: 'Flutter test framework',