Refactor the test framework (#3622)
* Refactor widget test framework
Instead of:
```dart
test("Card Collection smoke test", () {
testWidgets((WidgetTester tester) {
```
...you now say:
```dart
testWidgets("Card Collection smoke test", (WidgetTester tester) {
```
Instead of:
```dart
expect(tester, hasWidget(find.text('hello')));
```
...you now say:
```dart
expect(find.text('hello'), findsOneWidget);
```
Instead of the previous API (exists, widgets, widget, stateOf,
elementOf, etc), you now have the following comprehensive API. All these
are functions that take a Finder, except the all* properties.
* `any()` - true if anything matches, c.f. `Iterable.any`
* `allWidgets` - all the widgets in the tree
* `widget()` - the one and only widget that matches the finder
* `firstWidget()` - the first widget that matches the finder
* `allElements` - all the elements in the tree
* `element()` - the one and only element that matches the finder
* `firstElement()` - the first element that matches the finder
* `allStates` - all the `State`s in the tree
* `state()` - the one and only state that matches the finder
* `firstState()` - the first state that matches the finder
* `allRenderObjects` - all the render objects in the tree
* `renderObject()` - the one and only render object that matches the finder
* `firstRenderObject()` - the first render object that matches the finder
There's also `layers' which returns the list of current layers.
`tap`, `fling`, getCenter, getSize, etc, take Finders, like the APIs
above, and expect there to only be one matching widget.
The finders are:
* `find.text(String text)`
* `find.widgetWithText(Type widgetType, String text)`
* `find.byKey(Key key)`
* `find.byType(Type type)`
* `find.byElementType(Type type)`
* `find.byConfig(Widget config)`
* `find.byWidgetPredicate(WidgetPredicate predicate)`
* `find.byElementPredicate(ElementPredicate predicate)`
The matchers (for `expect`) are:
* `findsNothing`
* `findsWidgets`
* `findsOneWidget`
* `findsNWidgets(n)`
* `isOnStage`
* `isOffStage`
* `isInCard`
* `isNotInCard`
Benchmarks now use benchmarkWidgets instead of testWidgets.
Also, for those of you using mockers, `serviceMocker` now automatically
handles the binding initialization.
This patch also:
* changes how tests are run so that we can more easily swap the logic
out for a "real" mode instead of FakeAsync.
* introduces CachingIterable.
* changes how flutter_driver interacts with the widget tree to use the
aforementioned new API rather than ElementTreeTester, which is gone.
* removes ElementTreeTester.
* changes the semantics of a test for scrollables because we couldn't
convince ourselves that the old semantics made sense; it only worked
before because flushing the microtasks after every event was broken.
* fixes the flushing of microtasks after every event.
* Reindent the tests
* Fix review comments
This commit is contained in:
@@ -5,8 +5,11 @@
|
||||
/// Testing library for flutter, built on top of `package:test`.
|
||||
library flutter_test;
|
||||
|
||||
export 'src/all_elements.dart';
|
||||
export 'src/binding.dart';
|
||||
export 'src/instrumentation.dart';
|
||||
export 'src/controller.dart';
|
||||
export 'src/finders.dart';
|
||||
export 'src/matchers.dart';
|
||||
export 'src/service_mocker.dart';
|
||||
export 'src/test_pointer.dart';
|
||||
export 'src/widget_tester.dart';
|
||||
|
||||
50
packages/flutter_test/lib/src/all_elements.dart
Normal file
50
packages/flutter_test/lib/src/all_elements.dart
Normal file
@@ -0,0 +1,50 @@
|
||||
// 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';
|
||||
|
||||
/// Provides an iterable that efficiently returns all the elements
|
||||
/// rooted at the given element. See [CachingIterable] for details.
|
||||
///
|
||||
/// This method must be called again if the tree changes. You cannot
|
||||
/// call this function once, then reuse the iterable after having
|
||||
/// changed the state of the tree, because the iterable returned by
|
||||
/// this function caches the results and only walks the tree once.
|
||||
///
|
||||
/// The same applies to any iterable obtained indirectly through this
|
||||
/// one, for example the results of calling `where` on this iterable
|
||||
/// are also cached.
|
||||
Iterable<Element> collectAllElementsFrom(Element rootElement) {
|
||||
return new CachingIterable<Element>(new _DepthFirstChildIterator(rootElement));
|
||||
}
|
||||
|
||||
class _DepthFirstChildIterator implements Iterator<Element> {
|
||||
_DepthFirstChildIterator(Element rootElement)
|
||||
: _stack = _reverseChildrenOf(rootElement).toList();
|
||||
|
||||
Element _current;
|
||||
|
||||
final List<Element> _stack;
|
||||
|
||||
@override
|
||||
Element get current => _current;
|
||||
|
||||
@override
|
||||
bool moveNext() {
|
||||
if (_stack.isEmpty)
|
||||
return false;
|
||||
|
||||
_current = _stack.removeLast();
|
||||
// Stack children in reverse order to traverse first branch first
|
||||
_stack.addAll(_reverseChildrenOf(_current));
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
static Iterable<Element> _reverseChildrenOf(Element element) {
|
||||
final List<Element> children = <Element>[];
|
||||
element.visitChildren(children.add);
|
||||
return children.reversed;
|
||||
}
|
||||
}
|
||||
@@ -2,18 +2,19 @@
|
||||
// Use of this source code is governed by a BSD-style license that can be
|
||||
// found in the LICENSE file.
|
||||
|
||||
import 'dart:ui' as ui show window;
|
||||
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';
|
||||
|
||||
import 'instrumentation.dart';
|
||||
|
||||
/// Enumeration of possible phases to reach in pumpWidget.
|
||||
/// 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,
|
||||
@@ -24,25 +25,44 @@ enum EnginePhase {
|
||||
sendSemanticsTree
|
||||
}
|
||||
|
||||
class _SteppedWidgetFlutterBinding extends WidgetsFlutterBinding { // TODO(ianh): refactor so we're not extending a concrete binding
|
||||
_SteppedWidgetFlutterBinding(this.async);
|
||||
|
||||
final FakeAsync async;
|
||||
|
||||
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(FakeAsync async) {
|
||||
static WidgetsBinding ensureInitialized() {
|
||||
if (WidgetsBinding.instance == null)
|
||||
new _SteppedWidgetFlutterBinding(async);
|
||||
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();
|
||||
@@ -50,6 +70,7 @@ class _SteppedWidgetFlutterBinding extends WidgetsFlutterBinding { // TODO(ianh)
|
||||
|
||||
// Cloned from RendererBinding.beginFrame() but with early-exit semantics.
|
||||
void _beginFrame() {
|
||||
assert(inTest);
|
||||
assert(renderView != null);
|
||||
pipelineOwner.flushLayout();
|
||||
if (phase == EnginePhase.layout)
|
||||
@@ -73,45 +94,9 @@ class _SteppedWidgetFlutterBinding extends WidgetsFlutterBinding { // TODO(ianh)
|
||||
|
||||
@override
|
||||
void dispatchEvent(PointerEvent event, HitTestResult result) {
|
||||
assert(inTest);
|
||||
super.dispatchEvent(event, result);
|
||||
async.flushMicrotasks();
|
||||
}
|
||||
}
|
||||
|
||||
/// Helper class for flutter tests providing fake async.
|
||||
///
|
||||
/// This class extends Instrumentation to also abstract away the beginFrame
|
||||
/// and async/clock access to allow writing tests which depend on the passage
|
||||
/// of time without actually moving the clock forward.
|
||||
class ElementTreeTester extends Instrumentation {
|
||||
ElementTreeTester._(FakeAsync async)
|
||||
: async = async,
|
||||
clock = async.getClock(new DateTime.utc(2015, 1, 1)),
|
||||
super(binding: _SteppedWidgetFlutterBinding.ensureInitialized(async)) {
|
||||
timeDilation = 1.0;
|
||||
ui.window.onBeginFrame = null;
|
||||
debugPrint = _synchronousDebugPrint;
|
||||
}
|
||||
|
||||
void _synchronousDebugPrint(String message, { int wrapWidth }) {
|
||||
if (wrapWidth != null) {
|
||||
print(message.split('\n').expand((String line) => debugWordWrap(line, wrapWidth)).join('\n'));
|
||||
} else {
|
||||
print(message);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
final FakeAsync async;
|
||||
final Clock clock;
|
||||
|
||||
/// Calls [runApp] with the given widget, then triggers a frame sequence and
|
||||
/// flushes microtasks, by calling [pump] with the same duration (if any).
|
||||
/// The supplied [EnginePhase] is the final phase reached during the pump pass;
|
||||
/// if not supplied, the whole pass is executed.
|
||||
void pumpWidget(Widget widget, [ Duration duration, EnginePhase phase ]) {
|
||||
runApp(widget);
|
||||
pump(duration, phase);
|
||||
fakeAsync.flushMicrotasks();
|
||||
}
|
||||
|
||||
/// Triggers a frame sequence (build/layout/paint/etc),
|
||||
@@ -122,30 +107,25 @@ class ElementTreeTester extends Instrumentation {
|
||||
///
|
||||
/// 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 phase ]) {
|
||||
void pump([ Duration duration, EnginePhase newPhase = EnginePhase.sendSemanticsTree ]) {
|
||||
assert(inTest);
|
||||
assert(_clock != null);
|
||||
if (duration != null)
|
||||
async.elapse(duration);
|
||||
if (binding is _SteppedWidgetFlutterBinding) {
|
||||
// Some tests call WidgetsFlutterBinding.ensureInitialized() manually, so
|
||||
// we can't actually be sure we have a stepped binding.
|
||||
_SteppedWidgetFlutterBinding steppedBinding = binding;
|
||||
steppedBinding.phase = phase ?? EnginePhase.sendSemanticsTree;
|
||||
} else {
|
||||
// Can't step to a given phase in that case
|
||||
assert(phase == null);
|
||||
}
|
||||
binding.handleBeginFrame(new Duration(
|
||||
milliseconds: clock.now().millisecondsSinceEpoch)
|
||||
);
|
||||
async.flushMicrotasks();
|
||||
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);
|
||||
binding.dispatchLocaleChanged(locale);
|
||||
async.flushMicrotasks();
|
||||
dispatchLocaleChanged(locale);
|
||||
fakeAsync.flushMicrotasks();
|
||||
}
|
||||
|
||||
/// Returns the exception most recently caught by the Flutter framework.
|
||||
@@ -163,51 +143,124 @@ class ElementTreeTester extends Instrumentation {
|
||||
/// It's safe to call this when there's no pending exception; it will return
|
||||
/// null in that case.
|
||||
dynamic takeException() {
|
||||
dynamic result = _pendingException;
|
||||
assert(inTest);
|
||||
dynamic result = _pendingException?.exception;
|
||||
_pendingException = null;
|
||||
return result;
|
||||
}
|
||||
dynamic _pendingException;
|
||||
}
|
||||
FlutterErrorDetails _pendingException;
|
||||
FlutterExceptionHandler _oldHandler;
|
||||
int _exceptionCount;
|
||||
|
||||
void testElementTree(callback(ElementTreeTester tester)) {
|
||||
new FakeAsync().run((FakeAsync async) {
|
||||
FlutterExceptionHandler oldHandler = FlutterError.onError;
|
||||
ElementTreeTester tester = new ElementTreeTester._(async);
|
||||
try {
|
||||
FlutterError.onError = (FlutterErrorDetails details) {
|
||||
if (tester._pendingException != null) {
|
||||
FlutterError.dumpErrorToConsole(tester._pendingException);
|
||||
FlutterError.dumpErrorToConsole(details.exception);
|
||||
tester._pendingException = 'An uncaught exception was thrown.';
|
||||
throw details.exception;
|
||||
/// 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;
|
||||
}
|
||||
tester._pendingException = details;
|
||||
};
|
||||
runApp(new Container(key: new UniqueKey())); // Reset the tree to a known state.
|
||||
callback(tester);
|
||||
runApp(new Container(key: new UniqueKey())); // Unmount any remaining widgets.
|
||||
async.flushMicrotasks();
|
||||
assert(SchedulerBinding.instance.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 async.periodicTimerCount == 0;
|
||||
});
|
||||
assert(() {
|
||||
'A Timer is still running even after the widget tree was disposed.';
|
||||
return async.nonPeriodicTimerCount == 0;
|
||||
});
|
||||
assert(async.microtaskCount == 0); // Shouldn't be possible.
|
||||
if (tester._pendingException != null)
|
||||
throw 'An exception (shown above) was thrown during the test.';
|
||||
} finally {
|
||||
FlutterError.onError = oldHandler;
|
||||
if (tester._pendingException != null) {
|
||||
FlutterError.dumpErrorToConsole(tester._pendingException);
|
||||
tester._pendingException = null;
|
||||
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;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
277
packages/flutter_test/lib/src/controller.dart
Normal file
277
packages/flutter_test/lib/src/controller.dart
Normal file
@@ -0,0 +1,277 @@
|
||||
// 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/gestures.dart';
|
||||
import 'package:flutter/rendering.dart';
|
||||
import 'package:flutter/widgets.dart';
|
||||
|
||||
import 'test_pointer.dart';
|
||||
import 'finders.dart';
|
||||
import 'all_elements.dart';
|
||||
|
||||
/// Class that programmatically interacts with widgets.
|
||||
///
|
||||
/// For a variant of this class suited specifically for unit tests, see [WidgetTester].
|
||||
class WidgetController {
|
||||
WidgetController(this.binding);
|
||||
|
||||
final WidgetsBinding binding;
|
||||
|
||||
// FINDER API
|
||||
|
||||
// TODO(ianh): verify that the return values are of type T and throw
|
||||
// a good message otherwise, in all the generic methods below
|
||||
|
||||
/// Checks if `finder` exists in the tree.
|
||||
bool any(Finder finder) => 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 {
|
||||
return allElements
|
||||
.map((Element element) => element.widget);
|
||||
}
|
||||
|
||||
/// The matching widget in the widget tree.
|
||||
///
|
||||
/// Throws a [StateError] if `finder` is empty or matches more than
|
||||
/// one widget.
|
||||
Widget/*=T*/ widget/*<T extends Widget>*/(Finder finder) {
|
||||
return finder.evaluate().single.widget;
|
||||
}
|
||||
|
||||
/// The first matching widget according to a depth-first pre-order
|
||||
/// traversal of the widget tree.
|
||||
///
|
||||
/// Throws a [StateError] if `finder` is empty.
|
||||
Widget/*=T*/ firstWidget/*<T extends Widget>*/(Finder finder) {
|
||||
return finder.evaluate().first.widget;
|
||||
}
|
||||
|
||||
/// All elements currently in the widget tree (lazy pre-order traversal).
|
||||
///
|
||||
/// The returned iterable is lazy. It does not walk the entire widget tree
|
||||
/// immediately, but rather a chunk at a time as the iteration progresses
|
||||
/// using [Iterator.moveNext].
|
||||
Iterable<Element> get allElements {
|
||||
return collectAllElementsFrom(binding.renderViewElement);
|
||||
}
|
||||
|
||||
/// The matching element in the widget tree.
|
||||
///
|
||||
/// Throws a [StateError] if `finder` is empty or matches more than
|
||||
/// one element.
|
||||
Element/*=T*/ element/*<T extends Element>*/(Finder finder) {
|
||||
return finder.evaluate().single;
|
||||
}
|
||||
|
||||
/// The first matching element according to a depth-first pre-order
|
||||
/// traversal of the widget tree.
|
||||
///
|
||||
/// Throws a [StateError] if `finder` is empty.
|
||||
Element/*=T*/ firstElement/*<T extends Element>*/(Finder finder) {
|
||||
return finder.evaluate().first;
|
||||
}
|
||||
|
||||
/// All states currently in the widget tree (lazy pre-order traversal).
|
||||
///
|
||||
/// The returned iterable is lazy. It does not walk the entire widget tree
|
||||
/// immediately, but rather a chunk at a time as the iteration progresses
|
||||
/// using [Iterator.moveNext].
|
||||
Iterable<State> get allStates {
|
||||
return allElements
|
||||
.where((Element element) => element is StatefulElement)
|
||||
.map((StatefulElement element) => element.state);
|
||||
}
|
||||
|
||||
/// The matching state in the widget tree.
|
||||
///
|
||||
/// 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) {
|
||||
return _stateOf/*<T>*/(finder.evaluate().single, finder);
|
||||
}
|
||||
|
||||
/// The first matching state according to a depth-first pre-order
|
||||
/// traversal of the widget tree.
|
||||
///
|
||||
/// Throws a [StateError] if `finder` is empty or if the first
|
||||
/// matching widget has no state.
|
||||
State/*=T*/ firstState/*<T extends State>*/(Finder finder) {
|
||||
return _stateOf/*<T>*/(finder.evaluate().first, finder);
|
||||
}
|
||||
|
||||
State/*=T*/ _stateOf/*<T extends State>*/(Element element, Finder finder) {
|
||||
if (element is StatefulElement)
|
||||
return element.state;
|
||||
throw new StateError('Widget of type ${element.widget.runtimeType}, with ${finder.description}, is not a StatefulWidget.');
|
||||
}
|
||||
|
||||
/// Render objects of all the widgets currently in the widget tree
|
||||
/// (lazy pre-order traversal).
|
||||
///
|
||||
/// This will almost certainly include many duplicates since the
|
||||
/// render object of a [StatelessWidget] or [StatefulWidget] is the
|
||||
/// render object of its child; only [RenderObjectWidget]s have
|
||||
/// their own render object.
|
||||
Iterable<RenderObject> get allRenderObjects {
|
||||
return allElements
|
||||
.map((Element element) => element.renderObject);
|
||||
}
|
||||
|
||||
/// The render object of the matching widget in the widget tree.
|
||||
///
|
||||
/// 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) {
|
||||
return finder.evaluate().single.renderObject;
|
||||
}
|
||||
|
||||
/// The render object of the first matching widget according to a
|
||||
/// depth-first pre-order traversal of the widget tree.
|
||||
///
|
||||
/// Throws a [StateError] if `finder` is empty.
|
||||
RenderObject/*=T*/ firstRenderObject/*<T extends RenderObject>*/(Finder finder) {
|
||||
return finder.evaluate().first.renderObject;
|
||||
}
|
||||
|
||||
|
||||
/// 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* {
|
||||
yield layer;
|
||||
if (layer is ContainerLayer) {
|
||||
ContainerLayer root = layer;
|
||||
Layer child = root.firstChild;
|
||||
while (child != null) {
|
||||
yield* _walkLayers(child);
|
||||
child = child.nextSibling;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
// INTERACTION
|
||||
|
||||
/// Dispatch a pointer down / pointer up sequence at the center of
|
||||
/// 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);
|
||||
}
|
||||
|
||||
/// Dispatch a pointer down / pointer up sequence at the given
|
||||
/// location.
|
||||
void tapAt(Point location, { int pointer: 1 }) {
|
||||
startGesture(location, pointer: pointer)
|
||||
..up();
|
||||
}
|
||||
|
||||
/// Attempts a fling gesture starting from the center of the given
|
||||
/// widget, moving the given distance, reaching the given velocity.
|
||||
///
|
||||
/// 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);
|
||||
}
|
||||
|
||||
/// 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);
|
||||
}
|
||||
|
||||
/// Attempts to drag the given widget by the given offset, by
|
||||
/// starting a drag in the middle of the widget.
|
||||
///
|
||||
/// 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);
|
||||
}
|
||||
|
||||
/// 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();
|
||||
}
|
||||
|
||||
/// 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);
|
||||
}
|
||||
|
||||
HitTestResult _hitTest(Point location) {
|
||||
final HitTestResult result = new HitTestResult();
|
||||
binding.hitTest(result, location);
|
||||
return result;
|
||||
}
|
||||
|
||||
|
||||
// GEOMETRY
|
||||
|
||||
/// Returns the point at the center of the given widget.
|
||||
Point getCenter(Finder finder) {
|
||||
return _getElementPoint(finder, (Size size) => size.center(Point.origin));
|
||||
}
|
||||
|
||||
/// Returns the point at the top left of the given widget.
|
||||
Point getTopLeft(Finder finder) {
|
||||
return _getElementPoint(finder, (Size size) => Point.origin);
|
||||
}
|
||||
|
||||
/// Returns the point at the top right of the given widget. This
|
||||
/// point is not inside the object's hit test area.
|
||||
Point getTopRight(Finder finder) {
|
||||
return _getElementPoint(finder, (Size size) => size.topRight(Point.origin));
|
||||
}
|
||||
|
||||
/// Returns the point at the bottom left of the given widget. This
|
||||
/// point is not inside the object's hit test area.
|
||||
Point getBottomLeft(Finder finder) {
|
||||
return _getElementPoint(finder, (Size size) => size.bottomLeft(Point.origin));
|
||||
}
|
||||
|
||||
/// Returns the point at the bottom right of the given widget. This
|
||||
/// point is not inside the object's hit test area.
|
||||
Point getBottomRight(Finder finder) {
|
||||
return _getElementPoint(finder, (Size size) => size.bottomRight(Point.origin));
|
||||
}
|
||||
|
||||
Point _getElementPoint(Finder finder, Point sizeToPoint(Size size)) {
|
||||
Element element = finder.evaluate().single;
|
||||
RenderBox box = element.renderObject;
|
||||
assert(box != null);
|
||||
return box.localToGlobal(sizeToPoint(box.size));
|
||||
}
|
||||
|
||||
/// 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) {
|
||||
Element element = finder.evaluate().single;
|
||||
RenderBox box = element.renderObject;
|
||||
assert(box != null);
|
||||
return box.size;
|
||||
}
|
||||
}
|
||||
333
packages/flutter_test/lib/src/finders.dart
Normal file
333
packages/flutter_test/lib/src/finders.dart
Normal file
@@ -0,0 +1,333 @@
|
||||
// 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 'all_elements.dart';
|
||||
|
||||
/// Signature for [CommonFinders.byPredicate].
|
||||
typedef bool WidgetPredicate(Widget widget);
|
||||
|
||||
/// Signature for [CommonFinders.byElement].
|
||||
typedef bool ElementPredicate(Element element);
|
||||
|
||||
/// Some frequently used widget [Finder]s.
|
||||
final CommonFinders find = const CommonFinders._();
|
||||
|
||||
/// Provides lightweight syntax for getting frequently used widget [Finder]s.
|
||||
///
|
||||
/// This class is instantiated once, as [find].
|
||||
class CommonFinders {
|
||||
const CommonFinders._();
|
||||
|
||||
/// Finds [Text] widgets containing string equal to the `text`
|
||||
/// argument.
|
||||
///
|
||||
/// Example:
|
||||
///
|
||||
/// expect(tester, hasWidget(find.text('Back')));
|
||||
Finder text(String text) => new _TextFinder(text);
|
||||
|
||||
/// Looks for widgets that contain a [Text] descendant with `text`
|
||||
/// in it.
|
||||
///
|
||||
/// Example:
|
||||
///
|
||||
/// // Suppose you have a button with text 'Update' in it:
|
||||
/// new Button(
|
||||
/// child: new Text('Update')
|
||||
/// )
|
||||
///
|
||||
/// // You can find and tap on it like this:
|
||||
/// tester.tap(find.widgetWithText(Button, 'Update'));
|
||||
Finder widgetWithText(Type widgetType, String text) {
|
||||
return new _WidgetWithTextFinder(widgetType, text);
|
||||
}
|
||||
|
||||
/// Finds widgets by searching for one with a particular [Key].
|
||||
///
|
||||
/// Example:
|
||||
///
|
||||
/// expect(tester, hasWidget(find.byKey(backKey)));
|
||||
Finder byKey(Key key) => new _KeyFinder(key);
|
||||
|
||||
/// Finds widgets by searching for widgets with a particular type.
|
||||
///
|
||||
/// This does not do subclass tests, so for example
|
||||
/// `byType(StatefulWidget)` will never find anything since that's
|
||||
/// an abstract class.
|
||||
///
|
||||
/// The `type` argument must be a subclass of [Widget].
|
||||
///
|
||||
/// Example:
|
||||
///
|
||||
/// expect(tester, hasWidget(find.byType(IconButton)));
|
||||
Finder byType(Type type) => new _WidgetTypeFinder(type);
|
||||
|
||||
/// Finds widgets by searching for elements with a particular type.
|
||||
///
|
||||
/// This does not do subclass tests, so for example
|
||||
/// `byElementType(VirtualViewportElement)` will never find anything
|
||||
/// since that's an abstract class.
|
||||
///
|
||||
/// The `type` argument must be a subclass of [Element].
|
||||
///
|
||||
/// Example:
|
||||
///
|
||||
/// expect(tester, hasWidget(find.byElementType(SingleChildRenderObjectElement)));
|
||||
Finder byElementType(Type type) => new _ElementTypeFinder(type);
|
||||
|
||||
/// Finds widgets whose current widget is the instance given by the
|
||||
/// argument.
|
||||
///
|
||||
/// Example:
|
||||
///
|
||||
/// // Suppose you have a button created like this:
|
||||
/// Widget myButton = new Button(
|
||||
/// child: new Text('Update')
|
||||
/// );
|
||||
///
|
||||
/// // You can find and tap on it like this:
|
||||
/// tester.tap(find.byConfig(myButton));
|
||||
Finder byConfig(Widget config) => new _ConfigFinder(config);
|
||||
|
||||
/// Finds widgets using a widget predicate.
|
||||
///
|
||||
/// Example:
|
||||
///
|
||||
/// expect(tester, hasWidget(find.byWidgetPredicate(
|
||||
/// (Widget widget) => widget is Tooltip && widget.message == 'Back'
|
||||
/// )));
|
||||
Finder byWidgetPredicate(WidgetPredicate predicate) {
|
||||
return new _WidgetPredicateFinder(predicate);
|
||||
}
|
||||
|
||||
/// Finds widgets using an element predicate.
|
||||
///
|
||||
/// Example:
|
||||
///
|
||||
/// expect(tester, hasWidget(find.byWidgetPredicate(
|
||||
/// // finds elements of type SingleChildRenderObjectElement, including
|
||||
/// // those that are actually subclasses of that type.
|
||||
/// // (contrast with byElementType, which only returns exact matches)
|
||||
/// (Element element) => element is SingleChildRenderObjectElement
|
||||
/// )));
|
||||
Finder byElementPredicate(ElementPredicate predicate) {
|
||||
return new _ElementPredicateFinder(predicate);
|
||||
}
|
||||
}
|
||||
|
||||
/// Searches a widget tree and returns nodes that match a particular
|
||||
/// pattern.
|
||||
abstract class Finder {
|
||||
/// Describes what the finder is looking for. The description should be
|
||||
/// a brief English noun phrase describing the finder's pattern.
|
||||
String get description;
|
||||
|
||||
/// Returns all the elements in the given list that match this
|
||||
/// finder's pattern.
|
||||
///
|
||||
/// When implementing your own Finders that inherit directly from
|
||||
/// [Finder], this is the main method to override. If your finder
|
||||
/// can efficiently be described just in terms of a predicate
|
||||
/// function, consider extending [MatchFinder] instead.
|
||||
Iterable<Element> apply(Iterable<Element> candidates);
|
||||
|
||||
// Right now this is hard-coded to just grab the elements from the binding.
|
||||
//
|
||||
// One could imagine a world where CommonFinders and Finder can be configured
|
||||
// to work from a specific subtree, but we'll implement that when it's needed.
|
||||
static Iterable<Element> get _allElements => collectAllElementsFrom(WidgetsBinding.instance.renderViewElement);
|
||||
|
||||
Iterable<Element> _cachedResult;
|
||||
|
||||
/// Returns the current result. If [precache] was called and returned true, this will
|
||||
/// cheaply return the result that was computed then. Otherwise, it creates a new
|
||||
/// iterable to compute the answer.
|
||||
///
|
||||
/// Calling this clears the cache from [precache].
|
||||
Iterable<Element> evaluate() {
|
||||
final Iterable<Element> result = _cachedResult ?? apply(_allElements);
|
||||
_cachedResult = null;
|
||||
return result;
|
||||
}
|
||||
|
||||
/// Attempts to evaluate the finder. Returns whether any elements in the tree
|
||||
/// matched the finder. If any did, then the result is cached and can be obtained
|
||||
/// from [evaluate].
|
||||
///
|
||||
/// If this returns true, you must call [evaluate] before you call [precache] again.
|
||||
bool precache() {
|
||||
assert(_cachedResult == null);
|
||||
final Iterable<Element> result = apply(_allElements);
|
||||
if (result.isNotEmpty) {
|
||||
_cachedResult = result;
|
||||
return true;
|
||||
}
|
||||
_cachedResult = null;
|
||||
return false;
|
||||
}
|
||||
|
||||
@override
|
||||
String toString() {
|
||||
final List<Element> widgets = evaluate().toList();
|
||||
final int count = widgets.length;
|
||||
if (count == 0)
|
||||
return 'zero widgets with $description';
|
||||
if (count == 1)
|
||||
return 'exactly one widget with $description: ${widgets.single}';
|
||||
if (count < 4)
|
||||
return '$count widgets with $description: $widgets';
|
||||
return '$count widgets with $description: ${widgets[0]}, ${widgets[1]}, ${widgets[2]}, ...';
|
||||
}
|
||||
}
|
||||
|
||||
/// Searches a widget tree and returns nodes that match a particular
|
||||
/// pattern.
|
||||
abstract class MatchFinder extends Finder {
|
||||
/// Returns true if the given element matches the pattern.
|
||||
///
|
||||
/// When implementing your own MatchFinder, this is the main method to override.
|
||||
bool matches(Element candidate);
|
||||
|
||||
@override
|
||||
Iterable<Element> apply(Iterable<Element> candidates) {
|
||||
return candidates.where(matches);
|
||||
}
|
||||
}
|
||||
|
||||
class _TextFinder extends MatchFinder {
|
||||
_TextFinder(this.text);
|
||||
|
||||
final String text;
|
||||
|
||||
@override
|
||||
String get description => 'text "$text"';
|
||||
|
||||
@override
|
||||
bool matches(Element candidate) {
|
||||
if (candidate.widget is! Text)
|
||||
return false;
|
||||
Text textWidget = candidate.widget;
|
||||
return textWidget.data == text;
|
||||
}
|
||||
}
|
||||
|
||||
class _WidgetWithTextFinder extends Finder {
|
||||
_WidgetWithTextFinder(this.widgetType, this.text);
|
||||
|
||||
final Type widgetType;
|
||||
final String text;
|
||||
|
||||
@override
|
||||
String get description => 'type $widgetType with text "$text"';
|
||||
|
||||
@override
|
||||
Iterable<Element> apply(Iterable<Element> candidates) {
|
||||
return candidates
|
||||
.map((Element textElement) {
|
||||
if (textElement.widget is! Text)
|
||||
return null;
|
||||
|
||||
Text textWidget = textElement.widget;
|
||||
if (textWidget.data == text) {
|
||||
try {
|
||||
textElement.visitAncestorElements((Element element) {
|
||||
if (element.widget.runtimeType == widgetType)
|
||||
throw element;
|
||||
return true;
|
||||
});
|
||||
} on Element catch (result) {
|
||||
return result;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
})
|
||||
.where((Element element) => element != null);
|
||||
}
|
||||
}
|
||||
|
||||
class _KeyFinder extends MatchFinder {
|
||||
_KeyFinder(this.key);
|
||||
|
||||
final Key key;
|
||||
|
||||
@override
|
||||
String get description => 'key $key';
|
||||
|
||||
@override
|
||||
bool matches(Element candidate) {
|
||||
return candidate.widget.key == key;
|
||||
}
|
||||
}
|
||||
|
||||
class _WidgetTypeFinder extends MatchFinder {
|
||||
_WidgetTypeFinder(this.widgetType);
|
||||
|
||||
final Type widgetType;
|
||||
|
||||
@override
|
||||
String get description => 'type "$widgetType"';
|
||||
|
||||
@override
|
||||
bool matches(Element candidate) {
|
||||
return candidate.widget.runtimeType == widgetType;
|
||||
}
|
||||
}
|
||||
|
||||
class _ElementTypeFinder extends MatchFinder {
|
||||
_ElementTypeFinder(this.elementType);
|
||||
|
||||
final Type elementType;
|
||||
|
||||
@override
|
||||
String get description => 'type "$elementType"';
|
||||
|
||||
@override
|
||||
bool matches(Element candidate) {
|
||||
return candidate.runtimeType == elementType;
|
||||
}
|
||||
}
|
||||
|
||||
class _ConfigFinder extends MatchFinder {
|
||||
_ConfigFinder(this.config);
|
||||
|
||||
final Widget config;
|
||||
|
||||
@override
|
||||
String get description => 'the given configuration ($config)';
|
||||
|
||||
@override
|
||||
bool matches(Element candidate) {
|
||||
return candidate.widget == config;
|
||||
}
|
||||
}
|
||||
|
||||
class _WidgetPredicateFinder extends MatchFinder {
|
||||
_WidgetPredicateFinder(this.predicate);
|
||||
|
||||
final WidgetPredicate predicate;
|
||||
|
||||
@override
|
||||
String get description => 'widget matching predicate ($predicate)';
|
||||
|
||||
@override
|
||||
bool matches(Element candidate) {
|
||||
return predicate(candidate.widget);
|
||||
}
|
||||
}
|
||||
|
||||
class _ElementPredicateFinder extends MatchFinder {
|
||||
_ElementPredicateFinder(this.predicate);
|
||||
|
||||
final ElementPredicate predicate;
|
||||
|
||||
@override
|
||||
String get description => 'element matching predicate ($predicate)';
|
||||
|
||||
@override
|
||||
bool matches(Element candidate) {
|
||||
return predicate(candidate);
|
||||
}
|
||||
}
|
||||
@@ -1,227 +0,0 @@
|
||||
// Copyright 2015 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/gestures.dart';
|
||||
import 'package:flutter/rendering.dart';
|
||||
import 'package:flutter/widgets.dart';
|
||||
|
||||
import 'test_pointer.dart';
|
||||
|
||||
typedef Point SizeToPointFunction(Size size);
|
||||
|
||||
/// Helper class for flutter tests providing event dispatch.
|
||||
///
|
||||
/// This class provides hooks for accessing the rendering tree and dispatching
|
||||
/// fake tap/drag/etc. events.
|
||||
class Instrumentation {
|
||||
Instrumentation({ WidgetsBinding binding })
|
||||
: this.binding = binding ?? WidgetsFlutterBinding.ensureInitialized();
|
||||
|
||||
final WidgetsBinding binding;
|
||||
|
||||
/// Returns a list of all the [Layer] objects in the rendering.
|
||||
List<Layer> get layers => _layers(binding.renderView.layer);
|
||||
// TODO(ianh): This should not be O(N) hidden behind a getter!
|
||||
List<Layer> _layers(Layer layer) {
|
||||
List<Layer> result = <Layer>[layer];
|
||||
if (layer is ContainerLayer) {
|
||||
ContainerLayer root = layer;
|
||||
Layer child = root.firstChild;
|
||||
while (child != null) {
|
||||
result.addAll(_layers(child));
|
||||
child = child.nextSibling;
|
||||
}
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
/// Walks all the elements in the tree, in depth-first pre-order,
|
||||
/// calling the given function for each one.
|
||||
void walkElements(ElementVisitor visitor) {
|
||||
void walk(Element element) {
|
||||
visitor(element);
|
||||
element.visitChildren(walk);
|
||||
}
|
||||
binding.renderViewElement.visitChildren(walk);
|
||||
}
|
||||
|
||||
/// Returns the first element that for which the given predicate
|
||||
/// function returns true, if any, or null if the predicate function
|
||||
/// never returns true.
|
||||
Element findElement(bool predicate(Element element)) {
|
||||
try {
|
||||
walkElements((Element element) {
|
||||
if (predicate(element))
|
||||
throw element;
|
||||
});
|
||||
} on Element catch (e) {
|
||||
return e;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/// Returns the first element that corresponds to a widget with the
|
||||
/// given [Key], or null if there is no such element.
|
||||
Element findElementByKey(Key key) {
|
||||
return findElement((Element element) => element.widget.key == key);
|
||||
}
|
||||
|
||||
/// Returns the first element that corresponds to a [Text] widget
|
||||
/// whose data is the given string, or null if there is no such
|
||||
/// element.
|
||||
Element findText(String text) {
|
||||
return findElement((Element element) {
|
||||
if (element.widget is! Text)
|
||||
return false;
|
||||
Text textWidget = element.widget;
|
||||
return textWidget.data == text;
|
||||
});
|
||||
}
|
||||
|
||||
/// Returns the first [Widget] of the given [runtimeType], if any. Returns
|
||||
/// null if there is no matching widget.
|
||||
Widget findWidgetOfType(Type type) {
|
||||
Element element = findElement((Element element) {
|
||||
return element.widget.runtimeType == type;
|
||||
});
|
||||
return element?.widget;
|
||||
}
|
||||
|
||||
/// Returns the [State] object of the first element whose state has
|
||||
/// the given [runtimeType], if any. Returns null if there is no
|
||||
/// matching element.
|
||||
State findStateOfType(Type type) {
|
||||
StatefulElement element = findElement((Element element) {
|
||||
return element is StatefulElement && element.state.runtimeType == type;
|
||||
});
|
||||
return element?.state;
|
||||
}
|
||||
|
||||
/// Returns the [State] object of the first element whose
|
||||
/// configuration is the given widget, if any. Returns null if the
|
||||
/// given configuration is not that of a stateful widget or if there
|
||||
/// is no matching element.
|
||||
State findStateByConfig(Widget config) {
|
||||
StatefulElement element = findElement((Element element) {
|
||||
return element is StatefulElement && element.state.config == config;
|
||||
});
|
||||
return element?.state;
|
||||
}
|
||||
|
||||
/// Returns the point at the center of the given element.
|
||||
Point getCenter(Element element) {
|
||||
return _getElementPoint(element, (Size size) => size.center(Point.origin));
|
||||
}
|
||||
|
||||
/// Returns the point at the top left of the given element.
|
||||
Point getTopLeft(Element element) {
|
||||
return _getElementPoint(element, (_) => Point.origin);
|
||||
}
|
||||
|
||||
/// Returns the point at the top right of the given element. This
|
||||
/// point is not inside the object's hit test area.
|
||||
Point getTopRight(Element element) {
|
||||
return _getElementPoint(element, (Size size) => size.topRight(Point.origin));
|
||||
}
|
||||
|
||||
/// Returns the point at the bottom left of the given element. This
|
||||
/// point is not inside the object's hit test area.
|
||||
Point getBottomLeft(Element element) {
|
||||
return _getElementPoint(element, (Size size) => size.bottomLeft(Point.origin));
|
||||
}
|
||||
|
||||
/// Returns the point at the bottom right of the given element. This
|
||||
/// point is not inside the object's hit test area.
|
||||
Point getBottomRight(Element element) {
|
||||
return _getElementPoint(element, (Size size) => size.bottomRight(Point.origin));
|
||||
}
|
||||
|
||||
/// Returns the size of the given element. This is only valid once
|
||||
/// the element's render object has been laid out at least once.
|
||||
Size getSize(Element element) {
|
||||
assert(element != null);
|
||||
RenderBox box = element.renderObject;
|
||||
assert(box != null);
|
||||
return box.size;
|
||||
}
|
||||
|
||||
Point _getElementPoint(Element element, SizeToPointFunction sizeToPoint) {
|
||||
assert(element != null);
|
||||
RenderBox box = element.renderObject;
|
||||
assert(box != null);
|
||||
return box.localToGlobal(sizeToPoint(box.size));
|
||||
}
|
||||
|
||||
/// Dispatch a pointer down / pointer up sequence at the center of
|
||||
/// the given element, assuming it is exposed. If the center of the
|
||||
/// element is not exposed, this might send events to another
|
||||
/// object.
|
||||
void tap(Element element, { int pointer: 1 }) {
|
||||
tapAt(getCenter(element), 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();
|
||||
}
|
||||
|
||||
/// Attempts a fling gesture starting from the center of the given
|
||||
/// element, moving the given distance, reaching the given velocity.
|
||||
///
|
||||
/// If the middle of the element is not exposed, this might send
|
||||
/// events to another object.
|
||||
void fling(Element element, Offset offset, double velocity, { int pointer: 1 }) {
|
||||
flingFrom(getCenter(element), 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);
|
||||
}
|
||||
|
||||
/// Attempts to drag the given element by the given offset, by
|
||||
/// starting a drag in the middle of the element.
|
||||
///
|
||||
/// If the middle of the element is not exposed, this might send
|
||||
/// events to another object.
|
||||
void scroll(Element element, Offset offset, { int pointer: 1 }) {
|
||||
scrollAt(getCenter(element), 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();
|
||||
}
|
||||
|
||||
/// 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);
|
||||
}
|
||||
|
||||
HitTestResult _hitTest(Point location) {
|
||||
HitTestResult result = new HitTestResult();
|
||||
binding.hitTest(result, location);
|
||||
return result;
|
||||
}
|
||||
}
|
||||
184
packages/flutter_test/lib/src/matchers.dart
Normal file
184
packages/flutter_test/lib/src/matchers.dart
Normal file
@@ -0,0 +1,184 @@
|
||||
// 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/material.dart';
|
||||
import 'package:test/test.dart';
|
||||
|
||||
import 'finders.dart';
|
||||
|
||||
/// Asserts that the [Finder] matches no widgets in the widget tree.
|
||||
///
|
||||
/// Example:
|
||||
///
|
||||
/// expect(find.text('Save'), findsNothing);
|
||||
const Matcher findsNothing = const _FindsWidgetMatcher(null, 0);
|
||||
|
||||
/// Asserts that the [Finder] locates at least one widget in the widget tree.
|
||||
///
|
||||
/// Example:
|
||||
///
|
||||
/// expect(find.text('Save'), findsWidgets);
|
||||
const Matcher findsWidgets = const _FindsWidgetMatcher(1, null);
|
||||
|
||||
/// Asserts that the [Finder] locates at exactly one widget in the widget tree.
|
||||
///
|
||||
/// Example:
|
||||
///
|
||||
/// expect(find.text('Save'), findsOneWidget);
|
||||
const Matcher findsOneWidget = const _FindsWidgetMatcher(1, 1);
|
||||
|
||||
/// Asserts that the [Finder] locates the specified number of widgets in the widget tree.
|
||||
///
|
||||
/// Example:
|
||||
///
|
||||
/// expect(find.text('Save'), findsNWidgets(2));
|
||||
Matcher findsNWidgets(int n) => new _FindsWidgetMatcher(n, n);
|
||||
|
||||
/// Asserts that the [Finder] locates the a single widget that has at
|
||||
/// least one [OffStage] widget ancestor.
|
||||
const Matcher isOffStage = const _IsOffStage();
|
||||
|
||||
/// Asserts that the [Finder] locates the a single widget that has no
|
||||
/// [OffStage] widget ancestors.
|
||||
const Matcher isOnStage = const _IsOnStage();
|
||||
|
||||
/// Asserts that the [Finder] locates the a single widget that has at
|
||||
/// least one [Card] widget ancestor.
|
||||
const Matcher isInCard = const _IsInCard();
|
||||
|
||||
/// Asserts that the [Finder] locates the a single widget that has no
|
||||
/// [Card] widget ancestors.
|
||||
const Matcher isNotInCard = const _IsNotInCard();
|
||||
|
||||
class _FindsWidgetMatcher extends Matcher {
|
||||
const _FindsWidgetMatcher(this.min, this.max);
|
||||
|
||||
final int min;
|
||||
final int max;
|
||||
|
||||
@override
|
||||
bool matches(Finder finder, Map<dynamic, dynamic> matchState) {
|
||||
assert(min != null || max != null);
|
||||
matchState[Finder] = finder;
|
||||
if (min != null) {
|
||||
int count = 0;
|
||||
Iterator<Element> iterator = finder.evaluate().iterator;
|
||||
while (count < min && iterator.moveNext())
|
||||
count += 1;
|
||||
if (count < min)
|
||||
return false;
|
||||
}
|
||||
if (max != null) {
|
||||
int count = 0;
|
||||
Iterator<Element> iterator = finder.evaluate().iterator;
|
||||
while (count <= max && iterator.moveNext())
|
||||
count += 1;
|
||||
if (count > max)
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
@override
|
||||
Description describe(Description description) {
|
||||
assert(min != null || max != null);
|
||||
if (min == max) {
|
||||
if (min == 1)
|
||||
return description.add('exactly one matching node in the widget tree');
|
||||
return description.add('exactly $min matching nodes in the widget tree');
|
||||
}
|
||||
if (min == null) {
|
||||
if (max == 0)
|
||||
return description.add('no matching nodes in the widget tree');
|
||||
if (max == 1)
|
||||
return description.add('at most one matching node in the widget tree');
|
||||
return description.add('at most $max matching nodes in the widget tree');
|
||||
}
|
||||
if (max == null) {
|
||||
if (min == 1)
|
||||
return description.add('at least one matching node in the widget tree');
|
||||
return description.add('at least $min matching nodes in the widget tree');
|
||||
}
|
||||
return description.add('between $min and $max matching nodes in the widget tree (inclusive)');
|
||||
}
|
||||
|
||||
@override
|
||||
Description describeMismatch(
|
||||
dynamic item,
|
||||
Description mismatchDescription,
|
||||
Map<dynamic, dynamic> matchState,
|
||||
bool verbose
|
||||
) {
|
||||
Finder finder = matchState[Finder];
|
||||
int count = finder.evaluate().length;
|
||||
if (count == 0) {
|
||||
assert(min != null && min > 0);
|
||||
if (min == 1 && max == 1)
|
||||
return mismatchDescription.add('means none were found but one was expected');
|
||||
return mismatchDescription.add('means none were found but some were expected');
|
||||
}
|
||||
if (max == 0) {
|
||||
if (count == 1)
|
||||
return mismatchDescription.add('means one was found but none were expected');
|
||||
return mismatchDescription.add('means some were found but none were expected');
|
||||
}
|
||||
if (min != null && count < min)
|
||||
return mismatchDescription.add('is not enough');
|
||||
assert(max != null && count > min);
|
||||
return mismatchDescription.add('is too many');
|
||||
}
|
||||
}
|
||||
|
||||
bool _hasAncestorOfType(Finder finder, Type targetType) {
|
||||
expect(finder, findsOneWidget);
|
||||
bool result = false;
|
||||
finder.evaluate().single.visitAncestorElements((Element ancestor) {
|
||||
if (ancestor.widget.runtimeType == targetType) {
|
||||
result = true;
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
});
|
||||
return result;
|
||||
}
|
||||
|
||||
class _IsOffStage extends Matcher {
|
||||
const _IsOffStage();
|
||||
|
||||
@override
|
||||
bool matches(Finder finder, Map<dynamic, dynamic> matchState) => _hasAncestorOfType(finder, OffStage);
|
||||
|
||||
@override
|
||||
Description describe(Description description) => description.add('offstage');
|
||||
}
|
||||
|
||||
class _IsOnStage extends Matcher {
|
||||
const _IsOnStage();
|
||||
|
||||
@override
|
||||
bool matches(Finder finder, Map<dynamic, dynamic> matchState) => !_hasAncestorOfType(finder, OffStage);
|
||||
|
||||
@override
|
||||
Description describe(Description description) => description.add('onstage');
|
||||
}
|
||||
|
||||
class _IsInCard extends Matcher {
|
||||
const _IsInCard();
|
||||
|
||||
@override
|
||||
bool matches(Finder finder, Map<dynamic, dynamic> matchState) => _hasAncestorOfType(finder, Card);
|
||||
|
||||
@override
|
||||
Description describe(Description description) => description.add('in card');
|
||||
}
|
||||
|
||||
class _IsNotInCard extends Matcher {
|
||||
const _IsNotInCard();
|
||||
|
||||
@override
|
||||
bool matches(Finder finder, Map<dynamic, dynamic> matchState) => !_hasAncestorOfType(finder, Card);
|
||||
|
||||
@override
|
||||
Description describe(Description description) => description.add('not in card');
|
||||
}
|
||||
@@ -5,10 +5,13 @@
|
||||
import 'package:flutter/services.dart';
|
||||
import 'package:mojo/bindings.dart' as bindings;
|
||||
|
||||
// Tests can use ServiceMocker to register replacement implementations
|
||||
// of Mojo services.
|
||||
import 'binding.dart';
|
||||
|
||||
/// Tests can use [ServiceMocker] to register replacement implementations
|
||||
/// of Mojo services.
|
||||
class ServiceMocker {
|
||||
ServiceMocker._() {
|
||||
TestWidgetsFlutterBinding.ensureInitialized();
|
||||
shell.overrideConnectToService = _connectToService;
|
||||
}
|
||||
|
||||
@@ -27,12 +30,14 @@ class ServiceMocker {
|
||||
}
|
||||
}
|
||||
|
||||
// Provide a mock implementation for a Mojo interface.
|
||||
// Make sure you initialise the binding before calling this.
|
||||
// For example, by calling `WidgetsFlutterBinding.ensureInitialized();`
|
||||
/// Provide a mock implementation for a Mojo interface.
|
||||
void registerMockService(String interfaceName, Object mock) {
|
||||
_interfaceMocks[interfaceName] = mock;
|
||||
}
|
||||
}
|
||||
|
||||
/// Instance of the utility class for providing mocks for tests.
|
||||
///
|
||||
/// The first time this variable is accessed, it will initialize the
|
||||
/// [TestWidgetsFlutterBinding] if necessary.
|
||||
final ServiceMocker serviceMocker = new ServiceMocker._();
|
||||
|
||||
@@ -3,7 +3,6 @@
|
||||
// found in the LICENSE file.
|
||||
|
||||
import 'package:flutter/gestures.dart';
|
||||
import 'package:quiver/testing/async.dart';
|
||||
|
||||
export 'dart:ui' show Point;
|
||||
|
||||
@@ -140,12 +139,11 @@ class TestGesture {
|
||||
return new TestGesture._(dispatcher, result, testPointer);
|
||||
}
|
||||
|
||||
TestGesture._(this._dispatcher, this._result, this._pointer);
|
||||
const TestGesture._(this._dispatcher, this._result, this._pointer);
|
||||
|
||||
final HitTestDispatcher _dispatcher;
|
||||
final HitTestResult _result;
|
||||
final TestPointer _pointer;
|
||||
FakeAsync async;
|
||||
|
||||
/// Send a move event moving the pointer by the given offset.
|
||||
void moveBy(Offset offset) {
|
||||
@@ -157,7 +155,6 @@ class TestGesture {
|
||||
void moveTo(Point location) {
|
||||
assert(_pointer._isDown);
|
||||
_dispatcher.dispatchEvent(_pointer.move(location), _result);
|
||||
async?.flushMicrotasks();
|
||||
}
|
||||
|
||||
/// End the gesture by releasing the pointer.
|
||||
@@ -167,7 +164,6 @@ class TestGesture {
|
||||
assert(_pointer._isDown);
|
||||
_dispatcher.dispatchEvent(_pointer.up(), _result);
|
||||
assert(!_pointer._isDown);
|
||||
async?.flushMicrotasks();
|
||||
}
|
||||
|
||||
/// End the gesture by canceling the pointer (as would happen if the
|
||||
@@ -179,6 +175,5 @@ class TestGesture {
|
||||
assert(_pointer._isDown);
|
||||
_dispatcher.dispatchEvent(_pointer.cancel(), _result);
|
||||
assert(!_pointer._isDown);
|
||||
async?.flushMicrotasks();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2,596 +2,129 @@
|
||||
// Use of this source code is governed by a BSD-style license that can be
|
||||
// found in the LICENSE file.
|
||||
|
||||
import 'dart:collection';
|
||||
import 'dart:async';
|
||||
|
||||
import 'package:flutter/gestures.dart';
|
||||
import 'package:flutter/rendering.dart';
|
||||
import 'package:flutter/widgets.dart';
|
||||
import 'package:quiver/testing/async.dart';
|
||||
import 'package:test/test.dart';
|
||||
|
||||
import 'binding.dart';
|
||||
import 'test_pointer.dart';
|
||||
import 'finders.dart';
|
||||
import 'controller.dart';
|
||||
|
||||
/// Signature for [CommonFinders.byPredicate].
|
||||
typedef bool WidgetPredicate(Widget widget);
|
||||
|
||||
/// Signature for [CommonFinders.byElement].
|
||||
typedef bool ElementPredicate(Element element);
|
||||
/// Signature for callback to [testWidgets] and [benchmarkWidgets].
|
||||
typedef Future<Null> WidgetTesterCallback(WidgetTester widgetTester);
|
||||
|
||||
/// Runs the [callback] inside the Flutter test environment.
|
||||
///
|
||||
/// Use this function for testing custom [StatelessWidget]s and
|
||||
/// [StatefulWidget]s.
|
||||
///
|
||||
/// The callback can be asynchronous (using `async`/`await` or
|
||||
/// using explicit [Future]s).
|
||||
///
|
||||
/// This function uses the [test] function in the test package to
|
||||
/// register the given callback as a test. The callback, when run,
|
||||
/// will be given a new instance of [WidgetTester]. The [find] object
|
||||
/// provides convenient widget [Finder]s for use with the
|
||||
/// [WidgetTester].
|
||||
///
|
||||
/// Example:
|
||||
///
|
||||
/// test('MyWidget', () {
|
||||
/// testWidgets((WidgetTester tester) {
|
||||
/// tester.pumpWidget(new MyWidget());
|
||||
/// tester.tap(find.text('Save'));
|
||||
/// expect(tester, hasWidget(find.text('Success')));
|
||||
/// });
|
||||
/// testWidgets('MyWidget', (WidgetTester tester) {
|
||||
/// tester.pumpWidget(new MyWidget());
|
||||
/// tester.tap(find.text('Save'));
|
||||
/// expect(tester, hasWidget(find.text('Success')));
|
||||
/// });
|
||||
void testWidgets(void callback(WidgetTester widgetTester)) {
|
||||
testElementTree((ElementTreeTester elementTreeTester) {
|
||||
callback(new WidgetTester._(elementTreeTester));
|
||||
});
|
||||
void testWidgets(String description, WidgetTesterCallback callback, {
|
||||
Timeout timeout: const Timeout(const Duration(seconds: 5))
|
||||
}) {
|
||||
TestWidgetsFlutterBinding binding = TestWidgetsFlutterBinding.ensureInitialized();
|
||||
WidgetTester tester = new WidgetTester._(binding);
|
||||
group('-', () {
|
||||
setUp(binding.preTest);
|
||||
test(description, () => binding.runTest(() => callback(tester)));
|
||||
tearDown(binding.postTest);
|
||||
}, timeout: timeout);
|
||||
}
|
||||
|
||||
/// Runs the [callback] inside the Flutter benchmark environment.
|
||||
///
|
||||
/// Use this function for benchmarking custom [StatelessWidget]s and
|
||||
/// [StatefulWidget]s when you want to be able to use features from
|
||||
/// [TestWidgetsFlutterBinding]. The callback, when run, will be given
|
||||
/// a new instance of [WidgetTester]. The [find] object provides
|
||||
/// convenient widget [Finder]s for use with the [WidgetTester].
|
||||
///
|
||||
/// The callback can be asynchronous (using `async`/`await` or using
|
||||
/// explicit [Future]s). If it is, then [benchmarkWidgets] will return
|
||||
/// a [Future] that completes when the callback's does. Otherwise, it
|
||||
/// will return a widget that is always complete.
|
||||
///
|
||||
/// Benchmarks must not be run in checked mode. To avoid this, this
|
||||
/// function will assert if it is run in checked mode.
|
||||
///
|
||||
/// Example:
|
||||
///
|
||||
/// main() async {
|
||||
/// await benchmarkWidgets((WidgetTester tester) {
|
||||
/// tester.pumpWidget(new MyWidget());
|
||||
/// final Stopwatch timer = new Stopwatch()..start();
|
||||
/// for (int index = 0; index < 10000; index += 1) {
|
||||
/// tester.tap(find.text('Tap me'));
|
||||
/// tester.pump();
|
||||
/// }
|
||||
/// timer.stop();
|
||||
/// print('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();
|
||||
WidgetTester tester = new WidgetTester._(binding);
|
||||
return binding.runTest(() => callback(tester)) ?? new Future<Null>.value();
|
||||
}
|
||||
|
||||
/// Class that programmatically interacts with widgets and the test environment.
|
||||
class WidgetTester {
|
||||
WidgetTester._(this.elementTreeTester);
|
||||
class WidgetTester extends WidgetController {
|
||||
WidgetTester._(TestWidgetsFlutterBinding binding) : super(binding);
|
||||
|
||||
/// Exposes the [Element] tree created from widgets.
|
||||
final ElementTreeTester elementTreeTester;
|
||||
|
||||
/// The binding instance that the widget tester is using when it
|
||||
/// needs a binding (e.g. for event dispatch).
|
||||
WidgetsBinding get binding => elementTreeTester.binding;
|
||||
/// The binding instance used by the testing framework.
|
||||
@override
|
||||
TestWidgetsFlutterBinding get binding => super.binding;
|
||||
|
||||
/// Renders the UI from the given [widget].
|
||||
///
|
||||
/// See [ElementTreeTester.pumpWidget] for details.
|
||||
/// Calls [runApp] with the given widget, then triggers a frame sequence and
|
||||
/// flushes microtasks, by calling [pump] with the same duration (if any).
|
||||
/// The supplied [EnginePhase] is the final phase reached during the pump pass;
|
||||
/// if not supplied, the whole pass is executed.
|
||||
void pumpWidget(Widget widget, [ Duration duration, EnginePhase phase ]) {
|
||||
elementTreeTester.pumpWidget(widget, duration, phase);
|
||||
runApp(widget);
|
||||
binding.pump(duration, phase);
|
||||
}
|
||||
|
||||
/// Triggers a sequence of frames for [duration] amount of time.
|
||||
///
|
||||
/// See [ElementTreeTester.pump] for details.
|
||||
/// This is a convenience function that just calls
|
||||
/// [TestWidgetsFlutterBinding.pump].
|
||||
void pump([ Duration duration, EnginePhase phase ]) {
|
||||
elementTreeTester.pump(duration, phase);
|
||||
}
|
||||
|
||||
/// Changes the current locale.
|
||||
///
|
||||
/// See [ElementTreeTester.setLocale] for details.
|
||||
void setLocale(String languageCode, String countryCode) {
|
||||
elementTreeTester.setLocale(languageCode, countryCode);
|
||||
}
|
||||
|
||||
/// Sends an [event] at [result] location.
|
||||
void dispatchEvent(PointerEvent event, HitTestResult result) {
|
||||
binding.dispatchEvent(event, result);
|
||||
binding.pump(duration, phase);
|
||||
}
|
||||
|
||||
/// Returns the exception most recently caught by the Flutter framework.
|
||||
///
|
||||
/// See [ElementTreeTester.takeException] for details.
|
||||
/// See [TestWidgetsFlutterBinding.takeException] for details.
|
||||
dynamic takeException() {
|
||||
return elementTreeTester.takeException();
|
||||
return binding.takeException();
|
||||
}
|
||||
|
||||
/// Returns the fake implmentation of the event loop used by the test
|
||||
/// environment.
|
||||
///
|
||||
/// Use it to travel into the future without actually waiting, control the
|
||||
/// flushing of microtasks and timers.
|
||||
FakeAsync get async => elementTreeTester.async;
|
||||
|
||||
/// 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() {
|
||||
elementTreeTester.async.flushMicrotasks();
|
||||
}
|
||||
|
||||
/// Checks if the element identified by [finder] exists in the tree.
|
||||
bool exists(Finder finder) => finder.find(this).isNotEmpty;
|
||||
|
||||
/// All widgets currently live on the UI returned in a depth-first traversal
|
||||
/// order.
|
||||
Iterable<Widget> get widgets {
|
||||
return this.allElements.map((Element element) => element.widget);
|
||||
}
|
||||
|
||||
/// Finds the first widget, searching in the depth-first traversal order.
|
||||
Widget widget(Finder finder) {
|
||||
return finder.findFirst(this).widget;
|
||||
}
|
||||
|
||||
/// Finds the first state object, searching in the depth-first traversal order.
|
||||
State/*=T*/ stateOf/*<T extends State>*/(Finder finder) {
|
||||
Element element = finder.findFirst(this);
|
||||
Widget widget = element.widget;
|
||||
|
||||
if (widget is StatefulWidget) {
|
||||
StatefulElement statefulElement = element;
|
||||
return statefulElement.state;
|
||||
}
|
||||
|
||||
throw new ElementNotFoundError(
|
||||
'Widget of type ${widget.runtimeType} found by ${finder.description} does not correspond to a StatefulWidget'
|
||||
);
|
||||
}
|
||||
|
||||
/// Finds the [Element] corresponding to the first widget found by [finder],
|
||||
/// searching in the depth-first traversal order.
|
||||
Element elementOf(Finder finder) => finder.findFirst(this);
|
||||
|
||||
/// Finds the [RenderObject] corresponding to the first widget found by
|
||||
/// [finder], searching in the depth-first traversal order.
|
||||
RenderObject renderObjectOf(Finder finder) => finder.findFirst(this).findRenderObject();
|
||||
|
||||
/// Emulates a tapping action at the center of the widget found by [finder].
|
||||
void tap(Finder finder, { int pointer: 1 }) {
|
||||
tapAt(getCenter(finder), pointer: pointer);
|
||||
}
|
||||
|
||||
/// Emulates a tapping action at the given [location].
|
||||
///
|
||||
/// See [ElementTreeTester.tapAt] for details.
|
||||
void tapAt(Point location, { int pointer: 1 }) {
|
||||
startGesture(location, pointer: pointer)
|
||||
..up();
|
||||
}
|
||||
|
||||
/// Scrolls by dragging the center of a widget found by [finder] by [offset].
|
||||
void scroll(Finder finder, Offset offset, { int pointer: 1 }) {
|
||||
scrollAt(getCenter(finder), offset, pointer: pointer);
|
||||
}
|
||||
|
||||
/// Scrolls by dragging the screen at [startLocation] by [offset].
|
||||
///
|
||||
/// See [ElementTreeTester.scrollAt] for details.
|
||||
void scrollAt(Point startLocation, Offset offset, { int pointer: 1 }) {
|
||||
startGesture(startLocation, pointer: pointer)
|
||||
..moveBy(offset)
|
||||
..up();
|
||||
}
|
||||
|
||||
/// Attempts a fling gesture starting at the center of a widget found by
|
||||
/// [finder].
|
||||
///
|
||||
/// See also [flingFrom].
|
||||
void fling(Finder finder, Offset offset, double velocity, { int pointer: 1 }) {
|
||||
flingFrom(getCenter(finder), offset, velocity, pointer: pointer);
|
||||
}
|
||||
|
||||
/// Attempts a fling gesture starting at [startLocation], moving by [offset]
|
||||
/// with the given [velocity].
|
||||
///
|
||||
/// See [ElementTreeTester.flingFrom] for details.
|
||||
void flingFrom(Point startLocation, Offset offset, double velocity, { int pointer: 1 }) {
|
||||
elementTreeTester.flingFrom(startLocation, offset, velocity, pointer: pointer);
|
||||
flushMicrotasks();
|
||||
}
|
||||
|
||||
/// 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 }) {
|
||||
TestGesture gesture = elementTreeTester.startGesture(downLocation, pointer: pointer)..async = async;
|
||||
flushMicrotasks();
|
||||
return gesture;
|
||||
}
|
||||
|
||||
/// Returns the size of the element corresponding to the widget located by
|
||||
/// [finder].
|
||||
///
|
||||
/// This is only valid once the element's render object has been laid out at
|
||||
/// least once.
|
||||
Size getSize(Finder finder) {
|
||||
assert(finder != null);
|
||||
Element element = finder.findFirst(this);
|
||||
return elementTreeTester.getSize(element);
|
||||
}
|
||||
|
||||
/// Returns the point at the center of the widget found by [finder].
|
||||
Point getCenter(Finder finder) {
|
||||
Element element = finder.findFirst(this);
|
||||
return elementTreeTester.getCenter(element);
|
||||
}
|
||||
|
||||
/// Returns the point at the top left of the given element.
|
||||
Point getTopLeft(Finder finder) {
|
||||
Element element = finder.findFirst(this);
|
||||
return elementTreeTester.getTopLeft(element);
|
||||
}
|
||||
|
||||
/// Returns the point at the top right of the given element. This
|
||||
/// point is not inside the object's hit test area.
|
||||
Point getTopRight(Finder finder) {
|
||||
Element element = finder.findFirst(this);
|
||||
return elementTreeTester.getTopRight(element);
|
||||
}
|
||||
|
||||
/// Returns the point at the bottom left of the given element. This
|
||||
/// point is not inside the object's hit test area.
|
||||
Point getBottomLeft(Finder finder) {
|
||||
Element element = finder.findFirst(this);
|
||||
return elementTreeTester.getBottomLeft(element);
|
||||
}
|
||||
|
||||
/// Returns the point at the bottom right of the given element. This
|
||||
/// point is not inside the object's hit test area.
|
||||
Point getBottomRight(Finder finder) {
|
||||
Element element = finder.findFirst(this);
|
||||
return elementTreeTester.getBottomRight(element);
|
||||
}
|
||||
|
||||
/// Returns all elements ordered in a depth-first traversal fashion.
|
||||
///
|
||||
/// The returned iterable is lazy. It does not walk the entire element tree
|
||||
/// immediately, but rather a chunk at a time as the iteration progresses
|
||||
/// using [Iterator.moveNext].
|
||||
Iterable<Element> get allElements {
|
||||
return new _DepthFirstChildIterable(binding.renderViewElement);
|
||||
}
|
||||
}
|
||||
|
||||
class _DepthFirstChildIterable extends IterableBase<Element> {
|
||||
_DepthFirstChildIterable(this.rootElement);
|
||||
|
||||
Element rootElement;
|
||||
|
||||
@override
|
||||
Iterator<Element> get iterator => new _DepthFirstChildIterator(rootElement);
|
||||
}
|
||||
|
||||
class _DepthFirstChildIterator implements Iterator<Element> {
|
||||
_DepthFirstChildIterator(Element rootElement)
|
||||
: _stack = _reverseChildrenOf(rootElement).toList();
|
||||
|
||||
Element _current;
|
||||
|
||||
final List<Element> _stack;
|
||||
|
||||
@override
|
||||
Element get current => _current;
|
||||
|
||||
@override
|
||||
bool moveNext() {
|
||||
if (_stack.isEmpty)
|
||||
return false;
|
||||
|
||||
_current = _stack.removeLast();
|
||||
// Stack children in reverse order to traverse first branch first
|
||||
_stack.addAll(_reverseChildrenOf(_current));
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
static Iterable<Element> _reverseChildrenOf(Element element) {
|
||||
final List<Element> children = <Element>[];
|
||||
element.visitChildren(children.add);
|
||||
return children.reversed;
|
||||
}
|
||||
}
|
||||
|
||||
/// A convenient accessor to frequently used finders.
|
||||
///
|
||||
/// Examples:
|
||||
///
|
||||
/// tester.tap(find.text('Save'));
|
||||
/// tester.widget(find.byType(MyWidget));
|
||||
/// tester.stateOf(find.byConfig(config));
|
||||
/// tester.getSize(find.byKey(new ValueKey('save-button')));
|
||||
const CommonFinders find = const CommonFinders._();
|
||||
|
||||
/// Provides lightweight syntax for getting frequently used widget [Finder]s.
|
||||
///
|
||||
/// This class is instantiated once, as [find].
|
||||
class CommonFinders {
|
||||
const CommonFinders._();
|
||||
|
||||
/// Finds [Text] widgets containing string equal to the `text`
|
||||
/// argument.
|
||||
///
|
||||
/// Example:
|
||||
///
|
||||
/// expect(tester, hasWidget(find.text('Back')));
|
||||
Finder text(String text) => new _TextFinder(text);
|
||||
|
||||
/// Looks for widgets that contain a [Text] descendant with `text`
|
||||
/// in it.
|
||||
///
|
||||
/// Example:
|
||||
///
|
||||
/// // Suppose you have a button with text 'Update' in it:
|
||||
/// new Button(
|
||||
/// child: new Text('Update')
|
||||
/// )
|
||||
///
|
||||
/// // You can find and tap on it like this:
|
||||
/// tester.tap(find.widgetWithText(Button, 'Update'));
|
||||
Finder widgetWithText(Type widgetType, String text) => new _WidgetWithTextFinder(widgetType, text);
|
||||
|
||||
/// Finds widgets by searching for one with a particular [Key].
|
||||
///
|
||||
/// Example:
|
||||
///
|
||||
/// expect(tester, hasWidget(find.byKey(backKey)));
|
||||
Finder byKey(Key key) => new _KeyFinder(key);
|
||||
|
||||
/// Finds widgets by searching for widgets with a particular type.
|
||||
///
|
||||
/// The `type` argument must be a subclass of [Widget].
|
||||
///
|
||||
/// Example:
|
||||
///
|
||||
/// expect(tester, hasWidget(find.byType(IconButton)));
|
||||
Finder byType(Type type) => new _TypeFinder(type);
|
||||
|
||||
/// Finds widgets whose current widget is the instance given by the
|
||||
/// argument.
|
||||
///
|
||||
/// Example:
|
||||
///
|
||||
/// // Suppose you have a button created like this:
|
||||
/// Widget myButton = new Button(
|
||||
/// child: new Text('Update')
|
||||
/// );
|
||||
///
|
||||
/// // You can find and tap on it like this:
|
||||
/// tester.tap(find.byConfig(myButton));
|
||||
Finder byConfig(Widget config) => new _ConfigFinder(config);
|
||||
|
||||
/// Finds widgets using a widget predicate.
|
||||
///
|
||||
/// Example:
|
||||
///
|
||||
/// expect(tester, hasWidget(find.byWidgetPredicate(
|
||||
/// (Widget widget) => widget is Tooltip && widget.message == 'Back'
|
||||
/// )));
|
||||
Finder byWidgetPredicate(WidgetPredicate predicate) => new _WidgetPredicateFinder(predicate);
|
||||
|
||||
/// Finds widgets using an element predicate.
|
||||
///
|
||||
/// Example:
|
||||
///
|
||||
/// expect(tester, hasWidget(find.byWidgetPredicate(
|
||||
/// (Element element) => element is SingleChildRenderObjectElement
|
||||
/// )));
|
||||
Finder byElementPredicate(ElementPredicate predicate) => new _ElementPredicateFinder(predicate);
|
||||
}
|
||||
|
||||
/// Finds [Element]s inside the element tree.
|
||||
abstract class Finder {
|
||||
/// Returns all the elements that match this finder's pattern,
|
||||
/// using the given tester to determine which element tree to look at.
|
||||
Iterable<Element> find(WidgetTester tester);
|
||||
|
||||
/// Describes what the finder is looking for. The description should be
|
||||
/// a brief English noun phrase describing the finder's pattern.
|
||||
String get description;
|
||||
|
||||
/// Returns the first value returned from [find], unless no value is found,
|
||||
/// in which case it throws an [ElementNotFoundError].
|
||||
Element findFirst(WidgetTester tester) {
|
||||
Iterable<Element> results = find(tester);
|
||||
return results.isNotEmpty
|
||||
? results.first
|
||||
: throw new ElementNotFoundError.fromFinder(this);
|
||||
}
|
||||
|
||||
@override
|
||||
String toString() => '[Finder for $description]';
|
||||
}
|
||||
|
||||
/// Indicates that an attempt to find a widget within the current element tree
|
||||
/// failed.
|
||||
class ElementNotFoundError extends Error {
|
||||
ElementNotFoundError(this.message);
|
||||
|
||||
ElementNotFoundError.fromFinder(Finder finder)
|
||||
: message = 'Element not found by ${finder.description}';
|
||||
|
||||
final String message;
|
||||
|
||||
@override
|
||||
String toString() => 'ElementNotFoundError: $message';
|
||||
}
|
||||
|
||||
class _TextFinder extends Finder {
|
||||
_TextFinder(this.text);
|
||||
|
||||
final String text;
|
||||
|
||||
@override
|
||||
String get description => 'text "$text"';
|
||||
|
||||
@override
|
||||
Iterable<Element> find(WidgetTester tester) {
|
||||
return tester.allElements.where((Element element) {
|
||||
if (element.widget is! Text)
|
||||
return false;
|
||||
Text textWidget = element.widget;
|
||||
return textWidget.data == text;
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
class _WidgetWithTextFinder extends Finder {
|
||||
_WidgetWithTextFinder(this.widgetType, this.text);
|
||||
|
||||
final Type widgetType;
|
||||
final String text;
|
||||
|
||||
@override
|
||||
String get description => 'type $widgetType with text "$text"';
|
||||
|
||||
@override
|
||||
Iterable<Element> find(WidgetTester tester) {
|
||||
return tester.allElements
|
||||
.map((Element textElement) {
|
||||
if (textElement.widget is! Text)
|
||||
return null;
|
||||
|
||||
Text textWidget = textElement.widget;
|
||||
if (textWidget.data == text) {
|
||||
Element parent;
|
||||
textElement.visitAncestorElements((Element element) {
|
||||
if (element.widget.runtimeType == widgetType) {
|
||||
parent = element;
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
});
|
||||
return parent;
|
||||
}
|
||||
|
||||
return null;
|
||||
})
|
||||
.where((Element element) => element != null);
|
||||
}
|
||||
}
|
||||
|
||||
class _KeyFinder extends Finder {
|
||||
_KeyFinder(this.key);
|
||||
|
||||
final Key key;
|
||||
|
||||
@override
|
||||
String get description => 'key $key';
|
||||
|
||||
@override
|
||||
Iterable<Element> find(WidgetTester tester) {
|
||||
return tester.allElements.where((Element element) {
|
||||
return element.widget.key == key;
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
class _TypeFinder extends Finder {
|
||||
_TypeFinder(this.widgetType);
|
||||
|
||||
final Type widgetType;
|
||||
|
||||
@override
|
||||
String get description => 'type "$widgetType"';
|
||||
|
||||
@override
|
||||
Iterable<Element> find(WidgetTester tester) {
|
||||
return tester.allElements.where((Element element) {
|
||||
return element.widget.runtimeType == widgetType;
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
class _ConfigFinder extends Finder {
|
||||
_ConfigFinder(this.config);
|
||||
|
||||
final Widget config;
|
||||
|
||||
@override
|
||||
String get description => 'the given configuration ($config)';
|
||||
|
||||
@override
|
||||
Iterable<Element> find(WidgetTester tester) {
|
||||
return tester.allElements.where((Element element) {
|
||||
return element.widget == config;
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
class _WidgetPredicateFinder extends Finder {
|
||||
_WidgetPredicateFinder(this.predicate);
|
||||
|
||||
final WidgetPredicate predicate;
|
||||
|
||||
@override
|
||||
String get description => 'widget predicate ($predicate)';
|
||||
|
||||
@override
|
||||
Iterable<Element> find(WidgetTester tester) {
|
||||
return tester.allElements.where((Element element) {
|
||||
return predicate(element.widget);
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
class _ElementPredicateFinder extends Finder {
|
||||
_ElementPredicateFinder(this.predicate);
|
||||
|
||||
final ElementPredicate predicate;
|
||||
|
||||
@override
|
||||
String get description => 'element predicate ($predicate)';
|
||||
|
||||
@override
|
||||
Iterable<Element> find(WidgetTester tester) {
|
||||
return tester.allElements.where(predicate);
|
||||
}
|
||||
}
|
||||
|
||||
/// Asserts that [finder] locates a widget in the test element tree.
|
||||
///
|
||||
/// Example:
|
||||
///
|
||||
/// expect(tester, hasWidget(find.text('Save')));
|
||||
Matcher hasWidget(Finder finder) => new _HasWidgetMatcher(finder);
|
||||
|
||||
class _HasWidgetMatcher extends Matcher {
|
||||
const _HasWidgetMatcher(this.finder);
|
||||
|
||||
final Finder finder;
|
||||
|
||||
@override
|
||||
bool matches(WidgetTester tester, Map<dynamic, dynamic> matchState) {
|
||||
return tester.exists(finder);
|
||||
}
|
||||
|
||||
@override
|
||||
Description describe(Description description) {
|
||||
return description.add('$finder exists in the element tree');
|
||||
}
|
||||
|
||||
@override
|
||||
Description describeMismatch(
|
||||
dynamic item, Description mismatchDescription, Map<dynamic, dynamic> matchState, bool verbose) {
|
||||
return mismatchDescription.add('Does not contain $finder');
|
||||
}
|
||||
}
|
||||
|
||||
/// Asserts that [finder] does not locate a widget in the test element tree.
|
||||
/// Opposite of [hasWidget].
|
||||
///
|
||||
/// Example:
|
||||
///
|
||||
/// expect(tester, doesNotHaveWidget(find.text('Save')));
|
||||
Matcher doesNotHaveWidget(Finder finder) => new _DoesNotHaveWidgetMatcher(finder);
|
||||
|
||||
class _DoesNotHaveWidgetMatcher extends Matcher {
|
||||
const _DoesNotHaveWidgetMatcher(this.finder);
|
||||
|
||||
final Finder finder;
|
||||
|
||||
@override
|
||||
bool matches(WidgetTester tester, Map<dynamic, dynamic> matchState) {
|
||||
return !tester.exists(finder);
|
||||
}
|
||||
|
||||
@override
|
||||
Description describe(Description description) {
|
||||
return description.add('$finder does not exist in the element tree');
|
||||
}
|
||||
|
||||
@override
|
||||
Description describeMismatch(
|
||||
dynamic item, Description mismatchDescription, Map<dynamic, dynamic> matchState, bool verbose) {
|
||||
return mismatchDescription.add('Contains $finder');
|
||||
binding.fakeAsync.flushMicrotasks();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -7,56 +7,50 @@ import 'package:flutter_test/flutter_test.dart';
|
||||
import 'package:test/test.dart';
|
||||
|
||||
void main() {
|
||||
group('hasWidget', () {
|
||||
test('succeeds', () {
|
||||
testWidgets((WidgetTester tester) {
|
||||
tester.pumpWidget(new Text('foo'));
|
||||
expect(tester, hasWidget(find.text('foo')));
|
||||
});
|
||||
group('findsOneWidget', () {
|
||||
testWidgets('finds exactly one widget', (WidgetTester tester) {
|
||||
tester.pumpWidget(new Text('foo'));
|
||||
expect(find.text('foo'), findsOneWidget);
|
||||
});
|
||||
|
||||
test('fails with a descriptive message', () {
|
||||
testWidgets((WidgetTester tester) {
|
||||
TestFailure failure;
|
||||
try {
|
||||
expect(tester, hasWidget(find.text('foo')));
|
||||
} catch(e) {
|
||||
failure = e;
|
||||
}
|
||||
testWidgets('fails with a descriptive message', (WidgetTester tester) {
|
||||
TestFailure failure;
|
||||
try {
|
||||
expect(find.text('foo'), findsOneWidget);
|
||||
} catch(e) {
|
||||
failure = e;
|
||||
}
|
||||
|
||||
expect(failure, isNotNull);
|
||||
String message = failure.message;
|
||||
expect(message, contains('Expected: [Finder for text "foo"] exists in the element tree'));
|
||||
expect(message, contains("Actual: <Instance of 'WidgetTester'>"));
|
||||
expect(message, contains('Which: Does not contain [Finder for text "foo"]'));
|
||||
});
|
||||
expect(failure, isNotNull);
|
||||
String message = failure.message;
|
||||
expect(message, contains('Expected: exactly one matching node in the widget tree\n'));
|
||||
expect(message, contains('Actual: ?:<zero widgets with text "foo">\n'));
|
||||
expect(message, contains('Which: means none were found but one was expected\n'));
|
||||
});
|
||||
});
|
||||
|
||||
group('doesNotHaveWidget', () {
|
||||
test('succeeds', () {
|
||||
testWidgets((WidgetTester tester) {
|
||||
expect(tester, doesNotHaveWidget(find.text('foo')));
|
||||
});
|
||||
group('findsNothing', () {
|
||||
testWidgets('finds no widgets', (WidgetTester tester) {
|
||||
expect(find.text('foo'), findsNothing);
|
||||
});
|
||||
|
||||
test('fails with a descriptive message', () {
|
||||
testWidgets((WidgetTester tester) {
|
||||
tester.pumpWidget(new Text('foo'));
|
||||
testWidgets('fails with a descriptive message', (WidgetTester tester) {
|
||||
tester.pumpWidget(new Text('foo'));
|
||||
|
||||
TestFailure failure;
|
||||
try {
|
||||
expect(tester, doesNotHaveWidget(find.text('foo')));
|
||||
} catch(e) {
|
||||
failure = e;
|
||||
}
|
||||
TestFailure failure;
|
||||
try {
|
||||
expect(find.text('foo'), findsNothing);
|
||||
} catch(e) {
|
||||
failure = e;
|
||||
}
|
||||
|
||||
expect(failure, isNotNull);
|
||||
String message = failure.message;
|
||||
expect(message, contains('Expected: [Finder for text "foo"] does not exist in the element tree'));
|
||||
expect(message, contains("Actual: <Instance of 'WidgetTester'>"));
|
||||
expect(message, contains('Which: Contains [Finder for text "foo"]'));
|
||||
});
|
||||
expect(failure, isNotNull);
|
||||
String message = failure.message;
|
||||
|
||||
expect(message, contains('Expected: no matching nodes in the widget tree\n'));
|
||||
expect(message, contains('Actual: ?:<exactly one widget with text "foo": Text("foo")>\n'));
|
||||
expect(message, contains('Which: means one was found but none were expected\n'));
|
||||
});
|
||||
});
|
||||
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user