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
// Copyright 2016 The Chromium 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 '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:quiver/testing/async.dart';
import 'package:quiver/time.dart';
/// Enumeration of possible phases to reach in
/// [WidgetTester.pumpWidget] and [TestWidgetsFlutterBinding.pump].
// TODO(ianh): Merge with identical code in the rendering test code.
enum EnginePhase {
layout,
compositingBits,
paint,
composite,
flushSemantics,
sendSemanticsTree
}
class TestWidgetsFlutterBinding extends BindingBase with SchedulerBinding, GestureBinding, ServicesBinding, RendererBinding, WidgetsBinding {
/// Creates and initializes the binding. This constructor is
/// idempotent; calling it a second time will just return the
/// previously-created instance.
static WidgetsBinding ensureInitialized() {
if (WidgetsBinding.instance == null)
new TestWidgetsFlutterBinding();
assert(WidgetsBinding.instance is TestWidgetsFlutterBinding);
return WidgetsBinding.instance;
}
@override
void initInstances() {
timeDilation = 1.0; // just in case the developer has artificially changed it for development
debugPrint = _synchronousDebugPrint; // TODO(ianh): don't do this when running as 'flutter run'
super.initInstances();
}
void _synchronousDebugPrint(String message, { int wrapWidth }) {
if (wrapWidth != null) {
print(message.split('\n').expand((String line) => debugWordWrap(line, wrapWidth)).join('\n'));
} else {
print(message);
}
}
FakeAsync get fakeAsync => _fakeAsync;
bool get inTest => fakeAsync != null;
FakeAsync _fakeAsync;
Clock _clock;
EnginePhase phase = EnginePhase.sendSemanticsTree;
// Pump the rendering pipeline up to the given phase.
@override
void beginFrame() {
assert(inTest);
buildOwner.buildDirtyElements();
_beginFrame();
buildOwner.finalizeTree();
}
// Cloned from RendererBinding.beginFrame() but with early-exit semantics.
void _beginFrame() {
assert(inTest);
assert(renderView != null);
pipelineOwner.flushLayout();
if (phase == EnginePhase.layout)
return;
pipelineOwner.flushCompositingBits();
if (phase == EnginePhase.compositingBits)
return;
pipelineOwner.flushPaint();
if (phase == EnginePhase.paint)
return;
renderView.compositeFrame(); // this sends the bits to the GPU
if (phase == EnginePhase.composite)
return;
if (SemanticsNode.hasListeners) {
pipelineOwner.flushSemantics();
if (phase == EnginePhase.flushSemantics)
return;
SemanticsNode.sendSemanticsTree();
}
}
@override
void dispatchEvent(PointerEvent event, HitTestResult result) {
assert(inTest);
super.dispatchEvent(event, result);
fakeAsync.flushMicrotasks();
}
/// 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.
void pump([ Duration duration, EnginePhase newPhase = EnginePhase.sendSemanticsTree ]) {
assert(inTest);
assert(_clock != null);
if (duration != null)
fakeAsync.elapse(duration);
phase = newPhase;
handleBeginFrame(new Duration(
milliseconds: _clock.now().millisecondsSinceEpoch
));
fakeAsync.flushMicrotasks();
}
/// Artificially calls dispatchLocaleChanged on the Widget binding,
/// then flushes microtasks.
void setLocale(String languageCode, String countryCode) {
assert(inTest);
Locale locale = new Locale(languageCode, countryCode);
dispatchLocaleChanged(locale);
fakeAsync.flushMicrotasks();
}
/// 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);
dynamic result = _pendingException?.exception;
_pendingException = null;
return result;
}
FlutterErrorDetails _pendingException;
FlutterExceptionHandler _oldHandler;
int _exceptionCount;
/// Called by the [testWidgets] function before a test is executed.
void preTest() {
assert(fakeAsync == null);
assert(_clock == null);
_fakeAsync = new FakeAsync();
_clock = fakeAsync.getClock(new DateTime.utc(2015, 1, 1));
_oldHandler = FlutterError.onError;
_exceptionCount = 0; // number of un-taken exceptions
FlutterError.onError = (FlutterErrorDetails details) {
if (_pendingException != null) {
if (_exceptionCount == 0) {
_exceptionCount = 2;
FlutterError.dumpErrorToConsole(_pendingException, forceReport: true);
} else {
_exceptionCount += 1;
}
FlutterError.dumpErrorToConsole(details, forceReport: true);
_pendingException = new 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 {
_pendingException = details;
}
};
}
/// Invoke the callback 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.
Future<Null> runTest(Future<Null> callback()) {
assert(inTest);
Future<Null> callbackResult;
fakeAsync.run((FakeAsync fakeAsync) {
assert(fakeAsync == this.fakeAsync);
callbackResult = _runTest(callback);
fakeAsync.flushMicrotasks();
assert(inTest);
});
// callbackResult is a Future that was created in the Zone of the fakeAsync.
// This means that if we call .then() on it (as the test framework is about to),
// it will register a microtask to handle the future _in the fake async zone_.
// To avoid this, we wrap it in a Future that we've created _outside_ the fake
// async zone.
return new Future<Null>.value(callbackResult);
}
Future<Null> _runTest(Future<Null> callback()) async {
assert(inTest);
runApp(new Container(key: new UniqueKey())); // Reset the tree to a known state.
pump();
// run the test
try {
await callback();
fakeAsync.flushMicrotasks();
} catch (exception, stack) {
// call onError handler above
FlutterError.reportError(new FlutterErrorDetails(
exception: exception,
stack: stack,
library: 'Flutter test framework'
));
}
runApp(new Container(key: new UniqueKey())); // Unmount any remaining widgets.
pump();
// verify invariants
assert(debugAssertNoTransientCallbacks(
'An animation is still running even after the widget tree was disposed.'
));
assert(() {
'A Timer is still running even after the widget tree was disposed.';
return fakeAsync.periodicTimerCount == 0;
});
assert(() {
'A Timer is still running even after the widget tree was disposed.';
return fakeAsync.nonPeriodicTimerCount == 0;
});
assert(fakeAsync.microtaskCount == 0); // Shouldn't be possible.
// check for unexpected exceptions
if (_pendingException != null) {
if (_exceptionCount > 1)
throw 'Test failed. See exception logs above.';
throw 'Test failed. See exception log below.';
}
assert(inTest);
return null;
}
/// Called by the [testWidgets] function after a test is executed.
void postTest() {
assert(_fakeAsync != null);
assert(_clock != null);
FlutterError.onError = _oldHandler;
if (_pendingException != null)
FlutterError.dumpErrorToConsole(_pendingException, forceReport: true);
_pendingException = null;
_exceptionCount = null;
_clock = null;
_fakeAsync = null;
}
}