Make it possible to run tests live on a device (#3936)
This makes it possible to substitute 'flutter run' for 'flutter test'
and actually watch a test run on a device.
For any test that depends on flutter_test:
1. Remove any import of 'package:test/test.dart'.
2. Replace `testWidgets('...', (WidgetTester tester) {`
with `testWidgets('...', (WidgetTester tester) async {`
3. Add an "await" in front of calls to any of the following:
* tap()
* tapAt()
* fling()
* flingFrom()
* scroll()
* scrollAt()
* pump()
* pumpWidget()
4. Replace any calls to `tester.flushMicrotasks()` with calls to
`await tester.idle()`.
There's a guarding API that you can use, if you have particularly
complicated tests, to get better error messages. Search for
TestAsyncUtils.
This commit is contained in:
@@ -5,11 +5,15 @@
|
||||
/// Testing library for flutter, built on top of `package:test`.
|
||||
library flutter_test;
|
||||
|
||||
export 'dart:async' show Future;
|
||||
|
||||
export 'src/all_elements.dart';
|
||||
export 'src/binding.dart';
|
||||
export 'src/controller.dart';
|
||||
export 'src/finders.dart';
|
||||
export 'src/matchers.dart';
|
||||
export 'src/test_async_utils.dart';
|
||||
export 'src/service_mocker.dart';
|
||||
export 'src/stack_manipulation.dart';
|
||||
export 'src/test_pointer.dart';
|
||||
export 'src/widget_tester.dart';
|
||||
|
||||
@@ -3,6 +3,8 @@
|
||||
// found in the LICENSE file.
|
||||
|
||||
import 'dart:async';
|
||||
import 'dart:io';
|
||||
import 'dart:ui' as ui;
|
||||
|
||||
import 'package:flutter/foundation.dart';
|
||||
import 'package:flutter/gestures.dart';
|
||||
@@ -12,6 +14,11 @@ import 'package:flutter/services.dart';
|
||||
import 'package:flutter/widgets.dart';
|
||||
import 'package:quiver/testing/async.dart';
|
||||
import 'package:quiver/time.dart';
|
||||
import 'package:test/test.dart' as test_package;
|
||||
import 'package:vector_math/vector_math_64.dart';
|
||||
|
||||
import 'test_async_utils.dart';
|
||||
import 'stack_manipulation.dart';
|
||||
|
||||
/// Enumeration of possible phases to reach in
|
||||
/// [WidgetTester.pumpWidget] and [TestWidgetsFlutterBinding.pump].
|
||||
@@ -25,13 +32,38 @@ enum EnginePhase {
|
||||
sendSemanticsTree
|
||||
}
|
||||
|
||||
class TestWidgetsFlutterBinding extends BindingBase with SchedulerBinding, GestureBinding, ServicesBinding, RendererBinding, WidgetsBinding {
|
||||
/// Creates and initializes the binding. This constructor is
|
||||
const Size _kTestViewportSize = const Size(800.0, 600.0);
|
||||
|
||||
/// 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.
|
||||
abstract class TestWidgetsFlutterBinding extends BindingBase
|
||||
with SchedulerBinding,
|
||||
GestureBinding,
|
||||
ServicesBinding,
|
||||
RendererBinding,
|
||||
WidgetsBinding {
|
||||
/// 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`.)
|
||||
static WidgetsBinding ensureInitialized() {
|
||||
if (WidgetsBinding.instance == null)
|
||||
new TestWidgetsFlutterBinding();
|
||||
if (WidgetsBinding.instance == null) {
|
||||
if (Platform.environment.containsKey('FLUTTER_TEST')) {
|
||||
new AutomatedTestWidgetsFlutterBinding._();
|
||||
} else {
|
||||
new LiveTestWidgetsFlutterBinding._();
|
||||
}
|
||||
}
|
||||
assert(WidgetsBinding.instance is TestWidgetsFlutterBinding);
|
||||
return WidgetsBinding.instance;
|
||||
}
|
||||
@@ -39,65 +71,13 @@ class TestWidgetsFlutterBinding extends BindingBase with SchedulerBinding, Gestu
|
||||
@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);
|
||||
}
|
||||
}
|
||||
bool get inTest;
|
||||
|
||||
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();
|
||||
}
|
||||
/// The default test timeout for tests when using this binding.
|
||||
test_package.Timeout get defaultTestTimeout;
|
||||
|
||||
/// Triggers a frame sequence (build/layout/paint/etc),
|
||||
/// then flushes microtasks.
|
||||
@@ -107,25 +87,29 @@ class TestWidgetsFlutterBinding extends BindingBase with SchedulerBinding, Gestu
|
||||
///
|
||||
/// 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();
|
||||
}
|
||||
Future<Null> pump([ Duration duration, EnginePhase newPhase = EnginePhase.sendSemanticsTree ]);
|
||||
|
||||
/// 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();
|
||||
Future<Null> setLocale(String languageCode, String countryCode) {
|
||||
return TestAsyncUtils.guard(() async {
|
||||
assert(inTest);
|
||||
Locale locale = new Locale(languageCode, countryCode);
|
||||
dispatchLocaleChanged(locale);
|
||||
return null;
|
||||
});
|
||||
}
|
||||
|
||||
/// 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.
|
||||
///
|
||||
/// Does not run timers. May result in an infinite loop or run out of memory
|
||||
/// if microtasks continue to recursively schedule new microtasks.
|
||||
Future<Null> idle() {
|
||||
TestAsyncUtils.guardSync();
|
||||
return new Future<Null>.value();
|
||||
}
|
||||
|
||||
/// Returns the exception most recently caught by the Flutter framework.
|
||||
@@ -144,40 +128,30 @@ class TestWidgetsFlutterBinding extends BindingBase with SchedulerBinding, Gestu
|
||||
/// null in that case.
|
||||
dynamic takeException() {
|
||||
assert(inTest);
|
||||
dynamic result = _pendingException?.exception;
|
||||
_pendingException = null;
|
||||
dynamic result = _pendingExceptionDetails?.exception;
|
||||
_pendingExceptionDetails = null;
|
||||
return result;
|
||||
}
|
||||
FlutterErrorDetails _pendingException;
|
||||
FlutterExceptionHandler _oldHandler;
|
||||
int _exceptionCount;
|
||||
FlutterExceptionHandler _oldExceptionHandler;
|
||||
FlutterErrorDetails _pendingExceptionDetails;
|
||||
|
||||
/// 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;
|
||||
}
|
||||
};
|
||||
}
|
||||
static final Widget _kPreTestMessage = new Center(
|
||||
child: new Text(
|
||||
'Test starting...',
|
||||
style: const TextStyle(color: const Color(0xFFFF0000))
|
||||
)
|
||||
);
|
||||
|
||||
static final Widget _kPostTestMessage = new Center(
|
||||
child: new Text(
|
||||
'Test finished.',
|
||||
style: const TextStyle(color: const Color(0xFFFF0000))
|
||||
)
|
||||
);
|
||||
|
||||
/// Whether to include the output of debugDumpApp() when reporting
|
||||
/// test failures.
|
||||
bool showAppDumpInErrors = false;
|
||||
|
||||
/// Invoke the callback inside a [FakeAsync] scope on which [pump] can
|
||||
/// advance time.
|
||||
@@ -186,13 +160,272 @@ class TestWidgetsFlutterBinding extends BindingBase with SchedulerBinding, Gestu
|
||||
///
|
||||
/// Called by the [testWidgets] and [benchmarkWidgets] functions to
|
||||
/// run a test.
|
||||
Future<Null> runTest(Future<Null> callback()) {
|
||||
Future<Null> runTest(Future<Null> callback());
|
||||
|
||||
/// 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;
|
||||
Completer<Null> _currentTestCompleter;
|
||||
|
||||
void _testCompletionHandler() {
|
||||
// This can get called twice, in the case of a Future without listeners failing, and then
|
||||
// our main future completing.
|
||||
assert(Zone.current == _parentZone);
|
||||
assert(_currentTestCompleter != null);
|
||||
if (_pendingExceptionDetails != null) {
|
||||
FlutterError.dumpErrorToConsole(_pendingExceptionDetails, forceReport: true);
|
||||
// test_package.registerException actually just calls the current zone's error handler (that
|
||||
// is to say, _parentZone's handleUncaughtError function). FakeAsync doesn't add one of those,
|
||||
// but the test package does, that's how the test package tracks errors. So really we could
|
||||
// get the same effect here by calling that error handler directly or indeed just throwing.
|
||||
// However, we call registerException because that's the semantically correct thing...
|
||||
test_package.registerException('Test failed. See exception logs above.', _EmptyStack.instance);
|
||||
_pendingExceptionDetails = null;
|
||||
}
|
||||
if (!_currentTestCompleter.isCompleted)
|
||||
_currentTestCompleter.complete(null);
|
||||
}
|
||||
|
||||
Future<Null> _runTest(Future<Null> callback()) {
|
||||
assert(inTest);
|
||||
_oldExceptionHandler = FlutterError.onError;
|
||||
int _exceptionCount = 0; // number of un-taken exceptions
|
||||
FlutterError.onError = (FlutterErrorDetails details) {
|
||||
if (_pendingExceptionDetails != null) {
|
||||
if (_exceptionCount == 0) {
|
||||
_exceptionCount = 2;
|
||||
FlutterError.dumpErrorToConsole(_pendingExceptionDetails, forceReport: true);
|
||||
} else {
|
||||
_exceptionCount += 1;
|
||||
}
|
||||
FlutterError.dumpErrorToConsole(details, forceReport: true);
|
||||
_pendingExceptionDetails = 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 {
|
||||
_pendingExceptionDetails = details;
|
||||
}
|
||||
};
|
||||
_currentTestCompleter = new Completer<Null>();
|
||||
ZoneSpecification errorHandlingZoneSpecification = new ZoneSpecification(
|
||||
handleUncaughtError: (Zone self, ZoneDelegate parent, Zone zone, dynamic exception, StackTrace stack) {
|
||||
if (_currentTestCompleter.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.
|
||||
FlutterError.dumpErrorToConsole(new FlutterErrorDetails(
|
||||
exception: exception,
|
||||
stack: stack,
|
||||
context: '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.
|
||||
final String treeDump = renderViewElement?.toStringDeep() ?? '<no tree>';
|
||||
final StringBuffer expectLine = new StringBuffer();
|
||||
final int stackLinesToOmit = reportExpectCall(stack, expectLine);
|
||||
FlutterError.reportError(new FlutterErrorDetails(
|
||||
exception: exception,
|
||||
stack: stack,
|
||||
context: 'running a test',
|
||||
library: 'Flutter test framework',
|
||||
stackFilter: (List<String> frames) {
|
||||
return FlutterError.defaultStackFilter(frames.skip(stackLinesToOmit));
|
||||
},
|
||||
informationCollector: (StringBuffer information) {
|
||||
if (stackLinesToOmit > 0)
|
||||
information.writeln(expectLine.toString());
|
||||
if (showAppDumpInErrors) {
|
||||
information.writeln('At the time of the failure, the widget tree looked as follows:');
|
||||
information.writeln('# ${treeDump.split("\n").takeWhile((String s) => s != "").join("\n# ")}');
|
||||
}
|
||||
}
|
||||
));
|
||||
assert(_parentZone != null);
|
||||
assert(_pendingExceptionDetails != null);
|
||||
_parentZone.run(_testCompletionHandler);
|
||||
}
|
||||
);
|
||||
_parentZone = Zone.current;
|
||||
Zone testZone = _parentZone.fork(specification: errorHandlingZoneSpecification);
|
||||
testZone.runUnaryGuarded(_runTestBody, callback)
|
||||
.whenComplete(_testCompletionHandler);
|
||||
asyncBarrier(); // When using AutomatedTestWidgetsFlutterBinding, this flushes the microtasks.
|
||||
return _currentTestCompleter.future;
|
||||
}
|
||||
|
||||
Future<Null> _runTestBody(Future<Null> callback()) async {
|
||||
assert(inTest);
|
||||
|
||||
runApp(new Container(key: new UniqueKey(), child: _kPreTestMessage)); // Reset the tree to a known state.
|
||||
await pump();
|
||||
|
||||
// run the test
|
||||
await callback();
|
||||
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(new Container(key: new UniqueKey(), child: _kPostTestMessage)); // Unmount any remaining widgets.
|
||||
await pump();
|
||||
_verifyInvariants();
|
||||
}
|
||||
|
||||
assert(inTest);
|
||||
return null;
|
||||
}
|
||||
|
||||
void _verifyInvariants() {
|
||||
assert(debugAssertNoTransientCallbacks(
|
||||
'An animation is still running even after the widget tree was disposed.'
|
||||
));
|
||||
}
|
||||
|
||||
/// Called by the [testWidgets] function after a test is executed.
|
||||
void postTest() {
|
||||
assert(inTest);
|
||||
FlutterError.onError = _oldExceptionHandler;
|
||||
_pendingExceptionDetails = null;
|
||||
_currentTestCompleter = null;
|
||||
_parentZone = null;
|
||||
}
|
||||
}
|
||||
|
||||
/// 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.
|
||||
class AutomatedTestWidgetsFlutterBinding extends TestWidgetsFlutterBinding {
|
||||
AutomatedTestWidgetsFlutterBinding._();
|
||||
|
||||
@override
|
||||
void initInstances() {
|
||||
debugPrint = _synchronousDebugPrint;
|
||||
super.initInstances();
|
||||
ui.window.onBeginFrame = null;
|
||||
}
|
||||
|
||||
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 _fakeAsync;
|
||||
Clock _clock;
|
||||
|
||||
@override
|
||||
test_package.Timeout get defaultTestTimeout => const test_package.Timeout(const Duration(seconds: 5));
|
||||
|
||||
@override
|
||||
bool get inTest => _fakeAsync != null;
|
||||
|
||||
@override
|
||||
Future<Null> pump([ Duration duration, EnginePhase newPhase = EnginePhase.sendSemanticsTree ]) {
|
||||
return TestAsyncUtils.guard(() {
|
||||
assert(inTest);
|
||||
assert(_clock != null);
|
||||
if (duration != null)
|
||||
_fakeAsync.elapse(duration);
|
||||
_phase = newPhase;
|
||||
if (hasScheduledFrame) {
|
||||
handleBeginFrame(new Duration(
|
||||
milliseconds: _clock.now().millisecondsSinceEpoch
|
||||
));
|
||||
}
|
||||
_fakeAsync.flushMicrotasks();
|
||||
return new Future<Null>.value();
|
||||
});
|
||||
}
|
||||
|
||||
@override
|
||||
Future<Null> idle() {
|
||||
Future<Null> result = super.idle();
|
||||
_fakeAsync.flushMicrotasks();
|
||||
return result;
|
||||
}
|
||||
|
||||
EnginePhase _phase = EnginePhase.sendSemanticsTree;
|
||||
|
||||
// Cloned from RendererBinding.beginFrame() but with early-exit semantics.
|
||||
@override
|
||||
void beginFrame() {
|
||||
assert(inTest);
|
||||
buildOwner.buildDirtyElements();
|
||||
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();
|
||||
}
|
||||
buildOwner.finalizeTree();
|
||||
}
|
||||
|
||||
@override
|
||||
Future<Null> runTest(Future<Null> callback()) {
|
||||
assert(!inTest);
|
||||
assert(_fakeAsync == null);
|
||||
assert(_clock == null);
|
||||
_fakeAsync = new FakeAsync();
|
||||
_clock = _fakeAsync.getClock(new DateTime.utc(2015, 1, 1));
|
||||
Future<Null> callbackResult;
|
||||
fakeAsync.run((FakeAsync fakeAsync) {
|
||||
assert(fakeAsync == this.fakeAsync);
|
||||
_fakeAsync.run((FakeAsync fakeAsync) {
|
||||
assert(fakeAsync == _fakeAsync);
|
||||
callbackResult = _runTest(callback);
|
||||
fakeAsync.flushMicrotasks();
|
||||
assert(inTest);
|
||||
});
|
||||
// callbackResult is a Future that was created in the Zone of the fakeAsync.
|
||||
@@ -203,64 +436,188 @@ class TestWidgetsFlutterBinding extends BindingBase with SchedulerBinding, Gestu
|
||||
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;
|
||||
@override
|
||||
void asyncBarrier() {
|
||||
assert(_fakeAsync != null);
|
||||
_fakeAsync.flushMicrotasks();
|
||||
super.asyncBarrier();
|
||||
}
|
||||
|
||||
/// Called by the [testWidgets] function after a test is executed.
|
||||
@override
|
||||
void _verifyInvariants() {
|
||||
super._verifyInvariants();
|
||||
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.
|
||||
}
|
||||
|
||||
@override
|
||||
void postTest() {
|
||||
super.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;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
/// A variant of [TestWidgetsFlutterBinding] for executing tests in
|
||||
/// the `flutter run` environment, on a device. This is intended to
|
||||
/// allow interactive test development.
|
||||
///
|
||||
/// This is not the way to run a remote-control test. To run a test on
|
||||
/// a device from a development computer, see the [flutter_driver]
|
||||
/// package and the `flutter drive` command.
|
||||
///
|
||||
/// This binding overrides the default [SchedulerBinding] behavior to
|
||||
/// ensure that tests work in the same way in this environment as they
|
||||
/// would under the [AutomatedTestWidgetsFlutterBinding]. To override
|
||||
/// this (and see intermediate frames that the test does not
|
||||
/// explicitly trigger), set [allowAllFrames] to true. (This is likely
|
||||
/// to make tests fail, though, especially if e.g. they test how many
|
||||
/// times a particular widget was built.)
|
||||
///
|
||||
/// This binding does not support the [EnginePhase] argument to
|
||||
/// [pump]. (There would be no point setting it to a value that
|
||||
/// doesn't trigger a paint, since then you could not see anything
|
||||
/// anyway.)
|
||||
class LiveTestWidgetsFlutterBinding extends TestWidgetsFlutterBinding {
|
||||
LiveTestWidgetsFlutterBinding._();
|
||||
|
||||
@override
|
||||
bool get inTest => _inTest;
|
||||
bool _inTest = false;
|
||||
|
||||
@override
|
||||
test_package.Timeout get defaultTestTimeout => test_package.Timeout.none;
|
||||
|
||||
Completer<Null> _pendingFrame;
|
||||
bool _expectingFrame = false;
|
||||
|
||||
/// Whether to have [pump] with a duration only pump a single frame
|
||||
/// (as would happen in a normal test environment using
|
||||
/// [AutomatedTestWidgetsFlutterBinding]), or whether to instead
|
||||
/// pump every frame that the system requests during any
|
||||
/// asynchronous pause in the test (as would normally happen when
|
||||
/// running an application with [WidgetsFlutterBinding]).
|
||||
///
|
||||
/// `false` is the default behavior, which is to only pump once.
|
||||
///
|
||||
/// `true` allows all frame requests from the engine to be serviced.
|
||||
///
|
||||
/// Setting this to `true` means pumping extra frames, which might
|
||||
/// involve calling builders more, or calling paint callbacks more,
|
||||
/// etc, which might interfere with the test. If you know your test
|
||||
/// file wouldn't be affected by this, you can set it to true
|
||||
/// persistently in that particular test file. To set this to `true`
|
||||
/// while still allowing the test file to work as a normal test, add
|
||||
/// the following code to your test file at the top of your `void
|
||||
/// main() { }` function, before calls to `testWidgets`:
|
||||
///
|
||||
/// ```dart
|
||||
/// TestWidgetsFlutterBinding binding = TestWidgetsFlutterBinding.ensureInitialized();
|
||||
/// if (binding is LiveTestWidgetsFlutterBinding)
|
||||
/// binding.allowAllFrames = true;
|
||||
/// ```
|
||||
bool allowAllFrames = false;
|
||||
|
||||
@override
|
||||
void handleBeginFrame(Duration rawTimeStamp) {
|
||||
if (_expectingFrame || allowAllFrames)
|
||||
super.handleBeginFrame(rawTimeStamp);
|
||||
if (_expectingFrame) {
|
||||
assert(_pendingFrame != null);
|
||||
_pendingFrame.complete(); // unlocks the test API
|
||||
_pendingFrame = null;
|
||||
_expectingFrame = false;
|
||||
} else {
|
||||
ui.window.scheduleFrame();
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
Future<Null> pump([ Duration duration, EnginePhase newPhase = EnginePhase.sendSemanticsTree ]) {
|
||||
assert(newPhase == EnginePhase.sendSemanticsTree);
|
||||
assert(inTest);
|
||||
assert(!_expectingFrame);
|
||||
assert(_pendingFrame == null);
|
||||
return TestAsyncUtils.guard(() {
|
||||
if (duration != null) {
|
||||
new Timer(duration, () {
|
||||
_expectingFrame = true;
|
||||
scheduleFrame();
|
||||
});
|
||||
} else {
|
||||
_expectingFrame = true;
|
||||
scheduleFrame();
|
||||
}
|
||||
_pendingFrame = new Completer<Null>();
|
||||
return _pendingFrame.future;
|
||||
});
|
||||
}
|
||||
|
||||
@override
|
||||
Future<Null> runTest(Future<Null> callback()) async {
|
||||
assert(!inTest);
|
||||
_inTest = true;
|
||||
return _runTest(callback);
|
||||
}
|
||||
|
||||
@override
|
||||
void postTest() {
|
||||
super.postTest();
|
||||
assert(!_expectingFrame);
|
||||
assert(_pendingFrame == null);
|
||||
_inTest = false;
|
||||
}
|
||||
|
||||
@override
|
||||
ViewConfiguration createViewConfiguration() {
|
||||
final double actualWidth = ui.window.size.width * ui.window.devicePixelRatio;
|
||||
final double actualHeight = ui.window.size.height * ui.window.devicePixelRatio;
|
||||
final double desiredWidth = _kTestViewportSize.width;
|
||||
final double desiredHeight = _kTestViewportSize.height;
|
||||
double scale, shiftX, shiftY;
|
||||
if ((actualWidth / actualHeight) > (desiredWidth / desiredHeight)) {
|
||||
scale = actualHeight / desiredHeight;
|
||||
shiftX = (actualWidth - desiredWidth * scale) / 2.0;
|
||||
shiftY = 0.0;
|
||||
} else {
|
||||
scale = actualWidth / desiredWidth;
|
||||
shiftX = 0.0;
|
||||
shiftY = (actualHeight - desiredHeight * scale) / 2.0;
|
||||
}
|
||||
final Matrix4 matrix = new Matrix4.compose(
|
||||
new Vector3(shiftX, shiftY, 0.0), // translation
|
||||
new Quaternion.identity(), // rotation
|
||||
new Vector3(scale, scale, 0.0) // scale
|
||||
);
|
||||
return new _TestViewConfiguration(matrix);
|
||||
}
|
||||
}
|
||||
|
||||
class _TestViewConfiguration extends ViewConfiguration {
|
||||
_TestViewConfiguration(this.matrix) : super(size: _kTestViewportSize);
|
||||
|
||||
final Matrix4 matrix;
|
||||
|
||||
@override
|
||||
Matrix4 toMatrix() => matrix;
|
||||
|
||||
@override
|
||||
String toString() => 'TestViewConfiguration';
|
||||
}
|
||||
|
||||
class _EmptyStack implements StackTrace {
|
||||
const _EmptyStack._();
|
||||
static const _EmptyStack instance = const _EmptyStack._();
|
||||
@override
|
||||
String toString() => '';
|
||||
}
|
||||
@@ -2,13 +2,16 @@
|
||||
// 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/gestures.dart';
|
||||
import 'package:flutter/rendering.dart';
|
||||
import 'package:flutter/widgets.dart';
|
||||
|
||||
import 'test_pointer.dart';
|
||||
import 'finders.dart';
|
||||
import 'all_elements.dart';
|
||||
import 'finders.dart';
|
||||
import 'test_async_utils.dart';
|
||||
import 'test_pointer.dart';
|
||||
|
||||
/// Class that programmatically interacts with widgets.
|
||||
///
|
||||
@@ -24,13 +27,17 @@ class WidgetController {
|
||||
// a good message otherwise, in all the generic methods below
|
||||
|
||||
/// Checks if `finder` exists in the tree.
|
||||
bool any(Finder finder) => finder.evaluate().isNotEmpty;
|
||||
bool any(Finder finder) {
|
||||
TestAsyncUtils.guardSync();
|
||||
return finder.evaluate().isNotEmpty;
|
||||
}
|
||||
|
||||
/// All widgets currently in the widget tree (lazy pre-order traversal).
|
||||
///
|
||||
/// Can contain duplicates, since widgets can be used in multiple
|
||||
/// places in the widget tree.
|
||||
Iterable<Widget> get allWidgets {
|
||||
TestAsyncUtils.guardSync();
|
||||
return allElements
|
||||
.map((Element element) => element.widget);
|
||||
}
|
||||
@@ -40,6 +47,7 @@ class WidgetController {
|
||||
/// Throws a [StateError] if `finder` is empty or matches more than
|
||||
/// one widget.
|
||||
Widget/*=T*/ widget/*<T extends Widget>*/(Finder finder) {
|
||||
TestAsyncUtils.guardSync();
|
||||
return finder.evaluate().single.widget;
|
||||
}
|
||||
|
||||
@@ -48,6 +56,7 @@ class WidgetController {
|
||||
///
|
||||
/// Throws a [StateError] if `finder` is empty.
|
||||
Widget/*=T*/ firstWidget/*<T extends Widget>*/(Finder finder) {
|
||||
TestAsyncUtils.guardSync();
|
||||
return finder.evaluate().first.widget;
|
||||
}
|
||||
|
||||
@@ -57,6 +66,7 @@ class WidgetController {
|
||||
/// immediately, but rather a chunk at a time as the iteration progresses
|
||||
/// using [Iterator.moveNext].
|
||||
Iterable<Element> get allElements {
|
||||
TestAsyncUtils.guardSync();
|
||||
return collectAllElementsFrom(binding.renderViewElement);
|
||||
}
|
||||
|
||||
@@ -65,6 +75,7 @@ class WidgetController {
|
||||
/// Throws a [StateError] if `finder` is empty or matches more than
|
||||
/// one element.
|
||||
Element/*=T*/ element/*<T extends Element>*/(Finder finder) {
|
||||
TestAsyncUtils.guardSync();
|
||||
return finder.evaluate().single;
|
||||
}
|
||||
|
||||
@@ -73,6 +84,7 @@ class WidgetController {
|
||||
///
|
||||
/// Throws a [StateError] if `finder` is empty.
|
||||
Element/*=T*/ firstElement/*<T extends Element>*/(Finder finder) {
|
||||
TestAsyncUtils.guardSync();
|
||||
return finder.evaluate().first;
|
||||
}
|
||||
|
||||
@@ -82,6 +94,7 @@ class WidgetController {
|
||||
/// immediately, but rather a chunk at a time as the iteration progresses
|
||||
/// using [Iterator.moveNext].
|
||||
Iterable<State> get allStates {
|
||||
TestAsyncUtils.guardSync();
|
||||
return allElements
|
||||
.where((Element element) => element is StatefulElement)
|
||||
.map((StatefulElement element) => element.state);
|
||||
@@ -92,6 +105,7 @@ class WidgetController {
|
||||
/// Throws a [StateError] if `finder` is empty, matches more than
|
||||
/// one state, or matches a widget that has no state.
|
||||
State/*=T*/ state/*<T extends State>*/(Finder finder) {
|
||||
TestAsyncUtils.guardSync();
|
||||
return _stateOf/*<T>*/(finder.evaluate().single, finder);
|
||||
}
|
||||
|
||||
@@ -101,10 +115,12 @@ class WidgetController {
|
||||
/// Throws a [StateError] if `finder` is empty or if the first
|
||||
/// matching widget has no state.
|
||||
State/*=T*/ firstState/*<T extends State>*/(Finder finder) {
|
||||
TestAsyncUtils.guardSync();
|
||||
return _stateOf/*<T>*/(finder.evaluate().first, finder);
|
||||
}
|
||||
|
||||
State/*=T*/ _stateOf/*<T extends State>*/(Element element, Finder finder) {
|
||||
TestAsyncUtils.guardSync();
|
||||
if (element is StatefulElement)
|
||||
return element.state;
|
||||
throw new StateError('Widget of type ${element.widget.runtimeType}, with ${finder.description}, is not a StatefulWidget.');
|
||||
@@ -118,6 +134,7 @@ class WidgetController {
|
||||
/// render object of its child; only [RenderObjectWidget]s have
|
||||
/// their own render object.
|
||||
Iterable<RenderObject> get allRenderObjects {
|
||||
TestAsyncUtils.guardSync();
|
||||
return allElements
|
||||
.map((Element element) => element.renderObject);
|
||||
}
|
||||
@@ -127,6 +144,7 @@ class WidgetController {
|
||||
/// Throws a [StateError] if `finder` is empty or matches more than
|
||||
/// one widget (even if they all have the same render object).
|
||||
RenderObject/*=T*/ renderObject/*<T extends RenderObject>*/(Finder finder) {
|
||||
TestAsyncUtils.guardSync();
|
||||
return finder.evaluate().single.renderObject;
|
||||
}
|
||||
|
||||
@@ -135,6 +153,7 @@ class WidgetController {
|
||||
///
|
||||
/// Throws a [StateError] if `finder` is empty.
|
||||
RenderObject/*=T*/ firstRenderObject/*<T extends RenderObject>*/(Finder finder) {
|
||||
TestAsyncUtils.guardSync();
|
||||
return finder.evaluate().first.renderObject;
|
||||
}
|
||||
|
||||
@@ -142,6 +161,7 @@ class WidgetController {
|
||||
/// Returns a list of all the [Layer] objects in the rendering.
|
||||
List<Layer> get layers => _walkLayers(binding.renderView.layer).toList();
|
||||
Iterable<Layer> _walkLayers(Layer layer) sync* {
|
||||
TestAsyncUtils.guardSync();
|
||||
yield layer;
|
||||
if (layer is ContainerLayer) {
|
||||
ContainerLayer root = layer;
|
||||
@@ -160,15 +180,18 @@ class WidgetController {
|
||||
/// the given widget, assuming it is exposed. If the center of the
|
||||
/// widget is not exposed, this might send events to another
|
||||
/// object.
|
||||
void tap(Finder finder, { int pointer: 1 }) {
|
||||
tapAt(getCenter(finder), pointer: pointer);
|
||||
Future<Null> tap(Finder finder, { int pointer: 1 }) {
|
||||
return tapAt(getCenter(finder), pointer: pointer);
|
||||
}
|
||||
|
||||
/// Dispatch a pointer down / pointer up sequence at the given
|
||||
/// location.
|
||||
void tapAt(Point location, { int pointer: 1 }) {
|
||||
startGesture(location, pointer: pointer)
|
||||
..up();
|
||||
Future<Null> tapAt(Point location, { int pointer: 1 }) {
|
||||
return TestAsyncUtils.guard(() async {
|
||||
TestGesture gesture = await startGesture(location, pointer: pointer);
|
||||
await gesture.up();
|
||||
return null;
|
||||
});
|
||||
}
|
||||
|
||||
/// Attempts a fling gesture starting from the center of the given
|
||||
@@ -176,27 +199,30 @@ class WidgetController {
|
||||
///
|
||||
/// If the middle of the widget is not exposed, this might send
|
||||
/// events to another object.
|
||||
void fling(Finder finder, Offset offset, double velocity, { int pointer: 1 }) {
|
||||
flingFrom(getCenter(finder), offset, velocity, pointer: pointer);
|
||||
Future<Null> fling(Finder finder, Offset offset, double velocity, { int pointer: 1 }) {
|
||||
return flingFrom(getCenter(finder), offset, velocity, pointer: pointer);
|
||||
}
|
||||
|
||||
/// Attempts a fling gesture starting from the given location,
|
||||
/// moving the given distance, reaching the given velocity.
|
||||
void flingFrom(Point startLocation, Offset offset, double velocity, { int pointer: 1 }) {
|
||||
assert(offset.distance > 0.0);
|
||||
assert(velocity != 0.0); // velocity is pixels/second
|
||||
final TestPointer p = new TestPointer(pointer);
|
||||
final HitTestResult result = _hitTest(startLocation);
|
||||
const int kMoveCount = 50; // Needs to be >= kHistorySize, see _LeastSquaresVelocityTrackerStrategy
|
||||
final double timeStampDelta = 1000.0 * offset.distance / (kMoveCount * velocity);
|
||||
double timeStamp = 0.0;
|
||||
binding.dispatchEvent(p.down(startLocation, timeStamp: new Duration(milliseconds: timeStamp.round())), result);
|
||||
for (int i = 0; i <= kMoveCount; i++) {
|
||||
final Point location = startLocation + Offset.lerp(Offset.zero, offset, i / kMoveCount);
|
||||
binding.dispatchEvent(p.move(location, timeStamp: new Duration(milliseconds: timeStamp.round())), result);
|
||||
timeStamp += timeStampDelta;
|
||||
}
|
||||
binding.dispatchEvent(p.up(timeStamp: new Duration(milliseconds: timeStamp.round())), result);
|
||||
Future<Null> flingFrom(Point startLocation, Offset offset, double velocity, { int pointer: 1 }) {
|
||||
return TestAsyncUtils.guard(() async {
|
||||
assert(offset.distance > 0.0);
|
||||
assert(velocity != 0.0); // velocity is pixels/second
|
||||
final TestPointer p = new TestPointer(pointer);
|
||||
final HitTestResult result = _hitTest(startLocation);
|
||||
const int kMoveCount = 50; // Needs to be >= kHistorySize, see _LeastSquaresVelocityTrackerStrategy
|
||||
final double timeStampDelta = 1000.0 * offset.distance / (kMoveCount * velocity);
|
||||
double timeStamp = 0.0;
|
||||
await _dispatchEvent(p.down(startLocation, timeStamp: new Duration(milliseconds: timeStamp.round())), result);
|
||||
for (int i = 0; i <= kMoveCount; i++) {
|
||||
final Point location = startLocation + Offset.lerp(Offset.zero, offset, i / kMoveCount);
|
||||
await _dispatchEvent(p.move(location, timeStamp: new Duration(milliseconds: timeStamp.round())), result);
|
||||
timeStamp += timeStampDelta;
|
||||
}
|
||||
await _dispatchEvent(p.up(timeStamp: new Duration(milliseconds: timeStamp.round())), result);
|
||||
return null;
|
||||
});
|
||||
}
|
||||
|
||||
/// Attempts to drag the given widget by the given offset, by
|
||||
@@ -204,22 +230,25 @@ class WidgetController {
|
||||
///
|
||||
/// If the middle of the widget is not exposed, this might send
|
||||
/// events to another object.
|
||||
void scroll(Finder finder, Offset offset, { int pointer: 1 }) {
|
||||
scrollAt(getCenter(finder), offset, pointer: pointer);
|
||||
Future<Null> scroll(Finder finder, Offset offset, { int pointer: 1 }) {
|
||||
return scrollAt(getCenter(finder), offset, pointer: pointer);
|
||||
}
|
||||
|
||||
/// Attempts a drag gesture consisting of a pointer down, a move by
|
||||
/// the given offset, and a pointer up.
|
||||
void scrollAt(Point startLocation, Offset offset, { int pointer: 1 }) {
|
||||
startGesture(startLocation, pointer: pointer)
|
||||
..moveBy(offset)
|
||||
..up();
|
||||
Future<Null> scrollAt(Point startLocation, Offset offset, { int pointer: 1 }) {
|
||||
return TestAsyncUtils.guard(() async {
|
||||
TestGesture gesture = await startGesture(startLocation, pointer: pointer);
|
||||
await gesture.moveBy(offset);
|
||||
await gesture.up();
|
||||
return null;
|
||||
});
|
||||
}
|
||||
|
||||
/// Begins a gesture at a particular point, and returns the
|
||||
/// [TestGesture] object which you can use to continue the gesture.
|
||||
TestGesture startGesture(Point downLocation, { int pointer: 1 }) {
|
||||
return new TestGesture(downLocation, pointer: pointer);
|
||||
Future<TestGesture> startGesture(Point downLocation, { int pointer: 1 }) {
|
||||
return TestGesture.down(downLocation, pointer: pointer, dispatcher: _dispatchEvent);
|
||||
}
|
||||
|
||||
HitTestResult _hitTest(Point location) {
|
||||
@@ -228,6 +257,11 @@ class WidgetController {
|
||||
return result;
|
||||
}
|
||||
|
||||
Future<Null> _dispatchEvent(PointerEvent event, HitTestResult result) {
|
||||
binding.dispatchEvent(event, result);
|
||||
return new Future<Null>.value();
|
||||
}
|
||||
|
||||
|
||||
// GEOMETRY
|
||||
|
||||
@@ -260,6 +294,7 @@ class WidgetController {
|
||||
}
|
||||
|
||||
Point _getElementPoint(Finder finder, Point sizeToPoint(Size size)) {
|
||||
TestAsyncUtils.guardSync();
|
||||
Element element = finder.evaluate().single;
|
||||
RenderBox box = element.renderObject;
|
||||
assert(box != null);
|
||||
@@ -269,6 +304,7 @@ class WidgetController {
|
||||
/// Returns the size of the given widget. This is only valid once
|
||||
/// the widget's render object has been laid out at least once.
|
||||
Size getSize(Finder finder) {
|
||||
TestAsyncUtils.guardSync();
|
||||
Element element = finder.evaluate().single;
|
||||
RenderBox box = element.renderObject;
|
||||
assert(box != null);
|
||||
|
||||
31
packages/flutter_test/lib/src/stack_manipulation.dart
Normal file
31
packages/flutter_test/lib/src/stack_manipulation.dart
Normal file
@@ -0,0 +1,31 @@
|
||||
// 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.
|
||||
|
||||
// See also test_async_utils.dart which has some stack manipulation code.
|
||||
|
||||
/// Report call site for `expect()` call. Returns the number of frames that
|
||||
/// should be elided if a stack were to be modified to hide the expect call, or
|
||||
/// zero if no such call was found.
|
||||
///
|
||||
/// If the head of the stack trace consists of a failure as a result of calling
|
||||
/// the test_widgets [expect] function, this will fill the given StringBuffer
|
||||
/// with the precise file and line number that called that function.
|
||||
int reportExpectCall(StackTrace stack, StringBuffer information) {
|
||||
final RegExp line0 = new RegExp(r'^#0 +fail \(.+\)$');
|
||||
final RegExp line1 = new RegExp(r'^#1 +expect \(.+\)$');
|
||||
final RegExp line2 = new RegExp(r'^#2 +expect \(.+\)$');
|
||||
final RegExp line3 = new RegExp(r'^#3 +[^(]+ \((.+):([0-9]+):[0-9]+\)$');
|
||||
final List<String> stackLines = stack.toString().split('\n');
|
||||
if (line0.firstMatch(stackLines[0]) != null &&
|
||||
line1.firstMatch(stackLines[1]) != null &&
|
||||
line2.firstMatch(stackLines[2]) != null) {
|
||||
Match expectMatch = line3.firstMatch(stackLines[3]);
|
||||
assert(expectMatch != null);
|
||||
assert(expectMatch.groupCount == 2);
|
||||
information.writeln('This was caught by the test expectation on the following line:');
|
||||
information.writeln(' ${expectMatch.group(1)} line ${expectMatch.group(2)}');
|
||||
return 3;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
326
packages/flutter_test/lib/src/test_async_utils.dart
Normal file
326
packages/flutter_test/lib/src/test_async_utils.dart
Normal file
@@ -0,0 +1,326 @@
|
||||
// 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';
|
||||
|
||||
class _AsyncScope {
|
||||
_AsyncScope(this.creationStack, this.zone);
|
||||
final StackTrace creationStack;
|
||||
final Zone zone;
|
||||
}
|
||||
|
||||
/// Utility class for all the async APIs in the `flutter_test` library.
|
||||
///
|
||||
/// This class provides checking for asynchronous APIs, allowing the library to
|
||||
/// verify that all the asynchronous APIs are properly `await`ed before calling
|
||||
/// another.
|
||||
///
|
||||
/// For example, it prevents this kind of code:
|
||||
///
|
||||
/// ```dart
|
||||
/// tester.pump(); // forgot to call "await"!
|
||||
/// tester.pump();
|
||||
/// ```
|
||||
///
|
||||
/// ...by detecting, in the second call to `pump`, that it should actually be:
|
||||
///
|
||||
/// ```dart
|
||||
/// await tester.pump();
|
||||
/// await tester.pump();
|
||||
/// ```
|
||||
///
|
||||
/// It does this while still allowing nested calls, e.g. so that you can
|
||||
/// invoke [expect] from inside callbacks.
|
||||
///
|
||||
/// You can use this in your own test functions, if you have some asynchronous
|
||||
/// functions that must be used with "await". Wrap the contents of the function
|
||||
/// in a call to TestAsyncUtils.guard(), as follows:
|
||||
///
|
||||
/// ```dart
|
||||
/// Future<Null> myTestFunction() => TestAsyncUtils.guard(() async {
|
||||
/// // ...
|
||||
/// });
|
||||
/// ```
|
||||
class TestAsyncUtils {
|
||||
TestAsyncUtils._();
|
||||
static const String _className = 'TestAsyncUtils';
|
||||
|
||||
static List<_AsyncScope> _scopeStack = <_AsyncScope>[];
|
||||
|
||||
/// Invokes the given callback in a new async scope. The callback argument is
|
||||
/// the asynchronous body of the calling method. The calling method is said to
|
||||
/// be "guarded". Nested calls to guarded methods from within the body of this
|
||||
/// one are fine, but calls to other guarded methods from outside the body of
|
||||
/// this one before this one has finished will throw an exception.
|
||||
///
|
||||
/// This method first calls [guardSync].
|
||||
static Future<Null> guard(Future<Null> body()) {
|
||||
guardSync();
|
||||
Zone zone = Zone.current.fork(
|
||||
zoneValues: <dynamic, dynamic>{
|
||||
_scopeStack: true // so we can recognize this as our own zone
|
||||
}
|
||||
);
|
||||
_AsyncScope scope = new _AsyncScope(StackTrace.current, zone);
|
||||
_scopeStack.add(scope);
|
||||
Future<Null> result = scope.zone.run(body);
|
||||
result = result.whenComplete(() {
|
||||
assert(_scopeStack.isNotEmpty);
|
||||
assert(_scopeStack.contains(scope));
|
||||
bool leaked = false;
|
||||
_AsyncScope closedScope;
|
||||
StringBuffer message = new StringBuffer();
|
||||
while (_scopeStack.isNotEmpty) {
|
||||
closedScope = _scopeStack.removeLast();
|
||||
if (closedScope == scope)
|
||||
break;
|
||||
leaked = true;
|
||||
message.writeln('Asynchronous call to guarded function leaked. You must use "await" with all Future-returning test APIs.');
|
||||
final _StackEntry originalGuarder = _findResponsibleMethod(closedScope.creationStack, 'guard', message);
|
||||
if (originalGuarder != null) {
|
||||
message.writeln(
|
||||
'The test API method "${originalGuarder.methodName}" '
|
||||
'from class ${originalGuarder.className} '
|
||||
'was called from ${originalGuarder.callerFile} '
|
||||
'on line ${originalGuarder.callerLine}, '
|
||||
'but never completed before its parent scope closed.'
|
||||
);
|
||||
}
|
||||
}
|
||||
if (leaked)
|
||||
throw new FlutterError(message.toString().trimRight());
|
||||
});
|
||||
return result;
|
||||
}
|
||||
|
||||
static Zone get _currentScopeZone {
|
||||
Zone zone = Zone.current;
|
||||
while (zone != null) {
|
||||
if (zone[_scopeStack] == true)
|
||||
return zone;
|
||||
zone = zone.parent;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/// Verifies that there are no guarded methods currently pending (see [guard]).
|
||||
///
|
||||
/// If a guarded method is currently pending, and this is not a call nested
|
||||
/// from inside that method's body (directly or indirectly), then this method
|
||||
/// will throw a detailed exception.
|
||||
static void guardSync() {
|
||||
if (_scopeStack.isEmpty) {
|
||||
// No scopes open, so we must be fine.
|
||||
return;
|
||||
}
|
||||
// Find the current TestAsyncUtils scope zone so we can see if it's the one we expect.
|
||||
final Zone zone = _currentScopeZone;
|
||||
if (zone == _scopeStack.last.zone) {
|
||||
// We're still in the current scope zone. All good.
|
||||
return;
|
||||
}
|
||||
// If we get here, we know we've got a conflict on our hands.
|
||||
// We got an async barrier, but the current zone isn't the last scope that
|
||||
// we pushed on the stack.
|
||||
// Find which scope the conflict happened in, so that we know
|
||||
// which stack trace to report the conflict as starting from.
|
||||
//
|
||||
// For example, if we called an async method A, which ran its body in a
|
||||
// guarded block, and in its body it ran an async method B, which ran its
|
||||
// body in a guarded block, but we didn't await B, then in A's block we ran
|
||||
// an async method C, which ran its body in a guarded block, then we should
|
||||
// complain about the call to B then the call to C. BUT. If we called an async
|
||||
// method A, which ran its body in a guarded block, and in its body it ran
|
||||
// an async method B, which ran its body in a guarded block, but we didn't
|
||||
// await A, and then at the top level we called a method D, then we should
|
||||
// complain about the call to A then the call to D.
|
||||
//
|
||||
// In both examples, the scope stack would have two scopes. In the first
|
||||
// example, the current zone would be the zone of the _scopeStack[0] scope,
|
||||
// and we would want to show _scopeStack[1]'s creationStack. In the second
|
||||
// example, the current zone would not be in the _scopeStack, and we would
|
||||
// want to show _scopeStack[0]'s creationStack.
|
||||
int skipCount = 0;
|
||||
_AsyncScope candidateScope = _scopeStack.last;
|
||||
_AsyncScope scope;
|
||||
do {
|
||||
skipCount += 1;
|
||||
scope = candidateScope;
|
||||
candidateScope = skipCount < _scopeStack.length ? _scopeStack[_scopeStack.length - skipCount - 1] : null;
|
||||
} while (candidateScope?.zone != zone);
|
||||
assert(scope != null);
|
||||
StringBuffer message = new StringBuffer();
|
||||
message.writeln('Guarded function conflict. You must use "await" with all Future-returning test APIs.');
|
||||
final _StackEntry originalGuarder = _findResponsibleMethod(scope.creationStack, 'guard', message);
|
||||
final _StackEntry collidingGuarder = _findResponsibleMethod(StackTrace.current, 'guardSync', message);
|
||||
if (originalGuarder != null && collidingGuarder != null) {
|
||||
String originalName;
|
||||
if (originalGuarder.className == null) {
|
||||
originalName = '(${originalGuarder.methodName}) ';
|
||||
message.writeln(
|
||||
'The guarded "${originalGuarder.methodName}" function '
|
||||
'was called from ${originalGuarder.callerFile} '
|
||||
'on line ${originalGuarder.callerLine}.'
|
||||
);
|
||||
} else {
|
||||
originalName = '(${originalGuarder.className}.${originalGuarder.methodName}) ';
|
||||
message.writeln(
|
||||
'The guarded method "${originalGuarder.methodName}" '
|
||||
'from class ${originalGuarder.className} '
|
||||
'was called from ${originalGuarder.callerFile} '
|
||||
'on line ${originalGuarder.callerLine}.'
|
||||
);
|
||||
}
|
||||
final String again = (originalGuarder.callerFile == collidingGuarder.callerFile) &&
|
||||
(originalGuarder.callerLine == collidingGuarder.callerLine) ?
|
||||
'again ' : '';
|
||||
String collidingName;
|
||||
if ((originalGuarder.className == collidingGuarder.className) &&
|
||||
(originalGuarder.methodName == collidingGuarder.methodName)) {
|
||||
originalName = '';
|
||||
collidingName = '';
|
||||
message.writeln(
|
||||
'Then, it '
|
||||
'was called ${again}from ${collidingGuarder.callerFile} '
|
||||
'on line ${collidingGuarder.callerLine}.'
|
||||
);
|
||||
} else if (collidingGuarder.className == null) {
|
||||
collidingName = '(${collidingGuarder.methodName}) ';
|
||||
message.writeln(
|
||||
'Then, the "${collidingGuarder.methodName}" function '
|
||||
'was called ${again}from ${collidingGuarder.callerFile} '
|
||||
'on line ${collidingGuarder.callerLine}.'
|
||||
);
|
||||
} else {
|
||||
collidingName = '(${collidingGuarder.className}.${collidingGuarder.methodName}) ';
|
||||
message.writeln(
|
||||
'Then, the "${collidingGuarder.methodName}" method '
|
||||
'${originalGuarder.className == collidingGuarder.className ? "(also from class ${collidingGuarder.className})"
|
||||
: "from class ${collidingGuarder.className}"} '
|
||||
'was called ${again}from ${collidingGuarder.callerFile} '
|
||||
'on line ${collidingGuarder.callerLine}.'
|
||||
);
|
||||
}
|
||||
message.writeln(
|
||||
'The first ${originalGuarder.className == null ? "function" : "method"} $originalName'
|
||||
'had not yet finished executing at the time that '
|
||||
'the second ${collidingGuarder.className == null ? "function" : "method"} $collidingName'
|
||||
'was called. Since both are guarded, and the second was not a nested call inside the first, the '
|
||||
'first must complete its execution before the second can be called. Typically, this is achieved by '
|
||||
'putting an "await" statement in front of the call to the first.'
|
||||
);
|
||||
if (collidingGuarder.className == null && collidingGuarder.methodName == 'expect') {
|
||||
message.writeln(
|
||||
'If you are confident that all test APIs are being called using "await", and '
|
||||
'this expect() call is not being invoked at the top level but is itself being '
|
||||
'called from some sort of callback registered before the ${originalGuarder.methodName} '
|
||||
'method was called, then consider using expectSync() instead.'
|
||||
);
|
||||
}
|
||||
message.writeln(
|
||||
'\n'
|
||||
'When the first ${originalGuarder.className == null ? "function" : "method"} '
|
||||
'$originalName'
|
||||
'was called, this was the stack:'
|
||||
);
|
||||
message.writeln(FlutterError.defaultStackFilter(scope.creationStack.toString().trimRight().split('\n')).join('\n'));
|
||||
}
|
||||
throw new FlutterError(message.toString().trimRight());
|
||||
}
|
||||
|
||||
/// Verifies that there are no guarded methods currently pending (see [guard]).
|
||||
///
|
||||
/// This is used at the end of tests to ensure that nothing leaks out of the test.
|
||||
static void verifyAllScopesClosed() {
|
||||
if (_scopeStack.isNotEmpty) {
|
||||
StringBuffer message = new StringBuffer();
|
||||
message.writeln('Asynchronous call to guarded function leaked. You must use "await" with all Future-returning test APIs.');
|
||||
for (_AsyncScope scope in _scopeStack) {
|
||||
final _StackEntry guarder = _findResponsibleMethod(scope.creationStack, 'guard', message);
|
||||
if (guarder != null) {
|
||||
message.writeln(
|
||||
'The guarded method "${guarder.methodName}" '
|
||||
'${guarder.className != null ? "from class ${guarder.className} " : ""}'
|
||||
'was called from ${guarder.callerFile} '
|
||||
'on line ${guarder.callerLine}, '
|
||||
'but never completed before its parent scope closed.'
|
||||
);
|
||||
}
|
||||
}
|
||||
throw new FlutterError(message.toString().trimRight());
|
||||
}
|
||||
}
|
||||
|
||||
static _StackEntry _findResponsibleMethod(StackTrace rawStack, String method, StringBuffer errors) {
|
||||
assert(method == 'guard' || method == 'guardSync');
|
||||
final List<String> stack = rawStack.toString().split('\n');
|
||||
assert(stack.last == '');
|
||||
stack.removeLast();
|
||||
final RegExp getClassPattern = new RegExp(r'^#[0-9]+ +([^. ]+)');
|
||||
Match lineMatch;
|
||||
int index = -1;
|
||||
do { // skip past frames that are from this class
|
||||
index += 1;
|
||||
assert(index < stack.length);
|
||||
lineMatch = getClassPattern.matchAsPrefix(stack[index]);
|
||||
assert(lineMatch != null);
|
||||
assert(lineMatch.groupCount == 1);
|
||||
} while (lineMatch.group(1) == _className);
|
||||
// try to parse the stack to find the interesting frame
|
||||
if (index < stack.length) {
|
||||
final RegExp guardPattern = new RegExp(r'^#[0-9]+ +(?:([^. ]+)\.)?([^. ]+)');
|
||||
final Match guardMatch = guardPattern.matchAsPrefix(stack[index]); // find the class that called us
|
||||
if (guardMatch != null) {
|
||||
assert(guardMatch.groupCount == 2);
|
||||
final String guardClass = guardMatch.group(1); // might be null
|
||||
final String guardMethod = guardMatch.group(2);
|
||||
while (index < stack.length) { // find the last stack frame that called the class that called us
|
||||
lineMatch = getClassPattern.matchAsPrefix(stack[index]);
|
||||
if (lineMatch != null) {
|
||||
assert(lineMatch.groupCount == 1);
|
||||
if (lineMatch.group(1) == (guardClass ?? guardMethod)) {
|
||||
index += 1;
|
||||
continue;
|
||||
}
|
||||
}
|
||||
break;
|
||||
}
|
||||
if (index < stack.length) {
|
||||
final RegExp callerPattern = new RegExp(r'^#[0-9]+ .* \((.+):([0-9]+)(?::[0-9]+)?\)$');
|
||||
final Match callerMatch = callerPattern.matchAsPrefix(stack[index]); // extract the caller's info
|
||||
if (callerMatch != null) {
|
||||
assert(callerMatch.groupCount == 2);
|
||||
final String callerFile = callerMatch.group(1);
|
||||
final String callerLine = callerMatch.group(2);
|
||||
return new _StackEntry(guardClass, guardMethod, callerFile, callerLine);
|
||||
} else {
|
||||
// One reason you might get here is if the guarding method was called directly from
|
||||
// a 'dart:' API, like from the Future/microtask mechanism, because dart: URLs in the
|
||||
// stack trace don't have a column number and so don't match the regexp above.
|
||||
errors.writeln('(Unable to parse the stack frame of the method that called the method that called $_className.$method(). The stack may be incomplete or bogus.)');
|
||||
errors.writeln('${stack[index]}');
|
||||
}
|
||||
} else {
|
||||
errors.writeln('(Unable to find the stack frame of the method that called the method that called $_className.$method(). The stack may be incomplete or bogus.)');
|
||||
}
|
||||
} else {
|
||||
errors.writeln('(Unable to parse the stack frame of the method that called $_className.$method(). The stack may be incomplete or bogus.)');
|
||||
errors.writeln('${stack[index]}');
|
||||
}
|
||||
} else {
|
||||
errors.writeln('(Unable to find the method that called $_className.$method(). The stack may be incomplete or bogus.)');
|
||||
}
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
class _StackEntry {
|
||||
const _StackEntry(this.className, this.methodName, this.callerFile, this.callerLine);
|
||||
final String className;
|
||||
final String methodName;
|
||||
final String callerFile;
|
||||
final String callerLine;
|
||||
}
|
||||
@@ -2,8 +2,12 @@
|
||||
// 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/gestures.dart';
|
||||
|
||||
import 'test_async_utils.dart';
|
||||
|
||||
export 'dart:ui' show Point;
|
||||
|
||||
/// A class for generating coherent artificial pointer events.
|
||||
@@ -102,68 +106,85 @@ class TestPointer {
|
||||
}
|
||||
}
|
||||
|
||||
/// An callback that can dispatch events and returns a future that
|
||||
/// completes when the event dispatch is complete.
|
||||
typedef Future<Null> AsyncHitTestDispatcher(PointerEvent event, HitTestResult result);
|
||||
|
||||
/// A class for performing gestures in tests.
|
||||
///
|
||||
/// The simplest way to create a [TestGesture] is to call
|
||||
/// [WidgetTester.startGesture].
|
||||
class TestGesture {
|
||||
TestGesture._(this._dispatcher, this._result, this._pointer);
|
||||
|
||||
/// Create a [TestGesture] by starting with a pointerDown at the
|
||||
/// given point.
|
||||
///
|
||||
/// By default, the pointer ID used is 1. This can be overridden by
|
||||
/// providing the `pointer` argument.
|
||||
///
|
||||
/// By default, the global binding is used both for hit testing and
|
||||
/// for dispatching of events. The object to use for hit testing can
|
||||
/// be overridden by providing `hitTestTarget`, and the object to
|
||||
/// use for dispatching events can be overridden by providing an
|
||||
/// `dispatcher`.
|
||||
factory TestGesture(Point downLocation, {
|
||||
/// By default, the global binding is used for hit testing. The
|
||||
/// object to use for hit testing can be overridden by providing
|
||||
/// `hitTestTarget`.
|
||||
///
|
||||
/// An object to use for dispatching events must be provided via the
|
||||
/// `dispatcher` argument.
|
||||
static Future<TestGesture> down(Point downLocation, {
|
||||
int pointer: 1,
|
||||
HitTestable target,
|
||||
HitTestDispatcher dispatcher
|
||||
}) {
|
||||
// hit test
|
||||
final HitTestResult result = new HitTestResult();
|
||||
target ??= GestureBinding.instance;
|
||||
assert(target != null);
|
||||
target.hitTest(result, downLocation);
|
||||
|
||||
// dispatch down event
|
||||
final TestPointer testPointer = new TestPointer(pointer);
|
||||
dispatcher ??= GestureBinding.instance;
|
||||
AsyncHitTestDispatcher dispatcher
|
||||
}) async {
|
||||
assert(dispatcher != null);
|
||||
dispatcher.dispatchEvent(testPointer.down(downLocation), result);
|
||||
final Completer<TestGesture> completer = new Completer<TestGesture>();
|
||||
TestGesture result;
|
||||
TestAsyncUtils.guard(() async {
|
||||
// hit test
|
||||
final HitTestResult hitTestResult = new HitTestResult();
|
||||
target ??= GestureBinding.instance;
|
||||
assert(target != null);
|
||||
target.hitTest(hitTestResult, downLocation);
|
||||
|
||||
// create a TestGesture
|
||||
return new TestGesture._(dispatcher, result, testPointer);
|
||||
// dispatch down event
|
||||
final TestPointer testPointer = new TestPointer(pointer);
|
||||
await dispatcher(testPointer.down(downLocation), hitTestResult);
|
||||
|
||||
// create a TestGesture
|
||||
result = new TestGesture._(dispatcher, hitTestResult, testPointer);
|
||||
return null;
|
||||
}).whenComplete(() {
|
||||
completer.complete(result);
|
||||
});
|
||||
return completer.future;
|
||||
}
|
||||
|
||||
const TestGesture._(this._dispatcher, this._result, this._pointer);
|
||||
|
||||
final HitTestDispatcher _dispatcher;
|
||||
final AsyncHitTestDispatcher _dispatcher;
|
||||
final HitTestResult _result;
|
||||
final TestPointer _pointer;
|
||||
|
||||
/// Send a move event moving the pointer by the given offset.
|
||||
void moveBy(Offset offset) {
|
||||
Future<Null> moveBy(Offset offset) {
|
||||
assert(_pointer._isDown);
|
||||
moveTo(_pointer.location + offset);
|
||||
return moveTo(_pointer.location + offset);
|
||||
}
|
||||
|
||||
/// Send a move event moving the pointer to the given location.
|
||||
void moveTo(Point location) {
|
||||
assert(_pointer._isDown);
|
||||
_dispatcher.dispatchEvent(_pointer.move(location), _result);
|
||||
Future<Null> moveTo(Point location) {
|
||||
return TestAsyncUtils.guard(() {
|
||||
assert(_pointer._isDown);
|
||||
return _dispatcher(_pointer.move(location), _result);
|
||||
});
|
||||
}
|
||||
|
||||
/// End the gesture by releasing the pointer.
|
||||
///
|
||||
/// The object is no longer usable after this method has been called.
|
||||
void up() {
|
||||
assert(_pointer._isDown);
|
||||
_dispatcher.dispatchEvent(_pointer.up(), _result);
|
||||
assert(!_pointer._isDown);
|
||||
Future<Null> up() {
|
||||
return TestAsyncUtils.guard(() async {
|
||||
assert(_pointer._isDown);
|
||||
await _dispatcher(_pointer.up(), _result);
|
||||
assert(!_pointer._isDown);
|
||||
return null;
|
||||
});
|
||||
}
|
||||
|
||||
/// End the gesture by canceling the pointer (as would happen if the
|
||||
@@ -171,9 +192,12 @@ class TestGesture {
|
||||
/// for instance).
|
||||
///
|
||||
/// The object is no longer usable after this method has been called.
|
||||
void cancel() {
|
||||
assert(_pointer._isDown);
|
||||
_dispatcher.dispatchEvent(_pointer.cancel(), _result);
|
||||
assert(!_pointer._isDown);
|
||||
Future<Null> cancel() {
|
||||
return TestAsyncUtils.guard(() async {
|
||||
assert(_pointer._isDown);
|
||||
await _dispatcher(_pointer.cancel(), _result);
|
||||
assert(!_pointer._isDown);
|
||||
return null;
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
@@ -5,11 +5,14 @@
|
||||
import 'dart:async';
|
||||
|
||||
import 'package:flutter/widgets.dart';
|
||||
import 'package:test/test.dart';
|
||||
import 'package:test/test.dart' as test_package;
|
||||
|
||||
import 'binding.dart';
|
||||
import 'finders.dart';
|
||||
import 'controller.dart';
|
||||
import 'finders.dart';
|
||||
import 'test_async_utils.dart';
|
||||
|
||||
export 'package:test/test.dart' hide expect;
|
||||
|
||||
/// Signature for callback to [testWidgets] and [benchmarkWidgets].
|
||||
typedef Future<Null> WidgetTesterCallback(WidgetTester widgetTester);
|
||||
@@ -36,15 +39,15 @@ typedef Future<Null> WidgetTesterCallback(WidgetTester widgetTester);
|
||||
/// expect(tester, hasWidget(find.text('Success')));
|
||||
/// });
|
||||
void testWidgets(String description, WidgetTesterCallback callback, {
|
||||
Timeout timeout: const Timeout(const Duration(seconds: 5)),
|
||||
bool skip
|
||||
bool skip: false,
|
||||
test_package.Timeout timeout
|
||||
}) {
|
||||
TestWidgetsFlutterBinding binding = TestWidgetsFlutterBinding.ensureInitialized();
|
||||
WidgetTester tester = new WidgetTester._(binding);
|
||||
group('-', () {
|
||||
setUp(binding.preTest);
|
||||
test(description, () => binding.runTest(() => callback(tester)), skip: skip);
|
||||
tearDown(binding.postTest);
|
||||
timeout ??= binding.defaultTestTimeout;
|
||||
test_package.group('-', () {
|
||||
test_package.test(description, () => binding.runTest(() => callback(tester)), skip: skip);
|
||||
test_package.tearDown(binding.postTest);
|
||||
}, timeout: timeout);
|
||||
}
|
||||
|
||||
@@ -75,17 +78,49 @@ void testWidgets(String description, WidgetTesterCallback callback, {
|
||||
/// tester.pump();
|
||||
/// }
|
||||
/// timer.stop();
|
||||
/// print('Time taken: ${timer.elapsedMilliseconds}ms');
|
||||
/// debugPrint('Time taken: ${timer.elapsedMilliseconds}ms');
|
||||
/// });
|
||||
/// exit(0);
|
||||
/// }
|
||||
Future<Null> benchmarkWidgets(WidgetTesterCallback callback) {
|
||||
assert(false); // Don't run benchmarks in checked mode.
|
||||
TestWidgetsFlutterBinding binding = TestWidgetsFlutterBinding.ensureInitialized();
|
||||
assert(binding is! AutomatedTestWidgetsFlutterBinding);
|
||||
WidgetTester tester = new WidgetTester._(binding);
|
||||
return binding.runTest(() => callback(tester)) ?? new Future<Null>.value();
|
||||
}
|
||||
|
||||
/// 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.
|
||||
void expect(dynamic actual, dynamic matcher, {
|
||||
String reason,
|
||||
bool verbose: false,
|
||||
dynamic formatter
|
||||
}) {
|
||||
TestAsyncUtils.guardSync();
|
||||
test_package.expect(actual, matcher, reason: reason, verbose: verbose, formatter: formatter);
|
||||
}
|
||||
|
||||
/// 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.
|
||||
void expectSync(dynamic actual, dynamic matcher, {
|
||||
String reason,
|
||||
bool verbose: false,
|
||||
dynamic formatter
|
||||
}) {
|
||||
test_package.expect(actual, matcher, reason: reason, verbose: verbose, formatter: formatter);
|
||||
}
|
||||
|
||||
/// Class that programmatically interacts with widgets and the test environment.
|
||||
class WidgetTester extends WidgetController {
|
||||
WidgetTester._(TestWidgetsFlutterBinding binding) : super(binding);
|
||||
@@ -100,17 +135,25 @@ class WidgetTester extends WidgetController {
|
||||
/// 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.
|
||||
void pumpWidget(Widget widget, [ Duration duration, EnginePhase phase ]) {
|
||||
runApp(widget);
|
||||
binding.pump(duration, phase);
|
||||
Future<Null> pumpWidget(Widget widget, [
|
||||
Duration duration,
|
||||
EnginePhase phase = EnginePhase.sendSemanticsTree
|
||||
]) {
|
||||
return TestAsyncUtils.guard(() {
|
||||
runApp(widget);
|
||||
return binding.pump(duration, phase);
|
||||
});
|
||||
}
|
||||
|
||||
/// Triggers a sequence of frames for [duration] amount of time.
|
||||
///
|
||||
/// This is a convenience function that just calls
|
||||
/// [TestWidgetsFlutterBinding.pump].
|
||||
void pump([ Duration duration, EnginePhase phase ]) {
|
||||
binding.pump(duration, phase);
|
||||
Future<Null> pump([
|
||||
Duration duration,
|
||||
EnginePhase phase = EnginePhase.sendSemanticsTree
|
||||
]) {
|
||||
return TestAsyncUtils.guard(() => binding.pump(duration, phase));
|
||||
}
|
||||
|
||||
/// Returns the exception most recently caught by the Flutter framework.
|
||||
@@ -120,12 +163,14 @@ class WidgetTester extends WidgetController {
|
||||
return binding.takeException();
|
||||
}
|
||||
|
||||
/// 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.
|
||||
///
|
||||
/// Does not run timers. May result in an infinite loop or run out of memory
|
||||
/// if microtasks continue to recursively schedule new microtasks.
|
||||
void flushMicrotasks() {
|
||||
binding.fakeAsync.flushMicrotasks();
|
||||
Future<Null> idle() {
|
||||
return TestAsyncUtils.guard(() => binding.idle());
|
||||
}
|
||||
}
|
||||
|
||||
28
packages/flutter_test/test/stack_manipulation_test.dart
Normal file
28
packages/flutter_test/test/stack_manipulation_test.dart
Normal file
@@ -0,0 +1,28 @@
|
||||
// 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 'package:flutter_test/flutter_test.dart';
|
||||
|
||||
void main() {
|
||||
test('stack manipulation: reportExpectCall', () {
|
||||
try {
|
||||
expect(false, isTrue);
|
||||
} catch (e, stack) {
|
||||
StringBuffer information = new StringBuffer();
|
||||
expect(reportExpectCall(stack, information), 3);
|
||||
List<String> lines = information.toString().split('\n');
|
||||
expect(lines[0], 'This was caught by the test expectation on the following line:');
|
||||
expect(lines[1], matches(r'^ .*stack_manipulation_test.dart line [0-9]+$'));
|
||||
}
|
||||
|
||||
try {
|
||||
throw null;
|
||||
expect(false, isTrue); // shouldn't get here
|
||||
} catch (e, stack) {
|
||||
StringBuffer information = new StringBuffer();
|
||||
expect(reportExpectCall(stack, information), 0);
|
||||
expect(information.toString(), '');
|
||||
}
|
||||
});
|
||||
}
|
||||
178
packages/flutter_test/test/test_async_utils_test.dart
Normal file
178
packages/flutter_test/test/test_async_utils_test.dart
Normal file
@@ -0,0 +1,178 @@
|
||||
// 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 'package:flutter/widgets.dart';
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
|
||||
import 'package:flutter_test/flutter_test.dart' as flutter_test show expect;
|
||||
import 'package:test/test.dart' as real_test show expect;
|
||||
|
||||
// We have to use real_test's expect because the flutter_test expect() goes
|
||||
// out of its way to check that we're not leaking APIs and the whole point
|
||||
// of this test is to see how we handle leaking APIs.
|
||||
|
||||
class TestAPI {
|
||||
Future<Null> testGuard1() {
|
||||
return TestAsyncUtils.guard(() async { return null; });
|
||||
}
|
||||
Future<Null> testGuard2() {
|
||||
return TestAsyncUtils.guard(() async { return null; });
|
||||
}
|
||||
}
|
||||
|
||||
class TestAPISubclass extends TestAPI {
|
||||
Future<Null> testGuard3() {
|
||||
return TestAsyncUtils.guard(() async { return null; });
|
||||
}
|
||||
}
|
||||
|
||||
Future<Null> helperFunction(WidgetTester tester) async {
|
||||
await tester.pump();
|
||||
}
|
||||
|
||||
Future<Null> guardedHelper(WidgetTester tester) {
|
||||
return TestAsyncUtils.guard(() async {
|
||||
await tester.pumpWidget(new Text('Hello'));
|
||||
});
|
||||
}
|
||||
|
||||
void main() {
|
||||
test('TestAsyncUtils - one class', () async {
|
||||
TestAPI testAPI = new TestAPI();
|
||||
Future<Null> f1, f2;
|
||||
f1 = testAPI.testGuard1();
|
||||
try {
|
||||
f2 = testAPI.testGuard2();
|
||||
throw 'unexpectedly did not throw';
|
||||
} on FlutterError catch (e) {
|
||||
List<String> lines = e.message.split('\n');
|
||||
real_test.expect(lines[0], 'Guarded function conflict. You must use "await" with all Future-returning test APIs.');
|
||||
real_test.expect(lines[1], matches(r'The guarded method "testGuard1" from class TestAPI was called from .*test_async_utils.dart on line [0-9]+\.'));
|
||||
real_test.expect(lines[2], matches(r'Then, the "testGuard2" method \(also from class TestAPI\) was called from .*test_async_utils.dart on line [0-9]+\.'));
|
||||
real_test.expect(lines[3], 'The first method (TestAPI.testGuard1) had not yet finished executing at the time that the second method (TestAPI.testGuard2) was called. Since both are guarded, and the second was not a nested call inside the first, the first must complete its execution before the second can be called. Typically, this is achieved by putting an "await" statement in front of the call to the first.');
|
||||
real_test.expect(lines[4], '');
|
||||
real_test.expect(lines[5], 'When the first method (TestAPI.testGuard1) was called, this was the stack:');
|
||||
real_test.expect(lines.length, greaterThan(6));
|
||||
}
|
||||
expect(await f1, isNull);
|
||||
expect(f2, isNull);
|
||||
});
|
||||
|
||||
test('TestAsyncUtils - two classes, all callers in superclass', () async {
|
||||
TestAPI testAPI = new TestAPISubclass();
|
||||
Future<Null> f1, f2;
|
||||
f1 = testAPI.testGuard1();
|
||||
try {
|
||||
f2 = testAPI.testGuard2();
|
||||
throw 'unexpectedly did not throw';
|
||||
} on FlutterError catch (e) {
|
||||
List<String> lines = e.message.split('\n');
|
||||
real_test.expect(lines[0], 'Guarded function conflict. You must use "await" with all Future-returning test APIs.');
|
||||
real_test.expect(lines[1], matches(r'^The guarded method "testGuard1" from class TestAPI was called from .*test_async_utils.dart on line [0-9]+\.$'));
|
||||
real_test.expect(lines[2], matches(r'^Then, the "testGuard2" method \(also from class TestAPI\) was called from .*test_async_utils.dart on line [0-9]+\.$'));
|
||||
real_test.expect(lines[3], 'The first method (TestAPI.testGuard1) had not yet finished executing at the time that the second method (TestAPI.testGuard2) was called. Since both are guarded, and the second was not a nested call inside the first, the first must complete its execution before the second can be called. Typically, this is achieved by putting an "await" statement in front of the call to the first.');
|
||||
real_test.expect(lines[4], '');
|
||||
real_test.expect(lines[5], 'When the first method (TestAPI.testGuard1) was called, this was the stack:');
|
||||
real_test.expect(lines.length, greaterThan(6));
|
||||
}
|
||||
expect(await f1, isNull);
|
||||
expect(f2, isNull);
|
||||
});
|
||||
|
||||
test('TestAsyncUtils - two classes, mixed callers', () async {
|
||||
TestAPISubclass testAPI = new TestAPISubclass();
|
||||
Future<Null> f1, f2;
|
||||
f1 = testAPI.testGuard1();
|
||||
try {
|
||||
f2 = testAPI.testGuard3();
|
||||
throw 'unexpectedly did not throw';
|
||||
} on FlutterError catch (e) {
|
||||
List<String> lines = e.message.split('\n');
|
||||
real_test.expect(lines[0], 'Guarded function conflict. You must use "await" with all Future-returning test APIs.');
|
||||
real_test.expect(lines[1], matches(r'^The guarded method "testGuard1" from class TestAPI was called from .*test_async_utils.dart on line [0-9]+\.$'));
|
||||
real_test.expect(lines[2], matches(r'^Then, the "testGuard3" method from class TestAPISubclass was called from .*test_async_utils.dart on line [0-9]+\.$'));
|
||||
real_test.expect(lines[3], 'The first method (TestAPI.testGuard1) had not yet finished executing at the time that the second method (TestAPISubclass.testGuard3) was called. Since both are guarded, and the second was not a nested call inside the first, the first must complete its execution before the second can be called. Typically, this is achieved by putting an "await" statement in front of the call to the first.');
|
||||
real_test.expect(lines[4], '');
|
||||
real_test.expect(lines[5], 'When the first method (TestAPI.testGuard1) was called, this was the stack:');
|
||||
real_test.expect(lines.length, greaterThan(6));
|
||||
}
|
||||
expect(await f1, isNull);
|
||||
expect(f2, isNull);
|
||||
});
|
||||
|
||||
test('TestAsyncUtils - expect() catches pending async work', () async {
|
||||
TestAPI testAPI = new TestAPISubclass();
|
||||
Future<Null> f1;
|
||||
f1 = testAPI.testGuard1();
|
||||
try {
|
||||
flutter_test.expect(0, 0);
|
||||
throw 'unexpectedly did not throw';
|
||||
} on FlutterError catch (e) {
|
||||
List<String> lines = e.message.split('\n');
|
||||
real_test.expect(lines[0], 'Guarded function conflict. You must use "await" with all Future-returning test APIs.');
|
||||
real_test.expect(lines[1], matches(r'^The guarded method "testGuard1" from class TestAPI was called from .*test_async_utils.dart on line [0-9]+\.$'));
|
||||
real_test.expect(lines[2], matches(r'^Then, the "expect" function was called from .*test_async_utils.dart on line [0-9]+\.$'));
|
||||
real_test.expect(lines[3], 'The first method (TestAPI.testGuard1) had not yet finished executing at the time that the second function (expect) was called. Since both are guarded, and the second was not a nested call inside the first, the first must complete its execution before the second can be called. Typically, this is achieved by putting an "await" statement in front of the call to the first.');
|
||||
real_test.expect(lines[4], 'If you are confident that all test APIs are being called using "await", and this expect() call is not being invoked at the top level but is itself being called from some sort of callback registered before the testGuard1 method was called, then consider using expectSync() instead.');
|
||||
real_test.expect(lines[5], '');
|
||||
real_test.expect(lines[6], 'When the first method (TestAPI.testGuard1) was called, this was the stack:');
|
||||
real_test.expect(lines.length, greaterThan(7));
|
||||
}
|
||||
expect(await f1, isNull);
|
||||
});
|
||||
|
||||
testWidgets('TestAsyncUtils - expect() catches pending async work', (WidgetTester tester) async {
|
||||
Future<Null> f1, f2;
|
||||
try {
|
||||
f1 = tester.pump();
|
||||
f2 = tester.pump();
|
||||
throw 'unexpectedly did not throw';
|
||||
} on FlutterError catch (e) {
|
||||
List<String> lines = e.message.split('\n');
|
||||
real_test.expect(lines[0], 'Guarded function conflict. You must use "await" with all Future-returning test APIs.');
|
||||
real_test.expect(lines[1], matches(r'^The guarded method "pump" from class WidgetTester was called from .*test_async_utils.dart on line [0-9]+\.$'));
|
||||
real_test.expect(lines[2], matches(r'^Then, it was called from .*test_async_utils.dart on line [0-9]+\.$'));
|
||||
real_test.expect(lines[3], 'The first method had not yet finished executing at the time that the second method was called. Since both are guarded, and the second was not a nested call inside the first, the first must complete its execution before the second can be called. Typically, this is achieved by putting an "await" statement in front of the call to the first.');
|
||||
real_test.expect(lines[4], '');
|
||||
real_test.expect(lines[5], 'When the first method was called, this was the stack:');
|
||||
real_test.expect(lines.length, greaterThan(6));
|
||||
}
|
||||
await f1;
|
||||
await f2;
|
||||
});
|
||||
|
||||
testWidgets('TestAsyncUtils - expect() catches pending async work', (WidgetTester tester) async {
|
||||
Future<Null> f1;
|
||||
try {
|
||||
f1 = tester.pump();
|
||||
TestAsyncUtils.verifyAllScopesClosed();
|
||||
throw 'unexpectedly did not throw';
|
||||
} on FlutterError catch (e) {
|
||||
List<String> lines = e.message.split('\n');
|
||||
real_test.expect(lines[0], 'Asynchronous call to guarded function leaked. You must use "await" with all Future-returning test APIs.');
|
||||
real_test.expect(lines[1], matches(r'^The guarded method "pump" from class WidgetTester was called from .*test_async_utils.dart on line [0-9]+, but never completed before its parent scope closed\.$'));
|
||||
real_test.expect(lines[2], matches(r'^The guarded method "pump" from class AutomatedTestWidgetsFlutterBinding was called from [^ ]+ on line [0-9]+, but never completed before its parent scope closed\.'));
|
||||
real_test.expect(lines.length, 3);
|
||||
}
|
||||
await f1;
|
||||
});
|
||||
|
||||
testWidgets('TestAsyncUtils - expect() catches pending async work', (WidgetTester tester) async {
|
||||
Future<Null> f1;
|
||||
try {
|
||||
f1 = tester.pump();
|
||||
TestAsyncUtils.verifyAllScopesClosed();
|
||||
throw 'unexpectedly did not throw';
|
||||
} on FlutterError catch (e) {
|
||||
List<String> lines = e.message.split('\n');
|
||||
real_test.expect(lines[0], 'Asynchronous call to guarded function leaked. You must use "await" with all Future-returning test APIs.');
|
||||
real_test.expect(lines[1], matches(r'^The guarded method "pump" from class WidgetTester was called from .*test_async_utils.dart on line [0-9]+, but never completed before its parent scope closed\.$'));
|
||||
real_test.expect(lines[2], matches(r'^The guarded method "pump" from class AutomatedTestWidgetsFlutterBinding was called from [^ ]+ on line [0-9]+, but never completed before its parent scope closed\.'));
|
||||
real_test.expect(lines.length, 3);
|
||||
}
|
||||
await f1;
|
||||
});
|
||||
|
||||
// see also dev/manual_tests/test_data which contains tests run by the flutter_tools tests for 'flutter test'
|
||||
}
|
||||
@@ -4,16 +4,15 @@
|
||||
|
||||
import 'package:flutter/widgets.dart';
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
import 'package:test/test.dart';
|
||||
|
||||
void main() {
|
||||
group('findsOneWidget', () {
|
||||
testWidgets('finds exactly one widget', (WidgetTester tester) {
|
||||
tester.pumpWidget(new Text('foo'));
|
||||
testWidgets('finds exactly one widget', (WidgetTester tester) async {
|
||||
await tester.pumpWidget(new Text('foo'));
|
||||
expect(find.text('foo'), findsOneWidget);
|
||||
});
|
||||
|
||||
testWidgets('fails with a descriptive message', (WidgetTester tester) {
|
||||
testWidgets('fails with a descriptive message', (WidgetTester tester) async {
|
||||
TestFailure failure;
|
||||
try {
|
||||
expect(find.text('foo'), findsOneWidget);
|
||||
@@ -30,12 +29,12 @@ void main() {
|
||||
});
|
||||
|
||||
group('findsNothing', () {
|
||||
testWidgets('finds no widgets', (WidgetTester tester) {
|
||||
testWidgets('finds no widgets', (WidgetTester tester) async {
|
||||
expect(find.text('foo'), findsNothing);
|
||||
});
|
||||
|
||||
testWidgets('fails with a descriptive message', (WidgetTester tester) {
|
||||
tester.pumpWidget(new Text('foo'));
|
||||
testWidgets('fails with a descriptive message', (WidgetTester tester) async {
|
||||
await tester.pumpWidget(new Text('foo'));
|
||||
|
||||
TestFailure failure;
|
||||
try {
|
||||
|
||||
Reference in New Issue
Block a user