diff --git a/dev/manual_tests/test/card_collection_test.dart b/dev/manual_tests/test/card_collection_test.dart index ec7760b19f..5c07bb4b55 100644 --- a/dev/manual_tests/test/card_collection_test.dart +++ b/dev/manual_tests/test/card_collection_test.dart @@ -9,33 +9,31 @@ import 'package:test/test.dart'; import '../card_collection.dart' as card_collection; void main() { - test("Card Collection smoke test", () { - testWidgets((WidgetTester tester) { - card_collection.main(); // builds the app and schedules a frame but doesn't trigger one - tester.pump(); // see https://github.com/flutter/flutter/issues/1865 - tester.pump(); // triggers a frame + testWidgets("Card Collection smoke test", (WidgetTester tester) { + card_collection.main(); // builds the app and schedules a frame but doesn't trigger one + tester.pump(); // see https://github.com/flutter/flutter/issues/1865 + tester.pump(); // triggers a frame - Finder navigationMenu = find.byWidgetPredicate((Widget widget) { - if (widget is Tooltip) - return widget.message == 'Open navigation menu'; - return false; - }); - - expect(tester, hasWidget(navigationMenu)); - - tester.tap(navigationMenu); - tester.pump(); // start opening menu - tester.pump(const Duration(seconds: 1)); // wait til it's really opened - - // smoke test for various checkboxes - tester.tap(find.text('Make card labels editable')); - tester.pump(); - tester.tap(find.text('Let the sun shine')); - tester.pump(); - tester.tap(find.text('Make card labels editable')); - tester.pump(); - tester.tap(find.text('Vary font sizes')); - tester.pump(); + Finder navigationMenu = find.byWidgetPredicate((Widget widget) { + if (widget is Tooltip) + return widget.message == 'Open navigation menu'; + return false; }); + + expect(navigationMenu, findsOneWidget); + + tester.tap(navigationMenu); + tester.pump(); // start opening menu + tester.pump(const Duration(seconds: 1)); // wait til it's really opened + + // smoke test for various checkboxes + tester.tap(find.text('Make card labels editable')); + tester.pump(); + tester.tap(find.text('Let the sun shine')); + tester.pump(); + tester.tap(find.text('Make card labels editable')); + tester.pump(); + tester.tap(find.text('Vary font sizes')); + tester.pump(); }); } diff --git a/examples/hello_world/test/hello_test.dart b/examples/hello_world/test/hello_test.dart index f377d8a9fd..0ff5eb19cd 100644 --- a/examples/hello_world/test/hello_test.dart +++ b/examples/hello_world/test/hello_test.dart @@ -8,12 +8,10 @@ import 'package:test/test.dart'; import '../lib/main.dart' as hello_world; void main() { - test("Hello world smoke test", () { - testWidgets((WidgetTester tester) { - hello_world.main(); // builds the app and schedules a frame but doesn't trigger one - tester.pump(); // triggers a frame + testWidgets("Hello world smoke test", (WidgetTester tester) { + hello_world.main(); // builds the app and schedules a frame but doesn't trigger one + tester.pump(); // triggers a frame - expect(tester, hasWidget(find.text('Hello, world!'))); - }); + expect(find.text('Hello, world!'), findsOneWidget); }); } diff --git a/examples/material_gallery/test/smoke_test.dart b/examples/material_gallery/test/smoke_test.dart index ea73ac42b0..5ab6380fa9 100644 --- a/examples/material_gallery/test/smoke_test.dart +++ b/examples/material_gallery/test/smoke_test.dart @@ -35,7 +35,7 @@ Finder findBackButton(WidgetTester tester) => byTooltip(tester, 'Back'); void smokeDemo(WidgetTester tester, String routeName) { // Ensure that we're (likely to be) on the home page final Finder menuItem = findGalleryItemByRouteName(tester, routeName); - expect(tester, hasWidget(menuItem)); + expect(menuItem, findsOneWidget); tester.tap(menuItem); tester.pump(); // Launch the demo. @@ -43,58 +43,56 @@ void smokeDemo(WidgetTester tester, String routeName) { // Go back Finder backButton = findBackButton(tester); - expect(tester, hasWidget(backButton)); + expect(backButton, findsOneWidget); tester.tap(backButton); tester.pump(); // Start the navigator pop "back" operation. tester.pump(const Duration(seconds: 1)); // Wait until it has finished. } void main() { - test('Material Gallery app smoke test', () { - testWidgets((WidgetTester tester) { - material_gallery_main.main(); // builds the app and schedules a frame but doesn't trigger one - tester.pump(); // see https://github.com/flutter/flutter/issues/1865 - tester.pump(); // triggers a frame + testWidgets('Material Gallery app smoke test', (WidgetTester tester) { + material_gallery_main.main(); // builds the app and schedules a frame but doesn't trigger one + tester.pump(); // see https://github.com/flutter/flutter/issues/1865 + tester.pump(); // triggers a frame - // Expand the demo category submenus. - for (String category in demoCategories.reversed) { - tester.tap(find.text(category)); - tester.pump(); - tester.pump(const Duration(seconds: 1)); // Wait until the menu has expanded. - } - - final List scrollDeltas = new List(); - double previousY = tester.getTopRight(find.text(demoCategories[0])).y; - final List routeNames = material_gallery_app.kRoutes.keys.toList(); - for (String routeName in routeNames) { - final double y = tester.getTopRight(findGalleryItemByRouteName(tester, routeName)).y; - scrollDeltas.add(previousY - y); - previousY = y; - } - - // Launch each demo and then scroll that item out of the way. - for (int i = 0; i < routeNames.length; i += 1) { - final String routeName = routeNames[i]; - smokeDemo(tester, routeName); - tester.scroll(findGalleryItemByRouteName(tester, routeName), new Offset(0.0, scrollDeltas[i])); - tester.pump(); - } - - Finder navigationMenuButton = findNavigationMenuButton(tester); - expect(tester, hasWidget(navigationMenuButton)); - tester.tap(navigationMenuButton); - tester.pump(); // Start opening drawer. - tester.pump(const Duration(seconds: 1)); // Wait until it's really opened. - - // switch theme - tester.tap(find.text('Dark')); + // Expand the demo category submenus. + for (String category in demoCategories.reversed) { + tester.tap(find.text(category)); tester.pump(); - tester.pump(const Duration(seconds: 1)); // Wait until it's changed. + tester.pump(const Duration(seconds: 1)); // Wait until the menu has expanded. + } - // switch theme - tester.tap(find.text('Light')); + final List scrollDeltas = new List(); + double previousY = tester.getTopRight(find.text(demoCategories[0])).y; + final List routeNames = material_gallery_app.kRoutes.keys.toList(); + for (String routeName in routeNames) { + final double y = tester.getTopRight(findGalleryItemByRouteName(tester, routeName)).y; + scrollDeltas.add(previousY - y); + previousY = y; + } + + // Launch each demo and then scroll that item out of the way. + for (int i = 0; i < routeNames.length; i += 1) { + final String routeName = routeNames[i]; + smokeDemo(tester, routeName); + tester.scroll(findGalleryItemByRouteName(tester, routeName), new Offset(0.0, scrollDeltas[i])); tester.pump(); - tester.pump(const Duration(seconds: 1)); // Wait until it's changed. - }); + } + + Finder navigationMenuButton = findNavigationMenuButton(tester); + expect(navigationMenuButton, findsOneWidget); + tester.tap(navigationMenuButton); + tester.pump(); // Start opening drawer. + tester.pump(const Duration(seconds: 1)); // Wait until it's really opened. + + // switch theme + tester.tap(find.text('Dark')); + tester.pump(); + tester.pump(const Duration(seconds: 1)); // Wait until it's changed. + + // switch theme + tester.tap(find.text('Light')); + tester.pump(); + tester.pump(const Duration(seconds: 1)); // Wait until it's changed. }); } diff --git a/examples/stocks/test/icon_color_test.dart b/examples/stocks/test/icon_color_test.dart index 01513bea92..69e112e8d4 100644 --- a/examples/stocks/test/icon_color_test.dart +++ b/examples/stocks/test/icon_color_test.dart @@ -38,11 +38,11 @@ Element findElementOfExactWidgetTypeGoingUp(Element node, Type targetType) { final RegExp materialIconAssetNameColorExtractor = new RegExp(r'[^/]+/ic_.+_(white|black)_[0-9]+dp\.png'); -void checkIconColor(ElementTreeTester tester, String label, Color color) { +void checkIconColor(WidgetTester tester, String label, Color color) { // The icon is going to be in the same merged semantics box as the text // regardless of how the menu item is represented, so this is a good // way to find the menu item. I hope. - Element semantics = findElementOfExactWidgetTypeGoingUp(tester.findText(label), MergeSemantics); + Element semantics = findElementOfExactWidgetTypeGoingUp(tester.element(find.text(label)), MergeSemantics); expect(semantics, isNotNull); Element asset = findElementOfExactWidgetTypeGoingDown(semantics, Text); Text text = asset.widget; @@ -52,47 +52,44 @@ void checkIconColor(ElementTreeTester tester, String label, Color color) { void main() { stock_data.StockDataFetcher.actuallyFetchData = false; - test("Test icon colors", () { - testWidgets((WidgetTester tester) { - stocks.main(); // builds the app and schedules a frame but doesn't trigger one - tester.pump(); // see https://github.com/flutter/flutter/issues/1865 - tester.pump(); // triggers a frame + testWidgets("Test icon colors", (WidgetTester tester) { + stocks.main(); // builds the app and schedules a frame but doesn't trigger one + tester.pump(); // see https://github.com/flutter/flutter/issues/1865 + tester.pump(); // triggers a frame - // sanity check - expect(tester, hasWidget(find.text('MARKET'))); - expect(tester, doesNotHaveWidget(find.text('Help & Feedback'))); - tester.pump(new Duration(seconds: 2)); - expect(tester, hasWidget(find.text('MARKET'))); - expect(tester, doesNotHaveWidget(find.text('Help & Feedback'))); + // sanity check + expect(find.text('MARKET'), findsOneWidget); + expect(find.text('Help & Feedback'), findsNothing); + tester.pump(new Duration(seconds: 2)); + expect(find.text('MARKET'), findsOneWidget); + expect(find.text('Help & Feedback'), findsNothing); - // drag the drawer out - Point left = new Point(0.0, ui.window.size.height / 2.0); - Point right = new Point(ui.window.size.width, left.y); - TestGesture gesture = tester.startGesture(left); - tester.pump(); - gesture.moveTo(right); - tester.pump(); - gesture.up(); - tester.pump(); - expect(tester, hasWidget(find.text('MARKET'))); - expect(tester, hasWidget(find.text('Help & Feedback'))); + // drag the drawer out + Point left = new Point(0.0, ui.window.size.height / 2.0); + Point right = new Point(ui.window.size.width, left.y); + TestGesture gesture = tester.startGesture(left); + tester.pump(); + gesture.moveTo(right); + tester.pump(); + gesture.up(); + tester.pump(); + expect(find.text('MARKET'), findsOneWidget); + expect(find.text('Help & Feedback'), findsOneWidget); - // check the colour of the icon - light mode - checkIconColor(tester.elementTreeTester, 'Stock List', Colors.purple[500]); // theme primary color - checkIconColor(tester.elementTreeTester, 'Account Balance', Colors.black45); // enabled - checkIconColor(tester.elementTreeTester, 'Help & Feedback', Colors.black26); // disabled + // check the colour of the icon - light mode + checkIconColor(tester, 'Stock List', Colors.purple[500]); // theme primary color + checkIconColor(tester, 'Account Balance', Colors.black45); // enabled + checkIconColor(tester, 'Help & Feedback', Colors.black26); // disabled - // switch to dark mode - tester.tap(find.text('Pessimistic')); - tester.pump(); // get the tap and send the notification that the theme has changed - tester.pump(); // start the theme transition - tester.pump(const Duration(seconds: 5)); // end the transition + // switch to dark mode + tester.tap(find.text('Pessimistic')); + tester.pump(); // get the tap and send the notification that the theme has changed + tester.pump(); // start the theme transition + tester.pump(const Duration(seconds: 5)); // end the transition - // check the colour of the icon - dark mode - checkIconColor(tester.elementTreeTester, 'Stock List', Colors.redAccent[200]); // theme accent color - checkIconColor(tester.elementTreeTester, 'Account Balance', Colors.white); // enabled - checkIconColor(tester.elementTreeTester, 'Help & Feedback', Colors.white30); // disabled - - }); + // check the colour of the icon - dark mode + checkIconColor(tester, 'Stock List', Colors.redAccent[200]); // theme accent color + checkIconColor(tester, 'Account Balance', Colors.white); // enabled + checkIconColor(tester, 'Help & Feedback', Colors.white30); // disabled }); } diff --git a/examples/stocks/test/locale_test.dart b/examples/stocks/test/locale_test.dart index a23c1e9ee7..4502e97bbb 100644 --- a/examples/stocks/test/locale_test.dart +++ b/examples/stocks/test/locale_test.dart @@ -10,16 +10,13 @@ import 'package:test/test.dart'; void main() { stock_data.StockDataFetcher.actuallyFetchData = false; - test("Test changing locale", () { - testWidgets((WidgetTester tester) { - stocks.main(); - tester.flushMicrotasks(); // see https://github.com/flutter/flutter/issues/1865 - tester.pump(); - - expect(tester, hasWidget(find.text('MARKET'))); - tester.setLocale("es", "US"); - tester.pump(); - expect(tester, hasWidget(find.text('MERCADO'))); - }); + testWidgets("Test changing locale", (WidgetTester tester) { + stocks.main(); + tester.flushMicrotasks(); // see https://github.com/flutter/flutter/issues/1865 + tester.pump(); + expect(find.text('MARKET'), findsOneWidget); + tester.binding.setLocale("es", "US"); + tester.pump(); + expect(find.text('MERCADO'), findsOneWidget); }); } diff --git a/packages/flutter/benchmark/stocks/animation_bench.dart b/packages/flutter/benchmark/stocks/animation_bench.dart index bec8781e55..6b876a227b 100644 --- a/packages/flutter/benchmark/stocks/animation_bench.dart +++ b/packages/flutter/benchmark/stocks/animation_bench.dart @@ -10,7 +10,6 @@ const int _kNumberOfIterations = 50000; const bool _kRunForever = false; void main() { - assert(false); // Don't run in checked mode stock_data.StockDataFetcher.actuallyFetchData = false; const Duration _kAnimationDuration = const Duration(milliseconds: 200); @@ -21,7 +20,7 @@ void main() { Stopwatch watch = new Stopwatch() ..start(); - testWidgets((WidgetTester tester) { + benchmarkWidgets((WidgetTester tester) { stocks.main(); tester.pump(); // Start startup animation tester.pump(const Duration(seconds: 1)); // Complete startup animation diff --git a/packages/flutter/benchmark/stocks/build_bench.dart b/packages/flutter/benchmark/stocks/build_bench.dart index 963777c817..47ccf4f648 100644 --- a/packages/flutter/benchmark/stocks/build_bench.dart +++ b/packages/flutter/benchmark/stocks/build_bench.dart @@ -12,19 +12,18 @@ const bool _kRunForever = false; void _doNothing() { } void main() { - assert(false); // Don't run in checked mode stock_data.StockDataFetcher.actuallyFetchData = false; stocks.StocksAppState appState; - testWidgets((WidgetTester tester) { + benchmarkWidgets((WidgetTester tester) { stocks.main(); tester.pump(); // Start startup animation tester.pump(const Duration(seconds: 1)); // Complete startup animation tester.tapAt(new Point(20.0, 20.0)); // Open drawer tester.pump(); // Start drawer animation tester.pump(const Duration(seconds: 1)); // Complete drawer animation - appState = tester.stateOf(find.byType(stocks.StocksApp)); + appState = tester.state(find.byType(stocks.StocksApp)); }); BuildOwner buildOwner = WidgetsBinding.instance.buildOwner; diff --git a/packages/flutter/benchmark/stocks/layout_bench.dart b/packages/flutter/benchmark/stocks/layout_bench.dart index 48b4b9e7f4..8f81191ece 100644 --- a/packages/flutter/benchmark/stocks/layout_bench.dart +++ b/packages/flutter/benchmark/stocks/layout_bench.dart @@ -10,10 +10,9 @@ const int _kNumberOfIterations = 100000; const bool _kRunForever = false; void main() { - assert(false); // Don't run in checked mode stock_data.StockDataFetcher.actuallyFetchData = false; - testWidgets((WidgetTester tester) { + benchmarkWidgets((WidgetTester tester) { stocks.main(); tester.pump(); // Start startup animation tester.pump(const Duration(seconds: 1)); // Complete startup animation diff --git a/packages/flutter/lib/src/foundation/assertions.dart b/packages/flutter/lib/src/foundation/assertions.dart index e6e1a77b74..c190ad55fc 100644 --- a/packages/flutter/lib/src/foundation/assertions.dart +++ b/packages/flutter/lib/src/foundation/assertions.dart @@ -136,10 +136,11 @@ class FlutterError extends AssertionError { /// The first time this is called, it dumps a very verbose message to the /// console using [debugPrint]. /// - /// Subsequent calls only dump the first line of the exception. + /// Subsequent calls only dump the first line of the exception, unless + /// `forceReport` is set to true (in which case it dumps the verbose message). /// - /// This is the default behavior for the [onError] handler. - static void dumpErrorToConsole(FlutterErrorDetails details) { + /// The default behavior for the [onError] handler is to call this function. + static void dumpErrorToConsole(FlutterErrorDetails details, { bool forceReport: false }) { assert(details != null); assert(details.exception != null); bool reportError = details.silent != true; // could be null @@ -148,9 +149,9 @@ class FlutterError extends AssertionError { reportError = true; return true; }); - if (!reportError) + if (!reportError && !forceReport) return; - if (_errorCount == 0) { + if (_errorCount == 0 || forceReport) { final String header = '\u2550\u2550\u2561 EXCEPTION CAUGHT BY ${details.library} \u255E'.toUpperCase(); final String footer = '\u2501' * _kWrapWidth; debugPrint('$header${"\u2550" * (footer.length - header.length)}'); @@ -186,7 +187,7 @@ class FlutterError extends AssertionError { debugPrint(information.toString(), wrapWidth: _kWrapWidth); } if (details.stack != null) { - debugPrint('Stack trace:', wrapWidth: _kWrapWidth); + debugPrint('When the exception was thrown, this was the stack:', wrapWidth: _kWrapWidth); debugPrint('${details.stack}$footer'); // StackTrace objects include a trailing newline } else { debugPrint(footer); diff --git a/packages/flutter/lib/src/foundation/basic_types.dart b/packages/flutter/lib/src/foundation/basic_types.dart index d50368a942..70a389b07f 100644 --- a/packages/flutter/lib/src/foundation/basic_types.dart +++ b/packages/flutter/lib/src/foundation/basic_types.dart @@ -2,6 +2,8 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. +import 'dart:collection'; + export 'dart:ui' show VoidCallback; /// Signature for callbacks that report that an underlying value has changed. @@ -52,3 +54,153 @@ class BitField { _bits = value ? _kAllOnes : _kAllZeros; } } + +/// A lazy caching version of [Iterable]. +/// +/// This iterable is efficient in the following ways: +/// +/// * It will not walk the given iterator more than you ask for. +/// +/// * If you use it twice (e.g. you check [isNotEmpty], then +/// use [single]), it will only walk the given iterator +/// once. This caching will even work efficiently if you are +/// running two side-by-side iterators on the same iterable. +/// +/// * [toList] uses its EfficientLength variant to create its +/// list quickly. +/// +/// It is inefficient in the following ways: +/// +/// * The first iteration through has caching overhead. +/// +/// * It requires more memory than a non-caching iterator. +/// +/// * the [length] and [toList] properties immediately precache the +/// entire list. Using these fields therefore loses the laziness of +/// the iterable. However, it still gets cached. +/// +/// The caching behavior is propagated to the iterators that are +/// created by [map], [where], [expand], [take], [takeWhile], [skip], +/// and [skipWhile], and is used by the built-in methods that use an +/// iterator like [isNotEmpty] and [single]. +/// +/// Because a CachingIterable only walks the underlying data once, it +/// cannot be used multiple times with the underlying data changing +/// between each use. You must create a new iterable each time. This +/// also applies to any iterables derived from this one, e.g. as +/// returned by `where`. +class CachingIterable extends IterableBase { + /// Creates a CachingIterable using the given [Iterator] as the + /// source of data. The iterator must be non-null and must not throw + /// exceptions. + /// + /// Since the argument is an [Iterator], not an [Iterable], it is + /// guaranteed that the underlying data set will only be walked + /// once. If you have an [Iterable], you can pass its [iterator] + /// field as the argument to this constructor. + /// + /// You can use a `sync*` function with this as follows: + /// + /// ```dart + /// Iterable range(int start, int end) sync* { + /// for (int index = start; index <= end; index += 1) + /// yield index; + /// } + /// + /// Iterable i = new CachingIterable(range(1, 5).iterator); + /// print(i.length); // walks the list + /// print(i.length); // efficient + /// ``` + CachingIterable(this._prefillIterator); + + final Iterator _prefillIterator; + final List _results = []; + + @override + Iterator get iterator { + return new _LazyListIterator(this); + } + + @override + Iterable map/**/(/*=T*/ f(E e)) { + return new CachingIterable(super.map/**/(f).iterator); + } + + @override + Iterable where(bool f(E element)) { + return new CachingIterable(super.where(f).iterator); + } + + @override + Iterable expand/**/(Iterable/**/ f(E element)) { + return new CachingIterable(super.expand/**/(f).iterator); + } + + @override + Iterable take(int count) { + return new CachingIterable(super.take(count).iterator); + } + + @override + Iterable takeWhile(bool test(E value)) { + return new CachingIterable(super.takeWhile(test).iterator); + } + + @override + Iterable skip(int count) { + return new CachingIterable(super.skip(count).iterator); + } + + @override + Iterable skipWhile(bool test(E value)) { + return new CachingIterable(super.skipWhile(test).iterator); + } + + @override + int get length { + _precacheEntireList(); + return _results.length; + } + + @override + List toList({ bool growable: true }) { + _precacheEntireList(); + return new List.from(_results, growable: growable); + } + + void _precacheEntireList() { + while (_fillNext()) { } + } + + bool _fillNext() { + if (!_prefillIterator.moveNext()) + return false; + _results.add(_prefillIterator.current); + return true; + } +} + +class _LazyListIterator implements Iterator { + _LazyListIterator(this._owner) : _index = -1; + + final CachingIterable _owner; + int _index; + + @override + E get current { + assert(_index >= 0); // called "current" before "moveNext()" + if (_index < 0 || _index == _owner._results.length) + return null; + return _owner._results[_index]; + } + + @override + bool moveNext() { + if (_index >= _owner._results.length) + return false; + _index += 1; + if (_index == _owner._results.length) + return _owner._fillNext(); + return true; + } +} diff --git a/packages/flutter/lib/src/scheduler/binding.dart b/packages/flutter/lib/src/scheduler/binding.dart index 9c3123da3a..0ed95fef4b 100644 --- a/packages/flutter/lib/src/scheduler/binding.dart +++ b/packages/flutter/lib/src/scheduler/binding.dart @@ -398,7 +398,8 @@ abstract class SchedulerBinding extends BindingBase { library: 'scheduler library', context: 'during a scheduler callback', informationCollector: (callbackStack == null) ? null : (StringBuffer information) { - information.writeln('When this callback was registered, this was the stack:\n$callbackStack'); + // callbackStack ends with a newline, so don't introduce one artificially here + information.write('When this callback was registered, this was the stack:\n$callbackStack'); } )); } diff --git a/packages/flutter/lib/src/widgets/binding.dart b/packages/flutter/lib/src/widgets/binding.dart index e7f1b6a5d7..63702c196e 100644 --- a/packages/flutter/lib/src/widgets/binding.dart +++ b/packages/flutter/lib/src/widgets/binding.dart @@ -361,13 +361,19 @@ class RenderObjectToWidgetElement extends RootRenderObje /// A concrete binding for applications based on the Widgets framework. /// This is the glue that binds the framework to the Flutter engine. class WidgetsFlutterBinding extends BindingBase with SchedulerBinding, GestureBinding, ServicesBinding, RendererBinding, WidgetsBinding { - /// Creates and initializes the WidgetsFlutterBinding. This function - /// is idempotent; calling it a second time will just return the - /// previously-created instance. + + /// Returns an instance of the [WidgetsBinding], creating and + /// initializing it if necessary. If one is created, it will be a + /// [WidgetsFlutterBinding]. If one was previously initialized, then + /// it will at least implement [WidgetsBinding]. /// /// You only need to call this method if you need the binding to be /// initialized before calling [runApp]. - static WidgetsFlutterBinding ensureInitialized() { + /// + /// In the `flutter_test` framework, [testWidgets] initializes the + /// binding instance to a [TestWidgetsFlutterBinding], not a + /// [WidgetsFlutterBinding]. + static WidgetsBinding ensureInitialized() { if (WidgetsBinding.instance == null) new WidgetsFlutterBinding(); return WidgetsBinding.instance; diff --git a/packages/flutter/lib/src/widgets/framework.dart b/packages/flutter/lib/src/widgets/framework.dart index 88412b4021..b777bb6710 100644 --- a/packages/flutter/lib/src/widgets/framework.dart +++ b/packages/flutter/lib/src/widgets/framework.dart @@ -662,6 +662,12 @@ class _InactiveElements { } } +/// Signature for the callback to [BuildContext.visitChildElements]. +/// +/// The argument is the child being visited. +/// +/// It is safe to call `element.visitChildElements` reentrantly within +/// this callback. typedef void ElementVisitor(Element element); abstract class BuildContext { @@ -672,7 +678,7 @@ abstract class BuildContext { State ancestorStateOfType(TypeMatcher matcher); RenderObject ancestorRenderObjectOfType(TypeMatcher matcher); void visitAncestorElements(bool visitor(Element element)); - void visitChildElements(void visitor(Element element)); + void visitChildElements(ElementVisitor visitor); } class BuildOwner { @@ -688,8 +694,32 @@ class BuildOwner { /// Adds an element to the dirty elements list so that it will be rebuilt /// when buildDirtyElements is called. void scheduleBuildFor(BuildableElement element) { - assert(!_dirtyElements.contains(element)); - assert(element.dirty); + assert(() { + if (_dirtyElements.contains(element)) { + throw new FlutterError( + 'scheduleBuildFor() called for a widget for which a build was already scheduled.\n' + 'The method was invoked for the following element:\n' + ' $element\n' + 'The current dirty list consists of:\n' + ' $_dirtyElements\n' + 'This should not be possible and probably indicates a bug in the widgets framework. ' + 'Please report it: https://github.com/flutter/flutter/issues/new' + ); + } + if (!element.dirty) { + throw new FlutterError( + 'scheduleBuildFor() called for a widget that is not marked as dirty.\n' + 'The method was invoked for the following element:\n' + ' $element\n' + 'This element is not current marked as dirty. Make sure to set the dirty flag before ' + 'calling scheduleBuildFor().\n' + 'If you did not attempt to call scheduleBuildFor() yourself, then this probably ' + 'indicates a bug in the widgets framework. Please report it: ' + 'https://github.com/flutter/flutter/issues/new' + ); + } + return true; + }); if (_dirtyElements.isEmpty && onBuildScheduled != null) onBuildScheduled(); _dirtyElements.add(element); diff --git a/packages/flutter/test/foundation/caching_iterable_test.dart b/packages/flutter/test/foundation/caching_iterable_test.dart new file mode 100644 index 0000000000..f935b37154 --- /dev/null +++ b/packages/flutter/test/foundation/caching_iterable_test.dart @@ -0,0 +1,75 @@ +// 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/foundation.dart'; +import 'package:test/test.dart'; + +int yieldCount; + +Iterable range(int start, int end) sync* { + assert(yieldCount == 0); + for (int index = start; index <= end; index += 1) { + yieldCount += 1; + yield index; + } + } + +void main() { + setUp(() { + yieldCount = 0; + }); + + test("The Caching Iterable: length caches", () { + Iterable i = new CachingIterable(range(1, 5).iterator); + expect(yieldCount, equals(0)); + expect(i.length, equals(5)); + expect(yieldCount, equals(5)); + + expect(i.length, equals(5)); + expect(yieldCount, equals(5)); + + expect(i.last, equals(5)); + expect(yieldCount, equals(5)); + + expect(i, equals([1, 2, 3, 4, 5])); + expect(yieldCount, equals(5)); + }); + + test("The Caching Iterable: laziness", () { + Iterable i = new CachingIterable(range(1, 5).iterator); + expect(yieldCount, equals(0)); + + expect(i.first, equals(1)); + expect(yieldCount, equals(1)); + + expect(i.firstWhere((int i) => i == 3), equals(3)); + expect(yieldCount, equals(3)); + + expect(i.last, equals(5)); + expect(yieldCount, equals(5)); + }); + + test("The Caching Iterable: where and map", () { + Iterable integers = new CachingIterable(range(1, 5).iterator); + expect(yieldCount, equals(0)); + + Iterable evens = integers.where((int i) => i % 2 == 0); + expect(yieldCount, equals(0)); + + expect(evens.first, equals(2)); + expect(yieldCount, equals(2)); + + expect(integers.first, equals(1)); + expect(yieldCount, equals(2)); + + expect(evens.map((int i) => i + 1), equals([3, 5])); + expect(yieldCount, equals(5)); + + expect(evens, equals([2, 4])); + expect(yieldCount, equals(5)); + + expect(integers, equals([1, 2, 3, 4, 5])); + expect(yieldCount, equals(5)); + }); +} diff --git a/packages/flutter/test/material/progress_indicator_test.dart b/packages/flutter/test/material/progress_indicator_test.dart index 8455921d2f..6be3e23677 100644 --- a/packages/flutter/test/material/progress_indicator_test.dart +++ b/packages/flutter/test/material/progress_indicator_test.dart @@ -12,59 +12,49 @@ void main() { // The "can be constructed" tests that follow are primarily to ensure that any // animations started by the progress indicators are stopped at dispose() time. - test('LinearProgressIndicator(value: 0.0) can be constructed', () { - testWidgets((WidgetTester tester) { - tester.pumpWidget( - new Center( - child: new SizedBox( - width: 200.0, - child: new LinearProgressIndicator(value: 0.0) - ) + testWidgets('LinearProgressIndicator(value: 0.0) can be constructed', (WidgetTester tester) { + tester.pumpWidget( + new Center( + child: new SizedBox( + width: 200.0, + child: new LinearProgressIndicator(value: 0.0) ) - ); - }); + ) + ); }); - test('LinearProgressIndicator(value: null) can be constructed', () { - testWidgets((WidgetTester tester) { - tester.pumpWidget( - new Center( - child: new SizedBox( - width: 200.0, - child: new LinearProgressIndicator(value: null) - ) + testWidgets('LinearProgressIndicator(value: null) can be constructed', (WidgetTester tester) { + tester.pumpWidget( + new Center( + child: new SizedBox( + width: 200.0, + child: new LinearProgressIndicator(value: null) ) - ); - }); + ) + ); }); - test('CircularProgressIndicator(value: 0.0) can be constructed', () { - testWidgets((WidgetTester tester) { - tester.pumpWidget( - new Center( - child: new CircularProgressIndicator(value: 0.0) - ) - ); - }); + testWidgets('CircularProgressIndicator(value: 0.0) can be constructed', (WidgetTester tester) { + tester.pumpWidget( + new Center( + child: new CircularProgressIndicator(value: 0.0) + ) + ); }); - test('CircularProgressIndicator(value: null) can be constructed', () { - testWidgets((WidgetTester tester) { - tester.pumpWidget( - new Center( - child: new CircularProgressIndicator(value: null) - ) - ); - }); + testWidgets('CircularProgressIndicator(value: null) can be constructed', (WidgetTester tester) { + tester.pumpWidget( + new Center( + child: new CircularProgressIndicator(value: null) + ) + ); }); - test('LinearProgressIndicator changes when its value changes', () { - testElementTree((ElementTreeTester tester) { - tester.pumpWidget(new Block(children: [new LinearProgressIndicator(value: 0.0)])); - List layers1 = tester.layers; - tester.pumpWidget(new Block(children: [new LinearProgressIndicator(value: 0.5)])); - List layers2 = tester.layers; - expect(layers1, isNot(equals(layers2))); - }); + testWidgets('LinearProgressIndicator causes a repaint when it changes', (WidgetTester tester) { + tester.pumpWidget(new Block(children: [new LinearProgressIndicator(value: 0.0)])); + List layers1 = tester.layers; + tester.pumpWidget(new Block(children: [new LinearProgressIndicator(value: 0.5)])); + List layers2 = tester.layers; + expect(layers1, isNot(equals(layers2))); }); } diff --git a/packages/flutter/test/material/refresh_indicator_test.dart b/packages/flutter/test/material/refresh_indicator_test.dart index 90f09887ba..fb5cfbb95d 100644 --- a/packages/flutter/test/material/refresh_indicator_test.dart +++ b/packages/flutter/test/material/refresh_indicator_test.dart @@ -17,28 +17,26 @@ void main() { return new Future.value(); } - test('RefreshIndicator', () { - testWidgets((WidgetTester tester) { - tester.pumpWidget( - new RefreshIndicator( - refresh: refresh, - child: new Block( - children: ['A', 'B', 'C', 'D', 'E', 'F'].map((String item) { - return new SizedBox( - height: 200.0, - child: new Text(item) - ); - }).toList() - ) + testWidgets('RefreshIndicator', (WidgetTester tester) { + tester.pumpWidget( + new RefreshIndicator( + refresh: refresh, + child: new Block( + children: ['A', 'B', 'C', 'D', 'E', 'F'].map((String item) { + return new SizedBox( + height: 200.0, + child: new Text(item) + ); + }).toList() ) - ); + ) + ); - tester.fling(find.text('A'), const Offset(0.0, 200.0), -1000.0); - tester.pump(); - tester.pump(const Duration(seconds: 1)); // finish the scroll animation - tester.pump(const Duration(seconds: 1)); // finish the indicator settle animation - tester.pump(const Duration(seconds: 1)); // finish the indicator hide animation - expect(refreshCalled, true); - }); + tester.fling(find.text('A'), const Offset(0.0, 200.0), -1000.0); + tester.pump(); + tester.pump(const Duration(seconds: 1)); // finish the scroll animation + tester.pump(const Duration(seconds: 1)); // finish the indicator settle animation + tester.pump(const Duration(seconds: 1)); // finish the indicator hide animation + expect(refreshCalled, true); }); } diff --git a/packages/flutter/test/material/scaffold_test.dart b/packages/flutter/test/material/scaffold_test.dart index 76a8118330..fdd414890f 100644 --- a/packages/flutter/test/material/scaffold_test.dart +++ b/packages/flutter/test/material/scaffold_test.dart @@ -8,39 +8,37 @@ import 'package:flutter/rendering.dart'; import 'package:test/test.dart'; void main() { - test('Scaffold control test', () { - testWidgets((WidgetTester tester) { - Key bodyKey = new UniqueKey(); - tester.pumpWidget(new Scaffold( + testWidgets('Scaffold control test', (WidgetTester tester) { + Key bodyKey = new UniqueKey(); + tester.pumpWidget(new Scaffold( + appBar: new AppBar(title: new Text('Title')), + body: new Container(key: bodyKey) + )); + + RenderBox bodyBox = tester.renderObject(find.byKey(bodyKey)); + expect(bodyBox.size, equals(new Size(800.0, 544.0))); + + tester.pumpWidget(new MediaQuery( + data: new MediaQueryData(padding: new EdgeInsets.only(bottom: 100.0)), + child: new Scaffold( appBar: new AppBar(title: new Text('Title')), body: new Container(key: bodyKey) - )); + ) + )); - RenderBox bodyBox = tester.renderObjectOf(find.byKey(bodyKey)); - expect(bodyBox.size, equals(new Size(800.0, 544.0))); + bodyBox = tester.renderObject(find.byKey(bodyKey)); + expect(bodyBox.size, equals(new Size(800.0, 444.0))); - tester.pumpWidget(new MediaQuery( - data: new MediaQueryData(padding: new EdgeInsets.only(bottom: 100.0)), - child: new Scaffold( - appBar: new AppBar(title: new Text('Title')), - body: new Container(key: bodyKey) - ) - )); + tester.pumpWidget(new MediaQuery( + data: new MediaQueryData(padding: new EdgeInsets.only(bottom: 100.0)), + child: new Scaffold( + appBar: new AppBar(title: new Text('Title')), + body: new Container(key: bodyKey), + resizeToAvoidBottomPadding: false + ) + )); - bodyBox = tester.renderObjectOf(find.byKey(bodyKey)); - expect(bodyBox.size, equals(new Size(800.0, 444.0))); - - tester.pumpWidget(new MediaQuery( - data: new MediaQueryData(padding: new EdgeInsets.only(bottom: 100.0)), - child: new Scaffold( - appBar: new AppBar(title: new Text('Title')), - body: new Container(key: bodyKey), - resizeToAvoidBottomPadding: false - ) - )); - - bodyBox = tester.renderObjectOf(find.byKey(bodyKey)); - expect(bodyBox.size, equals(new Size(800.0, 544.0))); - }); + bodyBox = tester.renderObject(find.byKey(bodyKey)); + expect(bodyBox.size, equals(new Size(800.0, 544.0))); }); } diff --git a/packages/flutter/test/material/slider_test.dart b/packages/flutter/test/material/slider_test.dart index dff81b566a..ea5f181b84 100644 --- a/packages/flutter/test/material/slider_test.dart +++ b/packages/flutter/test/material/slider_test.dart @@ -8,83 +8,79 @@ import 'package:flutter_test/flutter_test.dart'; import 'package:test/test.dart'; void main() { - test('Slider can move when tapped', () { - testWidgets((WidgetTester tester) { - Key sliderKey = new UniqueKey(); - double value = 0.0; + testWidgets('Slider can move when tapped', (WidgetTester tester) { + Key sliderKey = new UniqueKey(); + double value = 0.0; - tester.pumpWidget( - new StatefulBuilder( - builder: (BuildContext context, StateSetter setState) { - return new Material( - child: new Center( - child: new Slider( - key: sliderKey, - value: value, - onChanged: (double newValue) { - setState(() { - value = newValue; - }); - } - ) + tester.pumpWidget( + new StatefulBuilder( + builder: (BuildContext context, StateSetter setState) { + return new Material( + child: new Center( + child: new Slider( + key: sliderKey, + value: value, + onChanged: (double newValue) { + setState(() { + value = newValue; + }); + } ) - ); - } - ) - ); + ) + ); + } + ) + ); - expect(value, equals(0.0)); - tester.tap(find.byKey(sliderKey)); - expect(value, equals(0.5)); - tester.pump(); // No animation should start. - expect(SchedulerBinding.instance.transientCallbackCount, equals(0)); - }); + expect(value, equals(0.0)); + tester.tap(find.byKey(sliderKey)); + expect(value, equals(0.5)); + tester.pump(); // No animation should start. + expect(SchedulerBinding.instance.transientCallbackCount, equals(0)); }); - test('Slider take on discrete values', () { - testWidgets((WidgetTester tester) { - Key sliderKey = new UniqueKey(); - double value = 0.0; + testWidgets('Slider take on discrete values', (WidgetTester tester) { + Key sliderKey = new UniqueKey(); + double value = 0.0; - tester.pumpWidget( - new StatefulBuilder( - builder: (BuildContext context, StateSetter setState) { - return new Material( - child: new Center( - child: new Slider( - key: sliderKey, - min: 0.0, - max: 100.0, - divisions: 10, - value: value, - onChanged: (double newValue) { - setState(() { - value = newValue; - }); - } - ) + tester.pumpWidget( + new StatefulBuilder( + builder: (BuildContext context, StateSetter setState) { + return new Material( + child: new Center( + child: new Slider( + key: sliderKey, + min: 0.0, + max: 100.0, + divisions: 10, + value: value, + onChanged: (double newValue) { + setState(() { + value = newValue; + }); + } ) - ); - } - ) - ); + ) + ); + } + ) + ); - expect(value, equals(0.0)); - tester.tap(find.byKey(sliderKey)); - expect(value, equals(50.0)); - tester.scroll(find.byKey(sliderKey), const Offset(5.0, 0.0)); - expect(value, equals(50.0)); - tester.scroll(find.byKey(sliderKey), const Offset(40.0, 0.0)); - expect(value, equals(80.0)); + expect(value, equals(0.0)); + tester.tap(find.byKey(sliderKey)); + expect(value, equals(50.0)); + tester.scroll(find.byKey(sliderKey), const Offset(5.0, 0.0)); + expect(value, equals(50.0)); + tester.scroll(find.byKey(sliderKey), const Offset(40.0, 0.0)); + expect(value, equals(80.0)); - tester.pump(); // Starts animation. - expect(SchedulerBinding.instance.transientCallbackCount, greaterThan(0)); - tester.pump(const Duration(milliseconds: 200)); - tester.pump(const Duration(milliseconds: 200)); - tester.pump(const Duration(milliseconds: 200)); - tester.pump(const Duration(milliseconds: 200)); - // Animation complete. - expect(SchedulerBinding.instance.transientCallbackCount, equals(0)); - }); + tester.pump(); // Starts animation. + expect(SchedulerBinding.instance.transientCallbackCount, greaterThan(0)); + tester.pump(const Duration(milliseconds: 200)); + tester.pump(const Duration(milliseconds: 200)); + tester.pump(const Duration(milliseconds: 200)); + tester.pump(const Duration(milliseconds: 200)); + // Animation complete. + expect(SchedulerBinding.instance.transientCallbackCount, equals(0)); }); } diff --git a/packages/flutter/test/material/snack_bar_test.dart b/packages/flutter/test/material/snack_bar_test.dart index 196bcc5895..c28da981fc 100644 --- a/packages/flutter/test/material/snack_bar_test.dart +++ b/packages/flutter/test/material/snack_bar_test.dart @@ -7,303 +7,293 @@ import 'package:flutter/material.dart'; import 'package:test/test.dart'; void main() { - test('SnackBar control test', () { - testWidgets((WidgetTester tester) { - String helloSnackBar = 'Hello SnackBar'; - Key tapTarget = new Key('tap-target'); - tester.pumpWidget(new MaterialApp( - home: new Scaffold( - body: new Builder( - builder: (BuildContext context) { - return new GestureDetector( - onTap: () { - Scaffold.of(context).showSnackBar(new SnackBar( - content: new Text(helloSnackBar), - duration: new Duration(seconds: 2) - )); - }, - behavior: HitTestBehavior.opaque, - child: new Container( - height: 100.0, - width: 100.0, - key: tapTarget - ) - ); - } - ) + testWidgets('SnackBar control test', (WidgetTester tester) { + String helloSnackBar = 'Hello SnackBar'; + Key tapTarget = new Key('tap-target'); + tester.pumpWidget(new MaterialApp( + home: new Scaffold( + body: new Builder( + builder: (BuildContext context) { + return new GestureDetector( + onTap: () { + Scaffold.of(context).showSnackBar(new SnackBar( + content: new Text(helloSnackBar), + duration: new Duration(seconds: 2) + )); + }, + behavior: HitTestBehavior.opaque, + child: new Container( + height: 100.0, + width: 100.0, + key: tapTarget + ) + ); + } ) - )); - expect(tester, doesNotHaveWidget(find.text(helloSnackBar))); - tester.tap(find.byKey(tapTarget)); - expect(tester, doesNotHaveWidget(find.text(helloSnackBar))); - tester.pump(); // schedule animation - expect(tester, hasWidget(find.text(helloSnackBar))); - tester.pump(); // begin animation - expect(tester, hasWidget(find.text(helloSnackBar))); - tester.pump(new Duration(milliseconds: 750)); // 0.75s // animation last frame; two second timer starts here - expect(tester, hasWidget(find.text(helloSnackBar))); - tester.pump(new Duration(milliseconds: 750)); // 1.50s - expect(tester, hasWidget(find.text(helloSnackBar))); - tester.pump(new Duration(milliseconds: 750)); // 2.25s - expect(tester, hasWidget(find.text(helloSnackBar))); - tester.pump(new Duration(milliseconds: 750)); // 3.00s // timer triggers to dismiss snackbar, reverse animation is scheduled - tester.pump(); // begin animation - expect(tester, hasWidget(find.text(helloSnackBar))); // frame 0 of dismiss animation - tester.pump(new Duration(milliseconds: 750)); // 3.75s // last frame of animation, snackbar removed from build - expect(tester, doesNotHaveWidget(find.text(helloSnackBar))); - }); + ) + )); + expect(find.text(helloSnackBar), findsNothing); + tester.tap(find.byKey(tapTarget)); + expect(find.text(helloSnackBar), findsNothing); + tester.pump(); // schedule animation + expect(find.text(helloSnackBar), findsOneWidget); + tester.pump(); // begin animation + expect(find.text(helloSnackBar), findsOneWidget); + tester.pump(new Duration(milliseconds: 750)); // 0.75s // animation last frame; two second timer starts here + expect(find.text(helloSnackBar), findsOneWidget); + tester.pump(new Duration(milliseconds: 750)); // 1.50s + expect(find.text(helloSnackBar), findsOneWidget); + tester.pump(new Duration(milliseconds: 750)); // 2.25s + expect(find.text(helloSnackBar), findsOneWidget); + tester.pump(new Duration(milliseconds: 750)); // 3.00s // timer triggers to dismiss snackbar, reverse animation is scheduled + tester.pump(); // begin animation + expect(find.text(helloSnackBar), findsOneWidget); // frame 0 of dismiss animation + tester.pump(new Duration(milliseconds: 750)); // 3.75s // last frame of animation, snackbar removed from build + expect(find.text(helloSnackBar), findsNothing); }); - test('SnackBar twice test', () { - testWidgets((WidgetTester tester) { - int snackBarCount = 0; - Key tapTarget = new Key('tap-target'); - tester.pumpWidget(new MaterialApp( - home: new Scaffold( - body: new Builder( - builder: (BuildContext context) { - return new GestureDetector( - onTap: () { - snackBarCount += 1; - Scaffold.of(context).showSnackBar(new SnackBar( - content: new Text("bar$snackBarCount"), - duration: new Duration(seconds: 2) - )); - }, - behavior: HitTestBehavior.opaque, - child: new Container( - height: 100.0, - width: 100.0, - key: tapTarget - ) - ); - } - ) + testWidgets('SnackBar twice test', (WidgetTester tester) { + int snackBarCount = 0; + Key tapTarget = new Key('tap-target'); + tester.pumpWidget(new MaterialApp( + home: new Scaffold( + body: new Builder( + builder: (BuildContext context) { + return new GestureDetector( + onTap: () { + snackBarCount += 1; + Scaffold.of(context).showSnackBar(new SnackBar( + content: new Text("bar$snackBarCount"), + duration: new Duration(seconds: 2) + )); + }, + behavior: HitTestBehavior.opaque, + child: new Container( + height: 100.0, + width: 100.0, + key: tapTarget + ) + ); + } ) - )); - expect(tester, doesNotHaveWidget(find.text('bar1'))); - expect(tester, doesNotHaveWidget(find.text('bar2'))); - tester.tap(find.byKey(tapTarget)); // queue bar1 - tester.tap(find.byKey(tapTarget)); // queue bar2 - expect(tester, doesNotHaveWidget(find.text('bar1'))); - expect(tester, doesNotHaveWidget(find.text('bar2'))); - tester.pump(); // schedule animation for bar1 - expect(tester, hasWidget(find.text('bar1'))); - expect(tester, doesNotHaveWidget(find.text('bar2'))); - tester.pump(); // begin animation - expect(tester, hasWidget(find.text('bar1'))); - expect(tester, doesNotHaveWidget(find.text('bar2'))); - tester.pump(new Duration(milliseconds: 750)); // 0.75s // animation last frame; two second timer starts here - expect(tester, hasWidget(find.text('bar1'))); - expect(tester, doesNotHaveWidget(find.text('bar2'))); - tester.pump(new Duration(milliseconds: 750)); // 1.50s - expect(tester, hasWidget(find.text('bar1'))); - expect(tester, doesNotHaveWidget(find.text('bar2'))); - tester.pump(new Duration(milliseconds: 750)); // 2.25s - expect(tester, hasWidget(find.text('bar1'))); - expect(tester, doesNotHaveWidget(find.text('bar2'))); - tester.pump(new Duration(milliseconds: 750)); // 3.00s // timer triggers to dismiss snackbar, reverse animation is scheduled - tester.pump(); // begin animation - expect(tester, hasWidget(find.text('bar1'))); - expect(tester, doesNotHaveWidget(find.text('bar2'))); - tester.pump(new Duration(milliseconds: 750)); // 3.75s // last frame of animation, snackbar removed from build, new snack bar put in its place - expect(tester, doesNotHaveWidget(find.text('bar1'))); - expect(tester, hasWidget(find.text('bar2'))); - tester.pump(); // begin animation - expect(tester, doesNotHaveWidget(find.text('bar1'))); - expect(tester, hasWidget(find.text('bar2'))); - tester.pump(new Duration(milliseconds: 750)); // 4.50s // animation last frame; two second timer starts here - expect(tester, doesNotHaveWidget(find.text('bar1'))); - expect(tester, hasWidget(find.text('bar2'))); - tester.pump(new Duration(milliseconds: 750)); // 5.25s - expect(tester, doesNotHaveWidget(find.text('bar1'))); - expect(tester, hasWidget(find.text('bar2'))); - tester.pump(new Duration(milliseconds: 750)); // 6.00s - expect(tester, doesNotHaveWidget(find.text('bar1'))); - expect(tester, hasWidget(find.text('bar2'))); - tester.pump(new Duration(milliseconds: 750)); // 6.75s // timer triggers to dismiss snackbar, reverse animation is scheduled - tester.pump(); // begin animation - expect(tester, doesNotHaveWidget(find.text('bar1'))); - expect(tester, hasWidget(find.text('bar2'))); - tester.pump(new Duration(milliseconds: 750)); // 7.50s // last frame of animation, snackbar removed from build, new snack bar put in its place - expect(tester, doesNotHaveWidget(find.text('bar1'))); - expect(tester, doesNotHaveWidget(find.text('bar2'))); - }); + ) + )); + expect(find.text('bar1'), findsNothing); + expect(find.text('bar2'), findsNothing); + tester.tap(find.byKey(tapTarget)); // queue bar1 + tester.tap(find.byKey(tapTarget)); // queue bar2 + expect(find.text('bar1'), findsNothing); + expect(find.text('bar2'), findsNothing); + tester.pump(); // schedule animation for bar1 + expect(find.text('bar1'), findsOneWidget); + expect(find.text('bar2'), findsNothing); + tester.pump(); // begin animation + expect(find.text('bar1'), findsOneWidget); + expect(find.text('bar2'), findsNothing); + tester.pump(new Duration(milliseconds: 750)); // 0.75s // animation last frame; two second timer starts here + expect(find.text('bar1'), findsOneWidget); + expect(find.text('bar2'), findsNothing); + tester.pump(new Duration(milliseconds: 750)); // 1.50s + expect(find.text('bar1'), findsOneWidget); + expect(find.text('bar2'), findsNothing); + tester.pump(new Duration(milliseconds: 750)); // 2.25s + expect(find.text('bar1'), findsOneWidget); + expect(find.text('bar2'), findsNothing); + tester.pump(new Duration(milliseconds: 750)); // 3.00s // timer triggers to dismiss snackbar, reverse animation is scheduled + tester.pump(); // begin animation + expect(find.text('bar1'), findsOneWidget); + expect(find.text('bar2'), findsNothing); + tester.pump(new Duration(milliseconds: 750)); // 3.75s // last frame of animation, snackbar removed from build, new snack bar put in its place + expect(find.text('bar1'), findsNothing); + expect(find.text('bar2'), findsOneWidget); + tester.pump(); // begin animation + expect(find.text('bar1'), findsNothing); + expect(find.text('bar2'), findsOneWidget); + tester.pump(new Duration(milliseconds: 750)); // 4.50s // animation last frame; two second timer starts here + expect(find.text('bar1'), findsNothing); + expect(find.text('bar2'), findsOneWidget); + tester.pump(new Duration(milliseconds: 750)); // 5.25s + expect(find.text('bar1'), findsNothing); + expect(find.text('bar2'), findsOneWidget); + tester.pump(new Duration(milliseconds: 750)); // 6.00s + expect(find.text('bar1'), findsNothing); + expect(find.text('bar2'), findsOneWidget); + tester.pump(new Duration(milliseconds: 750)); // 6.75s // timer triggers to dismiss snackbar, reverse animation is scheduled + tester.pump(); // begin animation + expect(find.text('bar1'), findsNothing); + expect(find.text('bar2'), findsOneWidget); + tester.pump(new Duration(milliseconds: 750)); // 7.50s // last frame of animation, snackbar removed from build, new snack bar put in its place + expect(find.text('bar1'), findsNothing); + expect(find.text('bar2'), findsNothing); }); - test('SnackBar cancel test', () { - testWidgets((WidgetTester tester) { - int snackBarCount = 0; - Key tapTarget = new Key('tap-target'); - int time; - ScaffoldFeatureController lastController; - tester.pumpWidget(new MaterialApp( - home: new Scaffold( - body: new Builder( - builder: (BuildContext context) { - return new GestureDetector( - onTap: () { - snackBarCount += 1; - lastController = Scaffold.of(context).showSnackBar(new SnackBar( - content: new Text("bar$snackBarCount"), - duration: new Duration(seconds: time) - )); - }, - behavior: HitTestBehavior.opaque, - child: new Container( - height: 100.0, - width: 100.0, - key: tapTarget - ) - ); - } - ) + testWidgets('SnackBar cancel test', (WidgetTester tester) { + int snackBarCount = 0; + Key tapTarget = new Key('tap-target'); + int time; + ScaffoldFeatureController lastController; + tester.pumpWidget(new MaterialApp( + home: new Scaffold( + body: new Builder( + builder: (BuildContext context) { + return new GestureDetector( + onTap: () { + snackBarCount += 1; + lastController = Scaffold.of(context).showSnackBar(new SnackBar( + content: new Text("bar$snackBarCount"), + duration: new Duration(seconds: time) + )); + }, + behavior: HitTestBehavior.opaque, + child: new Container( + height: 100.0, + width: 100.0, + key: tapTarget + ) + ); + } ) - )); - expect(tester, doesNotHaveWidget(find.text('bar1'))); - expect(tester, doesNotHaveWidget(find.text('bar2'))); - time = 1000; - tester.tap(find.byKey(tapTarget)); // queue bar1 - ScaffoldFeatureController firstController = lastController; - time = 2; - tester.tap(find.byKey(tapTarget)); // queue bar2 - expect(tester, doesNotHaveWidget(find.text('bar1'))); - expect(tester, doesNotHaveWidget(find.text('bar2'))); - tester.pump(); // schedule animation for bar1 - expect(tester, hasWidget(find.text('bar1'))); - expect(tester, doesNotHaveWidget(find.text('bar2'))); - tester.pump(); // begin animation - expect(tester, hasWidget(find.text('bar1'))); - expect(tester, doesNotHaveWidget(find.text('bar2'))); - tester.pump(new Duration(milliseconds: 750)); // 0.75s // animation last frame; two second timer starts here - expect(tester, hasWidget(find.text('bar1'))); - expect(tester, doesNotHaveWidget(find.text('bar2'))); - tester.pump(new Duration(milliseconds: 750)); // 1.50s - expect(tester, hasWidget(find.text('bar1'))); - expect(tester, doesNotHaveWidget(find.text('bar2'))); - tester.pump(new Duration(milliseconds: 750)); // 2.25s - expect(tester, hasWidget(find.text('bar1'))); - expect(tester, doesNotHaveWidget(find.text('bar2'))); - tester.pump(new Duration(milliseconds: 10000)); // 12.25s - expect(tester, hasWidget(find.text('bar1'))); - expect(tester, doesNotHaveWidget(find.text('bar2'))); + ) + )); + expect(find.text('bar1'), findsNothing); + expect(find.text('bar2'), findsNothing); + time = 1000; + tester.tap(find.byKey(tapTarget)); // queue bar1 + ScaffoldFeatureController firstController = lastController; + time = 2; + tester.tap(find.byKey(tapTarget)); // queue bar2 + expect(find.text('bar1'), findsNothing); + expect(find.text('bar2'), findsNothing); + tester.pump(); // schedule animation for bar1 + expect(find.text('bar1'), findsOneWidget); + expect(find.text('bar2'), findsNothing); + tester.pump(); // begin animation + expect(find.text('bar1'), findsOneWidget); + expect(find.text('bar2'), findsNothing); + tester.pump(new Duration(milliseconds: 750)); // 0.75s // animation last frame; two second timer starts here + expect(find.text('bar1'), findsOneWidget); + expect(find.text('bar2'), findsNothing); + tester.pump(new Duration(milliseconds: 750)); // 1.50s + expect(find.text('bar1'), findsOneWidget); + expect(find.text('bar2'), findsNothing); + tester.pump(new Duration(milliseconds: 750)); // 2.25s + expect(find.text('bar1'), findsOneWidget); + expect(find.text('bar2'), findsNothing); + tester.pump(new Duration(milliseconds: 10000)); // 12.25s + expect(find.text('bar1'), findsOneWidget); + expect(find.text('bar2'), findsNothing); - firstController.close(); // snackbar is manually dismissed + firstController.close(); // snackbar is manually dismissed - tester.pump(new Duration(milliseconds: 750)); // 13.00s // reverse animation is scheduled - tester.pump(); // begin animation - expect(tester, hasWidget(find.text('bar1'))); - expect(tester, doesNotHaveWidget(find.text('bar2'))); - tester.pump(new Duration(milliseconds: 750)); // 13.75s // last frame of animation, snackbar removed from build, new snack bar put in its place - expect(tester, doesNotHaveWidget(find.text('bar1'))); - expect(tester, hasWidget(find.text('bar2'))); - tester.pump(); // begin animation - expect(tester, doesNotHaveWidget(find.text('bar1'))); - expect(tester, hasWidget(find.text('bar2'))); - tester.pump(new Duration(milliseconds: 750)); // 14.50s // animation last frame; two second timer starts here - expect(tester, doesNotHaveWidget(find.text('bar1'))); - expect(tester, hasWidget(find.text('bar2'))); - tester.pump(new Duration(milliseconds: 750)); // 15.25s - expect(tester, doesNotHaveWidget(find.text('bar1'))); - expect(tester, hasWidget(find.text('bar2'))); - tester.pump(new Duration(milliseconds: 750)); // 16.00s - expect(tester, doesNotHaveWidget(find.text('bar1'))); - expect(tester, hasWidget(find.text('bar2'))); - tester.pump(new Duration(milliseconds: 750)); // 16.75s // timer triggers to dismiss snackbar, reverse animation is scheduled - tester.pump(); // begin animation - expect(tester, doesNotHaveWidget(find.text('bar1'))); - expect(tester, hasWidget(find.text('bar2'))); - tester.pump(new Duration(milliseconds: 750)); // 17.50s // last frame of animation, snackbar removed from build, new snack bar put in its place - expect(tester, doesNotHaveWidget(find.text('bar1'))); - expect(tester, doesNotHaveWidget(find.text('bar2'))); - }); + tester.pump(new Duration(milliseconds: 750)); // 13.00s // reverse animation is scheduled + tester.pump(); // begin animation + expect(find.text('bar1'), findsOneWidget); + expect(find.text('bar2'), findsNothing); + tester.pump(new Duration(milliseconds: 750)); // 13.75s // last frame of animation, snackbar removed from build, new snack bar put in its place + expect(find.text('bar1'), findsNothing); + expect(find.text('bar2'), findsOneWidget); + tester.pump(); // begin animation + expect(find.text('bar1'), findsNothing); + expect(find.text('bar2'), findsOneWidget); + tester.pump(new Duration(milliseconds: 750)); // 14.50s // animation last frame; two second timer starts here + expect(find.text('bar1'), findsNothing); + expect(find.text('bar2'), findsOneWidget); + tester.pump(new Duration(milliseconds: 750)); // 15.25s + expect(find.text('bar1'), findsNothing); + expect(find.text('bar2'), findsOneWidget); + tester.pump(new Duration(milliseconds: 750)); // 16.00s + expect(find.text('bar1'), findsNothing); + expect(find.text('bar2'), findsOneWidget); + tester.pump(new Duration(milliseconds: 750)); // 16.75s // timer triggers to dismiss snackbar, reverse animation is scheduled + tester.pump(); // begin animation + expect(find.text('bar1'), findsNothing); + expect(find.text('bar2'), findsOneWidget); + tester.pump(new Duration(milliseconds: 750)); // 17.50s // last frame of animation, snackbar removed from build, new snack bar put in its place + expect(find.text('bar1'), findsNothing); + expect(find.text('bar2'), findsNothing); }); - test('SnackBar dismiss test', () { - testWidgets((WidgetTester tester) { - int snackBarCount = 0; - Key tapTarget = new Key('tap-target'); - tester.pumpWidget(new MaterialApp( - home: new Scaffold( - body: new Builder( - builder: (BuildContext context) { - return new GestureDetector( - onTap: () { - snackBarCount += 1; - Scaffold.of(context).showSnackBar(new SnackBar( - content: new Text("bar$snackBarCount"), - duration: new Duration(seconds: 2) - )); - }, - behavior: HitTestBehavior.opaque, - child: new Container( - height: 100.0, - width: 100.0, - key: tapTarget - ) - ); - } - ) + testWidgets('SnackBar dismiss test', (WidgetTester tester) { + int snackBarCount = 0; + Key tapTarget = new Key('tap-target'); + tester.pumpWidget(new MaterialApp( + home: new Scaffold( + body: new Builder( + builder: (BuildContext context) { + return new GestureDetector( + onTap: () { + snackBarCount += 1; + Scaffold.of(context).showSnackBar(new SnackBar( + content: new Text("bar$snackBarCount"), + duration: new Duration(seconds: 2) + )); + }, + behavior: HitTestBehavior.opaque, + child: new Container( + height: 100.0, + width: 100.0, + key: tapTarget + ) + ); + } ) - )); - expect(tester, doesNotHaveWidget(find.text('bar1'))); - expect(tester, doesNotHaveWidget(find.text('bar2'))); - tester.tap(find.byKey(tapTarget)); // queue bar1 - tester.tap(find.byKey(tapTarget)); // queue bar2 - expect(tester, doesNotHaveWidget(find.text('bar1'))); - expect(tester, doesNotHaveWidget(find.text('bar2'))); - tester.pump(); // schedule animation for bar1 - expect(tester, hasWidget(find.text('bar1'))); - expect(tester, doesNotHaveWidget(find.text('bar2'))); - tester.pump(); // begin animation - expect(tester, hasWidget(find.text('bar1'))); - expect(tester, doesNotHaveWidget(find.text('bar2'))); - tester.pump(new Duration(milliseconds: 750)); // 0.75s // animation last frame; two second timer starts here - tester.scroll(find.text('bar1'), new Offset(0.0, 50.0)); - tester.pump(); // bar1 dismissed, bar2 begins animating - expect(tester, doesNotHaveWidget(find.text('bar1'))); - expect(tester, hasWidget(find.text('bar2'))); - }); + ) + )); + expect(find.text('bar1'), findsNothing); + expect(find.text('bar2'), findsNothing); + tester.tap(find.byKey(tapTarget)); // queue bar1 + tester.tap(find.byKey(tapTarget)); // queue bar2 + expect(find.text('bar1'), findsNothing); + expect(find.text('bar2'), findsNothing); + tester.pump(); // schedule animation for bar1 + expect(find.text('bar1'), findsOneWidget); + expect(find.text('bar2'), findsNothing); + tester.pump(); // begin animation + expect(find.text('bar1'), findsOneWidget); + expect(find.text('bar2'), findsNothing); + tester.pump(new Duration(milliseconds: 750)); // 0.75s // animation last frame; two second timer starts here + tester.scroll(find.text('bar1'), new Offset(0.0, 50.0)); + tester.pump(); // bar1 dismissed, bar2 begins animating + expect(find.text('bar1'), findsNothing); + expect(find.text('bar2'), findsOneWidget); }); - test('SnackBar cannot be tapped twice', () { - testWidgets((WidgetTester tester) { - int tapCount = 0; - tester.pumpWidget(new MaterialApp( - home: new Scaffold( - body: new Builder( - builder: (BuildContext context) { - return new GestureDetector( - onTap: () { - Scaffold.of(context).showSnackBar(new SnackBar( - content: new Text('I am a snack bar.'), - duration: new Duration(seconds: 2), - action: new SnackBarAction( - label: 'ACTION', - onPressed: () { - ++tapCount; - } - ) - )); - }, - child: new Text('X') - ); - } - ) + testWidgets('SnackBar cannot be tapped twice', (WidgetTester tester) { + int tapCount = 0; + tester.pumpWidget(new MaterialApp( + home: new Scaffold( + body: new Builder( + builder: (BuildContext context) { + return new GestureDetector( + onTap: () { + Scaffold.of(context).showSnackBar(new SnackBar( + content: new Text('I am a snack bar.'), + duration: new Duration(seconds: 2), + action: new SnackBarAction( + label: 'ACTION', + onPressed: () { + ++tapCount; + } + ) + )); + }, + child: new Text('X') + ); + } ) - )); - tester.tap(find.text('X')); - tester.pump(); // start animation - tester.pump(const Duration(milliseconds: 750)); + ) + )); + tester.tap(find.text('X')); + tester.pump(); // start animation + tester.pump(const Duration(milliseconds: 750)); - expect(tapCount, equals(0)); - tester.tap(find.text('ACTION')); - expect(tapCount, equals(1)); - tester.tap(find.text('ACTION')); - expect(tapCount, equals(1)); - tester.pump(); - tester.tap(find.text('ACTION')); - expect(tapCount, equals(1)); - }); + expect(tapCount, equals(0)); + tester.tap(find.text('ACTION')); + expect(tapCount, equals(1)); + tester.tap(find.text('ACTION')); + expect(tapCount, equals(1)); + tester.pump(); + tester.tap(find.text('ACTION')); + expect(tapCount, equals(1)); }); } diff --git a/packages/flutter/test/material/tabs_test.dart b/packages/flutter/test/material/tabs_test.dart index 6b502be3bd..d394758422 100644 --- a/packages/flutter/test/material/tabs_test.dart +++ b/packages/flutter/test/material/tabs_test.dart @@ -42,200 +42,190 @@ Widget buildFrame({ List tabs, String value, bool isScrollable: false, K } void main() { - test('TabBar tap selects tab', () { - testWidgets((WidgetTester tester) { - List tabs = ['A', 'B', 'C']; + testWidgets('TabBar tap selects tab', (WidgetTester tester) { + List tabs = ['A', 'B', 'C']; - tester.pumpWidget(buildFrame(tabs: tabs, value: 'C', isScrollable: false)); - TabBarSelectionState selection = TabBarSelection.of(tester.elementTreeTester.findText('A')); - expect(selection, isNotNull); - expect(selection.indexOf('A'), equals(0)); - expect(selection.indexOf('B'), equals(1)); - expect(selection.indexOf('C'), equals(2)); - expect(tester, hasWidget(find.text('A'))); - expect(tester, hasWidget(find.text('B'))); - expect(tester, hasWidget(find.text('C'))); - expect(selection.index, equals(2)); - expect(selection.previousIndex, equals(2)); - expect(selection.value, equals('C')); - expect(selection.previousValue, equals('C')); + tester.pumpWidget(buildFrame(tabs: tabs, value: 'C', isScrollable: false)); + TabBarSelectionState selection = TabBarSelection.of(tester.element(find.text('A'))); + expect(selection, isNotNull); + expect(selection.indexOf('A'), equals(0)); + expect(selection.indexOf('B'), equals(1)); + expect(selection.indexOf('C'), equals(2)); + expect(find.text('A'), findsOneWidget); + expect(find.text('B'), findsOneWidget); + expect(find.text('C'), findsOneWidget); + expect(selection.index, equals(2)); + expect(selection.previousIndex, equals(2)); + expect(selection.value, equals('C')); + expect(selection.previousValue, equals('C')); - tester.pumpWidget(buildFrame(tabs: tabs, value: 'C' ,isScrollable: false)); - tester.tap(find.text('B')); - tester.pump(); - expect(selection.valueIsChanging, true); - tester.pump(const Duration(seconds: 1)); // finish the animation - expect(selection.valueIsChanging, false); - expect(selection.value, equals('B')); - expect(selection.previousValue, equals('C')); - expect(selection.index, equals(1)); - expect(selection.previousIndex, equals(2)); + tester.pumpWidget(buildFrame(tabs: tabs, value: 'C' ,isScrollable: false)); + tester.tap(find.text('B')); + tester.pump(); + expect(selection.valueIsChanging, true); + tester.pump(const Duration(seconds: 1)); // finish the animation + expect(selection.valueIsChanging, false); + expect(selection.value, equals('B')); + expect(selection.previousValue, equals('C')); + expect(selection.index, equals(1)); + expect(selection.previousIndex, equals(2)); - tester.pumpWidget(buildFrame(tabs: tabs, value: 'C', isScrollable: false)); - tester.tap(find.text('C')); - tester.pump(); - tester.pump(const Duration(seconds: 1)); - expect(selection.value, equals('C')); - expect(selection.previousValue, equals('B')); - expect(selection.index, equals(2)); - expect(selection.previousIndex, equals(1)); + tester.pumpWidget(buildFrame(tabs: tabs, value: 'C', isScrollable: false)); + tester.tap(find.text('C')); + tester.pump(); + tester.pump(const Duration(seconds: 1)); + expect(selection.value, equals('C')); + expect(selection.previousValue, equals('B')); + expect(selection.index, equals(2)); + expect(selection.previousIndex, equals(1)); - tester.pumpWidget(buildFrame(tabs: tabs, value: 'C', isScrollable: false)); - tester.tap(find.text('A')); - tester.pump(); - tester.pump(const Duration(seconds: 1)); - expect(selection.value, equals('A')); - expect(selection.previousValue, equals('C')); - expect(selection.index, equals(0)); - expect(selection.previousIndex, equals(2)); - }); + tester.pumpWidget(buildFrame(tabs: tabs, value: 'C', isScrollable: false)); + tester.tap(find.text('A')); + tester.pump(); + tester.pump(const Duration(seconds: 1)); + expect(selection.value, equals('A')); + expect(selection.previousValue, equals('C')); + expect(selection.index, equals(0)); + expect(selection.previousIndex, equals(2)); }); - test('Scrollable TabBar tap selects tab', () { - testWidgets((WidgetTester tester) { - List tabs = ['A', 'B', 'C']; + testWidgets('Scrollable TabBar tap selects tab', (WidgetTester tester) { + List tabs = ['A', 'B', 'C']; - tester.pumpWidget(buildFrame(tabs: tabs, value: 'C', isScrollable: true)); - TabBarSelectionState selection = TabBarSelection.of(tester.elementTreeTester.findText('A')); - expect(selection, isNotNull); - expect(tester, hasWidget(find.text('A'))); - expect(tester, hasWidget(find.text('B'))); - expect(tester, hasWidget(find.text('C'))); - expect(selection.value, equals('C')); + tester.pumpWidget(buildFrame(tabs: tabs, value: 'C', isScrollable: true)); + TabBarSelectionState selection = TabBarSelection.of(tester.element(find.text('A'))); + expect(selection, isNotNull); + expect(find.text('A'), findsOneWidget); + expect(find.text('B'), findsOneWidget); + expect(find.text('C'), findsOneWidget); + expect(selection.value, equals('C')); - tester.pumpWidget(buildFrame(tabs: tabs, value: 'C', isScrollable: true)); - tester.tap(find.text('B')); - tester.pump(); - expect(selection.value, equals('B')); + tester.pumpWidget(buildFrame(tabs: tabs, value: 'C', isScrollable: true)); + tester.tap(find.text('B')); + tester.pump(); + expect(selection.value, equals('B')); - tester.pumpWidget(buildFrame(tabs: tabs, value: 'C', isScrollable: true)); - tester.tap(find.text('C')); - tester.pump(); - expect(selection.value, equals('C')); + tester.pumpWidget(buildFrame(tabs: tabs, value: 'C', isScrollable: true)); + tester.tap(find.text('C')); + tester.pump(); + expect(selection.value, equals('C')); - tester.pumpWidget(buildFrame(tabs: tabs, value: 'C', isScrollable: true)); - tester.tap(find.text('A')); - tester.pump(); - expect(selection.value, equals('A')); - }); + tester.pumpWidget(buildFrame(tabs: tabs, value: 'C', isScrollable: true)); + tester.tap(find.text('A')); + tester.pump(); + expect(selection.value, equals('A')); }); - test('Scrollable TabBar tap centers selected tab', () { - testWidgets((WidgetTester tester) { - List tabs = ['AAAAAA', 'BBBBBB', 'CCCCCC', 'DDDDDD', 'EEEEEE', 'FFFFFF', 'GGGGGG', 'HHHHHH', 'IIIIII', 'JJJJJJ', 'KKKKKK', 'LLLLLL']; - Key tabBarKey = new Key('TabBar'); - tester.pumpWidget(buildFrame(tabs: tabs, value: 'AAAAAA', isScrollable: true, tabBarKey: tabBarKey)); - TabBarSelectionState selection = TabBarSelection.of(tester.elementTreeTester.findText('AAAAAA')); - expect(selection, isNotNull); - expect(selection.value, equals('AAAAAA')); + testWidgets('Scrollable TabBar tap centers selected tab', (WidgetTester tester) { + List tabs = ['AAAAAA', 'BBBBBB', 'CCCCCC', 'DDDDDD', 'EEEEEE', 'FFFFFF', 'GGGGGG', 'HHHHHH', 'IIIIII', 'JJJJJJ', 'KKKKKK', 'LLLLLL']; + Key tabBarKey = new Key('TabBar'); + tester.pumpWidget(buildFrame(tabs: tabs, value: 'AAAAAA', isScrollable: true, tabBarKey: tabBarKey)); + TabBarSelectionState selection = TabBarSelection.of(tester.element(find.text('AAAAAA'))); + expect(selection, isNotNull); + expect(selection.value, equals('AAAAAA')); - expect(tester.getSize(find.byKey(tabBarKey)).width, equals(800.0)); - // The center of the FFFFFF item is to the right of the TabBar's center - expect(tester.getCenter(find.text('FFFFFF')).x, greaterThan(401.0)); + expect(tester.getSize(find.byKey(tabBarKey)).width, equals(800.0)); + // The center of the FFFFFF item is to the right of the TabBar's center + expect(tester.getCenter(find.text('FFFFFF')).x, greaterThan(401.0)); - tester.tap(find.text('FFFFFF')); - tester.pump(); - tester.pump(const Duration(seconds: 1)); // finish the scroll animation - expect(selection.value, equals('FFFFFF')); - // The center of the FFFFFF item is now at the TabBar's center - expect(tester.getCenter(find.text('FFFFFF')).x, closeTo(400.0, 1.0)); - }); + tester.tap(find.text('FFFFFF')); + tester.pump(); + tester.pump(const Duration(seconds: 1)); // finish the scroll animation + expect(selection.value, equals('FFFFFF')); + // The center of the FFFFFF item is now at the TabBar's center + expect(tester.getCenter(find.text('FFFFFF')).x, closeTo(400.0, 1.0)); }); - test('TabBar can be scrolled independent of the selection', () { - testWidgets((WidgetTester tester) { - List tabs = ['AAAAAA', 'BBBBBB', 'CCCCCC', 'DDDDDD', 'EEEEEE', 'FFFFFF', 'GGGGGG', 'HHHHHH', 'IIIIII', 'JJJJJJ', 'KKKKKK', 'LLLLLL']; - Key tabBarKey = new Key('TabBar'); - tester.pumpWidget(buildFrame(tabs: tabs, value: 'AAAAAA', isScrollable: true, tabBarKey: tabBarKey)); - TabBarSelectionState selection = TabBarSelection.of(tester.elementTreeTester.findText('AAAAAA')); - expect(selection, isNotNull); - expect(selection.value, equals('AAAAAA')); + testWidgets('TabBar can be scrolled independent of the selection', (WidgetTester tester) { + List tabs = ['AAAAAA', 'BBBBBB', 'CCCCCC', 'DDDDDD', 'EEEEEE', 'FFFFFF', 'GGGGGG', 'HHHHHH', 'IIIIII', 'JJJJJJ', 'KKKKKK', 'LLLLLL']; + Key tabBarKey = new Key('TabBar'); + tester.pumpWidget(buildFrame(tabs: tabs, value: 'AAAAAA', isScrollable: true, tabBarKey: tabBarKey)); + TabBarSelectionState selection = TabBarSelection.of(tester.element(find.text('AAAAAA'))); + expect(selection, isNotNull); + expect(selection.value, equals('AAAAAA')); - // Fling-scroll the TabBar to the left - expect(tester.getCenter(find.text('HHHHHH')).x, lessThan(700.0)); - tester.fling(find.byKey(tabBarKey), const Offset(-20.0, 0.0), 1000.0); - tester.pump(); - tester.pump(const Duration(seconds: 1)); // finish the scroll animation - expect(tester.getCenter(find.text('HHHHHH')).x, lessThan(500.0)); + // Fling-scroll the TabBar to the left + expect(tester.getCenter(find.text('HHHHHH')).x, lessThan(700.0)); + tester.fling(find.byKey(tabBarKey), const Offset(-20.0, 0.0), 1000.0); + tester.pump(); + tester.pump(const Duration(seconds: 1)); // finish the scroll animation + expect(tester.getCenter(find.text('HHHHHH')).x, lessThan(500.0)); - // Scrolling the TabBar doesn't change the selection - expect(selection.value, equals('AAAAAA')); - }); + // Scrolling the TabBar doesn't change the selection + expect(selection.value, equals('AAAAAA')); }); - test('TabView maintains state', () { - testWidgets((WidgetTester tester) { - List tabs = ['AAAAAA', 'BBBBBB', 'CCCCCC', 'DDDDDD', 'EEEEEE']; - String value = tabs[0]; + testWidgets('TabView maintains state', (WidgetTester tester) { + List tabs = ['AAAAAA', 'BBBBBB', 'CCCCCC', 'DDDDDD', 'EEEEEE']; + String value = tabs[0]; - void onTabSelectionChanged(String newValue) { - value = newValue; - } + void onTabSelectionChanged(String newValue) { + value = newValue; + } - Widget builder() { - return new Material( - child: new TabBarSelection( - value: value, - values: tabs, - onChanged: onTabSelectionChanged, - child: new TabBarView( - children: tabs.map((String name) { - return new StateMarker( - child: new Text(name) - ); - }).toList() - ) + Widget builder() { + return new Material( + child: new TabBarSelection( + value: value, + values: tabs, + onChanged: onTabSelectionChanged, + child: new TabBarView( + children: tabs.map((String name) { + return new StateMarker( + child: new Text(name) + ); + }).toList() ) - ); - } + ) + ); + } - StateMarkerState findStateMarkerState(String name) { - return tester.stateOf(find.widgetWithText(StateMarker, name)); - } + StateMarkerState findStateMarkerState(String name) { + return tester.state(find.widgetWithText(StateMarker, name)); + } - tester.pumpWidget(builder()); - TestGesture gesture = tester.startGesture(tester.getCenter(find.text(tabs[0]))); - gesture.moveBy(new Offset(-600.0, 0.0)); - tester.pump(); - expect(value, equals(tabs[0])); - findStateMarkerState(tabs[1]).marker = 'marked'; - gesture.up(); - tester.pump(); - tester.pump(const Duration(seconds: 1)); - expect(value, equals(tabs[1])); - tester.pumpWidget(builder()); - expect(findStateMarkerState(tabs[1]).marker, equals('marked')); + tester.pumpWidget(builder()); + TestGesture gesture = tester.startGesture(tester.getCenter(find.text(tabs[0]))); + gesture.moveBy(new Offset(-600.0, 0.0)); + tester.pump(); + expect(value, equals(tabs[0])); + findStateMarkerState(tabs[1]).marker = 'marked'; + gesture.up(); + tester.pump(); + tester.pump(const Duration(seconds: 1)); + expect(value, equals(tabs[1])); + tester.pumpWidget(builder()); + expect(findStateMarkerState(tabs[1]).marker, equals('marked')); - // Move to the third tab. + // Move to the third tab. - gesture = tester.startGesture(tester.getCenter(find.text(tabs[1]))); - gesture.moveBy(new Offset(-600.0, 0.0)); - gesture.up(); - tester.pump(); - expect(findStateMarkerState(tabs[1]).marker, equals('marked')); - tester.pump(const Duration(seconds: 1)); - expect(value, equals(tabs[2])); - tester.pumpWidget(builder()); + gesture = tester.startGesture(tester.getCenter(find.text(tabs[1]))); + gesture.moveBy(new Offset(-600.0, 0.0)); + gesture.up(); + tester.pump(); + expect(findStateMarkerState(tabs[1]).marker, equals('marked')); + tester.pump(const Duration(seconds: 1)); + expect(value, equals(tabs[2])); + tester.pumpWidget(builder()); - // The state is now gone. + // The state is now gone. - expect(tester, doesNotHaveWidget(find.text(tabs[1]))); + expect(find.text(tabs[1]), findsNothing); - // Move back to the second tab. + // Move back to the second tab. - gesture = tester.startGesture(tester.getCenter(find.text(tabs[2]))); - gesture.moveBy(new Offset(600.0, 0.0)); - tester.pump(); - StateMarkerState markerState = findStateMarkerState(tabs[1]); - expect(markerState.marker, isNull); - markerState.marker = 'marked'; - gesture.up(); - tester.pump(); - tester.pump(const Duration(seconds: 1)); - expect(value, equals(tabs[1])); - tester.pumpWidget(builder()); - expect(findStateMarkerState(tabs[1]).marker, equals('marked')); - }); + gesture = tester.startGesture(tester.getCenter(find.text(tabs[2]))); + gesture.moveBy(new Offset(600.0, 0.0)); + tester.pump(); + StateMarkerState markerState = findStateMarkerState(tabs[1]); + expect(markerState.marker, isNull); + markerState.marker = 'marked'; + gesture.up(); + tester.pump(); + tester.pump(const Duration(seconds: 1)); + expect(value, equals(tabs[1])); + tester.pumpWidget(builder()); + expect(findStateMarkerState(tabs[1]).marker, equals('marked')); }); } diff --git a/packages/flutter/test/material/time_picker_test.dart b/packages/flutter/test/material/time_picker_test.dart index 82c24aaecc..d2bb477ab6 100644 --- a/packages/flutter/test/material/time_picker_test.dart +++ b/packages/flutter/test/material/time_picker_test.dart @@ -7,120 +7,116 @@ import 'package:flutter_test/flutter_test.dart'; import 'package:test/test.dart'; void main() { - test('tap-select an hour', () { - testWidgets((WidgetTester tester) { - Key _timePickerKey = new UniqueKey(); - TimeOfDay _selectedTime = const TimeOfDay(hour: 7, minute: 0); + testWidgets('tap-select an hour', (WidgetTester tester) { + Key _timePickerKey = new UniqueKey(); + TimeOfDay _selectedTime = const TimeOfDay(hour: 7, minute: 0); - tester.pumpWidget( - new StatefulBuilder( - builder: (BuildContext context, StateSetter setState) { - return new Material( - child: new Center( - child: new SizedBox( - width: 200.0, - height: 400.0, - child: new TimePicker( - key: _timePickerKey, - selectedTime: _selectedTime, - onChanged: (TimeOfDay value) { - setState(() { - _selectedTime = value; - }); - } - ) + tester.pumpWidget( + new StatefulBuilder( + builder: (BuildContext context, StateSetter setState) { + return new Material( + child: new Center( + child: new SizedBox( + width: 200.0, + height: 400.0, + child: new TimePicker( + key: _timePickerKey, + selectedTime: _selectedTime, + onChanged: (TimeOfDay value) { + setState(() { + _selectedTime = value; + }); + } ) ) - ); - } - ) - ); + ) + ); + } + ) + ); - Point center = tester.getCenter(find.byKey(_timePickerKey)); + Point center = tester.getCenter(find.byKey(_timePickerKey)); - Point hour0 = new Point(center.x, center.y - 50.0); // 12:00 AM - tester.tapAt(hour0); - expect(_selectedTime.hour, equals(0)); + Point hour0 = new Point(center.x, center.y - 50.0); // 12:00 AM + tester.tapAt(hour0); + expect(_selectedTime.hour, equals(0)); - Point hour3 = new Point(center.x + 50.0, center.y); - tester.tapAt(hour3); - expect(_selectedTime.hour, equals(3)); + Point hour3 = new Point(center.x + 50.0, center.y); + tester.tapAt(hour3); + expect(_selectedTime.hour, equals(3)); - Point hour6 = new Point(center.x, center.y + 50.0); - tester.tapAt(hour6); - expect(_selectedTime.hour, equals(6)); + Point hour6 = new Point(center.x, center.y + 50.0); + tester.tapAt(hour6); + expect(_selectedTime.hour, equals(6)); - Point hour9 = new Point(center.x - 50.0, center.y); - tester.tapAt(hour9); - expect(_selectedTime.hour, equals(9)); + Point hour9 = new Point(center.x - 50.0, center.y); + tester.tapAt(hour9); + expect(_selectedTime.hour, equals(9)); - tester.pump(const Duration(seconds: 1)); // Finish gesture animation. - tester.pump(const Duration(seconds: 1)); // Finish settling animation. - }); + tester.pump(const Duration(seconds: 1)); // Finish gesture animation. + tester.pump(const Duration(seconds: 1)); // Finish settling animation. }); - test('drag-select an hour', () { - testWidgets((WidgetTester tester) { - Key _timePickerKey = new UniqueKey(); - TimeOfDay _selectedTime = const TimeOfDay(hour: 7, minute: 0); + testWidgets('drag-select an hour', (WidgetTester tester) { + Key _timePickerKey = new UniqueKey(); + TimeOfDay _selectedTime = const TimeOfDay(hour: 7, minute: 0); - tester.pumpWidget( - new StatefulBuilder( - builder: (BuildContext context, StateSetter setState) { - return new Material( - child: new Center( - child: new SizedBox( - width: 200.0, - height: 400.0, - child: new TimePicker( - key: _timePickerKey, - selectedTime: _selectedTime, - onChanged: (TimeOfDay value) { - setState(() { - _selectedTime = value; - }); - } - ) + tester.pumpWidget( + new StatefulBuilder( + builder: (BuildContext context, StateSetter setState) { + return new Material( + child: new Center( + child: new SizedBox( + width: 200.0, + height: 400.0, + child: new TimePicker( + key: _timePickerKey, + selectedTime: _selectedTime, + onChanged: (TimeOfDay value) { + setState(() { + _selectedTime = value; + }); + } ) ) - ); - } - ) - ); + ) + ); + } + ) + ); - Point center = tester.getCenter(find.byKey(_timePickerKey)); - Point hour0 = new Point(center.x, center.y - 50.0); // 12:00 AM - Point hour3 = new Point(center.x + 50.0, center.y); - Point hour6 = new Point(center.x, center.y + 50.0); - Point hour9 = new Point(center.x - 50.0, center.y); + Point center = tester.getCenter(find.byKey(_timePickerKey)); + Point hour0 = new Point(center.x, center.y - 50.0); // 12:00 AM + Point hour3 = new Point(center.x + 50.0, center.y); + Point hour6 = new Point(center.x, center.y + 50.0); + Point hour9 = new Point(center.x - 50.0, center.y); - tester.startGesture(hour3) - ..moveBy(hour0 - hour3) - ..up(); - expect(_selectedTime.hour, equals(0)); - tester.pump(const Duration(seconds: 1)); // Finish gesture animation. - tester.pump(const Duration(seconds: 1)); // Finish settling animation. + tester.startGesture(hour3) + ..moveBy(hour0 - hour3) + ..up(); + expect(_selectedTime.hour, equals(0)); + tester.pump(const Duration(seconds: 1)); // Finish gesture animation. + tester.pump(const Duration(seconds: 1)); // Finish settling animation. - tester.startGesture(hour0) - ..moveBy(hour3 - hour0) - ..up(); - expect(_selectedTime.hour, equals(3)); - tester.pump(const Duration(seconds: 1)); - tester.pump(const Duration(seconds: 1)); + tester.startGesture(hour0) + ..moveBy(hour3 - hour0) + ..up(); + expect(_selectedTime.hour, equals(3)); + tester.pump(const Duration(seconds: 1)); + tester.pump(const Duration(seconds: 1)); - tester.startGesture(hour3) - ..moveBy(hour6 - hour3) - ..up(); - expect(_selectedTime.hour, equals(6)); - tester.pump(const Duration(seconds: 1)); - tester.pump(const Duration(seconds: 1)); + tester.startGesture(hour3) + ..moveBy(hour6 - hour3) + ..up(); + expect(_selectedTime.hour, equals(6)); + tester.pump(const Duration(seconds: 1)); + tester.pump(const Duration(seconds: 1)); - tester.startGesture(hour6) - ..moveBy(hour9 - hour6) - ..up(); - expect(_selectedTime.hour, equals(9)); - tester.pump(const Duration(seconds: 1)); - tester.pump(const Duration(seconds: 1)); - }); + tester.startGesture(hour6) + ..moveBy(hour9 - hour6) + ..up(); + expect(_selectedTime.hour, equals(9)); + tester.pump(const Duration(seconds: 1)); + tester.pump(const Duration(seconds: 1)); }); } diff --git a/packages/flutter/test/material/tooltip_test.dart b/packages/flutter/test/material/tooltip_test.dart index eb636c958c..56a087539c 100644 --- a/packages/flutter/test/material/tooltip_test.dart +++ b/packages/flutter/test/material/tooltip_test.dart @@ -26,473 +26,457 @@ import '../widget/test_semantics.dart'; // production code. void main() { - test('Does tooltip end up in the right place - center', () { - testElementTree((ElementTreeTester tester) { - GlobalKey key = new GlobalKey(); - tester.pumpWidget( - new Overlay( - initialEntries: [ - new OverlayEntry( - builder: (BuildContext context) { - return new Stack( - children: [ - new Positioned( - left: 300.0, - top: 0.0, - child: new Tooltip( - key: key, - message: 'TIP', - height: 20.0, - padding: const EdgeInsets.all(5.0), - verticalOffset: 20.0, - screenEdgeMargin: const EdgeInsets.all(10.0), - preferBelow: false, - fadeDuration: const Duration(seconds: 1), - showDuration: const Duration(seconds: 2), - child: new Container( - width: 0.0, - height: 0.0 - ) + testWidgets('Does tooltip end up in the right place - center', (WidgetTester tester) { + GlobalKey key = new GlobalKey(); + tester.pumpWidget( + new Overlay( + initialEntries: [ + new OverlayEntry( + builder: (BuildContext context) { + return new Stack( + children: [ + new Positioned( + left: 300.0, + top: 0.0, + child: new Tooltip( + key: key, + message: 'TIP', + height: 20.0, + padding: const EdgeInsets.all(5.0), + verticalOffset: 20.0, + screenEdgeMargin: const EdgeInsets.all(10.0), + preferBelow: false, + fadeDuration: const Duration(seconds: 1), + showDuration: const Duration(seconds: 2), + child: new Container( + width: 0.0, + height: 0.0 ) - ), - ] - ); - } - ), - ] - ) - ); - (key.currentState as dynamic).showTooltip(); // before using "as dynamic" in your code, see note top of file - tester.pump(const Duration(seconds: 2)); // faded in, show timer started (and at 0.0) + ) + ), + ] + ); + } + ), + ] + ) + ); + (key.currentState as dynamic).showTooltip(); // before using "as dynamic" in your code, see note top of file + tester.pump(const Duration(seconds: 2)); // faded in, show timer started (and at 0.0) - /********************* 800x600 screen - * o * y=0 - * | * }- 20.0 vertical offset, of which 10.0 is in the screen edge margin - * +----+ * \- (5.0 padding in height) - * | | * |- 20 height - * +----+ * /- (5.0 padding in height) - * * - *********************/ + /********************* 800x600 screen + * o * y=0 + * | * }- 20.0 vertical offset, of which 10.0 is in the screen edge margin + * +----+ * \- (5.0 padding in height) + * | | * |- 20 height + * +----+ * /- (5.0 padding in height) + * * + *********************/ - RenderBox tip = tester.findText('TIP').renderObject.parent.parent.parent.parent.parent; - expect(tip.localToGlobal(tip.size.topLeft(Point.origin)), equals(const Point(284.0, 20.0))); - }); + RenderBox tip = tester.renderObject(find.text('TIP')).parent.parent.parent.parent.parent; + expect(tip.localToGlobal(tip.size.topLeft(Point.origin)), equals(const Point(284.0, 20.0))); }); - test('Does tooltip end up in the right place - top left', () { - testElementTree((ElementTreeTester tester) { - GlobalKey key = new GlobalKey(); - tester.pumpWidget( - new Overlay( - initialEntries: [ - new OverlayEntry( - builder: (BuildContext context) { - return new Stack( - children: [ - new Positioned( - left: 0.0, - top: 0.0, - child: new Tooltip( - key: key, - message: 'TIP', - height: 20.0, - padding: const EdgeInsets.all(5.0), - verticalOffset: 20.0, - screenEdgeMargin: const EdgeInsets.all(10.0), - preferBelow: false, - fadeDuration: const Duration(seconds: 1), - showDuration: const Duration(seconds: 2), - child: new Container( - width: 0.0, - height: 0.0 - ) + testWidgets('Does tooltip end up in the right place - top left', (WidgetTester tester) { + GlobalKey key = new GlobalKey(); + tester.pumpWidget( + new Overlay( + initialEntries: [ + new OverlayEntry( + builder: (BuildContext context) { + return new Stack( + children: [ + new Positioned( + left: 0.0, + top: 0.0, + child: new Tooltip( + key: key, + message: 'TIP', + height: 20.0, + padding: const EdgeInsets.all(5.0), + verticalOffset: 20.0, + screenEdgeMargin: const EdgeInsets.all(10.0), + preferBelow: false, + fadeDuration: const Duration(seconds: 1), + showDuration: const Duration(seconds: 2), + child: new Container( + width: 0.0, + height: 0.0 ) - ), - ] - ); - } - ), - ] - ) - ); - (key.currentState as dynamic).showTooltip(); // before using "as dynamic" in your code, see note top of file - tester.pump(const Duration(seconds: 2)); // faded in, show timer started (and at 0.0) + ) + ), + ] + ); + } + ), + ] + ) + ); + (key.currentState as dynamic).showTooltip(); // before using "as dynamic" in your code, see note top of file + tester.pump(const Duration(seconds: 2)); // faded in, show timer started (and at 0.0) - /********************* 800x600 screen - *o * y=0 - *| * }- 20.0 vertical offset, of which 10.0 is in the screen edge margin - *+----+ * \- (5.0 padding in height) - *| | * |- 20 height - *+----+ * /- (5.0 padding in height) - * * - *********************/ + /********************* 800x600 screen + *o * y=0 + *| * }- 20.0 vertical offset, of which 10.0 is in the screen edge margin + *+----+ * \- (5.0 padding in height) + *| | * |- 20 height + *+----+ * /- (5.0 padding in height) + * * + *********************/ - RenderBox tip = tester.findText('TIP').renderObject.parent.parent.parent.parent.parent; - expect(tip.size.height, equals(20.0)); // 10.0 height + 5.0 padding * 2 (top, bottom) - expect(tip.localToGlobal(tip.size.topLeft(Point.origin)), equals(const Point(10.0, 20.0))); - }); + RenderBox tip = tester.renderObject(find.text('TIP')).parent.parent.parent.parent.parent; + expect(tip.size.height, equals(20.0)); // 10.0 height + 5.0 padding * 2 (top, bottom) + expect(tip.localToGlobal(tip.size.topLeft(Point.origin)), equals(const Point(10.0, 20.0))); }); - test('Does tooltip end up in the right place - center prefer above fits', () { - testElementTree((ElementTreeTester tester) { - GlobalKey key = new GlobalKey(); - tester.pumpWidget( - new Overlay( - initialEntries: [ - new OverlayEntry( - builder: (BuildContext context) { - return new Stack( - children: [ - new Positioned( - left: 400.0, - top: 300.0, - child: new Tooltip( - key: key, - message: 'TIP', - height: 100.0, - padding: const EdgeInsets.all(0.0), - verticalOffset: 100.0, - screenEdgeMargin: const EdgeInsets.all(100.0), - preferBelow: false, - fadeDuration: const Duration(seconds: 1), - showDuration: const Duration(seconds: 2), - child: new Container( - width: 0.0, - height: 0.0 - ) + testWidgets('Does tooltip end up in the right place - center prefer above fits', (WidgetTester tester) { + GlobalKey key = new GlobalKey(); + tester.pumpWidget( + new Overlay( + initialEntries: [ + new OverlayEntry( + builder: (BuildContext context) { + return new Stack( + children: [ + new Positioned( + left: 400.0, + top: 300.0, + child: new Tooltip( + key: key, + message: 'TIP', + height: 100.0, + padding: const EdgeInsets.all(0.0), + verticalOffset: 100.0, + screenEdgeMargin: const EdgeInsets.all(100.0), + preferBelow: false, + fadeDuration: const Duration(seconds: 1), + showDuration: const Duration(seconds: 2), + child: new Container( + width: 0.0, + height: 0.0 ) - ), - ] - ); - } - ), - ] - ) - ); - (key.currentState as dynamic).showTooltip(); // before using "as dynamic" in your code, see note top of file - tester.pump(const Duration(seconds: 2)); // faded in, show timer started (and at 0.0) + ) + ), + ] + ); + } + ), + ] + ) + ); + (key.currentState as dynamic).showTooltip(); // before using "as dynamic" in your code, see note top of file + tester.pump(const Duration(seconds: 2)); // faded in, show timer started (and at 0.0) - /********************* 800x600 screen - * ___ * }-100.0 margin - * |___| * }-100.0 height - * | * }-100.0 vertical offset - * o * y=300.0 - * * - * * - * * - *********************/ + /********************* 800x600 screen + * ___ * }-100.0 margin + * |___| * }-100.0 height + * | * }-100.0 vertical offset + * o * y=300.0 + * * + * * + * * + *********************/ - RenderBox tip = tester.findText('TIP').renderObject.parent; - expect(tip.size.height, equals(100.0)); - expect(tip.localToGlobal(tip.size.topLeft(Point.origin)).y, equals(100.0)); - expect(tip.localToGlobal(tip.size.bottomRight(Point.origin)).y, equals(200.0)); - }); + RenderBox tip = tester.renderObject(find.text('TIP')).parent; + expect(tip.size.height, equals(100.0)); + expect(tip.localToGlobal(tip.size.topLeft(Point.origin)).y, equals(100.0)); + expect(tip.localToGlobal(tip.size.bottomRight(Point.origin)).y, equals(200.0)); }); - test('Does tooltip end up in the right place - center prefer above does not fit', () { - testElementTree((ElementTreeTester tester) { - GlobalKey key = new GlobalKey(); - tester.pumpWidget( - new Overlay( - initialEntries: [ - new OverlayEntry( - builder: (BuildContext context) { - return new Stack( - children: [ - new Positioned( - left: 400.0, - top: 299.0, - child: new Tooltip( - key: key, - message: 'TIP', - height: 100.0, - padding: const EdgeInsets.all(0.0), - verticalOffset: 100.0, - screenEdgeMargin: const EdgeInsets.all(100.0), - preferBelow: false, - fadeDuration: const Duration(seconds: 1), - showDuration: const Duration(seconds: 2), - child: new Container( - width: 0.0, - height: 0.0 - ) + testWidgets('Does tooltip end up in the right place - center prefer above does not fit', (WidgetTester tester) { + GlobalKey key = new GlobalKey(); + tester.pumpWidget( + new Overlay( + initialEntries: [ + new OverlayEntry( + builder: (BuildContext context) { + return new Stack( + children: [ + new Positioned( + left: 400.0, + top: 299.0, + child: new Tooltip( + key: key, + message: 'TIP', + height: 100.0, + padding: const EdgeInsets.all(0.0), + verticalOffset: 100.0, + screenEdgeMargin: const EdgeInsets.all(100.0), + preferBelow: false, + fadeDuration: const Duration(seconds: 1), + showDuration: const Duration(seconds: 2), + child: new Container( + width: 0.0, + height: 0.0 ) - ), - ] - ); - } - ), - ] - ) - ); - (key.currentState as dynamic).showTooltip(); // before using "as dynamic" in your code, see note top of file - tester.pump(const Duration(seconds: 2)); // faded in, show timer started (and at 0.0) + ) + ), + ] + ); + } + ), + ] + ) + ); + (key.currentState as dynamic).showTooltip(); // before using "as dynamic" in your code, see note top of file + tester.pump(const Duration(seconds: 2)); // faded in, show timer started (and at 0.0) - // we try to put it here but it doesn't fit: - /********************* 800x600 screen - * ___ * }-100.0 margin - * |___| * }-100.0 height (starts at y=99.0) - * | * }-100.0 vertical offset - * o * y=299.0 - * * - * * - * * - *********************/ + // we try to put it here but it doesn't fit: + /********************* 800x600 screen + * ___ * }-100.0 margin + * |___| * }-100.0 height (starts at y=99.0) + * | * }-100.0 vertical offset + * o * y=299.0 + * * + * * + * * + *********************/ - // so we put it here: - /********************* 800x600 screen - * * - * * - * o * y=299.0 - * _|_ * }-100.0 vertical offset - * |___| * }-100.0 height - * * }-100.0 margin - *********************/ + // so we put it here: + /********************* 800x600 screen + * * + * * + * o * y=299.0 + * _|_ * }-100.0 vertical offset + * |___| * }-100.0 height + * * }-100.0 margin + *********************/ - RenderBox tip = tester.findText('TIP').renderObject.parent; - expect(tip.size.height, equals(100.0)); - expect(tip.localToGlobal(tip.size.topLeft(Point.origin)).y, equals(399.0)); - expect(tip.localToGlobal(tip.size.bottomRight(Point.origin)).y, equals(499.0)); - }); + RenderBox tip = tester.renderObject(find.text('TIP')).parent; + expect(tip.size.height, equals(100.0)); + expect(tip.localToGlobal(tip.size.topLeft(Point.origin)).y, equals(399.0)); + expect(tip.localToGlobal(tip.size.bottomRight(Point.origin)).y, equals(499.0)); }); - test('Does tooltip end up in the right place - center prefer below fits', () { - testElementTree((ElementTreeTester tester) { - GlobalKey key = new GlobalKey(); - tester.pumpWidget( - new Overlay( - initialEntries: [ - new OverlayEntry( - builder: (BuildContext context) { - return new Stack( - children: [ - new Positioned( - left: 400.0, - top: 300.0, - child: new Tooltip( - key: key, - message: 'TIP', - height: 100.0, - padding: const EdgeInsets.all(0.0), - verticalOffset: 100.0, - screenEdgeMargin: const EdgeInsets.all(100.0), - preferBelow: true, - fadeDuration: const Duration(seconds: 1), - showDuration: const Duration(seconds: 2), - child: new Container( - width: 0.0, - height: 0.0 - ) + testWidgets('Does tooltip end up in the right place - center prefer below fits', (WidgetTester tester) { + GlobalKey key = new GlobalKey(); + tester.pumpWidget( + new Overlay( + initialEntries: [ + new OverlayEntry( + builder: (BuildContext context) { + return new Stack( + children: [ + new Positioned( + left: 400.0, + top: 300.0, + child: new Tooltip( + key: key, + message: 'TIP', + height: 100.0, + padding: const EdgeInsets.all(0.0), + verticalOffset: 100.0, + screenEdgeMargin: const EdgeInsets.all(100.0), + preferBelow: true, + fadeDuration: const Duration(seconds: 1), + showDuration: const Duration(seconds: 2), + child: new Container( + width: 0.0, + height: 0.0 ) - ), - ] - ); - } - ), - ] - ) - ); - (key.currentState as dynamic).showTooltip(); // before using "as dynamic" in your code, see note top of file - tester.pump(const Duration(seconds: 2)); // faded in, show timer started (and at 0.0) + ) + ), + ] + ); + } + ), + ] + ) + ); + (key.currentState as dynamic).showTooltip(); // before using "as dynamic" in your code, see note top of file + tester.pump(const Duration(seconds: 2)); // faded in, show timer started (and at 0.0) - /********************* 800x600 screen - * * - * * - * o * y=300.0 - * _|_ * }-100.0 vertical offset - * |___| * }-100.0 height - * * }-100.0 margin - *********************/ + /********************* 800x600 screen + * * + * * + * o * y=300.0 + * _|_ * }-100.0 vertical offset + * |___| * }-100.0 height + * * }-100.0 margin + *********************/ - RenderBox tip = tester.findText('TIP').renderObject.parent; - expect(tip.size.height, equals(100.0)); - expect(tip.localToGlobal(tip.size.topLeft(Point.origin)).y, equals(400.0)); - expect(tip.localToGlobal(tip.size.bottomRight(Point.origin)).y, equals(500.0)); - }); + RenderBox tip = tester.renderObject(find.text('TIP')).parent; + expect(tip.size.height, equals(100.0)); + expect(tip.localToGlobal(tip.size.topLeft(Point.origin)).y, equals(400.0)); + expect(tip.localToGlobal(tip.size.bottomRight(Point.origin)).y, equals(500.0)); }); - test('Does tooltip end up in the right place - way off to the right', () { - testElementTree((ElementTreeTester tester) { - GlobalKey key = new GlobalKey(); - tester.pumpWidget( - new Overlay( - initialEntries: [ - new OverlayEntry( - builder: (BuildContext context) { - return new Stack( - children: [ - new Positioned( - left: 1600.0, - top: 300.0, - child: new Tooltip( - key: key, - message: 'TIP', - height: 10.0, - padding: const EdgeInsets.all(0.0), - verticalOffset: 10.0, - screenEdgeMargin: const EdgeInsets.all(10.0), - preferBelow: true, - fadeDuration: const Duration(seconds: 1), - showDuration: const Duration(seconds: 2), - child: new Container( - width: 0.0, - height: 0.0 - ) + testWidgets('Does tooltip end up in the right place - way off to the right', (WidgetTester tester) { + GlobalKey key = new GlobalKey(); + tester.pumpWidget( + new Overlay( + initialEntries: [ + new OverlayEntry( + builder: (BuildContext context) { + return new Stack( + children: [ + new Positioned( + left: 1600.0, + top: 300.0, + child: new Tooltip( + key: key, + message: 'TIP', + height: 10.0, + padding: const EdgeInsets.all(0.0), + verticalOffset: 10.0, + screenEdgeMargin: const EdgeInsets.all(10.0), + preferBelow: true, + fadeDuration: const Duration(seconds: 1), + showDuration: const Duration(seconds: 2), + child: new Container( + width: 0.0, + height: 0.0 ) - ), - ] - ); - } - ), - ] - ) - ); - (key.currentState as dynamic).showTooltip(); // before using "as dynamic" in your code, see note top of file - tester.pump(const Duration(seconds: 2)); // faded in, show timer started (and at 0.0) + ) + ), + ] + ); + } + ), + ] + ) + ); + (key.currentState as dynamic).showTooltip(); // before using "as dynamic" in your code, see note top of file + tester.pump(const Duration(seconds: 2)); // faded in, show timer started (and at 0.0) - /********************* 800x600 screen - * * - * * - * * y=300.0; target --> o - * ___| * }-10.0 vertical offset - * |___| * }-10.0 height - * * - * * }-10.0 margin - *********************/ + /********************* 800x600 screen + * * + * * + * * y=300.0; target --> o + * ___| * }-10.0 vertical offset + * |___| * }-10.0 height + * * + * * }-10.0 margin + *********************/ - RenderBox tip = tester.findText('TIP').renderObject.parent; - expect(tip.size.height, equals(10.0)); - expect(tip.localToGlobal(tip.size.topLeft(Point.origin)).y, equals(310.0)); - expect(tip.localToGlobal(tip.size.bottomRight(Point.origin)).x, equals(790.0)); - expect(tip.localToGlobal(tip.size.bottomRight(Point.origin)).y, equals(320.0)); - }); + RenderBox tip = tester.renderObject(find.text('TIP')).parent; + expect(tip.size.height, equals(10.0)); + expect(tip.localToGlobal(tip.size.topLeft(Point.origin)).y, equals(310.0)); + expect(tip.localToGlobal(tip.size.bottomRight(Point.origin)).x, equals(790.0)); + expect(tip.localToGlobal(tip.size.bottomRight(Point.origin)).y, equals(320.0)); }); - test('Does tooltip end up in the right place - near the edge', () { - testElementTree((ElementTreeTester tester) { - GlobalKey key = new GlobalKey(); - tester.pumpWidget( - new Overlay( - initialEntries: [ - new OverlayEntry( - builder: (BuildContext context) { - return new Stack( - children: [ - new Positioned( - left: 780.0, - top: 300.0, - child: new Tooltip( - key: key, - message: 'TIP', - height: 10.0, - padding: const EdgeInsets.all(0.0), - verticalOffset: 10.0, - screenEdgeMargin: const EdgeInsets.all(10.0), - preferBelow: true, - fadeDuration: const Duration(seconds: 1), - showDuration: const Duration(seconds: 2), - child: new Container( - width: 0.0, - height: 0.0 - ) + testWidgets('Does tooltip end up in the right place - near the edge', (WidgetTester tester) { + GlobalKey key = new GlobalKey(); + tester.pumpWidget( + new Overlay( + initialEntries: [ + new OverlayEntry( + builder: (BuildContext context) { + return new Stack( + children: [ + new Positioned( + left: 780.0, + top: 300.0, + child: new Tooltip( + key: key, + message: 'TIP', + height: 10.0, + padding: const EdgeInsets.all(0.0), + verticalOffset: 10.0, + screenEdgeMargin: const EdgeInsets.all(10.0), + preferBelow: true, + fadeDuration: const Duration(seconds: 1), + showDuration: const Duration(seconds: 2), + child: new Container( + width: 0.0, + height: 0.0 ) - ), - ] - ); - } - ), - ] - ) - ); - (key.currentState as dynamic).showTooltip(); // before using "as dynamic" in your code, see note top of file - tester.pump(const Duration(seconds: 2)); // faded in, show timer started (and at 0.0) + ) + ), + ] + ); + } + ), + ] + ) + ); + (key.currentState as dynamic).showTooltip(); // before using "as dynamic" in your code, see note top of file + tester.pump(const Duration(seconds: 2)); // faded in, show timer started (and at 0.0) - /********************* 800x600 screen - * * - * * - * o * y=300.0 - * __| * }-10.0 vertical offset - * |___| * }-10.0 height - * * - * * }-10.0 margin - *********************/ + /********************* 800x600 screen + * * + * * + * o * y=300.0 + * __| * }-10.0 vertical offset + * |___| * }-10.0 height + * * + * * }-10.0 margin + *********************/ - RenderBox tip = tester.findText('TIP').renderObject.parent; - expect(tip.size.height, equals(10.0)); - expect(tip.localToGlobal(tip.size.topLeft(Point.origin)).y, equals(310.0)); - expect(tip.localToGlobal(tip.size.bottomRight(Point.origin)).x, equals(790.0)); - expect(tip.localToGlobal(tip.size.bottomRight(Point.origin)).y, equals(320.0)); - }); + RenderBox tip = tester.renderObject(find.text('TIP')).parent; + expect(tip.size.height, equals(10.0)); + expect(tip.localToGlobal(tip.size.topLeft(Point.origin)).y, equals(310.0)); + expect(tip.localToGlobal(tip.size.bottomRight(Point.origin)).x, equals(790.0)); + expect(tip.localToGlobal(tip.size.bottomRight(Point.origin)).y, equals(320.0)); }); - test('Does tooltip contribute semantics', () { - testElementTree((ElementTreeTester tester) { - TestSemanticsListener client = new TestSemanticsListener(); - GlobalKey key = new GlobalKey(); - tester.pumpWidget( - new Overlay( - initialEntries: [ - new OverlayEntry( - builder: (BuildContext context) { - return new Stack( - children: [ - new Positioned( - left: 780.0, - top: 300.0, - child: new Tooltip( - key: key, - message: 'TIP', - fadeDuration: const Duration(seconds: 1), - showDuration: const Duration(seconds: 2), - child: new Container(width: 0.0, height: 0.0) - ) - ), - ] - ); - } - ), - ] - ) - ); - expect(client.updates.length, equals(2)); - expect(client.updates[0].id, equals(0)); - expect(client.updates[0].flags.canBeTapped, isFalse); - expect(client.updates[0].flags.canBeLongPressed, isFalse); - expect(client.updates[0].flags.canBeScrolledHorizontally, isFalse); - expect(client.updates[0].flags.canBeScrolledVertically, isFalse); - expect(client.updates[0].flags.hasCheckedState, isFalse); - expect(client.updates[0].flags.isChecked, isFalse); - expect(client.updates[0].strings.label, equals('TIP')); - expect(client.updates[0].geometry.transform, isNull); - expect(client.updates[0].geometry.left, equals(0.0)); - expect(client.updates[0].geometry.top, equals(0.0)); - expect(client.updates[0].geometry.width, equals(800.0)); - expect(client.updates[0].geometry.height, equals(600.0)); - expect(client.updates[0].children.length, equals(0)); - expect(client.updates[1], isNull); - client.updates.clear(); + testWidgets('Does tooltip contribute semantics', (WidgetTester tester) { + TestSemanticsListener client = new TestSemanticsListener(); + GlobalKey key = new GlobalKey(); + tester.pumpWidget( + new Overlay( + initialEntries: [ + new OverlayEntry( + builder: (BuildContext context) { + return new Stack( + children: [ + new Positioned( + left: 780.0, + top: 300.0, + child: new Tooltip( + key: key, + message: 'TIP', + fadeDuration: const Duration(seconds: 1), + showDuration: const Duration(seconds: 2), + child: new Container(width: 0.0, height: 0.0) + ) + ), + ] + ); + } + ), + ] + ) + ); + expect(client.updates.length, equals(2)); + expect(client.updates[0].id, equals(0)); + expect(client.updates[0].flags.canBeTapped, isFalse); + expect(client.updates[0].flags.canBeLongPressed, isFalse); + expect(client.updates[0].flags.canBeScrolledHorizontally, isFalse); + expect(client.updates[0].flags.canBeScrolledVertically, isFalse); + expect(client.updates[0].flags.hasCheckedState, isFalse); + expect(client.updates[0].flags.isChecked, isFalse); + expect(client.updates[0].strings.label, equals('TIP')); + expect(client.updates[0].geometry.transform, isNull); + expect(client.updates[0].geometry.left, equals(0.0)); + expect(client.updates[0].geometry.top, equals(0.0)); + expect(client.updates[0].geometry.width, equals(800.0)); + expect(client.updates[0].geometry.height, equals(600.0)); + expect(client.updates[0].children.length, equals(0)); + expect(client.updates[1], isNull); + client.updates.clear(); - // before using "as dynamic" in your code, see note top of file - (key.currentState as dynamic).showTooltip(); // this triggers a rebuild of the semantics because the tree changes + // before using "as dynamic" in your code, see note top of file + (key.currentState as dynamic).showTooltip(); // this triggers a rebuild of the semantics because the tree changes - tester.pump(const Duration(seconds: 2)); // faded in, show timer started (and at 0.0) - expect(client.updates.length, equals(2)); - expect(client.updates[0].id, equals(0)); - expect(client.updates[0].flags.canBeTapped, isFalse); - expect(client.updates[0].flags.canBeLongPressed, isFalse); - expect(client.updates[0].flags.canBeScrolledHorizontally, isFalse); - expect(client.updates[0].flags.canBeScrolledVertically, isFalse); - expect(client.updates[0].flags.hasCheckedState, isFalse); - expect(client.updates[0].flags.isChecked, isFalse); - expect(client.updates[0].strings.label, equals('TIP')); - expect(client.updates[0].geometry.transform, isNull); - expect(client.updates[0].geometry.left, equals(0.0)); - expect(client.updates[0].geometry.top, equals(0.0)); - expect(client.updates[0].geometry.width, equals(800.0)); - expect(client.updates[0].geometry.height, equals(600.0)); - expect(client.updates[0].children.length, equals(0)); - expect(client.updates[1], isNull); - client.updates.clear(); - }); + tester.pump(const Duration(seconds: 2)); // faded in, show timer started (and at 0.0) + expect(client.updates.length, equals(2)); + expect(client.updates[0].id, equals(0)); + expect(client.updates[0].flags.canBeTapped, isFalse); + expect(client.updates[0].flags.canBeLongPressed, isFalse); + expect(client.updates[0].flags.canBeScrolledHorizontally, isFalse); + expect(client.updates[0].flags.canBeScrolledVertically, isFalse); + expect(client.updates[0].flags.hasCheckedState, isFalse); + expect(client.updates[0].flags.isChecked, isFalse); + expect(client.updates[0].strings.label, equals('TIP')); + expect(client.updates[0].geometry.transform, isNull); + expect(client.updates[0].geometry.left, equals(0.0)); + expect(client.updates[0].geometry.top, equals(0.0)); + expect(client.updates[0].geometry.width, equals(800.0)); + expect(client.updates[0].geometry.height, equals(600.0)); + expect(client.updates[0].children.length, equals(0)); + expect(client.updates[1], isNull); + client.updates.clear(); }); } diff --git a/packages/flutter/test/widget/align_test.dart b/packages/flutter/test/widget/align_test.dart index 7081dbbf56..c8d46496af 100644 --- a/packages/flutter/test/widget/align_test.dart +++ b/packages/flutter/test/widget/align_test.dart @@ -8,43 +8,39 @@ import 'package:flutter/widgets.dart'; import 'package:test/test.dart'; void main() { - test('Align smoke test', () { - testWidgets((WidgetTester tester) { - tester.pumpWidget( - new Align( - child: new Container(), - alignment: const FractionalOffset(0.75, 0.75) - ) - ); + testWidgets('Align smoke test', (WidgetTester tester) { + tester.pumpWidget( + new Align( + child: new Container(), + alignment: const FractionalOffset(0.75, 0.75) + ) + ); - tester.pumpWidget( - new Align( - child: new Container(), - alignment: const FractionalOffset(0.5, 0.5) - ) - ); - }); + tester.pumpWidget( + new Align( + child: new Container(), + alignment: const FractionalOffset(0.5, 0.5) + ) + ); }); - test('Shrink wraps in finite space', () { - testWidgets((WidgetTester tester) { - GlobalKey alignKey = new GlobalKey(); - tester.pumpWidget( - new ScrollableViewport( - child: new Align( - key: alignKey, - child: new Container( - width: 10.0, - height: 10.0 - ), - alignment: const FractionalOffset(0.50, 0.50) - ) + testWidgets('Shrink wraps in finite space', (WidgetTester tester) { + GlobalKey alignKey = new GlobalKey(); + tester.pumpWidget( + new ScrollableViewport( + child: new Align( + key: alignKey, + child: new Container( + width: 10.0, + height: 10.0 + ), + alignment: const FractionalOffset(0.50, 0.50) ) - ); + ) + ); - RenderBox box = alignKey.currentContext.findRenderObject(); - expect(box.size.width, equals(800.0)); - expect(box.size.height, equals(10.0)); - }); + RenderBox box = alignKey.currentContext.findRenderObject(); + expect(box.size.width, equals(800.0)); + expect(box.size.height, equals(10.0)); }); } diff --git a/packages/flutter/test/widget/animated_container_test.dart b/packages/flutter/test/widget/animated_container_test.dart index 78c9db3dcf..2eeb9094ea 100644 --- a/packages/flutter/test/widget/animated_container_test.dart +++ b/packages/flutter/test/widget/animated_container_test.dart @@ -8,166 +8,159 @@ import 'package:flutter/widgets.dart'; import 'package:test/test.dart'; void main() { - test('AnimatedContainer control test', () { - testWidgets((WidgetTester tester) { - GlobalKey key = new GlobalKey(); + testWidgets('AnimatedContainer control test', (WidgetTester tester) { + GlobalKey key = new GlobalKey(); - BoxDecoration decorationA = new BoxDecoration( - backgroundColor: new Color(0xFF00FF00) - ); + BoxDecoration decorationA = new BoxDecoration( + backgroundColor: new Color(0xFF00FF00) + ); - BoxDecoration decorationB = new BoxDecoration( - backgroundColor: new Color(0xFF0000FF) - ); + BoxDecoration decorationB = new BoxDecoration( + backgroundColor: new Color(0xFF0000FF) + ); - BoxDecoration actualDecoration; + BoxDecoration actualDecoration; - tester.pumpWidget( - new AnimatedContainer( - key: key, - duration: const Duration(milliseconds: 200), - decoration: decorationA - ) - ); + tester.pumpWidget( + new AnimatedContainer( + key: key, + duration: const Duration(milliseconds: 200), + decoration: decorationA + ) + ); - RenderDecoratedBox box = key.currentContext.findRenderObject(); - actualDecoration = box.decoration; - expect(actualDecoration.backgroundColor, equals(decorationA.backgroundColor)); + RenderDecoratedBox box = key.currentContext.findRenderObject(); + actualDecoration = box.decoration; + expect(actualDecoration.backgroundColor, equals(decorationA.backgroundColor)); - tester.pumpWidget( - new AnimatedContainer( - key: key, - duration: const Duration(milliseconds: 200), - decoration: decorationB - ) - ); + tester.pumpWidget( + new AnimatedContainer( + key: key, + duration: const Duration(milliseconds: 200), + decoration: decorationB + ) + ); - expect(key.currentContext.findRenderObject(), equals(box)); - actualDecoration = box.decoration; - expect(actualDecoration.backgroundColor, equals(decorationA.backgroundColor)); + expect(key.currentContext.findRenderObject(), equals(box)); + actualDecoration = box.decoration; + expect(actualDecoration.backgroundColor, equals(decorationA.backgroundColor)); - tester.pump(const Duration(seconds: 1)); + tester.pump(const Duration(seconds: 1)); - actualDecoration = box.decoration; - expect(actualDecoration.backgroundColor, equals(decorationB.backgroundColor)); - - }); + actualDecoration = box.decoration; + expect(actualDecoration.backgroundColor, equals(decorationB.backgroundColor)); }); - test('AnimatedContainer overanimate test', () { - testWidgets((WidgetTester tester) { - tester.pumpWidget( - new AnimatedContainer( - duration: const Duration(milliseconds: 200), - decoration: new BoxDecoration( - backgroundColor: new Color(0xFF00FF00) - ) + testWidgets('AnimatedContainer overanimate test', (WidgetTester tester) { + tester.pumpWidget( + new AnimatedContainer( + duration: const Duration(milliseconds: 200), + decoration: new BoxDecoration( + backgroundColor: new Color(0xFF00FF00) ) - ); - expect(tester.binding.transientCallbackCount, 0); - tester.pump(new Duration(seconds: 1)); - expect(tester.binding.transientCallbackCount, 0); - tester.pumpWidget( - new AnimatedContainer( - duration: const Duration(milliseconds: 200), - decoration: new BoxDecoration( - backgroundColor: new Color(0xFF00FF00) - ) + ) + ); + expect(tester.binding.transientCallbackCount, 0); + tester.pump(new Duration(seconds: 1)); + expect(tester.binding.transientCallbackCount, 0); + tester.pumpWidget( + new AnimatedContainer( + duration: const Duration(milliseconds: 200), + decoration: new BoxDecoration( + backgroundColor: new Color(0xFF00FF00) ) - ); - expect(tester.binding.transientCallbackCount, 0); - tester.pump(new Duration(seconds: 1)); - expect(tester.binding.transientCallbackCount, 0); - tester.pumpWidget( - new AnimatedContainer( - duration: const Duration(milliseconds: 200), - decoration: new BoxDecoration( - backgroundColor: new Color(0xFF0000FF) - ) + ) + ); + expect(tester.binding.transientCallbackCount, 0); + tester.pump(new Duration(seconds: 1)); + expect(tester.binding.transientCallbackCount, 0); + tester.pumpWidget( + new AnimatedContainer( + duration: const Duration(milliseconds: 200), + decoration: new BoxDecoration( + backgroundColor: new Color(0xFF0000FF) ) - ); - expect(tester.binding.transientCallbackCount, 1); // this is the only time an animation should have started! - tester.pump(new Duration(seconds: 1)); - expect(tester.binding.transientCallbackCount, 0); - tester.pumpWidget( - new AnimatedContainer( - duration: const Duration(milliseconds: 200), - decoration: new BoxDecoration( - backgroundColor: new Color(0xFF0000FF) - ) + ) + ); + expect(tester.binding.transientCallbackCount, 1); // this is the only time an animation should have started! + tester.pump(new Duration(seconds: 1)); + expect(tester.binding.transientCallbackCount, 0); + tester.pumpWidget( + new AnimatedContainer( + duration: const Duration(milliseconds: 200), + decoration: new BoxDecoration( + backgroundColor: new Color(0xFF0000FF) ) - ); - expect(tester.binding.transientCallbackCount, 0); - }); + ) + ); + expect(tester.binding.transientCallbackCount, 0); }); - test('Animation rerun', () { - testElementTree((ElementTreeTester tester) { - tester.pumpWidget( - new Center( - child: new AnimatedContainer( - duration: const Duration(milliseconds: 200), - width: 100.0, - height: 100.0, - child: new Text('X') - ) + testWidgets('Animation rerun', (WidgetTester tester) { + tester.pumpWidget( + new Center( + child: new AnimatedContainer( + duration: const Duration(milliseconds: 200), + width: 100.0, + height: 100.0, + child: new Text('X') ) - ); + ) + ); - tester.pump(); - tester.pump(new Duration(milliseconds: 100)); + tester.pump(); + tester.pump(new Duration(milliseconds: 100)); - RenderBox text = tester.findText('X').renderObject; - expect(text.size.width, equals(100.0)); - expect(text.size.height, equals(100.0)); + RenderBox text = tester.renderObject(find.text('X')); + expect(text.size.width, equals(100.0)); + expect(text.size.height, equals(100.0)); - tester.pump(new Duration(milliseconds: 1000)); + tester.pump(new Duration(milliseconds: 1000)); - tester.pumpWidget( - new Center( - child: new AnimatedContainer( - duration: const Duration(milliseconds: 200), - width: 200.0, - height: 200.0, - child: new Text('X') - ) + tester.pumpWidget( + new Center( + child: new AnimatedContainer( + duration: const Duration(milliseconds: 200), + width: 200.0, + height: 200.0, + child: new Text('X') ) - ); - tester.pump(); - tester.pump(new Duration(milliseconds: 100)); + ) + ); + tester.pump(); + tester.pump(new Duration(milliseconds: 100)); - text = tester.findText('X').renderObject; - expect(text.size.width, greaterThan(110.0)); - expect(text.size.width, lessThan(190.0)); - expect(text.size.height, greaterThan(110.0)); - expect(text.size.height, lessThan(190.0)); + text = tester.renderObject(find.text('X')); + expect(text.size.width, greaterThan(110.0)); + expect(text.size.width, lessThan(190.0)); + expect(text.size.height, greaterThan(110.0)); + expect(text.size.height, lessThan(190.0)); - tester.pump(new Duration(milliseconds: 1000)); + tester.pump(new Duration(milliseconds: 1000)); - expect(text.size.width, equals(200.0)); - expect(text.size.height, equals(200.0)); + expect(text.size.width, equals(200.0)); + expect(text.size.height, equals(200.0)); - tester.pumpWidget( - new Center( - child: new AnimatedContainer( - duration: const Duration(milliseconds: 200), - width: 200.0, - height: 100.0, - child: new Text('X') - ) + tester.pumpWidget( + new Center( + child: new AnimatedContainer( + duration: const Duration(milliseconds: 200), + width: 200.0, + height: 100.0, + child: new Text('X') ) - ); - tester.pump(); - tester.pump(new Duration(milliseconds: 100)); + ) + ); + tester.pump(); + tester.pump(new Duration(milliseconds: 100)); - expect(text.size.width, equals(200.0)); - expect(text.size.height, greaterThan(110.0)); - expect(text.size.height, lessThan(190.0)); + expect(text.size.width, equals(200.0)); + expect(text.size.height, greaterThan(110.0)); + expect(text.size.height, lessThan(190.0)); - tester.pump(new Duration(milliseconds: 1000)); + tester.pump(new Duration(milliseconds: 1000)); - expect(text.size.width, equals(200.0)); - expect(text.size.height, equals(100.0)); - }); + expect(text.size.width, equals(200.0)); + expect(text.size.height, equals(100.0)); }); } diff --git a/packages/flutter/test/widget/animated_positioned_test.dart b/packages/flutter/test/widget/animated_positioned_test.dart index 73ab5d88fd..0534998bb2 100644 --- a/packages/flutter/test/widget/animated_positioned_test.dart +++ b/packages/flutter/test/widget/animated_positioned_test.dart @@ -8,208 +8,199 @@ import 'package:flutter/widgets.dart'; import 'package:test/test.dart'; void main() { - test('AnimatedPositioned - basics', () { - testWidgets((WidgetTester tester) { - GlobalKey key = new GlobalKey(); + testWidgets('AnimatedPositioned - basics', (WidgetTester tester) { + GlobalKey key = new GlobalKey(); - RenderBox box; + RenderBox box; - tester.pumpWidget( - new Stack( - children: [ - new AnimatedPositioned( - child: new Container(key: key), - left: 50.0, - top: 30.0, - width: 70.0, - height: 110.0, - duration: const Duration(seconds: 2) - ) - ] - ) - ); + tester.pumpWidget( + new Stack( + children: [ + new AnimatedPositioned( + child: new Container(key: key), + left: 50.0, + top: 30.0, + width: 70.0, + height: 110.0, + duration: const Duration(seconds: 2) + ) + ] + ) + ); - box = key.currentContext.findRenderObject(); - expect(box.localToGlobal(box.size.center(Point.origin)), equals(const Point(50.0 + 70.0 / 2.0, 30.0 + 110.0 / 2.0))); + box = key.currentContext.findRenderObject(); + expect(box.localToGlobal(box.size.center(Point.origin)), equals(const Point(50.0 + 70.0 / 2.0, 30.0 + 110.0 / 2.0))); - tester.pump(const Duration(seconds: 1)); + tester.pump(const Duration(seconds: 1)); - box = key.currentContext.findRenderObject(); - expect(box.localToGlobal(box.size.center(Point.origin)), equals(const Point(50.0 + 70.0 / 2.0, 30.0 + 110.0 / 2.0))); + box = key.currentContext.findRenderObject(); + expect(box.localToGlobal(box.size.center(Point.origin)), equals(const Point(50.0 + 70.0 / 2.0, 30.0 + 110.0 / 2.0))); - tester.pumpWidget( - new Stack( - children: [ - new AnimatedPositioned( - child: new Container(key: key), - left: 37.0, - top: 31.0, - width: 59.0, - height: 71.0, - duration: const Duration(seconds: 2) - ) - ] - ) - ); + tester.pumpWidget( + new Stack( + children: [ + new AnimatedPositioned( + child: new Container(key: key), + left: 37.0, + top: 31.0, + width: 59.0, + height: 71.0, + duration: const Duration(seconds: 2) + ) + ] + ) + ); - box = key.currentContext.findRenderObject(); - expect(box.localToGlobal(box.size.center(Point.origin)), equals(const Point(50.0 + 70.0 / 2.0, 30.0 + 110.0 / 2.0))); + box = key.currentContext.findRenderObject(); + expect(box.localToGlobal(box.size.center(Point.origin)), equals(const Point(50.0 + 70.0 / 2.0, 30.0 + 110.0 / 2.0))); - tester.pump(const Duration(seconds: 1)); + tester.pump(const Duration(seconds: 1)); - box = key.currentContext.findRenderObject(); - expect(box.localToGlobal(box.size.center(Point.origin)), equals(const Point(50.0 - (50.0 - 37.0) / 2.0 + (70.0 - (70.0 - 59.0) / 2.0) / 2.0, - 30.0 + (31.0 - 30.0) / 2.0 + (110.0 - (110.0 - 71.0) / 2.0) / 2.0))); + box = key.currentContext.findRenderObject(); + expect(box.localToGlobal(box.size.center(Point.origin)), equals(const Point(50.0 - (50.0 - 37.0) / 2.0 + (70.0 - (70.0 - 59.0) / 2.0) / 2.0, + 30.0 + (31.0 - 30.0) / 2.0 + (110.0 - (110.0 - 71.0) / 2.0) / 2.0))); - tester.pump(const Duration(seconds: 1)); + tester.pump(const Duration(seconds: 1)); - box = key.currentContext.findRenderObject(); - expect(box.localToGlobal(box.size.center(Point.origin)), equals(const Point(37.0 + 59.0 / 2.0, 31.0 + 71.0 / 2.0))); - - }); + box = key.currentContext.findRenderObject(); + expect(box.localToGlobal(box.size.center(Point.origin)), equals(const Point(37.0 + 59.0 / 2.0, 31.0 + 71.0 / 2.0))); }); - test('AnimatedPositioned - interrupted animation', () { - testWidgets((WidgetTester tester) { - GlobalKey key = new GlobalKey(); + testWidgets('AnimatedPositioned - interrupted animation', (WidgetTester tester) { + GlobalKey key = new GlobalKey(); - RenderBox box; + RenderBox box; - tester.pumpWidget( - new Stack( - children: [ - new AnimatedPositioned( - child: new Container(key: key), - left: 0.0, - top: 0.0, - width: 100.0, - height: 100.0, - duration: const Duration(seconds: 2) - ) - ] - ) - ); + tester.pumpWidget( + new Stack( + children: [ + new AnimatedPositioned( + child: new Container(key: key), + left: 0.0, + top: 0.0, + width: 100.0, + height: 100.0, + duration: const Duration(seconds: 2) + ) + ] + ) + ); - box = key.currentContext.findRenderObject(); - expect(box.localToGlobal(box.size.center(Point.origin)), equals(const Point(50.0, 50.0))); + box = key.currentContext.findRenderObject(); + expect(box.localToGlobal(box.size.center(Point.origin)), equals(const Point(50.0, 50.0))); - tester.pump(const Duration(seconds: 1)); + tester.pump(const Duration(seconds: 1)); - box = key.currentContext.findRenderObject(); - expect(box.localToGlobal(box.size.center(Point.origin)), equals(const Point(50.0, 50.0))); + box = key.currentContext.findRenderObject(); + expect(box.localToGlobal(box.size.center(Point.origin)), equals(const Point(50.0, 50.0))); - tester.pumpWidget( - new Stack( - children: [ - new AnimatedPositioned( - child: new Container(key: key), - left: 100.0, - top: 100.0, - width: 100.0, - height: 100.0, - duration: const Duration(seconds: 2) - ) - ] - ) - ); + tester.pumpWidget( + new Stack( + children: [ + new AnimatedPositioned( + child: new Container(key: key), + left: 100.0, + top: 100.0, + width: 100.0, + height: 100.0, + duration: const Duration(seconds: 2) + ) + ] + ) + ); - box = key.currentContext.findRenderObject(); - expect(box.localToGlobal(box.size.center(Point.origin)), equals(const Point(50.0, 50.0))); + box = key.currentContext.findRenderObject(); + expect(box.localToGlobal(box.size.center(Point.origin)), equals(const Point(50.0, 50.0))); - tester.pump(const Duration(seconds: 1)); + tester.pump(const Duration(seconds: 1)); - box = key.currentContext.findRenderObject(); - expect(box.localToGlobal(box.size.center(Point.origin)), equals(const Point(100.0, 100.0))); + box = key.currentContext.findRenderObject(); + expect(box.localToGlobal(box.size.center(Point.origin)), equals(const Point(100.0, 100.0))); - tester.pumpWidget( - new Stack( - children: [ - new AnimatedPositioned( - child: new Container(key: key), - left: 150.0, - top: 150.0, - width: 100.0, - height: 100.0, - duration: const Duration(seconds: 2) - ) - ] - ) - ); + tester.pumpWidget( + new Stack( + children: [ + new AnimatedPositioned( + child: new Container(key: key), + left: 150.0, + top: 150.0, + width: 100.0, + height: 100.0, + duration: const Duration(seconds: 2) + ) + ] + ) + ); - box = key.currentContext.findRenderObject(); - expect(box.localToGlobal(box.size.center(Point.origin)), equals(const Point(100.0, 100.0))); + box = key.currentContext.findRenderObject(); + expect(box.localToGlobal(box.size.center(Point.origin)), equals(const Point(100.0, 100.0))); - tester.pump(const Duration(seconds: 1)); + tester.pump(const Duration(seconds: 1)); - box = key.currentContext.findRenderObject(); - expect(box.localToGlobal(box.size.center(Point.origin)), equals(const Point(150.0, 150.0))); + box = key.currentContext.findRenderObject(); + expect(box.localToGlobal(box.size.center(Point.origin)), equals(const Point(150.0, 150.0))); - tester.pump(const Duration(seconds: 1)); + tester.pump(const Duration(seconds: 1)); - box = key.currentContext.findRenderObject(); - expect(box.localToGlobal(box.size.center(Point.origin)), equals(const Point(200.0, 200.0))); - - }); + box = key.currentContext.findRenderObject(); + expect(box.localToGlobal(box.size.center(Point.origin)), equals(const Point(200.0, 200.0))); }); - test('AnimatedPositioned - switching variables', () { - testWidgets((WidgetTester tester) { - GlobalKey key = new GlobalKey(); + testWidgets('AnimatedPositioned - switching variables', (WidgetTester tester) { + GlobalKey key = new GlobalKey(); - RenderBox box; + RenderBox box; - tester.pumpWidget( - new Stack( - children: [ - new AnimatedPositioned( - child: new Container(key: key), - left: 0.0, - top: 0.0, - width: 100.0, - height: 100.0, - duration: const Duration(seconds: 2) - ) - ] - ) - ); + tester.pumpWidget( + new Stack( + children: [ + new AnimatedPositioned( + child: new Container(key: key), + left: 0.0, + top: 0.0, + width: 100.0, + height: 100.0, + duration: const Duration(seconds: 2) + ) + ] + ) + ); - box = key.currentContext.findRenderObject(); - expect(box.localToGlobal(box.size.center(Point.origin)), equals(const Point(50.0, 50.0))); + box = key.currentContext.findRenderObject(); + expect(box.localToGlobal(box.size.center(Point.origin)), equals(const Point(50.0, 50.0))); - tester.pump(const Duration(seconds: 1)); + tester.pump(const Duration(seconds: 1)); - box = key.currentContext.findRenderObject(); - expect(box.localToGlobal(box.size.center(Point.origin)), equals(const Point(50.0, 50.0))); + box = key.currentContext.findRenderObject(); + expect(box.localToGlobal(box.size.center(Point.origin)), equals(const Point(50.0, 50.0))); - tester.pumpWidget( - new Stack( - children: [ - new AnimatedPositioned( - child: new Container(key: key), - left: 0.0, - top: 100.0, - right: 100.0, // 700.0 from the left - height: 100.0, - duration: const Duration(seconds: 2) - ) - ] - ) - ); + tester.pumpWidget( + new Stack( + children: [ + new AnimatedPositioned( + child: new Container(key: key), + left: 0.0, + top: 100.0, + right: 100.0, // 700.0 from the left + height: 100.0, + duration: const Duration(seconds: 2) + ) + ] + ) + ); - box = key.currentContext.findRenderObject(); - expect(box.localToGlobal(box.size.center(Point.origin)), equals(const Point(350.0, 50.0))); + box = key.currentContext.findRenderObject(); + expect(box.localToGlobal(box.size.center(Point.origin)), equals(const Point(350.0, 50.0))); - tester.pump(const Duration(seconds: 1)); + tester.pump(const Duration(seconds: 1)); - box = key.currentContext.findRenderObject(); - expect(box.localToGlobal(box.size.center(Point.origin)), equals(const Point(350.0, 100.0))); + box = key.currentContext.findRenderObject(); + expect(box.localToGlobal(box.size.center(Point.origin)), equals(const Point(350.0, 100.0))); - tester.pump(const Duration(seconds: 1)); + tester.pump(const Duration(seconds: 1)); - box = key.currentContext.findRenderObject(); - expect(box.localToGlobal(box.size.center(Point.origin)), equals(const Point(350.0, 150.0))); - - }); + box = key.currentContext.findRenderObject(); + expect(box.localToGlobal(box.size.center(Point.origin)), equals(const Point(350.0, 150.0))); }); } diff --git a/packages/flutter/test/widget/aspect_ratio_test.dart b/packages/flutter/test/widget/aspect_ratio_test.dart index 82fa8fee6d..c7e2a8baec 100644 --- a/packages/flutter/test/widget/aspect_ratio_test.dart +++ b/packages/flutter/test/widget/aspect_ratio_test.dart @@ -7,7 +7,7 @@ import 'package:flutter/rendering.dart'; import 'package:flutter/widgets.dart'; import 'package:test/test.dart'; -Size _getSize(ElementTreeTester tester, BoxConstraints constraints, double aspectRatio) { +Size _getSize(WidgetTester tester, BoxConstraints constraints, double aspectRatio) { Key childKey = new UniqueKey(); tester.pumpWidget( new Center( @@ -22,36 +22,32 @@ Size _getSize(ElementTreeTester tester, BoxConstraints constraints, double aspec ) ) ); - RenderBox box = tester.findElementByKey(childKey).renderObject; + RenderBox box = tester.renderObject(find.byKey(childKey)); return box.size; } void main() { - test('Aspect ratio control test', () { - testElementTree((ElementTreeTester tester) { - expect(_getSize(tester, new BoxConstraints.loose(new Size(500.0, 500.0)), 2.0), equals(new Size(500.0, 250.0))); - expect(_getSize(tester, new BoxConstraints.loose(new Size(500.0, 500.0)), 0.5), equals(new Size(250.0, 500.0))); - }); + testWidgets('Aspect ratio control test', (WidgetTester tester) { + expect(_getSize(tester, new BoxConstraints.loose(new Size(500.0, 500.0)), 2.0), equals(new Size(500.0, 250.0))); + expect(_getSize(tester, new BoxConstraints.loose(new Size(500.0, 500.0)), 0.5), equals(new Size(250.0, 500.0))); }); - test('Aspect ratio infinite width', () { - testElementTree((ElementTreeTester tester) { - Key childKey = new UniqueKey(); - tester.pumpWidget( - new Center( - child: new Viewport( - mainAxis: Axis.horizontal, - child: new AspectRatio( - aspectRatio: 2.0, - child: new Container( - key: childKey - ) + testWidgets('Aspect ratio infinite width', (WidgetTester tester) { + Key childKey = new UniqueKey(); + tester.pumpWidget( + new Center( + child: new Viewport( + mainAxis: Axis.horizontal, + child: new AspectRatio( + aspectRatio: 2.0, + child: new Container( + key: childKey ) ) ) - ); - RenderBox box = tester.findElementByKey(childKey).renderObject; - expect(box.size, equals(new Size(1200.0, 600.0))); - }); + ) + ); + RenderBox box = tester.renderObject(find.byKey(childKey)); + expect(box.size, equals(new Size(1200.0, 600.0))); }); } diff --git a/packages/flutter/test/widget/asset_vendor_test.dart b/packages/flutter/test/widget/asset_vendor_test.dart index 4f2e4de779..835692df53 100644 --- a/packages/flutter/test/widget/asset_vendor_test.dart +++ b/packages/flutter/test/widget/asset_vendor_test.dart @@ -120,15 +120,14 @@ Widget buildImageAtRatio(String image, Key key, double ratio, bool inferSize) { ); } -RenderImage getRenderImage(ElementTreeTester tester, Key key) { - return tester.findElementByKey(key).renderObject; +RenderImage getRenderImage(WidgetTester tester, Key key) { + return tester.renderObject/**/(find.byKey(key)); +} +TestImage getTestImage(WidgetTester tester, Key key) { + return tester.renderObject/**/(find.byKey(key)).image; } -TestImage getTestImage(ElementTreeTester tester, Key key) { - return getRenderImage(tester, key).image; -} - -void pumpTreeToLayout(ElementTreeTester tester, Widget widget) { +void pumpTreeToLayout(WidgetTester tester, Widget widget) { Duration pumpDuration = const Duration(milliseconds: 0); EnginePhase pumpPhase = EnginePhase.layout; tester.pumpWidget(widget, pumpDuration, pumpPhase); @@ -137,102 +136,88 @@ void pumpTreeToLayout(ElementTreeTester tester, Widget widget) { void main() { String image = 'assets/image.png'; - test('Image for device pixel ratio 1.0', () { + testWidgets('Image for device pixel ratio 1.0', (WidgetTester tester) { const double ratio = 1.0; - testElementTree((ElementTreeTester tester) { - Key key = new GlobalKey(); - pumpTreeToLayout(tester, buildImageAtRatio(image, key, ratio, false)); - expect(getRenderImage(tester, key).size, const Size(200.0, 200.0)); - expect(getTestImage(tester, key).scale, 1.0); - key = new GlobalKey(); - pumpTreeToLayout(tester, buildImageAtRatio(image, key, ratio, true)); - expect(getRenderImage(tester, key).size, const Size(48.0, 48.0)); - expect(getTestImage(tester, key).scale, 1.0); - }); + Key key = new GlobalKey(); + pumpTreeToLayout(tester, buildImageAtRatio(image, key, ratio, false)); + expect(getRenderImage(tester, key).size, const Size(200.0, 200.0)); + expect(getTestImage(tester, key).scale, 1.0); + key = new GlobalKey(); + pumpTreeToLayout(tester, buildImageAtRatio(image, key, ratio, true)); + expect(getRenderImage(tester, key).size, const Size(48.0, 48.0)); + expect(getTestImage(tester, key).scale, 1.0); }); - test('Image for device pixel ratio 0.5', () { + testWidgets('Image for device pixel ratio 0.5', (WidgetTester tester) { const double ratio = 0.5; - testElementTree((ElementTreeTester tester) { - Key key = new GlobalKey(); - pumpTreeToLayout(tester, buildImageAtRatio(image, key, ratio, false)); - expect(getRenderImage(tester, key).size, const Size(200.0, 200.0)); - expect(getTestImage(tester, key).scale, 1.0); - key = new GlobalKey(); - pumpTreeToLayout(tester, buildImageAtRatio(image, key, ratio, true)); - expect(getRenderImage(tester, key).size, const Size(48.0, 48.0)); - expect(getTestImage(tester, key).scale, 1.0); - }); + Key key = new GlobalKey(); + pumpTreeToLayout(tester, buildImageAtRatio(image, key, ratio, false)); + expect(getRenderImage(tester, key).size, const Size(200.0, 200.0)); + expect(getTestImage(tester, key).scale, 1.0); + key = new GlobalKey(); + pumpTreeToLayout(tester, buildImageAtRatio(image, key, ratio, true)); + expect(getRenderImage(tester, key).size, const Size(48.0, 48.0)); + expect(getTestImage(tester, key).scale, 1.0); }); - test('Image for device pixel ratio 1.5', () { + testWidgets('Image for device pixel ratio 1.5', (WidgetTester tester) { const double ratio = 1.5; - testElementTree((ElementTreeTester tester) { - Key key = new GlobalKey(); - pumpTreeToLayout(tester, buildImageAtRatio(image, key, ratio, false)); - expect(getRenderImage(tester, key).size, const Size(200.0, 200.0)); - expect(getTestImage(tester, key).scale, 1.5); - key = new GlobalKey(); - pumpTreeToLayout(tester, buildImageAtRatio(image, key, ratio, true)); - expect(getRenderImage(tester, key).size, const Size(48.0, 48.0)); - expect(getTestImage(tester, key).scale, 1.5); - }); + Key key = new GlobalKey(); + pumpTreeToLayout(tester, buildImageAtRatio(image, key, ratio, false)); + expect(getRenderImage(tester, key).size, const Size(200.0, 200.0)); + expect(getTestImage(tester, key).scale, 1.5); + key = new GlobalKey(); + pumpTreeToLayout(tester, buildImageAtRatio(image, key, ratio, true)); + expect(getRenderImage(tester, key).size, const Size(48.0, 48.0)); + expect(getTestImage(tester, key).scale, 1.5); }); - test('Image for device pixel ratio 1.75', () { + testWidgets('Image for device pixel ratio 1.75', (WidgetTester tester) { const double ratio = 1.75; - testElementTree((ElementTreeTester tester) { - Key key = new GlobalKey(); - pumpTreeToLayout(tester, buildImageAtRatio(image, key, ratio, false)); - expect(getRenderImage(tester, key).size, const Size(200.0, 200.0)); - expect(getTestImage(tester, key).scale, 1.5); - key = new GlobalKey(); - pumpTreeToLayout(tester, buildImageAtRatio(image, key, ratio, true)); - expect(getRenderImage(tester, key).size, const Size(48.0, 48.0)); - expect(getTestImage(tester, key).scale, 1.5); - }); + Key key = new GlobalKey(); + pumpTreeToLayout(tester, buildImageAtRatio(image, key, ratio, false)); + expect(getRenderImage(tester, key).size, const Size(200.0, 200.0)); + expect(getTestImage(tester, key).scale, 1.5); + key = new GlobalKey(); + pumpTreeToLayout(tester, buildImageAtRatio(image, key, ratio, true)); + expect(getRenderImage(tester, key).size, const Size(48.0, 48.0)); + expect(getTestImage(tester, key).scale, 1.5); }); - test('Image for device pixel ratio 2.3', () { + testWidgets('Image for device pixel ratio 2.3', (WidgetTester tester) { const double ratio = 2.3; - testElementTree((ElementTreeTester tester) { - Key key = new GlobalKey(); - pumpTreeToLayout(tester, buildImageAtRatio(image, key, ratio, false)); - expect(getRenderImage(tester, key).size, const Size(200.0, 200.0)); - expect(getTestImage(tester, key).scale, 2.0); - key = new GlobalKey(); - pumpTreeToLayout(tester, buildImageAtRatio(image, key, ratio, true)); - expect(getRenderImage(tester, key).size, const Size(48.0, 48.0)); - expect(getTestImage(tester, key).scale, 2.0); - }); + Key key = new GlobalKey(); + pumpTreeToLayout(tester, buildImageAtRatio(image, key, ratio, false)); + expect(getRenderImage(tester, key).size, const Size(200.0, 200.0)); + expect(getTestImage(tester, key).scale, 2.0); + key = new GlobalKey(); + pumpTreeToLayout(tester, buildImageAtRatio(image, key, ratio, true)); + expect(getRenderImage(tester, key).size, const Size(48.0, 48.0)); + expect(getTestImage(tester, key).scale, 2.0); }); - test('Image for device pixel ratio 3.7', () { + testWidgets('Image for device pixel ratio 3.7', (WidgetTester tester) { const double ratio = 3.7; - testElementTree((ElementTreeTester tester) { - Key key = new GlobalKey(); - pumpTreeToLayout(tester, buildImageAtRatio(image, key, ratio, false)); - expect(getRenderImage(tester, key).size, const Size(200.0, 200.0)); - expect(getTestImage(tester, key).scale, 4.0); - key = new GlobalKey(); - pumpTreeToLayout(tester, buildImageAtRatio(image, key, ratio, true)); - expect(getRenderImage(tester, key).size, const Size(48.0, 48.0)); - expect(getTestImage(tester, key).scale, 4.0); - }); + Key key = new GlobalKey(); + pumpTreeToLayout(tester, buildImageAtRatio(image, key, ratio, false)); + expect(getRenderImage(tester, key).size, const Size(200.0, 200.0)); + expect(getTestImage(tester, key).scale, 4.0); + key = new GlobalKey(); + pumpTreeToLayout(tester, buildImageAtRatio(image, key, ratio, true)); + expect(getRenderImage(tester, key).size, const Size(48.0, 48.0)); + expect(getTestImage(tester, key).scale, 4.0); }); - test('Image for device pixel ratio 5.1', () { + testWidgets('Image for device pixel ratio 5.1', (WidgetTester tester) { const double ratio = 5.1; - testElementTree((ElementTreeTester tester) { - Key key = new GlobalKey(); - pumpTreeToLayout(tester, buildImageAtRatio(image, key, ratio, false)); - expect(getRenderImage(tester, key).size, const Size(200.0, 200.0)); - expect(getTestImage(tester, key).scale, 4.0); - key = new GlobalKey(); - pumpTreeToLayout(tester, buildImageAtRatio(image, key, ratio, true)); - expect(getRenderImage(tester, key).size, const Size(48.0, 48.0)); - expect(getTestImage(tester, key).scale, 4.0); - }); + Key key = new GlobalKey(); + pumpTreeToLayout(tester, buildImageAtRatio(image, key, ratio, false)); + expect(getRenderImage(tester, key).size, const Size(200.0, 200.0)); + expect(getTestImage(tester, key).scale, 4.0); + key = new GlobalKey(); + pumpTreeToLayout(tester, buildImageAtRatio(image, key, ratio, true)); + expect(getRenderImage(tester, key).size, const Size(48.0, 48.0)); + expect(getTestImage(tester, key).scale, 4.0); }); } diff --git a/packages/flutter/test/widget/block_test.dart b/packages/flutter/test/widget/block_test.dart index 73152a7336..33ceada685 100644 --- a/packages/flutter/test/widget/block_test.dart +++ b/packages/flutter/test/widget/block_test.dart @@ -9,107 +9,101 @@ import 'package:test/test.dart'; final Key blockKey = new Key('test'); void main() { - test('Cannot scroll a non-overflowing block', () { - testWidgets((WidgetTester tester) { - tester.pumpWidget( - new Block( - key: blockKey, - children: [ - new Container( - height: 200.0, // less than 600, the height of the test area - child: new Text('Hello') - ) - ] - ) - ); + testWidgets('Cannot scroll a non-overflowing block', (WidgetTester tester) { + tester.pumpWidget( + new Block( + key: blockKey, + children: [ + new Container( + height: 200.0, // less than 600, the height of the test area + child: new Text('Hello') + ) + ] + ) + ); - Point middleOfContainer = tester.getCenter(find.text('Hello')); - Point target = tester.getCenter(find.byKey(blockKey)); - TestGesture gesture = tester.startGesture(target); - gesture.moveBy(const Offset(0.0, -10.0)); + Point middleOfContainer = tester.getCenter(find.text('Hello')); + Point target = tester.getCenter(find.byKey(blockKey)); + TestGesture gesture = tester.startGesture(target); + gesture.moveBy(const Offset(0.0, -10.0)); - tester.pump(const Duration(milliseconds: 1)); + tester.pump(const Duration(milliseconds: 1)); - expect(tester.getCenter(find.text('Hello')) == middleOfContainer, isTrue); + expect(tester.getCenter(find.text('Hello')) == middleOfContainer, isTrue); - gesture.up(); - }); + gesture.up(); }); - test('Can scroll an overflowing block', () { - testWidgets((WidgetTester tester) { - tester.pumpWidget( - new Block( - key: blockKey, - children: [ - new Container( + testWidgets('Can scroll an overflowing block', (WidgetTester tester) { + tester.pumpWidget( + new Block( + key: blockKey, + children: [ + new Container( + height: 2000.0, // more than 600, the height of the test area + child: new Text('Hello') + ) + ] + ) + ); + + Point middleOfContainer = tester.getCenter(find.text('Hello')); + expect(middleOfContainer.x, equals(400.0)); + expect(middleOfContainer.y, equals(1000.0)); + + Point target = tester.getCenter(find.byKey(blockKey)); + TestGesture gesture = tester.startGesture(target); + gesture.moveBy(const Offset(0.0, -10.0)); + + tester.pump(); // redo layout + + expect(tester.getCenter(find.text('Hello')), isNot(equals(middleOfContainer))); + + gesture.up(); + }); + + testWidgets('Scroll anchor', (WidgetTester tester) { + int first = 0; + int second = 0; + + Widget buildBlock(ViewportAnchor scrollAnchor) { + return new Block( + key: new UniqueKey(), + scrollAnchor: scrollAnchor, + children: [ + new GestureDetector( + onTap: () { ++first; }, + child: new Container( height: 2000.0, // more than 600, the height of the test area - child: new Text('Hello') + decoration: new BoxDecoration( + backgroundColor: new Color(0xFF00FF00) + ) ) - ] - ) + ), + new GestureDetector( + onTap: () { ++second; }, + child: new Container( + height: 2000.0, // more than 600, the height of the test area + decoration: new BoxDecoration( + backgroundColor: new Color(0xFF0000FF) + ) + ) + ) + ] ); + } - Point middleOfContainer = tester.getCenter(find.text('Hello')); - expect(middleOfContainer.x, equals(400.0)); - expect(middleOfContainer.y, equals(1000.0)); + tester.pumpWidget(buildBlock(ViewportAnchor.end)); - Point target = tester.getCenter(find.byKey(blockKey)); - TestGesture gesture = tester.startGesture(target); - gesture.moveBy(const Offset(0.0, -10.0)); + Point target = const Point(200.0, 200.0); + tester.tapAt(target); + expect(first, equals(0)); + expect(second, equals(1)); - tester.pump(); // redo layout + tester.pumpWidget(buildBlock(ViewportAnchor.start)); - expect(tester.getCenter(find.text('Hello')), isNot(equals(middleOfContainer))); - - gesture.up(); - }); - }); - - test('Scroll anchor', () { - testWidgets((WidgetTester tester) { - int first = 0; - int second = 0; - - Widget buildBlock(ViewportAnchor scrollAnchor) { - return new Block( - key: new UniqueKey(), - scrollAnchor: scrollAnchor, - children: [ - new GestureDetector( - onTap: () { ++first; }, - child: new Container( - height: 2000.0, // more than 600, the height of the test area - decoration: new BoxDecoration( - backgroundColor: new Color(0xFF00FF00) - ) - ) - ), - new GestureDetector( - onTap: () { ++second; }, - child: new Container( - height: 2000.0, // more than 600, the height of the test area - decoration: new BoxDecoration( - backgroundColor: new Color(0xFF0000FF) - ) - ) - ) - ] - ); - } - - tester.pumpWidget(buildBlock(ViewportAnchor.end)); - - Point target = const Point(200.0, 200.0); - tester.tapAt(target); - expect(first, equals(0)); - expect(second, equals(1)); - - tester.pumpWidget(buildBlock(ViewportAnchor.start)); - - tester.tapAt(target); - expect(first, equals(1)); - expect(second, equals(1)); - }); + tester.tapAt(target); + expect(first, equals(1)); + expect(second, equals(1)); }); } diff --git a/packages/flutter/test/widget/bottom_sheet_rebuild_test.dart b/packages/flutter/test/widget/bottom_sheet_rebuild_test.dart index 11a793f93d..02d87ba37a 100644 --- a/packages/flutter/test/widget/bottom_sheet_rebuild_test.dart +++ b/packages/flutter/test/widget/bottom_sheet_rebuild_test.dart @@ -7,35 +7,33 @@ import 'package:flutter/material.dart'; import 'package:test/test.dart'; void main() { - test('Verify that a BottomSheet can be rebuilt with ScaffoldFeatureController.setState()', () { - testWidgets((WidgetTester tester) { - final GlobalKey scaffoldKey = new GlobalKey(); - PersistentBottomSheetController bottomSheet; - int buildCount = 0; + testWidgets('Verify that a BottomSheet can be rebuilt with ScaffoldFeatureController.setState()', (WidgetTester tester) { + final GlobalKey scaffoldKey = new GlobalKey(); + PersistentBottomSheetController bottomSheet; + int buildCount = 0; - tester.pumpWidget(new MaterialApp( - home: new Scaffold( - key: scaffoldKey, - body: new Center(child: new Text('body')) - ) - )); + tester.pumpWidget(new MaterialApp( + home: new Scaffold( + key: scaffoldKey, + body: new Center(child: new Text('body')) + ) + )); - bottomSheet = scaffoldKey.currentState.showBottomSheet/**/((_) { - return new Builder( - builder: (BuildContext context) { - buildCount += 1; - return new Container(height: 200.0); - } - ); - }); - - tester.pump(); - expect(buildCount, equals(1)); - - bottomSheet.setState((){ }); - tester.pump(); - expect(buildCount, equals(2)); + bottomSheet = scaffoldKey.currentState.showBottomSheet/**/((_) { + return new Builder( + builder: (BuildContext context) { + buildCount += 1; + return new Container(height: 200.0); + } + ); }); + + tester.pump(); + expect(buildCount, equals(1)); + + bottomSheet.setState((){ }); + tester.pump(); + expect(buildCount, equals(2)); }); } diff --git a/packages/flutter/test/widget/bottom_sheet_test.dart b/packages/flutter/test/widget/bottom_sheet_test.dart index c5740e6266..96a35c1593 100644 --- a/packages/flutter/test/widget/bottom_sheet_test.dart +++ b/packages/flutter/test/widget/bottom_sheet_test.dart @@ -8,111 +8,107 @@ import 'package:flutter/widgets.dart'; import 'package:test/test.dart'; void main() { - test('Verify that a tap dismisses a modal BottomSheet', () { - testWidgets((WidgetTester tester) { - BuildContext savedContext; - bool showBottomSheetThenCalled = false; + testWidgets('Verify that a tap dismisses a modal BottomSheet', (WidgetTester tester) { + BuildContext savedContext; + bool showBottomSheetThenCalled = false; - tester.pumpWidget(new MaterialApp( - home: new Builder( - builder: (BuildContext context) { - savedContext = context; - return new Container(); - } - ) - )); + tester.pumpWidget(new MaterialApp( + home: new Builder( + builder: (BuildContext context) { + savedContext = context; + return new Container(); + } + ) + )); - tester.pump(); - expect(tester, doesNotHaveWidget(find.text('BottomSheet'))); + tester.pump(); + expect(find.text('BottomSheet'), findsNothing); - showModalBottomSheet/**/( - context: savedContext, - builder: (BuildContext context) => new Text('BottomSheet') - ).then((Null result) { - expect(result, isNull); - showBottomSheetThenCalled = true; - }); - - tester.pump(); // bottom sheet show animation starts - tester.pump(new Duration(seconds: 1)); // animation done - expect(tester, hasWidget(find.text('BottomSheet'))); - expect(showBottomSheetThenCalled, isFalse); - - // Tap on the the bottom sheet itself to dismiss it - tester.tap(find.text('BottomSheet')); - tester.pump(); // bottom sheet dismiss animation starts - expect(showBottomSheetThenCalled, isTrue); - tester.pump(new Duration(seconds: 1)); // last frame of animation (sheet is entirely off-screen, but still present) - tester.pump(new Duration(seconds: 1)); // frame after the animation (sheet has been removed) - expect(tester, doesNotHaveWidget(find.text('BottomSheet'))); - - showModalBottomSheet/**/(context: savedContext, builder: (BuildContext context) => new Text('BottomSheet')); - tester.pump(); // bottom sheet show animation starts - tester.pump(new Duration(seconds: 1)); // animation done - expect(tester, hasWidget(find.text('BottomSheet'))); - - // Tap above the the bottom sheet to dismiss it - tester.tapAt(new Point(20.0, 20.0)); - tester.pump(); // bottom sheet dismiss animation starts - tester.pump(new Duration(seconds: 1)); // animation done - tester.pump(new Duration(seconds: 1)); // rebuild frame - expect(tester, doesNotHaveWidget(find.text('BottomSheet'))); + showModalBottomSheet/**/( + context: savedContext, + builder: (BuildContext context) => new Text('BottomSheet') + ).then((Null result) { + expect(result, isNull); + showBottomSheetThenCalled = true; }); + + tester.pump(); // bottom sheet show animation starts + tester.pump(new Duration(seconds: 1)); // animation done + expect(find.text('BottomSheet'), findsOneWidget); + expect(showBottomSheetThenCalled, isFalse); + + // Tap on the the bottom sheet itself to dismiss it + tester.tap(find.text('BottomSheet')); + tester.pump(); // bottom sheet dismiss animation starts + expect(showBottomSheetThenCalled, isTrue); + tester.pump(new Duration(seconds: 1)); // last frame of animation (sheet is entirely off-screen, but still present) + tester.pump(new Duration(seconds: 1)); // frame after the animation (sheet has been removed) + expect(find.text('BottomSheet'), findsNothing); + + showModalBottomSheet/**/(context: savedContext, builder: (BuildContext context) => new Text('BottomSheet')); + tester.pump(); // bottom sheet show animation starts + tester.pump(new Duration(seconds: 1)); // animation done + expect(find.text('BottomSheet'), findsOneWidget); + + // Tap above the the bottom sheet to dismiss it + tester.tapAt(new Point(20.0, 20.0)); + tester.pump(); // bottom sheet dismiss animation starts + tester.pump(new Duration(seconds: 1)); // animation done + tester.pump(new Duration(seconds: 1)); // rebuild frame + expect(find.text('BottomSheet'), findsNothing); }); - test('Verify that a downwards fling dismisses a persistent BottomSheet', () { - testWidgets((WidgetTester tester) { - GlobalKey scaffoldKey = new GlobalKey(); - bool showBottomSheetThenCalled = false; + testWidgets('Verify that a downwards fling dismisses a persistent BottomSheet', (WidgetTester tester) { + GlobalKey scaffoldKey = new GlobalKey(); + bool showBottomSheetThenCalled = false; - tester.pumpWidget(new MaterialApp( - home: new Scaffold( - key: scaffoldKey, - body: new Center(child: new Text('body')) - ) - )); + tester.pumpWidget(new MaterialApp( + home: new Scaffold( + key: scaffoldKey, + body: new Center(child: new Text('body')) + ) + )); - expect(showBottomSheetThenCalled, isFalse); - expect(tester, doesNotHaveWidget(find.text('BottomSheet'))); + expect(showBottomSheetThenCalled, isFalse); + expect(find.text('BottomSheet'), findsNothing); - scaffoldKey.currentState.showBottomSheet((BuildContext context) { - return new Container( - margin: new EdgeInsets.all(40.0), - child: new Text('BottomSheet') - ); - }).closed.then((_) { - showBottomSheetThenCalled = true; - }); - - expect(showBottomSheetThenCalled, isFalse); - expect(tester, doesNotHaveWidget(find.text('BottomSheet'))); - - tester.pump(); // bottom sheet show animation starts - - expect(showBottomSheetThenCalled, isFalse); - expect(tester, hasWidget(find.text('BottomSheet'))); - - tester.pump(new Duration(seconds: 1)); // animation done - - expect(showBottomSheetThenCalled, isFalse); - expect(tester, hasWidget(find.text('BottomSheet'))); - - tester.fling(find.text('BottomSheet'), const Offset(0.0, 20.0), 1000.0); - tester.pump(); // drain the microtask queue (Future completion callback) - - expect(showBottomSheetThenCalled, isTrue); - expect(tester, hasWidget(find.text('BottomSheet'))); - - tester.pump(); // bottom sheet dismiss animation starts - - expect(showBottomSheetThenCalled, isTrue); - expect(tester, hasWidget(find.text('BottomSheet'))); - - tester.pump(new Duration(seconds: 1)); // animation done - - expect(showBottomSheetThenCalled, isTrue); - expect(tester, doesNotHaveWidget(find.text('BottomSheet'))); + scaffoldKey.currentState.showBottomSheet((BuildContext context) { + return new Container( + margin: new EdgeInsets.all(40.0), + child: new Text('BottomSheet') + ); + }).closed.then((_) { + showBottomSheetThenCalled = true; }); + + expect(showBottomSheetThenCalled, isFalse); + expect(find.text('BottomSheet'), findsNothing); + + tester.pump(); // bottom sheet show animation starts + + expect(showBottomSheetThenCalled, isFalse); + expect(find.text('BottomSheet'), findsOneWidget); + + tester.pump(new Duration(seconds: 1)); // animation done + + expect(showBottomSheetThenCalled, isFalse); + expect(find.text('BottomSheet'), findsOneWidget); + + tester.fling(find.text('BottomSheet'), const Offset(0.0, 20.0), 1000.0); + tester.pump(); // drain the microtask queue (Future completion callback) + + expect(showBottomSheetThenCalled, isTrue); + expect(find.text('BottomSheet'), findsOneWidget); + + tester.pump(); // bottom sheet dismiss animation starts + + expect(showBottomSheetThenCalled, isTrue); + expect(find.text('BottomSheet'), findsOneWidget); + + tester.pump(new Duration(seconds: 1)); // animation done + + expect(showBottomSheetThenCalled, isTrue); + expect(find.text('BottomSheet'), findsNothing); }); } diff --git a/packages/flutter/test/widget/box_decoration_test.dart b/packages/flutter/test/widget/box_decoration_test.dart index 60520c8741..8588f58208 100644 --- a/packages/flutter/test/widget/box_decoration_test.dart +++ b/packages/flutter/test/widget/box_decoration_test.dart @@ -8,37 +8,33 @@ import 'package:flutter/widgets.dart'; import 'package:test/test.dart'; void main() { - test('Circles can have uniform borders', () { - testWidgets((WidgetTester tester) { - tester.pumpWidget( - new Container( - padding: new EdgeInsets.all(50.0), - decoration: new BoxDecoration( - shape: BoxShape.circle, - border: new Border.all(width: 10.0, color: const Color(0x80FF00FF)), - backgroundColor: Colors.teal[600] - ) + testWidgets('Circles can have uniform borders', (WidgetTester tester) { + tester.pumpWidget( + new Container( + padding: new EdgeInsets.all(50.0), + decoration: new BoxDecoration( + shape: BoxShape.circle, + border: new Border.all(width: 10.0, color: const Color(0x80FF00FF)), + backgroundColor: Colors.teal[600] ) - ); - }); + ) + ); }); - test('Bordered Container insets its child', () { - testWidgets((WidgetTester tester) { - Key key = new Key('outerContainer'); - tester.pumpWidget( - new Center( + testWidgets('Bordered Container insets its child', (WidgetTester tester) { + Key key = new Key('outerContainer'); + tester.pumpWidget( + new Center( + child: new Container( + key: key, + decoration: new BoxDecoration(border: new Border.all(width: 10.0)), child: new Container( - key: key, - decoration: new BoxDecoration(border: new Border.all(width: 10.0)), - child: new Container( - width: 25.0, - height: 25.0 - ) + width: 25.0, + height: 25.0 ) ) - ); - expect(tester.getSize(find.byKey(key)), equals(const Size(45.0, 45.0))); - }); + ) + ); + expect(tester.getSize(find.byKey(key)), equals(const Size(45.0, 45.0))); }); } diff --git a/packages/flutter/test/widget/build_scope_test.dart b/packages/flutter/test/widget/build_scope_test.dart index 2693fa5c38..d799413dd4 100644 --- a/packages/flutter/test/widget/build_scope_test.dart +++ b/packages/flutter/test/widget/build_scope_test.dart @@ -78,47 +78,41 @@ class BadDisposeWidgetState extends State { } void main() { - test('Legal times for setState', () { - testWidgets((WidgetTester tester) { - GlobalKey flipKey = new GlobalKey(); - expect(ProbeWidgetState.buildCount, equals(0)); - tester.pumpWidget(new ProbeWidget()); - expect(ProbeWidgetState.buildCount, equals(1)); - tester.pumpWidget(new ProbeWidget()); - expect(ProbeWidgetState.buildCount, equals(2)); - tester.pumpWidget(new FlipWidget( - key: flipKey, - left: new Container(), - right: new ProbeWidget() - )); - expect(ProbeWidgetState.buildCount, equals(2)); - FlipWidgetState flipState1 = flipKey.currentState; - flipState1.flip(); - tester.pump(); - expect(ProbeWidgetState.buildCount, equals(3)); - FlipWidgetState flipState2 = flipKey.currentState; - flipState2.flip(); - tester.pump(); - expect(ProbeWidgetState.buildCount, equals(3)); - tester.pumpWidget(new Container()); - expect(ProbeWidgetState.buildCount, equals(3)); - }); + testWidgets('Legal times for setState', (WidgetTester tester) { + GlobalKey flipKey = new GlobalKey(); + expect(ProbeWidgetState.buildCount, equals(0)); + tester.pumpWidget(new ProbeWidget()); + expect(ProbeWidgetState.buildCount, equals(1)); + tester.pumpWidget(new ProbeWidget()); + expect(ProbeWidgetState.buildCount, equals(2)); + tester.pumpWidget(new FlipWidget( + key: flipKey, + left: new Container(), + right: new ProbeWidget() + )); + expect(ProbeWidgetState.buildCount, equals(2)); + FlipWidgetState flipState1 = flipKey.currentState; + flipState1.flip(); + tester.pump(); + expect(ProbeWidgetState.buildCount, equals(3)); + FlipWidgetState flipState2 = flipKey.currentState; + flipState2.flip(); + tester.pump(); + expect(ProbeWidgetState.buildCount, equals(3)); + tester.pumpWidget(new Container()); + expect(ProbeWidgetState.buildCount, equals(3)); }); - test('Setting parent state during build is forbidden', () { - testWidgets((WidgetTester tester) { - tester.pumpWidget(new BadWidgetParent()); - expect(tester.takeException(), isNotNull); - tester.pumpWidget(new Container()); - }); + testWidgets('Setting parent state during build is forbidden', (WidgetTester tester) { + tester.pumpWidget(new BadWidgetParent()); + expect(tester.takeException(), isNotNull); + tester.pumpWidget(new Container()); }); - test('Setting state during dispose is forbidden', () { - testWidgets((WidgetTester tester) { - tester.pumpWidget(new BadDisposeWidget()); - expect(tester.takeException(), isNull); - tester.pumpWidget(new Container()); - expect(tester.takeException(), isNotNull); - }); + testWidgets('Setting state during dispose is forbidden', (WidgetTester tester) { + tester.pumpWidget(new BadDisposeWidget()); + expect(tester.takeException(), isNull); + tester.pumpWidget(new Container()); + expect(tester.takeException(), isNotNull); }); } diff --git a/packages/flutter/test/widget/buttons_test.dart b/packages/flutter/test/widget/buttons_test.dart index c35ac33d4c..eea80aeab5 100644 --- a/packages/flutter/test/widget/buttons_test.dart +++ b/packages/flutter/test/widget/buttons_test.dart @@ -10,45 +10,43 @@ import 'package:test/test.dart'; import 'test_semantics.dart'; void main() { - test('Does FlatButton contribute semantics', () { - testWidgets((WidgetTester tester) { - TestSemanticsListener client = new TestSemanticsListener(); - tester.pumpWidget( - new Material( - child: new Center( - child: new FlatButton( - onPressed: () { }, - child: new Text('Hello') - ) + testWidgets('Does FlatButton contribute semantics', (WidgetTester tester) { + TestSemanticsListener client = new TestSemanticsListener(); + tester.pumpWidget( + new Material( + child: new Center( + child: new FlatButton( + onPressed: () { }, + child: new Text('Hello') ) ) - ); - expect(client.updates.length, equals(2)); - expect(client.updates[0].id, equals(0)); - expect(client.updates[0].flags.canBeTapped, isFalse); - expect(client.updates[0].flags.canBeLongPressed, isFalse); - expect(client.updates[0].flags.canBeScrolledHorizontally, isFalse); - expect(client.updates[0].flags.canBeScrolledVertically, isFalse); - expect(client.updates[0].flags.hasCheckedState, isFalse); - expect(client.updates[0].flags.isChecked, isFalse); - expect(client.updates[0].strings.label, equals('')); - expect(client.updates[0].geometry.transform, isNull); - expect(client.updates[0].geometry.left, equals(0.0)); - expect(client.updates[0].geometry.top, equals(0.0)); - expect(client.updates[0].geometry.width, equals(800.0)); - expect(client.updates[0].geometry.height, equals(600.0)); - expect(client.updates[0].children.length, equals(1)); - expect(client.updates[0].children[0].id, equals(1)); - expect(client.updates[0].children[0].flags.canBeTapped, isTrue); - expect(client.updates[0].children[0].flags.canBeLongPressed, isFalse); - expect(client.updates[0].children[0].flags.canBeScrolledHorizontally, isFalse); - expect(client.updates[0].children[0].flags.canBeScrolledVertically, isFalse); - expect(client.updates[0].children[0].flags.hasCheckedState, isFalse); - expect(client.updates[0].children[0].flags.isChecked, isFalse); - expect(client.updates[0].children[0].strings.label, equals('Hello')); - expect(client.updates[0].children[0].children.length, equals(0)); - expect(client.updates[1], isNull); - client.updates.clear(); - }); + ) + ); + expect(client.updates.length, equals(2)); + expect(client.updates[0].id, equals(0)); + expect(client.updates[0].flags.canBeTapped, isFalse); + expect(client.updates[0].flags.canBeLongPressed, isFalse); + expect(client.updates[0].flags.canBeScrolledHorizontally, isFalse); + expect(client.updates[0].flags.canBeScrolledVertically, isFalse); + expect(client.updates[0].flags.hasCheckedState, isFalse); + expect(client.updates[0].flags.isChecked, isFalse); + expect(client.updates[0].strings.label, equals('')); + expect(client.updates[0].geometry.transform, isNull); + expect(client.updates[0].geometry.left, equals(0.0)); + expect(client.updates[0].geometry.top, equals(0.0)); + expect(client.updates[0].geometry.width, equals(800.0)); + expect(client.updates[0].geometry.height, equals(600.0)); + expect(client.updates[0].children.length, equals(1)); + expect(client.updates[0].children[0].id, equals(1)); + expect(client.updates[0].children[0].flags.canBeTapped, isTrue); + expect(client.updates[0].children[0].flags.canBeLongPressed, isFalse); + expect(client.updates[0].children[0].flags.canBeScrolledHorizontally, isFalse); + expect(client.updates[0].children[0].flags.canBeScrolledVertically, isFalse); + expect(client.updates[0].children[0].flags.hasCheckedState, isFalse); + expect(client.updates[0].children[0].flags.isChecked, isFalse); + expect(client.updates[0].children[0].strings.label, equals('Hello')); + expect(client.updates[0].children[0].children.length, equals(0)); + expect(client.updates[1], isNull); + client.updates.clear(); }); } diff --git a/packages/flutter/test/widget/center_test.dart b/packages/flutter/test/widget/center_test.dart index e19ceab3aa..0baeaca5c0 100644 --- a/packages/flutter/test/widget/center_test.dart +++ b/packages/flutter/test/widget/center_test.dart @@ -4,12 +4,9 @@ import 'package:flutter_test/flutter_test.dart'; import 'package:flutter/widgets.dart'; -import 'package:test/test.dart'; void main() { - test('Can be placed in an infinite box', () { - testWidgets((WidgetTester tester) { - tester.pumpWidget(new Block(children: [new Center()])); - }); + testWidgets('Can be placed in an infinite box', (WidgetTester tester) { + tester.pumpWidget(new Block(children: [new Center()])); }); } diff --git a/packages/flutter/test/widget/coordinates_test.dart b/packages/flutter/test/widget/coordinates_test.dart index ac59ede4c9..0c9245b46b 100644 --- a/packages/flutter/test/widget/coordinates_test.dart +++ b/packages/flutter/test/widget/coordinates_test.dart @@ -8,42 +8,40 @@ import 'package:flutter/widgets.dart'; import 'package:test/test.dart'; void main() { - test('Comparing coordinates', () { - testElementTree((ElementTreeTester tester) { - Key keyA = new GlobalKey(); - Key keyB = new GlobalKey(); + testWidgets('Comparing coordinates', (WidgetTester tester) { + Key keyA = new GlobalKey(); + Key keyB = new GlobalKey(); - tester.pumpWidget( - new Stack( - children: [ - new Positioned( - top: 100.0, - left: 100.0, - child: new SizedBox( - key: keyA, - width: 10.0, - height: 10.0 - ) - ), - new Positioned( - left: 100.0, - top: 200.0, - child: new SizedBox( - key: keyB, - width: 20.0, - height: 10.0 - ) - ), - ] - ) - ); + tester.pumpWidget( + new Stack( + children: [ + new Positioned( + top: 100.0, + left: 100.0, + child: new SizedBox( + key: keyA, + width: 10.0, + height: 10.0 + ) + ), + new Positioned( + left: 100.0, + top: 200.0, + child: new SizedBox( + key: keyB, + width: 20.0, + height: 10.0 + ) + ), + ] + ) + ); - RenderBox boxA = tester.findElementByKey(keyA).renderObject; - expect(boxA.localToGlobal(const Point(0.0, 0.0)), equals(const Point(100.0, 100.0))); + RenderBox boxA = tester.renderObject(find.byKey(keyA)); + expect(boxA.localToGlobal(const Point(0.0, 0.0)), equals(const Point(100.0, 100.0))); - RenderBox boxB = tester.findElementByKey(keyB).renderObject; - expect(boxB.localToGlobal(const Point(0.0, 0.0)), equals(const Point(100.0, 200.0))); - expect(boxB.globalToLocal(const Point(110.0, 205.0)), equals(const Point(10.0, 5.0))); - }); + RenderBox boxB = tester.renderObject(find.byKey(keyB)); + expect(boxB.localToGlobal(const Point(0.0, 0.0)), equals(const Point(100.0, 200.0))); + expect(boxB.globalToLocal(const Point(110.0, 205.0)), equals(const Point(10.0, 5.0))); }); } diff --git a/packages/flutter/test/widget/custom_multi_child_layout_test.dart b/packages/flutter/test/widget/custom_multi_child_layout_test.dart index aa6953a925..84e85558d0 100644 --- a/packages/flutter/test/widget/custom_multi_child_layout_test.dart +++ b/packages/flutter/test/widget/custom_multi_child_layout_test.dart @@ -75,99 +75,91 @@ class PreferredSizeDelegate extends MultiChildLayoutDelegate { } void main() { - test('Control test for CustomMultiChildLayout', () { - testWidgets((WidgetTester tester) { - TestMultiChildLayoutDelegate delegate = new TestMultiChildLayoutDelegate(); - tester.pumpWidget(buildFrame(delegate)); + testWidgets('Control test for CustomMultiChildLayout', (WidgetTester tester) { + TestMultiChildLayoutDelegate delegate = new TestMultiChildLayoutDelegate(); + tester.pumpWidget(buildFrame(delegate)); - expect(delegate.getSizeConstraints.minWidth, 0.0); - expect(delegate.getSizeConstraints.maxWidth, 800.0); - expect(delegate.getSizeConstraints.minHeight, 0.0); - expect(delegate.getSizeConstraints.maxHeight, 600.0); + expect(delegate.getSizeConstraints.minWidth, 0.0); + expect(delegate.getSizeConstraints.maxWidth, 800.0); + expect(delegate.getSizeConstraints.minHeight, 0.0); + expect(delegate.getSizeConstraints.maxHeight, 600.0); - expect(delegate.performLayoutSize.width, 200.0); - expect(delegate.performLayoutSize.height, 300.0); - expect(delegate.performLayoutSize0.width, 150.0); - expect(delegate.performLayoutSize0.height, 100.0); - expect(delegate.performLayoutSize1.width, 100.0); - expect(delegate.performLayoutSize1.height, 200.0); - expect(delegate.performLayoutIsChild, false); - }); + expect(delegate.performLayoutSize.width, 200.0); + expect(delegate.performLayoutSize.height, 300.0); + expect(delegate.performLayoutSize0.width, 150.0); + expect(delegate.performLayoutSize0.height, 100.0); + expect(delegate.performLayoutSize1.width, 100.0); + expect(delegate.performLayoutSize1.height, 200.0); + expect(delegate.performLayoutIsChild, false); }); - test('Test MultiChildDelegate shouldRelayout method', () { - testWidgets((WidgetTester tester) { - TestMultiChildLayoutDelegate delegate = new TestMultiChildLayoutDelegate(); - tester.pumpWidget(buildFrame(delegate)); + testWidgets('Test MultiChildDelegate shouldRelayout method', (WidgetTester tester) { + TestMultiChildLayoutDelegate delegate = new TestMultiChildLayoutDelegate(); + tester.pumpWidget(buildFrame(delegate)); - // Layout happened because the delegate was set. - expect(delegate.performLayoutSize, isNotNull); // i.e. layout happened - expect(delegate.shouldRelayoutCalled, isFalse); + // Layout happened because the delegate was set. + expect(delegate.performLayoutSize, isNotNull); // i.e. layout happened + expect(delegate.shouldRelayoutCalled, isFalse); - // Layout did not happen because shouldRelayout() returned false. - delegate = new TestMultiChildLayoutDelegate(); - delegate.shouldRelayoutValue = false; - tester.pumpWidget(buildFrame(delegate)); - expect(delegate.shouldRelayoutCalled, isTrue); - expect(delegate.performLayoutSize, isNull); + // Layout did not happen because shouldRelayout() returned false. + delegate = new TestMultiChildLayoutDelegate(); + delegate.shouldRelayoutValue = false; + tester.pumpWidget(buildFrame(delegate)); + expect(delegate.shouldRelayoutCalled, isTrue); + expect(delegate.performLayoutSize, isNull); - // Layout happened because shouldRelayout() returned true. - delegate = new TestMultiChildLayoutDelegate(); - delegate.shouldRelayoutValue = true; - tester.pumpWidget(buildFrame(delegate)); - expect(delegate.shouldRelayoutCalled, isTrue); - expect(delegate.performLayoutSize, isNotNull); - }); + // Layout happened because shouldRelayout() returned true. + delegate = new TestMultiChildLayoutDelegate(); + delegate.shouldRelayoutValue = true; + tester.pumpWidget(buildFrame(delegate)); + expect(delegate.shouldRelayoutCalled, isTrue); + expect(delegate.performLayoutSize, isNotNull); }); - test('Nested CustomMultiChildLayouts', () { - testWidgets((WidgetTester tester) { - TestMultiChildLayoutDelegate delegate = new TestMultiChildLayoutDelegate(); - tester.pumpWidget(new Center( - child: new CustomMultiChildLayout( - children: [ - new LayoutId( - id: 0, - child: new CustomMultiChildLayout( - children: [ - new LayoutId(id: 0, child: new Container(width: 150.0, height: 100.0)), - new LayoutId(id: 1, child: new Container(width: 100.0, height: 200.0)), - ], - delegate: delegate - ) - ), - new LayoutId(id: 1, child: new Container(width: 100.0, height: 200.0)), - ], - delegate: delegate - ) - )); + testWidgets('Nested CustomMultiChildLayouts', (WidgetTester tester) { + TestMultiChildLayoutDelegate delegate = new TestMultiChildLayoutDelegate(); + tester.pumpWidget(new Center( + child: new CustomMultiChildLayout( + children: [ + new LayoutId( + id: 0, + child: new CustomMultiChildLayout( + children: [ + new LayoutId(id: 0, child: new Container(width: 150.0, height: 100.0)), + new LayoutId(id: 1, child: new Container(width: 100.0, height: 200.0)), + ], + delegate: delegate + ) + ), + new LayoutId(id: 1, child: new Container(width: 100.0, height: 200.0)), + ], + delegate: delegate + ) + )); - }); }); - test('Loose constraints', () { - testElementTree((ElementTreeTester tester) { - Key key = new UniqueKey(); - tester.pumpWidget(new Center( - child: new CustomMultiChildLayout( - key: key, - delegate: new PreferredSizeDelegate(preferredSize: new Size(300.0, 200.0)) - ) - )); + testWidgets('Loose constraints', (WidgetTester tester) { + Key key = new UniqueKey(); + tester.pumpWidget(new Center( + child: new CustomMultiChildLayout( + key: key, + delegate: new PreferredSizeDelegate(preferredSize: new Size(300.0, 200.0)) + ) + )); - RenderBox box = tester.findElementByKey(key).renderObject; - expect(box.size.width, equals(300.0)); - expect(box.size.height, equals(200.0)); + RenderBox box = tester.renderObject(find.byKey(key)); + expect(box.size.width, equals(300.0)); + expect(box.size.height, equals(200.0)); - tester.pumpWidget(new Center( - child: new CustomMultiChildLayout( - key: key, - delegate: new PreferredSizeDelegate(preferredSize: new Size(350.0, 250.0)) - ) - )); + tester.pumpWidget(new Center( + child: new CustomMultiChildLayout( + key: key, + delegate: new PreferredSizeDelegate(preferredSize: new Size(350.0, 250.0)) + ) + )); - expect(box.size.width, equals(350.0)); - expect(box.size.height, equals(250.0)); - }); + expect(box.size.width, equals(350.0)); + expect(box.size.height, equals(250.0)); }); } diff --git a/packages/flutter/test/widget/custom_one_child_layout_test.dart b/packages/flutter/test/widget/custom_one_child_layout_test.dart index bc88e8a81d..80ca6341d0 100644 --- a/packages/flutter/test/widget/custom_one_child_layout_test.dart +++ b/packages/flutter/test/widget/custom_one_child_layout_test.dart @@ -56,8 +56,7 @@ Widget buildFrame(SingleChildLayoutDelegate delegate) { } void main() { - test('Control test for CustomSingleChildLayout', () { - testWidgets((WidgetTester tester) { + testWidgets('Control test for CustomSingleChildLayout', (WidgetTester tester) { TestSingleChildLayoutDelegate delegate = new TestSingleChildLayoutDelegate(); tester.pumpWidget(buildFrame(delegate)); @@ -76,11 +75,9 @@ void main() { expect(delegate.childSizeFromGetPositionForChild.width, 150.0); expect(delegate.childSizeFromGetPositionForChild.height, 400.0); - }); }); - test('Test SingleChildDelegate shouldRelayout method', () { - testWidgets((WidgetTester tester) { + testWidgets('Test SingleChildDelegate shouldRelayout method', (WidgetTester tester) { TestSingleChildLayoutDelegate delegate = new TestSingleChildLayoutDelegate(); tester.pumpWidget(buildFrame(delegate)); @@ -101,7 +98,6 @@ void main() { tester.pumpWidget(buildFrame(delegate)); expect(delegate.shouldRelayoutCalled, isTrue); expect(delegate.constraintsFromGetConstraintsForChild, isNotNull); - }); }); } diff --git a/packages/flutter/test/widget/custom_paint_test.dart b/packages/flutter/test/widget/custom_paint_test.dart index b8371a0f81..d4df472612 100644 --- a/packages/flutter/test/widget/custom_paint_test.dart +++ b/packages/flutter/test/widget/custom_paint_test.dart @@ -22,27 +22,25 @@ class TestCustomPainter extends CustomPainter { } void main() { - test('Control test for custom painting', () { - testWidgets((WidgetTester tester) { - List log = []; - tester.pumpWidget(new CustomPaint( + testWidgets('Control test for custom painting', (WidgetTester tester) { + List log = []; + tester.pumpWidget(new CustomPaint( + painter: new TestCustomPainter( + log: log, + name: 'background' + ), + foregroundPainter: new TestCustomPainter( + log: log, + name: 'foreground' + ), + child: new CustomPaint( painter: new TestCustomPainter( log: log, - name: 'background' - ), - foregroundPainter: new TestCustomPainter( - log: log, - name: 'foreground' - ), - child: new CustomPaint( - painter: new TestCustomPainter( - log: log, - name: 'child' - ) + name: 'child' ) - )); + ) + )); - expect(log, equals(['background', 'child', 'foreground'])); - }); + expect(log, equals(['background', 'child', 'foreground'])); }); } diff --git a/packages/flutter/test/widget/date_picker_test_disabled.dart b/packages/flutter/test/widget/date_picker_test_disabled.dart index e73e16c63e..bb0bac140a 100644 --- a/packages/flutter/test/widget/date_picker_test_disabled.dart +++ b/packages/flutter/test/widget/date_picker_test_disabled.dart @@ -7,35 +7,33 @@ import 'package:flutter/material.dart'; import 'package:test/test.dart'; void main() { - test('Can select a day', () { - testWidgets((WidgetTester tester) { - DateTime currentValue; + testWidgets('Can select a day', (WidgetTester tester) { + DateTime currentValue; - Widget widget = new Material( - child: new Block( - children: [ - new DatePicker( - selectedDate: new DateTime.utc(2015, 6, 9, 7, 12), - firstDate: new DateTime.utc(2013), - lastDate: new DateTime.utc(2018), - onChanged: (DateTime dateTime) { - currentValue = dateTime; - } - ) - ] - ) - ); + Widget widget = new Material( + child: new Block( + children: [ + new DatePicker( + selectedDate: new DateTime.utc(2015, 6, 9, 7, 12), + firstDate: new DateTime.utc(2013), + lastDate: new DateTime.utc(2018), + onChanged: (DateTime dateTime) { + currentValue = dateTime; + } + ) + ] + ) + ); - tester.pumpWidget(widget); + tester.pumpWidget(widget); - expect(currentValue, isNull); - tester.tap(find.text('2015')); - tester.pumpWidget(widget); - tester.tap(find.text('2014')); - tester.pumpWidget(widget); - expect(currentValue, equals(new DateTime(2014, 6, 9))); - tester.tap(find.text('30')); - expect(currentValue, equals(new DateTime(2013, 1, 30))); - }); + expect(currentValue, isNull); + tester.tap(find.text('2015')); + tester.pumpWidget(widget); + tester.tap(find.text('2014')); + tester.pumpWidget(widget); + expect(currentValue, equals(new DateTime(2014, 6, 9))); + tester.tap(find.text('30')); + expect(currentValue, equals(new DateTime(2013, 1, 30))); }); } diff --git a/packages/flutter/test/widget/dismissable_test.dart b/packages/flutter/test/widget/dismissable_test.dart index 2b0f190841..836d0bcce3 100644 --- a/packages/flutter/test/widget/dismissable_test.dart +++ b/packages/flutter/test/widget/dismissable_test.dart @@ -53,7 +53,7 @@ Widget widgetBuilder() { } void dismissElement(WidgetTester tester, Finder finder, { DismissDirection gestureDirection }) { - assert(tester.exists(finder)); + assert(tester.any(finder)); assert(gestureDirection != DismissDirection.horizontal); assert(gestureDirection != DismissDirection.vertical); @@ -96,7 +96,7 @@ void dismissItem(WidgetTester tester, int item, { DismissDirection gestureDirect assert(gestureDirection != DismissDirection.vertical); Finder itemFinder = find.text(item.toString()); - expect(tester, hasWidget(itemFinder)); + expect(itemFinder, findsOneWidget); dismissElement(tester, itemFinder, gestureDirection: gestureDirection); @@ -130,118 +130,106 @@ void main() { background = null; }); - test('Horizontal drag triggers dismiss scrollDirection=vertical', () { - testWidgets((WidgetTester tester) { - scrollDirection = Axis.vertical; - dismissDirection = DismissDirection.horizontal; + testWidgets('Horizontal drag triggers dismiss scrollDirection=vertical', (WidgetTester tester) { + scrollDirection = Axis.vertical; + dismissDirection = DismissDirection.horizontal; - tester.pumpWidget(widgetBuilder()); - expect(dismissedItems, isEmpty); + tester.pumpWidget(widgetBuilder()); + expect(dismissedItems, isEmpty); - dismissItem(tester, 0, gestureDirection: DismissDirection.startToEnd); - expect(tester, doesNotHaveWidget(find.text('0'))); - expect(dismissedItems, equals([0])); - expect(reportedDismissDirection, DismissDirection.startToEnd); + dismissItem(tester, 0, gestureDirection: DismissDirection.startToEnd); + expect(find.text('0'), findsNothing); + expect(dismissedItems, equals([0])); + expect(reportedDismissDirection, DismissDirection.startToEnd); - dismissItem(tester, 1, gestureDirection: DismissDirection.endToStart); - expect(tester, doesNotHaveWidget(find.text('1'))); - expect(dismissedItems, equals([0, 1])); - expect(reportedDismissDirection, DismissDirection.endToStart); - }); + dismissItem(tester, 1, gestureDirection: DismissDirection.endToStart); + expect(find.text('1'), findsNothing); + expect(dismissedItems, equals([0, 1])); + expect(reportedDismissDirection, DismissDirection.endToStart); }); - test('Vertical drag triggers dismiss scrollDirection=horizontal', () { - testWidgets((WidgetTester tester) { - scrollDirection = Axis.horizontal; - dismissDirection = DismissDirection.vertical; + testWidgets('Vertical drag triggers dismiss scrollDirection=horizontal', (WidgetTester tester) { + scrollDirection = Axis.horizontal; + dismissDirection = DismissDirection.vertical; - tester.pumpWidget(widgetBuilder()); - expect(dismissedItems, isEmpty); + tester.pumpWidget(widgetBuilder()); + expect(dismissedItems, isEmpty); - dismissItem(tester, 0, gestureDirection: DismissDirection.up); - expect(tester, doesNotHaveWidget(find.text('0'))); - expect(dismissedItems, equals([0])); - expect(reportedDismissDirection, DismissDirection.up); + dismissItem(tester, 0, gestureDirection: DismissDirection.up); + expect(find.text('0'), findsNothing); + expect(dismissedItems, equals([0])); + expect(reportedDismissDirection, DismissDirection.up); - dismissItem(tester, 1, gestureDirection: DismissDirection.down); - expect(tester, doesNotHaveWidget(find.text('1'))); - expect(dismissedItems, equals([0, 1])); - expect(reportedDismissDirection, DismissDirection.down); - }); + dismissItem(tester, 1, gestureDirection: DismissDirection.down); + expect(find.text('1'), findsNothing); + expect(dismissedItems, equals([0, 1])); + expect(reportedDismissDirection, DismissDirection.down); }); - test('drag-left with DismissDirection.left triggers dismiss', () { - testWidgets((WidgetTester tester) { - scrollDirection = Axis.vertical; - dismissDirection = DismissDirection.endToStart; + testWidgets('drag-left with DismissDirection.left triggers dismiss', (WidgetTester tester) { + scrollDirection = Axis.vertical; + dismissDirection = DismissDirection.endToStart; - tester.pumpWidget(widgetBuilder()); - expect(dismissedItems, isEmpty); + tester.pumpWidget(widgetBuilder()); + expect(dismissedItems, isEmpty); - dismissItem(tester, 0, gestureDirection: DismissDirection.startToEnd); - expect(tester, hasWidget(find.text('0'))); - expect(dismissedItems, isEmpty); - dismissItem(tester, 1, gestureDirection: DismissDirection.startToEnd); + dismissItem(tester, 0, gestureDirection: DismissDirection.startToEnd); + expect(find.text('0'), findsOneWidget); + expect(dismissedItems, isEmpty); + dismissItem(tester, 1, gestureDirection: DismissDirection.startToEnd); - dismissItem(tester, 0, gestureDirection: DismissDirection.endToStart); - expect(tester, doesNotHaveWidget(find.text('0'))); - expect(dismissedItems, equals([0])); - dismissItem(tester, 1, gestureDirection: DismissDirection.endToStart); - }); + dismissItem(tester, 0, gestureDirection: DismissDirection.endToStart); + expect(find.text('0'), findsNothing); + expect(dismissedItems, equals([0])); + dismissItem(tester, 1, gestureDirection: DismissDirection.endToStart); }); - test('drag-right with DismissDirection.right triggers dismiss', () { - testWidgets((WidgetTester tester) { - scrollDirection = Axis.vertical; - dismissDirection = DismissDirection.startToEnd; + testWidgets('drag-right with DismissDirection.right triggers dismiss', (WidgetTester tester) { + scrollDirection = Axis.vertical; + dismissDirection = DismissDirection.startToEnd; - tester.pumpWidget(widgetBuilder()); - expect(dismissedItems, isEmpty); + tester.pumpWidget(widgetBuilder()); + expect(dismissedItems, isEmpty); - dismissItem(tester, 0, gestureDirection: DismissDirection.endToStart); - expect(tester, hasWidget(find.text('0'))); - expect(dismissedItems, isEmpty); + dismissItem(tester, 0, gestureDirection: DismissDirection.endToStart); + expect(find.text('0'), findsOneWidget); + expect(dismissedItems, isEmpty); - dismissItem(tester, 0, gestureDirection: DismissDirection.startToEnd); - expect(tester, doesNotHaveWidget(find.text('0'))); - expect(dismissedItems, equals([0])); - }); + dismissItem(tester, 0, gestureDirection: DismissDirection.startToEnd); + expect(find.text('0'), findsNothing); + expect(dismissedItems, equals([0])); }); - test('drag-up with DismissDirection.up triggers dismiss', () { - testWidgets((WidgetTester tester) { - scrollDirection = Axis.horizontal; - dismissDirection = DismissDirection.up; + testWidgets('drag-up with DismissDirection.up triggers dismiss', (WidgetTester tester) { + scrollDirection = Axis.horizontal; + dismissDirection = DismissDirection.up; - tester.pumpWidget(widgetBuilder()); - expect(dismissedItems, isEmpty); + tester.pumpWidget(widgetBuilder()); + expect(dismissedItems, isEmpty); - dismissItem(tester, 0, gestureDirection: DismissDirection.down); - expect(tester, hasWidget(find.text('0'))); - expect(dismissedItems, isEmpty); + dismissItem(tester, 0, gestureDirection: DismissDirection.down); + expect(find.text('0'), findsOneWidget); + expect(dismissedItems, isEmpty); - dismissItem(tester, 0, gestureDirection: DismissDirection.up); - expect(tester, doesNotHaveWidget(find.text('0'))); - expect(dismissedItems, equals([0])); - }); + dismissItem(tester, 0, gestureDirection: DismissDirection.up); + expect(find.text('0'), findsNothing); + expect(dismissedItems, equals([0])); }); - test('drag-down with DismissDirection.down triggers dismiss', () { - testWidgets((WidgetTester tester) { - scrollDirection = Axis.horizontal; - dismissDirection = DismissDirection.down; + testWidgets('drag-down with DismissDirection.down triggers dismiss', (WidgetTester tester) { + scrollDirection = Axis.horizontal; + dismissDirection = DismissDirection.down; - tester.pumpWidget(widgetBuilder()); - expect(dismissedItems, isEmpty); + tester.pumpWidget(widgetBuilder()); + expect(dismissedItems, isEmpty); - dismissItem(tester, 0, gestureDirection: DismissDirection.up); - expect(tester, hasWidget(find.text('0'))); - expect(dismissedItems, isEmpty); + dismissItem(tester, 0, gestureDirection: DismissDirection.up); + expect(find.text('0'), findsOneWidget); + expect(dismissedItems, isEmpty); - dismissItem(tester, 0, gestureDirection: DismissDirection.down); - expect(tester, doesNotHaveWidget(find.text('0'))); - expect(dismissedItems, equals([0])); - }); + dismissItem(tester, 0, gestureDirection: DismissDirection.down); + expect(find.text('0'), findsNothing); + expect(dismissedItems, equals([0])); }); // This is a regression test for an fn2 bug where dragging a card caused an @@ -250,25 +238,23 @@ void main() { // now since we migrated to the new repo. The bug was fixed by // https://github.com/flutter/engine/pull/1134 at the time, and later made // irrelevant by fn3, but just in case... - test('Verify that drag-move events do not assert', () { - testWidgets((WidgetTester tester) { - scrollDirection = Axis.horizontal; - dismissDirection = DismissDirection.down; + testWidgets('Verify that drag-move events do not assert', (WidgetTester tester) { + scrollDirection = Axis.horizontal; + dismissDirection = DismissDirection.down; - tester.pumpWidget(widgetBuilder()); - Point location = tester.getTopLeft(find.text('0')); - Offset offset = new Offset(0.0, 5.0); - TestGesture gesture = tester.startGesture(location, pointer: 5); - gesture.moveBy(offset); - tester.pumpWidget(widgetBuilder()); - gesture.moveBy(offset); - tester.pumpWidget(widgetBuilder()); - gesture.moveBy(offset); - tester.pumpWidget(widgetBuilder()); - gesture.moveBy(offset); - tester.pumpWidget(widgetBuilder()); - gesture.up(); - }); + tester.pumpWidget(widgetBuilder()); + Point location = tester.getTopLeft(find.text('0')); + Offset offset = new Offset(0.0, 5.0); + TestGesture gesture = tester.startGesture(location, pointer: 5); + gesture.moveBy(offset); + tester.pumpWidget(widgetBuilder()); + gesture.moveBy(offset); + tester.pumpWidget(widgetBuilder()); + gesture.moveBy(offset); + tester.pumpWidget(widgetBuilder()); + gesture.moveBy(offset); + tester.pumpWidget(widgetBuilder()); + gesture.up(); }); // This one is for a case where dssmissing a widget above a previously @@ -277,51 +263,48 @@ void main() { // died in the migration to the new repo). Don't copy this test; it doesn't // actually remove the dismissed widget, which is a violation of the // Dismissable contract. This is not an example of good practice. - test('dismissing bottom then top (smoketest)', () { - testWidgets((WidgetTester tester) { - tester.pumpWidget(new Center( - child: new Container( - width: 100.0, - height: 1000.0, - child: new Column( - children: [ - new Test1215DismissableWidget('1'), - new Test1215DismissableWidget('2') - ] - ) + testWidgets('dismissing bottom then top (smoketest)', (WidgetTester tester) { + tester.pumpWidget(new Center( + child: new Container( + width: 100.0, + height: 1000.0, + child: new Column( + children: [ + new Test1215DismissableWidget('1'), + new Test1215DismissableWidget('2') + ] ) - )); - expect(tester, hasWidget(find.text('1'))); - expect(tester, hasWidget(find.text('2'))); - dismissElement(tester, find.text('2'), gestureDirection: DismissDirection.startToEnd); - tester.pump(); // start the slide away - tester.pump(new Duration(seconds: 1)); // finish the slide away - expect(tester, hasWidget(find.text('1'))); - expect(tester, doesNotHaveWidget(find.text('2'))); - dismissElement(tester, find.text('1'), gestureDirection: DismissDirection.startToEnd); - tester.pump(); // start the slide away - tester.pump(new Duration(seconds: 1)); // finish the slide away (at which point the child is no longer included in the tree) - expect(tester, doesNotHaveWidget(find.text('1'))); - expect(tester, doesNotHaveWidget(find.text('2'))); - }); + ) + )); + expect(find.text('1'), findsOneWidget); + expect(find.text('2'), findsOneWidget); + dismissElement(tester, find.text('2'), gestureDirection: DismissDirection.startToEnd); + tester.pump(); // start the slide away + tester.pump(new Duration(seconds: 1)); // finish the slide away + expect(find.text('1'), findsOneWidget); + expect(find.text('2'), findsNothing); + dismissElement(tester, find.text('1'), gestureDirection: DismissDirection.startToEnd); + tester.pump(); // start the slide away + tester.pump(new Duration(seconds: 1)); // finish the slide away (at which point the child is no longer included in the tree) + expect(find.text('1'), findsNothing); + expect(find.text('2'), findsNothing); }); - test('Dismissable starts from the full size when collapsing', () { - testWidgets((WidgetTester tester) { - scrollDirection = Axis.vertical; - dismissDirection = DismissDirection.horizontal; - background = new Text('background'); + testWidgets('Dismissable starts from the full size when collapsing', (WidgetTester tester) { + scrollDirection = Axis.vertical; + dismissDirection = DismissDirection.horizontal; + background = new Text('background'); - tester.pumpWidget(widgetBuilder()); - expect(dismissedItems, isEmpty); + tester.pumpWidget(widgetBuilder()); + expect(dismissedItems, isEmpty); - Finder itemFinder = find.text('0'); - expect(tester, hasWidget(itemFinder)); - dismissElement(tester, itemFinder, gestureDirection: DismissDirection.startToEnd); - tester.pump(); + Finder itemFinder = find.text('0'); + expect(itemFinder, findsOneWidget); + dismissElement(tester, itemFinder, gestureDirection: DismissDirection.startToEnd); + tester.pump(); - RenderBox backgroundBox = tester.renderObjectOf(find.text('background')); - expect(backgroundBox.size.height, equals(100.0)); - }); + expect(find.text('background'), findsNWidgets(5)); + RenderBox backgroundBox = tester.firstRenderObject(find.text('background')); + expect(backgroundBox.size.height, equals(100.0)); }); } diff --git a/packages/flutter/test/widget/draggable_test.dart b/packages/flutter/test/widget/draggable_test.dart index 63f51918eb..75c038396b 100644 --- a/packages/flutter/test/widget/draggable_test.dart +++ b/packages/flutter/test/widget/draggable_test.dart @@ -7,681 +7,584 @@ import 'package:flutter/material.dart'; import 'package:test/test.dart'; void main() { - test('Drag and drop - control test', () { - testWidgets((WidgetTester tester) { - List accepted = []; + testWidgets('Drag and drop - control test', (WidgetTester tester) { + List accepted = []; - tester.pumpWidget(new MaterialApp( - home: new Column( - children: [ - new Draggable( - data: 1, - child: new Text('Source'), - feedback: new Text('Dragging') - ), - new DragTarget( - builder: (BuildContext context, List data, List rejects) { - return new Container(height: 100.0, child: new Text('Target')); - }, - onAccept: (int data) { - accepted.add(data); - } - ), - ] - ) - )); + tester.pumpWidget(new MaterialApp( + home: new Column( + children: [ + new Draggable( + data: 1, + child: new Text('Source'), + feedback: new Text('Dragging') + ), + new DragTarget( + builder: (BuildContext context, List data, List rejects) { + return new Container(height: 100.0, child: new Text('Target')); + }, + onAccept: (int data) { + accepted.add(data); + } + ), + ] + ) + )); - expect(accepted, isEmpty); - expect(tester, hasWidget(find.text('Source'))); - expect(tester, doesNotHaveWidget(find.text('Dragging'))); - expect(tester, hasWidget(find.text('Target'))); + expect(accepted, isEmpty); + expect(find.text('Source'), findsOneWidget); + expect(find.text('Dragging'), findsNothing); + expect(find.text('Target'), findsOneWidget); - Point firstLocation = tester.getCenter(find.text('Source')); - TestGesture gesture = tester.startGesture(firstLocation, pointer: 7); - tester.pump(); + Point firstLocation = tester.getCenter(find.text('Source')); + TestGesture gesture = tester.startGesture(firstLocation, pointer: 7); + tester.pump(); - expect(accepted, isEmpty); - expect(tester, hasWidget(find.text('Source'))); - expect(tester, hasWidget(find.text('Dragging'))); - expect(tester, hasWidget(find.text('Target'))); + expect(accepted, isEmpty); + expect(find.text('Source'), findsOneWidget); + expect(find.text('Dragging'), findsOneWidget); + expect(find.text('Target'), findsOneWidget); - Point secondLocation = tester.getCenter(find.text('Target')); - gesture.moveTo(secondLocation); - tester.pump(); + Point secondLocation = tester.getCenter(find.text('Target')); + gesture.moveTo(secondLocation); + tester.pump(); - expect(accepted, isEmpty); - expect(tester, hasWidget(find.text('Source'))); - expect(tester, hasWidget(find.text('Dragging'))); - expect(tester, hasWidget(find.text('Target'))); + expect(accepted, isEmpty); + expect(find.text('Source'), findsOneWidget); + expect(find.text('Dragging'), findsOneWidget); + expect(find.text('Target'), findsOneWidget); - gesture.up(); - tester.pump(); + gesture.up(); + tester.pump(); - expect(accepted, equals([1])); - expect(tester, hasWidget(find.text('Source'))); - expect(tester, doesNotHaveWidget(find.text('Dragging'))); - expect(tester, hasWidget(find.text('Target'))); - }); + expect(accepted, equals([1])); + expect(find.text('Source'), findsOneWidget); + expect(find.text('Dragging'), findsNothing); + expect(find.text('Target'), findsOneWidget); }); - test('Drag and drop - dragging over button', () { - testWidgets((WidgetTester tester) { - List events = []; - Point firstLocation, secondLocation; + testWidgets('Drag and drop - dragging over button', (WidgetTester tester) { + List events = []; + Point firstLocation, secondLocation; - tester.pumpWidget(new MaterialApp( - home: new Column( - children: [ - new Draggable( - data: 1, - child: new Text('Source'), - feedback: new Text('Dragging') - ), - new Stack( - children: [ - new GestureDetector( - behavior: HitTestBehavior.opaque, - onTap: () { - events.add('tap'); - }, - child: new Container(child: new Text('Button') - ) - ), - new DragTarget( - builder: (BuildContext context, List data, List rejects) { - return new IgnorePointer( - child: new Container(child: new Text('Target')) - ); - }, - onAccept: (int data) { - events.add('drop'); - }), - ] - ), - ] - ) - )); - - expect(events, isEmpty); - expect(tester, hasWidget(find.text('Source'))); - expect(tester, doesNotHaveWidget(find.text('Dragging'))); - expect(tester, hasWidget(find.text('Target'))); - expect(tester, hasWidget(find.text('Button'))); - - // taps (we check both to make sure the test is consistent) - - expect(events, isEmpty); - tester.tap(find.text('Button')); - expect(events, equals(['tap'])); - events.clear(); - - expect(events, isEmpty); - tester.tap(find.text('Target')); - expect(events, equals(['tap'])); - events.clear(); - - // drag and drop - - firstLocation = tester.getCenter(find.text('Source')); - TestGesture gesture = tester.startGesture(firstLocation, pointer: 7); - tester.pump(); - - secondLocation = tester.getCenter(find.text('Target')); - gesture.moveTo(secondLocation); - tester.pump(); - - expect(events, isEmpty); - gesture.up(); - tester.pump(); - expect(events, equals(['drop'])); - events.clear(); - - // drag and tap and drop - - firstLocation = tester.getCenter(find.text('Source')); - gesture = tester.startGesture(firstLocation, pointer: 7); - tester.pump(); - - secondLocation = tester.getCenter(find.text('Target')); - gesture.moveTo(secondLocation); - tester.pump(); - - expect(events, isEmpty); - tester.tap(find.text('Button')); - tester.tap(find.text('Target')); - gesture.up(); - tester.pump(); - expect(events, equals(['tap', 'tap', 'drop'])); - events.clear(); - }); - }); - - test('Drag and drop - tapping button', () { - testWidgets((WidgetTester tester) { - List events = []; - Point firstLocation, secondLocation; - - tester.pumpWidget(new MaterialApp( - home: new Column( - children: [ - new Draggable( - data: 1, - child: new GestureDetector( + tester.pumpWidget(new MaterialApp( + home: new Column( + children: [ + new Draggable( + data: 1, + child: new Text('Source'), + feedback: new Text('Dragging') + ), + new Stack( + children: [ + new GestureDetector( behavior: HitTestBehavior.opaque, onTap: () { events.add('tap'); }, - child: new Container(child: new Text('Button')) - ), - feedback: new Text('Dragging') + child: new Container(child: new Text('Button') + ) ), new DragTarget( builder: (BuildContext context, List data, List rejects) { - return new Text('Target'); - }, - onAccept: (int data) { - events.add('drop'); - } - ), - ] - ) - )); - - expect(events, isEmpty); - expect(tester, hasWidget(find.text('Button'))); - expect(tester, hasWidget(find.text('Target'))); - - expect(events, isEmpty); - tester.tap(find.text('Button')); - expect(events, equals(['tap'])); - events.clear(); - - firstLocation = tester.getCenter(find.text('Button')); - TestGesture gesture = tester.startGesture(firstLocation, pointer: 7); - tester.pump(); - - secondLocation = tester.getCenter(find.text('Target')); - gesture.moveTo(secondLocation); - tester.pump(); - - expect(events, isEmpty); - gesture.up(); - tester.pump(); - expect(events, equals(['drop'])); - events.clear(); - }); - }); - - test('Drag and drop - long press draggable, short press', () { - testWidgets((WidgetTester tester) { - List events = []; - Point firstLocation, secondLocation; - - tester.pumpWidget(new MaterialApp( - home: new Column( - children: [ - new LongPressDraggable( - data: 1, - child: new Text('Source'), - feedback: new Text('Dragging') - ), - new DragTarget( - builder: (BuildContext context, List data, List rejects) { - return new Text('Target'); - }, - onAccept: (int data) { - events.add('drop'); - } - ), - ] - ) - )); - - expect(events, isEmpty); - expect(tester, hasWidget(find.text('Source'))); - expect(tester, hasWidget(find.text('Target'))); - - expect(events, isEmpty); - tester.tap(find.text('Source')); - expect(events, isEmpty); - - firstLocation = tester.getCenter(find.text('Source')); - TestGesture gesture = tester.startGesture(firstLocation, pointer: 7); - tester.pump(); - - secondLocation = tester.getCenter(find.text('Target')); - gesture.moveTo(secondLocation); - tester.pump(); - - expect(events, isEmpty); - gesture.up(); - tester.pump(); - expect(events, isEmpty); - }); - }); - - test('Drag and drop - long press draggable, long press', () { - testWidgets((WidgetTester tester) { - List events = []; - Point firstLocation, secondLocation; - - tester.pumpWidget(new MaterialApp( - home: new Column( - children: [ - new Draggable( - data: 1, - child: new Text('Source'), - feedback: new Text('Dragging') - ), - new DragTarget( - builder: (BuildContext context, List data, List rejects) { - return new Text('Target'); - }, - onAccept: (int data) { - events.add('drop'); - } - ), - ] - ) - )); - - expect(events, isEmpty); - expect(tester, hasWidget(find.text('Source'))); - expect(tester, hasWidget(find.text('Target'))); - - expect(events, isEmpty); - tester.tap(find.text('Source')); - expect(events, isEmpty); - - firstLocation = tester.getCenter(find.text('Source')); - TestGesture gesture = tester.startGesture(firstLocation, pointer: 7); - tester.pump(); - - tester.pump(const Duration(seconds: 20)); - - secondLocation = tester.getCenter(find.text('Target')); - gesture.moveTo(secondLocation); - tester.pump(); - - expect(events, isEmpty); - gesture.up(); - tester.pump(); - expect(events, equals(['drop'])); - }); - }); - - test('Drag and drop - horizontal and vertical draggables in vertical block', - () { - testWidgets((WidgetTester tester) { - List events = []; - Point firstLocation, secondLocation, thirdLocation; - - tester.pumpWidget(new MaterialApp( - home: new Block( - children: [ - new DragTarget( - builder: (BuildContext context, List data, List rejects) { - return new Text('Target'); - }, - onAccept: (int data) { - events.add('drop $data'); - } - ), - new Container(height: 400.0), - new HorizontalDraggable( - data: 1, - child: new Text('H'), - feedback: new Text('Dragging') - ), - new VerticalDraggable( - data: 2, - child: new Text('V'), - feedback: new Text('Dragging') - ), - new Container(height: 500.0), - new Container(height: 500.0), - new Container(height: 500.0), - new Container(height: 500.0), - ] - ) - )); - - expect(events, isEmpty); - expect(tester, hasWidget(find.text('Target'))); - expect(tester, hasWidget(find.text('H'))); - expect(tester, hasWidget(find.text('V'))); - - // vertical draggable drags vertically - expect(events, isEmpty); - firstLocation = tester.getCenter(find.text('V')); - secondLocation = tester.getCenter(find.text('Target')); - TestGesture gesture = tester.startGesture(firstLocation, pointer: 7); - tester.pump(); - gesture.moveTo(secondLocation); - tester.pump(); - gesture.up(); - tester.pump(); - expect(events, equals(['drop 2'])); - expect(tester.getCenter(find.text('Target')).y, greaterThan(0.0)); - events.clear(); - - // horizontal draggable drags horizontally - expect(events, isEmpty); - firstLocation = tester.getTopLeft(find.text('H')); - secondLocation = tester.getTopRight(find.text('H')); - thirdLocation = tester.getCenter(find.text('Target')); - gesture = tester.startGesture(firstLocation, pointer: 7); - tester.pump(); - gesture.moveTo(secondLocation); - tester.pump(); - gesture.moveTo(thirdLocation); - tester.pump(); - gesture.up(); - tester.pump(); - expect(events, equals(['drop 1'])); - expect(tester.getCenter(find.text('Target')).y, greaterThan(0.0)); - events.clear(); - - // vertical draggable drags horizontally when there's no competition - // from other gesture detectors - expect(events, isEmpty); - firstLocation = tester.getTopLeft(find.text('V')); - secondLocation = tester.getTopRight(find.text('V')); - thirdLocation = tester.getCenter(find.text('Target')); - gesture = tester.startGesture(firstLocation, pointer: 7); - tester.pump(); - gesture.moveTo(secondLocation); - tester.pump(); - gesture.moveTo(thirdLocation); - tester.pump(); - gesture.up(); - tester.pump(); - expect(events, equals(['drop 2'])); - expect(tester.getCenter(find.text('Target')).y, greaterThan(0.0)); - events.clear(); - - // horizontal draggable doesn't drag vertically when there is competition - // for vertical gestures - expect(events, isEmpty); - firstLocation = tester.getCenter(find.text('H')); - secondLocation = tester.getCenter(find.text('Target')); - gesture = tester.startGesture(firstLocation, pointer: 7); - tester.pump(); - gesture.moveTo(secondLocation); - tester.pump(); // scrolls off screen! - gesture.up(); - tester.pump(); - expect(events, equals([])); - expect(tester.getCenter(find.text('Target')).y, lessThan(0.0)); - events.clear(); - }); - }); - - test('Drag and drop - horizontal and vertical draggables in horizontal block', - () { - testWidgets((WidgetTester tester) { - List events = []; - Point firstLocation, secondLocation, thirdLocation; - - tester.pumpWidget(new MaterialApp( - home: new Block( - scrollDirection: Axis.horizontal, - children: [ - new DragTarget( - builder: (BuildContext context, List data, List rejects) { - return new Text('Target'); - }, - onAccept: (int data) { - events.add('drop $data'); - } - ), - new Container(width: 400.0), - new HorizontalDraggable( - data: 1, - child: new Text('H'), - feedback: new Text('Dragging') - ), - new VerticalDraggable( - data: 2, - child: new Text('V'), - feedback: new Text('Dragging') - ), - new Container(width: 500.0), - new Container(width: 500.0), - new Container(width: 500.0), - new Container(width: 500.0), - ] - ) - )); - - expect(events, isEmpty); - expect(tester, hasWidget(find.text('Target'))); - expect(tester, hasWidget(find.text('H'))); - expect(tester, hasWidget(find.text('V'))); - - // horizontal draggable drags horizontally - expect(events, isEmpty); - firstLocation = tester.getCenter(find.text('H')); - secondLocation = tester.getCenter(find.text('Target')); - TestGesture gesture = tester.startGesture(firstLocation, pointer: 7); - tester.pump(); - gesture.moveTo(secondLocation); - tester.pump(); - gesture.up(); - tester.pump(); - expect(events, equals(['drop 1'])); - expect(tester.getCenter(find.text('Target')).x, greaterThan(0.0)); - events.clear(); - - // vertical draggable drags vertically - expect(events, isEmpty); - firstLocation = tester.getTopLeft(find.text('V')); - secondLocation = tester.getBottomLeft(find.text('V')); - thirdLocation = tester.getCenter(find.text('Target')); - gesture = tester.startGesture(firstLocation, pointer: 7); - tester.pump(); - gesture.moveTo(secondLocation); - tester.pump(); - gesture.moveTo(thirdLocation); - tester.pump(); - gesture.up(); - tester.pump(); - expect(events, equals(['drop 2'])); - expect(tester.getCenter(find.text('Target')).x, greaterThan(0.0)); - events.clear(); - - // horizontal draggable drags vertically when there's no competition - // from other gesture detectors - expect(events, isEmpty); - firstLocation = tester.getTopLeft(find.text('H')); - secondLocation = tester.getBottomLeft(find.text('H')); - thirdLocation = tester.getCenter(find.text('Target')); - gesture = tester.startGesture(firstLocation, pointer: 7); - tester.pump(); - gesture.moveTo(secondLocation); - tester.pump(); - gesture.moveTo(thirdLocation); - tester.pump(); - gesture.up(); - tester.pump(); - expect(events, equals(['drop 1'])); - expect(tester.getCenter(find.text('Target')).x, greaterThan(0.0)); - events.clear(); - - // vertical draggable doesn't drag horizontally when there is competition - // for horizontal gestures - expect(events, isEmpty); - firstLocation = tester.getCenter(find.text('V')); - secondLocation = tester.getCenter(find.text('Target')); - gesture = tester.startGesture(firstLocation, pointer: 7); - tester.pump(); - gesture.moveTo(secondLocation); - tester.pump(); // scrolls off screen! - gesture.up(); - tester.pump(); - expect(events, equals([])); - expect(tester.getCenter(find.text('Target')).x, lessThan(0.0)); - events.clear(); - }); - }); - - test( - 'Drag and drop - onDraggableDropped not called if dropped on accepting target', - () { - testWidgets((WidgetTester tester) { - List accepted = []; - bool onDraggableCanceledCalled = false; - - tester.pumpWidget(new MaterialApp( - home: new Column( - children: [ - new Draggable( - data: 1, - child: new Text('Source'), - feedback: new Text('Dragging'), - onDraggableCanceled: (Velocity velocity, Offset offset) { - onDraggableCanceledCalled = true; - } - ), - new DragTarget( - builder: (BuildContext context, List data, List rejects) { - return new Container(height: 100.0, child: new Text('Target')); - }, - onAccept: (int data) { - accepted.add(data); - } - ), - ] - ) - )); - - expect(accepted, isEmpty); - expect(tester, hasWidget(find.text('Source'))); - expect(tester, doesNotHaveWidget(find.text('Dragging'))); - expect(tester, hasWidget(find.text('Target'))); - expect(onDraggableCanceledCalled, isFalse); - - Point firstLocation = tester.getCenter(find.text('Source')); - TestGesture gesture = tester.startGesture(firstLocation, pointer: 7); - tester.pump(); - - expect(accepted, isEmpty); - expect(tester, hasWidget(find.text('Source'))); - expect(tester, hasWidget(find.text('Dragging'))); - expect(tester, hasWidget(find.text('Target'))); - expect(onDraggableCanceledCalled, isFalse); - - Point secondLocation = tester.getCenter(find.text('Target')); - gesture.moveTo(secondLocation); - tester.pump(); - - expect(accepted, isEmpty); - expect(tester, hasWidget(find.text('Source'))); - expect(tester, hasWidget(find.text('Dragging'))); - expect(tester, hasWidget(find.text('Target'))); - expect(onDraggableCanceledCalled, isFalse); - - gesture.up(); - tester.pump(); - - expect(accepted, equals([1])); - expect(tester, hasWidget(find.text('Source'))); - expect(tester, doesNotHaveWidget(find.text('Dragging'))); - expect(tester, hasWidget(find.text('Target'))); - expect(onDraggableCanceledCalled, isFalse); - }); - }); - - test( - 'Drag and drop - onDraggableDropped called if dropped on non-accepting target', - () { - testWidgets((WidgetTester tester) { - List accepted = []; - bool onDraggableCanceledCalled = false; - Velocity onDraggableCanceledVelocity; - Offset onDraggableCanceledOffset; - - tester.pumpWidget(new MaterialApp( - home: new Column( - children: [ - new Draggable( - data: 1, - child: new Text('Source'), - feedback: new Text('Dragging'), - onDraggableCanceled: (Velocity velocity, Offset offset) { - onDraggableCanceledCalled = true; - onDraggableCanceledVelocity = velocity; - onDraggableCanceledOffset = offset; - } - ), - new DragTarget( - builder: (BuildContext context, List data, List rejects) { - return new Container( - height: 100.0, - child: new Text('Target') + return new IgnorePointer( + child: new Container(child: new Text('Target')) ); }, - onWillAccept: (int data) => false - ), - ] - ) - )); + onAccept: (int data) { + events.add('drop'); + }), + ] + ), + ] + ) + )); - expect(accepted, isEmpty); - expect(tester, hasWidget(find.text('Source'))); - expect(tester, doesNotHaveWidget(find.text('Dragging'))); - expect(tester, hasWidget(find.text('Target'))); - expect(onDraggableCanceledCalled, isFalse); + expect(events, isEmpty); + expect(find.text('Source'), findsOneWidget); + expect(find.text('Dragging'), findsNothing); + expect(find.text('Target'), findsOneWidget); + expect(find.text('Button'), findsOneWidget); - Point firstLocation = tester.getTopLeft(find.text('Source')); - TestGesture gesture = tester.startGesture(firstLocation, pointer: 7); - tester.pump(); + // taps (we check both to make sure the test is consistent) - expect(accepted, isEmpty); - expect(tester, hasWidget(find.text('Source'))); - expect(tester, hasWidget(find.text('Dragging'))); - expect(tester, hasWidget(find.text('Target'))); - expect(onDraggableCanceledCalled, isFalse); + expect(events, isEmpty); + tester.tap(find.text('Button')); + expect(events, equals(['tap'])); + events.clear(); - Point secondLocation = tester.getCenter(find.text('Target')); - gesture.moveTo(secondLocation); - tester.pump(); + expect(events, isEmpty); + tester.tap(find.text('Target')); + expect(events, equals(['tap'])); + events.clear(); - expect(accepted, isEmpty); - expect(tester, hasWidget(find.text('Source'))); - expect(tester, hasWidget(find.text('Dragging'))); - expect(tester, hasWidget(find.text('Target'))); - expect(onDraggableCanceledCalled, isFalse); + // drag and drop - gesture.up(); - tester.pump(); + firstLocation = tester.getCenter(find.text('Source')); + TestGesture gesture = tester.startGesture(firstLocation, pointer: 7); + tester.pump(); - expect(accepted, isEmpty); - expect(tester, hasWidget(find.text('Source'))); - expect(tester, doesNotHaveWidget(find.text('Dragging'))); - expect(tester, hasWidget(find.text('Target'))); - expect(onDraggableCanceledCalled, isTrue); - expect(onDraggableCanceledVelocity, equals(Velocity.zero)); - expect(onDraggableCanceledOffset, - equals(new Offset(secondLocation.x, secondLocation.y))); - }); + secondLocation = tester.getCenter(find.text('Target')); + gesture.moveTo(secondLocation); + tester.pump(); + + expect(events, isEmpty); + gesture.up(); + tester.pump(); + expect(events, equals(['drop'])); + events.clear(); + + // drag and tap and drop + + firstLocation = tester.getCenter(find.text('Source')); + gesture = tester.startGesture(firstLocation, pointer: 7); + tester.pump(); + + secondLocation = tester.getCenter(find.text('Target')); + gesture.moveTo(secondLocation); + tester.pump(); + + expect(events, isEmpty); + tester.tap(find.text('Button')); + tester.tap(find.text('Target')); + gesture.up(); + tester.pump(); + expect(events, equals(['tap', 'tap', 'drop'])); + events.clear(); }); - test( - 'Drag and drop - onDraggableDropped called if dropped on non-accepting target with correct velocity', - () { - testWidgets((WidgetTester tester) { - List accepted = []; - bool onDraggableCanceledCalled = false; - Velocity onDraggableCanceledVelocity; - Offset onDraggableCanceledOffset; + testWidgets('Drag and drop - tapping button', (WidgetTester tester) { + List events = []; + Point firstLocation, secondLocation; - tester.pumpWidget(new MaterialApp( - home: new Column(children: [ + tester.pumpWidget(new MaterialApp( + home: new Column( + children: [ + new Draggable( + data: 1, + child: new GestureDetector( + behavior: HitTestBehavior.opaque, + onTap: () { + events.add('tap'); + }, + child: new Container(child: new Text('Button')) + ), + feedback: new Text('Dragging') + ), + new DragTarget( + builder: (BuildContext context, List data, List rejects) { + return new Text('Target'); + }, + onAccept: (int data) { + events.add('drop'); + } + ), + ] + ) + )); + + expect(events, isEmpty); + expect(find.text('Button'), findsOneWidget); + expect(find.text('Target'), findsOneWidget); + + expect(events, isEmpty); + tester.tap(find.text('Button')); + expect(events, equals(['tap'])); + events.clear(); + + firstLocation = tester.getCenter(find.text('Button')); + TestGesture gesture = tester.startGesture(firstLocation, pointer: 7); + tester.pump(); + + secondLocation = tester.getCenter(find.text('Target')); + gesture.moveTo(secondLocation); + tester.pump(); + + expect(events, isEmpty); + gesture.up(); + tester.pump(); + expect(events, equals(['drop'])); + events.clear(); + }); + + testWidgets('Drag and drop - long press draggable, short press', (WidgetTester tester) { + List events = []; + Point firstLocation, secondLocation; + + tester.pumpWidget(new MaterialApp( + home: new Column( + children: [ + new LongPressDraggable( + data: 1, + child: new Text('Source'), + feedback: new Text('Dragging') + ), + new DragTarget( + builder: (BuildContext context, List data, List rejects) { + return new Text('Target'); + }, + onAccept: (int data) { + events.add('drop'); + } + ), + ] + ) + )); + + expect(events, isEmpty); + expect(find.text('Source'), findsOneWidget); + expect(find.text('Target'), findsOneWidget); + + expect(events, isEmpty); + tester.tap(find.text('Source')); + expect(events, isEmpty); + + firstLocation = tester.getCenter(find.text('Source')); + TestGesture gesture = tester.startGesture(firstLocation, pointer: 7); + tester.pump(); + + secondLocation = tester.getCenter(find.text('Target')); + gesture.moveTo(secondLocation); + tester.pump(); + + expect(events, isEmpty); + gesture.up(); + tester.pump(); + expect(events, isEmpty); + }); + + testWidgets('Drag and drop - long press draggable, long press', (WidgetTester tester) { + List events = []; + Point firstLocation, secondLocation; + + tester.pumpWidget(new MaterialApp( + home: new Column( + children: [ new Draggable( data: 1, child: new Text('Source'), - feedback: new Text('Source'), + feedback: new Text('Dragging') + ), + new DragTarget( + builder: (BuildContext context, List data, List rejects) { + return new Text('Target'); + }, + onAccept: (int data) { + events.add('drop'); + } + ), + ] + ) + )); + + expect(events, isEmpty); + expect(find.text('Source'), findsOneWidget); + expect(find.text('Target'), findsOneWidget); + + expect(events, isEmpty); + tester.tap(find.text('Source')); + expect(events, isEmpty); + + firstLocation = tester.getCenter(find.text('Source')); + TestGesture gesture = tester.startGesture(firstLocation, pointer: 7); + tester.pump(); + + tester.pump(const Duration(seconds: 20)); + + secondLocation = tester.getCenter(find.text('Target')); + gesture.moveTo(secondLocation); + tester.pump(); + + expect(events, isEmpty); + gesture.up(); + tester.pump(); + expect(events, equals(['drop'])); + }); + + testWidgets('Drag and drop - horizontal and vertical draggables in vertical block', (WidgetTester tester) { + List events = []; + Point firstLocation, secondLocation, thirdLocation; + + tester.pumpWidget(new MaterialApp( + home: new Block( + children: [ + new DragTarget( + builder: (BuildContext context, List data, List rejects) { + return new Text('Target'); + }, + onAccept: (int data) { + events.add('drop $data'); + } + ), + new Container(height: 400.0), + new HorizontalDraggable( + data: 1, + child: new Text('H'), + feedback: new Text('Dragging') + ), + new VerticalDraggable( + data: 2, + child: new Text('V'), + feedback: new Text('Dragging') + ), + new Container(height: 500.0), + new Container(height: 500.0), + new Container(height: 500.0), + new Container(height: 500.0), + ] + ) + )); + + expect(events, isEmpty); + expect(find.text('Target'), findsOneWidget); + expect(find.text('H'), findsOneWidget); + expect(find.text('V'), findsOneWidget); + + // vertical draggable drags vertically + expect(events, isEmpty); + firstLocation = tester.getCenter(find.text('V')); + secondLocation = tester.getCenter(find.text('Target')); + TestGesture gesture = tester.startGesture(firstLocation, pointer: 7); + tester.pump(); + gesture.moveTo(secondLocation); + tester.pump(); + gesture.up(); + tester.pump(); + expect(events, equals(['drop 2'])); + expect(tester.getCenter(find.text('Target')).y, greaterThan(0.0)); + events.clear(); + + // horizontal draggable drags horizontally + expect(events, isEmpty); + firstLocation = tester.getTopLeft(find.text('H')); + secondLocation = tester.getTopRight(find.text('H')); + thirdLocation = tester.getCenter(find.text('Target')); + gesture = tester.startGesture(firstLocation, pointer: 7); + tester.pump(); + gesture.moveTo(secondLocation); + tester.pump(); + gesture.moveTo(thirdLocation); + tester.pump(); + gesture.up(); + tester.pump(); + expect(events, equals(['drop 1'])); + expect(tester.getCenter(find.text('Target')).y, greaterThan(0.0)); + events.clear(); + + // vertical draggable drags horizontally when there's no competition + // from other gesture detectors + expect(events, isEmpty); + firstLocation = tester.getTopLeft(find.text('V')); + secondLocation = tester.getTopRight(find.text('V')); + thirdLocation = tester.getCenter(find.text('Target')); + gesture = tester.startGesture(firstLocation, pointer: 7); + tester.pump(); + gesture.moveTo(secondLocation); + tester.pump(); + gesture.moveTo(thirdLocation); + tester.pump(); + gesture.up(); + tester.pump(); + expect(events, equals(['drop 2'])); + expect(tester.getCenter(find.text('Target')).y, greaterThan(0.0)); + events.clear(); + + // horizontal draggable doesn't drag vertically when there is competition + // for vertical gestures + expect(events, isEmpty); + firstLocation = tester.getCenter(find.text('H')); + secondLocation = tester.getCenter(find.text('Target')); + gesture = tester.startGesture(firstLocation, pointer: 7); + tester.pump(); + gesture.moveTo(secondLocation); + tester.pump(); // scrolls off screen! + gesture.up(); + tester.pump(); + expect(events, equals([])); + expect(tester.getCenter(find.text('Target')).y, lessThan(0.0)); + events.clear(); + }); + + testWidgets('Drag and drop - horizontal and vertical draggables in horizontal block', (WidgetTester tester) { + List events = []; + Point firstLocation, secondLocation, thirdLocation; + + tester.pumpWidget(new MaterialApp( + home: new Block( + scrollDirection: Axis.horizontal, + children: [ + new DragTarget( + builder: (BuildContext context, List data, List rejects) { + return new Text('Target'); + }, + onAccept: (int data) { + events.add('drop $data'); + } + ), + new Container(width: 400.0), + new HorizontalDraggable( + data: 1, + child: new Text('H'), + feedback: new Text('Dragging') + ), + new VerticalDraggable( + data: 2, + child: new Text('V'), + feedback: new Text('Dragging') + ), + new Container(width: 500.0), + new Container(width: 500.0), + new Container(width: 500.0), + new Container(width: 500.0), + ] + ) + )); + + expect(events, isEmpty); + expect(find.text('Target'), findsOneWidget); + expect(find.text('H'), findsOneWidget); + expect(find.text('V'), findsOneWidget); + + // horizontal draggable drags horizontally + expect(events, isEmpty); + firstLocation = tester.getCenter(find.text('H')); + secondLocation = tester.getCenter(find.text('Target')); + TestGesture gesture = tester.startGesture(firstLocation, pointer: 7); + tester.pump(); + gesture.moveTo(secondLocation); + tester.pump(); + gesture.up(); + tester.pump(); + expect(events, equals(['drop 1'])); + expect(tester.getCenter(find.text('Target')).x, greaterThan(0.0)); + events.clear(); + + // vertical draggable drags vertically + expect(events, isEmpty); + firstLocation = tester.getTopLeft(find.text('V')); + secondLocation = tester.getBottomLeft(find.text('V')); + thirdLocation = tester.getCenter(find.text('Target')); + gesture = tester.startGesture(firstLocation, pointer: 7); + tester.pump(); + gesture.moveTo(secondLocation); + tester.pump(); + gesture.moveTo(thirdLocation); + tester.pump(); + gesture.up(); + tester.pump(); + expect(events, equals(['drop 2'])); + expect(tester.getCenter(find.text('Target')).x, greaterThan(0.0)); + events.clear(); + + // horizontal draggable drags vertically when there's no competition + // from other gesture detectors + expect(events, isEmpty); + firstLocation = tester.getTopLeft(find.text('H')); + secondLocation = tester.getBottomLeft(find.text('H')); + thirdLocation = tester.getCenter(find.text('Target')); + gesture = tester.startGesture(firstLocation, pointer: 7); + tester.pump(); + gesture.moveTo(secondLocation); + tester.pump(); + gesture.moveTo(thirdLocation); + tester.pump(); + gesture.up(); + tester.pump(); + expect(events, equals(['drop 1'])); + expect(tester.getCenter(find.text('Target')).x, greaterThan(0.0)); + events.clear(); + + // vertical draggable doesn't drag horizontally when there is competition + // for horizontal gestures + expect(events, isEmpty); + firstLocation = tester.getCenter(find.text('V')); + secondLocation = tester.getCenter(find.text('Target')); + gesture = tester.startGesture(firstLocation, pointer: 7); + tester.pump(); + gesture.moveTo(secondLocation); + tester.pump(); // scrolls off screen! + gesture.up(); + tester.pump(); + expect(events, equals([])); + expect(tester.getCenter(find.text('Target')).x, lessThan(0.0)); + events.clear(); + }); + + testWidgets('Drag and drop - onDraggableDropped not called if dropped on accepting target', (WidgetTester tester) { + List accepted = []; + bool onDraggableCanceledCalled = false; + + tester.pumpWidget(new MaterialApp( + home: new Column( + children: [ + new Draggable( + data: 1, + child: new Text('Source'), + feedback: new Text('Dragging'), + onDraggableCanceled: (Velocity velocity, Offset offset) { + onDraggableCanceledCalled = true; + } + ), + new DragTarget( + builder: (BuildContext context, List data, List rejects) { + return new Container(height: 100.0, child: new Text('Target')); + }, + onAccept: (int data) { + accepted.add(data); + } + ), + ] + ) + )); + + expect(accepted, isEmpty); + expect(find.text('Source'), findsOneWidget); + expect(find.text('Dragging'), findsNothing); + expect(find.text('Target'), findsOneWidget); + expect(onDraggableCanceledCalled, isFalse); + + Point firstLocation = tester.getCenter(find.text('Source')); + TestGesture gesture = tester.startGesture(firstLocation, pointer: 7); + tester.pump(); + + expect(accepted, isEmpty); + expect(find.text('Source'), findsOneWidget); + expect(find.text('Dragging'), findsOneWidget); + expect(find.text('Target'), findsOneWidget); + expect(onDraggableCanceledCalled, isFalse); + + Point secondLocation = tester.getCenter(find.text('Target')); + gesture.moveTo(secondLocation); + tester.pump(); + + expect(accepted, isEmpty); + expect(find.text('Source'), findsOneWidget); + expect(find.text('Dragging'), findsOneWidget); + expect(find.text('Target'), findsOneWidget); + expect(onDraggableCanceledCalled, isFalse); + + gesture.up(); + tester.pump(); + + expect(accepted, equals([1])); + expect(find.text('Source'), findsOneWidget); + expect(find.text('Dragging'), findsNothing); + expect(find.text('Target'), findsOneWidget); + expect(onDraggableCanceledCalled, isFalse); + }); + + testWidgets('Drag and drop - onDraggableDropped called if dropped on non-accepting target', (WidgetTester tester) { + List accepted = []; + bool onDraggableCanceledCalled = false; + Velocity onDraggableCanceledVelocity; + Offset onDraggableCanceledOffset; + + tester.pumpWidget(new MaterialApp( + home: new Column( + children: [ + new Draggable( + data: 1, + child: new Text('Source'), + feedback: new Text('Dragging'), onDraggableCanceled: (Velocity velocity, Offset offset) { onDraggableCanceledCalled = true; onDraggableCanceledVelocity = velocity; @@ -695,226 +598,283 @@ void main() { child: new Text('Target') ); }, - onWillAccept: (int data) => false), - ] - ) - )); + onWillAccept: (int data) => false + ), + ] + ) + )); - expect(accepted, isEmpty); - expect(tester, hasWidget(find.text('Source'))); - expect(tester, doesNotHaveWidget(find.text('Dragging'))); - expect(tester, hasWidget(find.text('Target'))); - expect(onDraggableCanceledCalled, isFalse); + expect(accepted, isEmpty); + expect(find.text('Source'), findsOneWidget); + expect(find.text('Dragging'), findsNothing); + expect(find.text('Target'), findsOneWidget); + expect(onDraggableCanceledCalled, isFalse); - Point flingStart = tester.getTopLeft(find.text('Source')); - tester.flingFrom(flingStart, new Offset(0.0, 100.0), 1000.0); - tester.pump(); + Point firstLocation = tester.getTopLeft(find.text('Source')); + TestGesture gesture = tester.startGesture(firstLocation, pointer: 7); + tester.pump(); - expect(accepted, isEmpty); - expect(tester, hasWidget(find.text('Source'))); - expect(tester, doesNotHaveWidget(find.text('Dragging'))); - expect(tester, hasWidget(find.text('Target'))); - expect(onDraggableCanceledCalled, isTrue); - expect(onDraggableCanceledVelocity.pixelsPerSecond.dx.abs(), - lessThan(0.0000001)); - expect((onDraggableCanceledVelocity.pixelsPerSecond.dy - 1000.0).abs(), - lessThan(0.0000001)); - expect( - onDraggableCanceledOffset, - equals( - new Offset(flingStart.x, flingStart.y) + new Offset(0.0, 100.0))); - }); + expect(accepted, isEmpty); + expect(find.text('Source'), findsOneWidget); + expect(find.text('Dragging'), findsOneWidget); + expect(find.text('Target'), findsOneWidget); + expect(onDraggableCanceledCalled, isFalse); + + Point secondLocation = tester.getCenter(find.text('Target')); + gesture.moveTo(secondLocation); + tester.pump(); + + expect(accepted, isEmpty); + expect(find.text('Source'), findsOneWidget); + expect(find.text('Dragging'), findsOneWidget); + expect(find.text('Target'), findsOneWidget); + expect(onDraggableCanceledCalled, isFalse); + + gesture.up(); + tester.pump(); + + expect(accepted, isEmpty); + expect(find.text('Source'), findsOneWidget); + expect(find.text('Dragging'), findsNothing); + expect(find.text('Target'), findsOneWidget); + expect(onDraggableCanceledCalled, isTrue); + expect(onDraggableCanceledVelocity, equals(Velocity.zero)); + expect(onDraggableCanceledOffset, equals(new Offset(secondLocation.x, secondLocation.y))); }); - test('Drag and drop - allow pass thru of unaccepted data test', () { - testWidgets((WidgetTester tester) { - List acceptedInts = []; - List acceptedDoubles = []; + testWidgets('Drag and drop - onDraggableDropped called if dropped on non-accepting target with correct velocity', (WidgetTester tester) { + List accepted = []; + bool onDraggableCanceledCalled = false; + Velocity onDraggableCanceledVelocity; + Offset onDraggableCanceledOffset; - tester.pumpWidget(new MaterialApp( - home: new Column( - children: [ - new Draggable( - data: 1, - child: new Text('IntSource'), - feedback: new Text('IntDragging') - ), - new Draggable( - data: 1.0, - child: new Text('DoubleSource'), - feedback: new Text('DoubleDragging') - ), - new Stack( - children: [ - new DragTarget( - builder: (BuildContext context, List data, List rejects) { - return new IgnorePointer( - child: new Container( - height: 100.0, - child: new Text('Target1') - ) - ); - }, - onAccept: (int data) { - acceptedInts.add(data); - } - ), - new DragTarget( - builder: (BuildContext context, List data, List rejects) { - return new IgnorePointer( - child: new Container( - height: 100.0, - child: new Text('Target2') - ) - ); - }, - onAccept: (double data) { - acceptedDoubles.add(data); - } - ), - ] - ) - ] - ) - )); + tester.pumpWidget(new MaterialApp( + home: new Column(children: [ + new Draggable( + data: 1, + child: new Text('Source'), + feedback: new Text('Source'), + onDraggableCanceled: (Velocity velocity, Offset offset) { + onDraggableCanceledCalled = true; + onDraggableCanceledVelocity = velocity; + onDraggableCanceledOffset = offset; + } + ), + new DragTarget( + builder: (BuildContext context, List data, List rejects) { + return new Container( + height: 100.0, + child: new Text('Target') + ); + }, + onWillAccept: (int data) => false), + ] + ) + )); - expect(acceptedInts, isEmpty); - expect(acceptedDoubles, isEmpty); - expect(tester, hasWidget(find.text('IntSource'))); - expect(tester, doesNotHaveWidget(find.text('IntDragging'))); - expect(tester, hasWidget(find.text('DoubleSource'))); - expect(tester, doesNotHaveWidget(find.text('DoubleDragging'))); - expect(tester, hasWidget(find.text('Target1'))); - expect(tester, hasWidget(find.text('Target2'))); + expect(accepted, isEmpty); + expect(find.text('Source'), findsOneWidget); + expect(find.text('Dragging'), findsNothing); + expect(find.text('Target'), findsOneWidget); + expect(onDraggableCanceledCalled, isFalse); - Point intLocation = tester.getCenter(find.text('IntSource')); - Point doubleLocation = tester.getCenter(find.text('DoubleSource')); - Point targetLocation = tester.getCenter(find.text('Target1')); + Point flingStart = tester.getTopLeft(find.text('Source')); + tester.flingFrom(flingStart, new Offset(0.0, 100.0), 1000.0); + tester.pump(); - // Drag the double draggable. - TestGesture doubleGesture = - tester.startGesture(doubleLocation, pointer: 7); - tester.pump(); - - expect(acceptedInts, isEmpty); - expect(acceptedDoubles, isEmpty); - expect(tester, doesNotHaveWidget(find.text('IntDragging'))); - expect(tester, hasWidget(find.text('DoubleDragging'))); - - doubleGesture.moveTo(targetLocation); - tester.pump(); - - expect(acceptedInts, isEmpty); - expect(acceptedDoubles, isEmpty); - expect(tester, doesNotHaveWidget(find.text('IntDragging'))); - expect(tester, hasWidget(find.text('DoubleDragging'))); - - doubleGesture.up(); - tester.pump(); - - expect(acceptedInts, isEmpty); - expect(acceptedDoubles, equals([1.0])); - expect(tester, doesNotHaveWidget(find.text('IntDragging'))); - expect(tester, doesNotHaveWidget(find.text('DoubleDragging'))); - - acceptedDoubles.clear(); - - // Drag the int draggable. - TestGesture intGesture = tester.startGesture(intLocation, pointer: 7); - tester.pump(); - - expect(acceptedInts, isEmpty); - expect(acceptedDoubles, isEmpty); - expect(tester, hasWidget(find.text('IntDragging'))); - expect(tester, doesNotHaveWidget(find.text('DoubleDragging'))); - - intGesture.moveTo(targetLocation); - tester.pump(); - - expect(acceptedInts, isEmpty); - expect(acceptedDoubles, isEmpty); - expect(tester, hasWidget(find.text('IntDragging'))); - expect(tester, doesNotHaveWidget(find.text('DoubleDragging'))); - - intGesture.up(); - tester.pump(); - - expect(acceptedInts, equals([1])); - expect(acceptedDoubles, isEmpty); - expect(tester, doesNotHaveWidget(find.text('IntDragging'))); - expect(tester, doesNotHaveWidget(find.text('DoubleDragging'))); - }); + expect(accepted, isEmpty); + expect(find.text('Source'), findsOneWidget); + expect(find.text('Dragging'), findsNothing); + expect(find.text('Target'), findsOneWidget); + expect(onDraggableCanceledCalled, isTrue); + expect(onDraggableCanceledVelocity.pixelsPerSecond.dx.abs(), lessThan(0.0000001)); + expect((onDraggableCanceledVelocity.pixelsPerSecond.dy - 1000.0).abs(), lessThan(0.0000001)); + expect(onDraggableCanceledOffset, equals(new Offset(flingStart.x, flingStart.y) + new Offset(0.0, 100.0))); }); - test('Drag and drop - allow pass thru of unaccepted data twice test', () { - testWidgets((WidgetTester tester) { - List acceptedDragTargetDatas = []; - List acceptedExtendedDragTargetDatas = []; - DragTargetData dragTargetData = new DragTargetData(); - tester.pumpWidget(new MaterialApp( - home: new Column( - children: [ - new Draggable( - data: dragTargetData, - child: new Text('Source'), - feedback: new Text('Dragging') - ), - new Stack( - children: [ - new DragTarget( - builder: (BuildContext context, List data, List rejects) { - return new IgnorePointer( - child: new Container( - height: 100.0, - child: new Text('Target1') - ) - ); - }, onAccept: (DragTargetData data) { - acceptedDragTargetDatas.add(data); - } - ), - new DragTarget( - builder: (BuildContext context, List data, List rejects) { - return new IgnorePointer( - child: new Container( - height: 100.0, - child: new Text('Target2') - ) - ); - }, - onAccept: (ExtendedDragTargetData data) { - acceptedExtendedDragTargetDatas.add(data); - } - ), - ] - ) - ] - ) - )); + testWidgets('Drag and drop - allow pass thru of unaccepted data test', (WidgetTester tester) { + List acceptedInts = []; + List acceptedDoubles = []; - Point dragTargetLocation = tester.getCenter(find.text('Source')); - Point targetLocation = tester.getCenter(find.text('Target1')); + tester.pumpWidget(new MaterialApp( + home: new Column( + children: [ + new Draggable( + data: 1, + child: new Text('IntSource'), + feedback: new Text('IntDragging') + ), + new Draggable( + data: 1.0, + child: new Text('DoubleSource'), + feedback: new Text('DoubleDragging') + ), + new Stack( + children: [ + new DragTarget( + builder: (BuildContext context, List data, List rejects) { + return new IgnorePointer( + child: new Container( + height: 100.0, + child: new Text('Target1') + ) + ); + }, + onAccept: (int data) { + acceptedInts.add(data); + } + ), + new DragTarget( + builder: (BuildContext context, List data, List rejects) { + return new IgnorePointer( + child: new Container( + height: 100.0, + child: new Text('Target2') + ) + ); + }, + onAccept: (double data) { + acceptedDoubles.add(data); + } + ), + ] + ) + ] + ) + )); - for (int i = 0; i < 2; i += 1) { - TestGesture gesture = tester.startGesture(dragTargetLocation); - tester.pump(); - gesture.moveTo(targetLocation); - tester.pump(); - gesture.up(); - tester.pump(); + expect(acceptedInts, isEmpty); + expect(acceptedDoubles, isEmpty); + expect(find.text('IntSource'), findsOneWidget); + expect(find.text('IntDragging'), findsNothing); + expect(find.text('DoubleSource'), findsOneWidget); + expect(find.text('DoubleDragging'), findsNothing); + expect(find.text('Target1'), findsOneWidget); + expect(find.text('Target2'), findsOneWidget); - expect(acceptedDragTargetDatas, equals([dragTargetData])); - expect(acceptedExtendedDragTargetDatas, isEmpty); + Point intLocation = tester.getCenter(find.text('IntSource')); + Point doubleLocation = tester.getCenter(find.text('DoubleSource')); + Point targetLocation = tester.getCenter(find.text('Target1')); - acceptedDragTargetDatas.clear(); - tester.pump(); - } - }); + // Drag the double draggable. + TestGesture doubleGesture = + tester.startGesture(doubleLocation, pointer: 7); + tester.pump(); + + expect(acceptedInts, isEmpty); + expect(acceptedDoubles, isEmpty); + expect(find.text('IntDragging'), findsNothing); + expect(find.text('DoubleDragging'), findsOneWidget); + + doubleGesture.moveTo(targetLocation); + tester.pump(); + + expect(acceptedInts, isEmpty); + expect(acceptedDoubles, isEmpty); + expect(find.text('IntDragging'), findsNothing); + expect(find.text('DoubleDragging'), findsOneWidget); + + doubleGesture.up(); + tester.pump(); + + expect(acceptedInts, isEmpty); + expect(acceptedDoubles, equals([1.0])); + expect(find.text('IntDragging'), findsNothing); + expect(find.text('DoubleDragging'), findsNothing); + + acceptedDoubles.clear(); + + // Drag the int draggable. + TestGesture intGesture = tester.startGesture(intLocation, pointer: 7); + tester.pump(); + + expect(acceptedInts, isEmpty); + expect(acceptedDoubles, isEmpty); + expect(find.text('IntDragging'), findsOneWidget); + expect(find.text('DoubleDragging'), findsNothing); + + intGesture.moveTo(targetLocation); + tester.pump(); + + expect(acceptedInts, isEmpty); + expect(acceptedDoubles, isEmpty); + expect(find.text('IntDragging'), findsOneWidget); + expect(find.text('DoubleDragging'), findsNothing); + + intGesture.up(); + tester.pump(); + + expect(acceptedInts, equals([1])); + expect(acceptedDoubles, isEmpty); + expect(find.text('IntDragging'), findsNothing); + expect(find.text('DoubleDragging'), findsNothing); + }); + + testWidgets('Drag and drop - allow pass thru of unaccepted data twice test', (WidgetTester tester) { + List acceptedDragTargetDatas = []; + List acceptedExtendedDragTargetDatas = []; + DragTargetData dragTargetData = new DragTargetData(); + tester.pumpWidget(new MaterialApp( + home: new Column( + children: [ + new Draggable( + data: dragTargetData, + child: new Text('Source'), + feedback: new Text('Dragging') + ), + new Stack( + children: [ + new DragTarget( + builder: (BuildContext context, List data, List rejects) { + return new IgnorePointer( + child: new Container( + height: 100.0, + child: new Text('Target1') + ) + ); + }, onAccept: (DragTargetData data) { + acceptedDragTargetDatas.add(data); + } + ), + new DragTarget( + builder: (BuildContext context, List data, List rejects) { + return new IgnorePointer( + child: new Container( + height: 100.0, + child: new Text('Target2') + ) + ); + }, + onAccept: (ExtendedDragTargetData data) { + acceptedExtendedDragTargetDatas.add(data); + } + ), + ] + ) + ] + ) + )); + + Point dragTargetLocation = tester.getCenter(find.text('Source')); + Point targetLocation = tester.getCenter(find.text('Target1')); + + for (int i = 0; i < 2; i += 1) { + TestGesture gesture = tester.startGesture(dragTargetLocation); + tester.pump(); + gesture.moveTo(targetLocation); + tester.pump(); + gesture.up(); + tester.pump(); + + expect(acceptedDragTargetDatas, equals([dragTargetData])); + expect(acceptedExtendedDragTargetDatas, isEmpty); + + acceptedDragTargetDatas.clear(); + tester.pump(); + } }); } -class DragTargetData { -} +class DragTargetData { } -class ExtendedDragTargetData extends DragTargetData { -} +class ExtendedDragTargetData extends DragTargetData { } diff --git a/packages/flutter/test/widget/drawer_test.dart b/packages/flutter/test/widget/drawer_test.dart index e13dec9128..5d81319e8b 100644 --- a/packages/flutter/test/widget/drawer_test.dart +++ b/packages/flutter/test/widget/drawer_test.dart @@ -9,126 +9,120 @@ import 'package:test/test.dart'; void main() { - test('Drawer control test', () { - testWidgets((WidgetTester tester) { - GlobalKey scaffoldKey = new GlobalKey(); - BuildContext savedContext; - tester.pumpWidget( - new MaterialApp( - home: new Builder( - builder: (BuildContext context) { - savedContext = context; - return new Scaffold( - key: scaffoldKey, - drawer: new Text('drawer'), - body: new Container() - ); - } - ) + testWidgets('Drawer control test', (WidgetTester tester) { + GlobalKey scaffoldKey = new GlobalKey(); + BuildContext savedContext; + tester.pumpWidget( + new MaterialApp( + home: new Builder( + builder: (BuildContext context) { + savedContext = context; + return new Scaffold( + key: scaffoldKey, + drawer: new Text('drawer'), + body: new Container() + ); + } ) - ); - tester.pump(); // no effect - expect(tester, doesNotHaveWidget(find.text('drawer'))); - scaffoldKey.currentState.openDrawer(); - tester.pump(); // drawer should be starting to animate in - expect(tester, hasWidget(find.text('drawer'))); - tester.pump(new Duration(seconds: 1)); // animation done - expect(tester, hasWidget(find.text('drawer'))); - Navigator.pop(savedContext); - tester.pump(); // drawer should be starting to animate away - expect(tester, hasWidget(find.text('drawer'))); - tester.pump(new Duration(seconds: 1)); // animation done - expect(tester, doesNotHaveWidget(find.text('drawer'))); - }); + ) + ); + tester.pump(); // no effect + expect(find.text('drawer'), findsNothing); + scaffoldKey.currentState.openDrawer(); + tester.pump(); // drawer should be starting to animate in + expect(find.text('drawer'), findsOneWidget); + tester.pump(new Duration(seconds: 1)); // animation done + expect(find.text('drawer'), findsOneWidget); + Navigator.pop(savedContext); + tester.pump(); // drawer should be starting to animate away + expect(find.text('drawer'), findsOneWidget); + tester.pump(new Duration(seconds: 1)); // animation done + expect(find.text('drawer'), findsNothing); }); - test('Drawer tap test', () { - testWidgets((WidgetTester tester) { - GlobalKey scaffoldKey = new GlobalKey(); - tester.pumpWidget( - new MaterialApp( - home: new Scaffold( - key: scaffoldKey, - drawer: new Text('drawer'), - body: new Container() - ) + testWidgets('Drawer tap test', (WidgetTester tester) { + GlobalKey scaffoldKey = new GlobalKey(); + tester.pumpWidget( + new MaterialApp( + home: new Scaffold( + key: scaffoldKey, + drawer: new Text('drawer'), + body: new Container() ) - ); - tester.pump(); // no effect - expect(tester, doesNotHaveWidget(find.text('drawer'))); - scaffoldKey.currentState.openDrawer(); - tester.pump(); // drawer should be starting to animate in - expect(tester, hasWidget(find.text('drawer'))); - tester.pump(new Duration(seconds: 1)); // animation done - expect(tester, hasWidget(find.text('drawer'))); - tester.tap(find.text('drawer')); - tester.pump(); // nothing should have happened - expect(tester, hasWidget(find.text('drawer'))); - tester.pump(new Duration(seconds: 1)); // ditto - expect(tester, hasWidget(find.text('drawer'))); - tester.tapAt(const Point(750.0, 100.0)); // on the mask - tester.pump(); - tester.pump(new Duration(milliseconds: 10)); - // drawer should be starting to animate away - expect(tester, hasWidget(find.text('drawer'))); - tester.pump(new Duration(seconds: 1)); // animation done - expect(tester, doesNotHaveWidget(find.text('drawer'))); - }); + ) + ); + tester.pump(); // no effect + expect(find.text('drawer'), findsNothing); + scaffoldKey.currentState.openDrawer(); + tester.pump(); // drawer should be starting to animate in + expect(find.text('drawer'), findsOneWidget); + tester.pump(new Duration(seconds: 1)); // animation done + expect(find.text('drawer'), findsOneWidget); + tester.tap(find.text('drawer')); + tester.pump(); // nothing should have happened + expect(find.text('drawer'), findsOneWidget); + tester.pump(new Duration(seconds: 1)); // ditto + expect(find.text('drawer'), findsOneWidget); + tester.tapAt(const Point(750.0, 100.0)); // on the mask + tester.pump(); + tester.pump(new Duration(milliseconds: 10)); + // drawer should be starting to animate away + expect(find.text('drawer'), findsOneWidget); + tester.pump(new Duration(seconds: 1)); // animation done + expect(find.text('drawer'), findsNothing); }); - test('Drawer drag cancel resume', () { - testWidgets((WidgetTester tester) { - GlobalKey scaffoldKey = new GlobalKey(); - tester.pumpWidget( - new MaterialApp( - home: new Scaffold( - key: scaffoldKey, - drawer: new Drawer( - child: new Block( - children: [ - new Text('drawer'), - new Container( - height: 1000.0, - decoration: new BoxDecoration( - backgroundColor: Colors.blue[500] - ) - ), - ] - ) - ), - body: new Container() - ) + testWidgets('Drawer drag cancel resume', (WidgetTester tester) { + GlobalKey scaffoldKey = new GlobalKey(); + tester.pumpWidget( + new MaterialApp( + home: new Scaffold( + key: scaffoldKey, + drawer: new Drawer( + child: new Block( + children: [ + new Text('drawer'), + new Container( + height: 1000.0, + decoration: new BoxDecoration( + backgroundColor: Colors.blue[500] + ) + ), + ] + ) + ), + body: new Container() ) - ); - expect(tester, doesNotHaveWidget(find.text('drawer'))); - scaffoldKey.currentState.openDrawer(); - tester.pump(); // drawer should be starting to animate in - expect(tester, hasWidget(find.text('drawer'))); - tester.pump(new Duration(seconds: 1)); // animation done - expect(tester, hasWidget(find.text('drawer'))); + ) + ); + expect(find.text('drawer'), findsNothing); + scaffoldKey.currentState.openDrawer(); + tester.pump(); // drawer should be starting to animate in + expect(find.text('drawer'), findsOneWidget); + tester.pump(new Duration(seconds: 1)); // animation done + expect(find.text('drawer'), findsOneWidget); - tester.tapAt(const Point(750.0, 100.0)); // on the mask - tester.pump(); - tester.pump(new Duration(milliseconds: 10)); - // drawer should be starting to animate away - RenderBox textBox = tester.renderObjectOf(find.text('drawer')); - double textLeft = textBox.localToGlobal(Point.origin).x; - expect(textLeft, lessThan(0.0)); + tester.tapAt(const Point(750.0, 100.0)); // on the mask + tester.pump(); + tester.pump(new Duration(milliseconds: 10)); + // drawer should be starting to animate away + RenderBox textBox = tester.renderObject(find.text('drawer')); + double textLeft = textBox.localToGlobal(Point.origin).x; + expect(textLeft, lessThan(0.0)); - TestGesture gesture = tester.startGesture(new Point(100.0, 100.0)); - // drawer should be stopped. - tester.pump(); - tester.pump(new Duration(milliseconds: 10)); - expect(textBox.localToGlobal(Point.origin).x, equals(textLeft)); + TestGesture gesture = tester.startGesture(new Point(100.0, 100.0)); + // drawer should be stopped. + tester.pump(); + tester.pump(new Duration(milliseconds: 10)); + expect(textBox.localToGlobal(Point.origin).x, equals(textLeft)); - gesture.moveBy(new Offset(0.0, -50.0)); - // drawer should be returning to visible - tester.pump(); - tester.pump(new Duration(seconds: 1)); - expect(textBox.localToGlobal(Point.origin).x, equals(0.0)); + gesture.moveBy(new Offset(0.0, -50.0)); + // drawer should be returning to visible + tester.pump(); + tester.pump(new Duration(seconds: 1)); + expect(textBox.localToGlobal(Point.origin).x, equals(0.0)); - gesture.up(); - }); + gesture.up(); }); } diff --git a/packages/flutter/test/widget/duplicate_key_test.dart b/packages/flutter/test/widget/duplicate_key_test.dart index 4fe48b6f74..a433ae4930 100644 --- a/packages/flutter/test/widget/duplicate_key_test.dart +++ b/packages/flutter/test/widget/duplicate_key_test.dart @@ -4,7 +4,6 @@ import 'package:flutter_test/flutter_test.dart'; import 'package:flutter/widgets.dart'; -import 'package:test/test.dart'; class Item { GlobalKey key1 = new GlobalKey(); @@ -55,16 +54,14 @@ Widget builder() { } void main() { - test('duplicate key smoke test', () { - testWidgets((WidgetTester tester) { - tester.pumpWidget(builder()); - StatefulLeafState leaf = tester.stateOf(find.byType(StatefulLeaf)); - leaf.test(); - tester.pump(); - Item lastItem = items[1]; - items.remove(lastItem); - items.insert(0, lastItem); - tester.pumpWidget(builder()); // this marks the app dirty and rebuilds it - }); + testWidgets('duplicate key smoke test', (WidgetTester tester) { + tester.pumpWidget(builder()); + StatefulLeafState leaf = tester.firstState(find.byType(StatefulLeaf)); + leaf.test(); + tester.pump(); + Item lastItem = items[1]; + items.remove(lastItem); + items.insert(0, lastItem); + tester.pumpWidget(builder()); // this marks the app dirty and rebuilds it }); } diff --git a/packages/flutter/test/widget/flex_test.dart b/packages/flutter/test/widget/flex_test.dart index f403290518..806673109b 100644 --- a/packages/flutter/test/widget/flex_test.dart +++ b/packages/flutter/test/widget/flex_test.dart @@ -8,160 +8,156 @@ import 'package:flutter/widgets.dart'; import 'package:test/test.dart'; void main() { - test('Can hit test flex children of stacks', () { - testWidgets((WidgetTester tester) { - bool didReceiveTap = false; - tester.pumpWidget( - new Container( - decoration: const BoxDecoration( - backgroundColor: const Color(0xFF00FF00) - ), - child: new Stack( - children: [ - new Positioned( - top: 10.0, - left: 10.0, - child: new Column( - children: [ - new GestureDetector( - onTap: () { - didReceiveTap = true; - }, - child: new Container( - decoration: const BoxDecoration( - backgroundColor: const Color(0xFF0000FF) - ), - width: 100.0, - height: 100.0, - child: new Center( - child: new Text('X') - ) + testWidgets('Can hit test flex children of stacks', (WidgetTester tester) { + bool didReceiveTap = false; + tester.pumpWidget( + new Container( + decoration: const BoxDecoration( + backgroundColor: const Color(0xFF00FF00) + ), + child: new Stack( + children: [ + new Positioned( + top: 10.0, + left: 10.0, + child: new Column( + children: [ + new GestureDetector( + onTap: () { + didReceiveTap = true; + }, + child: new Container( + decoration: const BoxDecoration( + backgroundColor: const Color(0xFF0000FF) + ), + width: 100.0, + height: 100.0, + child: new Center( + child: new Text('X') ) ) - ] - ) + ) + ] ) - ] - ) + ) + ] ) - ); + ) + ); - tester.tap(find.text('X')); - expect(didReceiveTap, isTrue); - }); + tester.tap(find.text('X')); + expect(didReceiveTap, isTrue); }); - test('Row, Column and FlexJustifyContent.collapse', () { + testWidgets('Row and FlexJustifyContent.collapse', (WidgetTester tester) { final Key flexKey = new Key('flexKey'); // Row without mainAxisAlignment: FlexJustifyContent.collapse - testWidgets((WidgetTester tester) { - tester.pumpWidget(new Center( - child: new Row( - children: [ - new Container(width: 10.0, height: 100.0), - new Container(width: 30.0, height: 100.0) - ], - key: flexKey - ) - )); - RenderBox renderBox = tester.renderObjectOf(find.byKey(flexKey)); - expect(renderBox.size.width, equals(800.0)); - expect(renderBox.size.height, equals(100.0)); + tester.pumpWidget(new Center( + child: new Row( + children: [ + new Container(width: 10.0, height: 100.0), + new Container(width: 30.0, height: 100.0) + ], + key: flexKey + ) + )); + RenderBox renderBox = tester.renderObject(find.byKey(flexKey)); + expect(renderBox.size.width, equals(800.0)); + expect(renderBox.size.height, equals(100.0)); - // Row with mainAxisAlignment: FlexJustifyContent.collapse - tester.pumpWidget(new Center( - child: new Row( - children: [ - new Container(width: 10.0, height: 100.0), - new Container(width: 30.0, height: 100.0) - ], - key: flexKey, - mainAxisAlignment: MainAxisAlignment.collapse - ) - )); - renderBox = tester.renderObjectOf(find.byKey(flexKey)); - expect(renderBox.size.width, equals(40.0)); - expect(renderBox.size.height, equals(100.0)); - }); + // Row with mainAxisAlignment: FlexJustifyContent.collapse + tester.pumpWidget(new Center( + child: new Row( + children: [ + new Container(width: 10.0, height: 100.0), + new Container(width: 30.0, height: 100.0) + ], + key: flexKey, + mainAxisAlignment: MainAxisAlignment.collapse + ) + )); + renderBox = tester.renderObject(find.byKey(flexKey)); + expect(renderBox.size.width, equals(40.0)); + expect(renderBox.size.height, equals(100.0)); + }); + + testWidgets('Column and FlexJustifyContent.collapse', (WidgetTester tester) { + final Key flexKey = new Key('flexKey'); // Column without mainAxisAlignment: FlexJustifyContent.collapse - testWidgets((WidgetTester tester) { - tester.pumpWidget(new Center( - child: new Column( - children: [ - new Container(width: 100.0, height: 100.0), - new Container(width: 100.0, height: 150.0) - ], - key: flexKey - ) - )); - RenderBox renderBox = tester.renderObjectOf(find.byKey(flexKey)); - expect(renderBox.size.width, equals(100.0)); - expect(renderBox.size.height, equals(600.0)); + tester.pumpWidget(new Center( + child: new Column( + children: [ + new Container(width: 100.0, height: 100.0), + new Container(width: 100.0, height: 150.0) + ], + key: flexKey + ) + )); + RenderBox renderBox = tester.renderObject(find.byKey(flexKey)); + expect(renderBox.size.width, equals(100.0)); + expect(renderBox.size.height, equals(600.0)); - // Column with mainAxisAlignment: FlexJustifyContent.collapse - tester.pumpWidget(new Center( - child: new Column( - children: [ - new Container(width: 100.0, height: 100.0), - new Container(width: 100.0, height: 150.0) - ], - key: flexKey, - mainAxisAlignment: MainAxisAlignment.collapse - ) - )); - renderBox = tester.renderObjectOf(find.byKey(flexKey)); - expect(renderBox.size.width, equals(100.0)); - expect(renderBox.size.height, equals(250.0)); - }); + // Column with mainAxisAlignment: FlexJustifyContent.collapse + tester.pumpWidget(new Center( + child: new Column( + children: [ + new Container(width: 100.0, height: 100.0), + new Container(width: 100.0, height: 150.0) + ], + key: flexKey, + mainAxisAlignment: MainAxisAlignment.collapse + ) + )); + renderBox = tester.renderObject(find.byKey(flexKey)); + expect(renderBox.size.width, equals(100.0)); + expect(renderBox.size.height, equals(250.0)); }); - test('Can layout at zero size', () { + testWidgets('Can layout at zero size', (WidgetTester tester) { final Key childKey = new Key('childKey'); - testWidgets((WidgetTester tester) { - tester.pumpWidget(new Center( - child: new Container( - width: 0.0, - height: 0.0, - child: new Column( - children: [ - new Container( - key: childKey, - width: 100.0, - height: 100.0 - ) - ], - mainAxisAlignment: MainAxisAlignment.collapse - ) + tester.pumpWidget(new Center( + child: new Container( + width: 0.0, + height: 0.0, + child: new Column( + children: [ + new Container( + key: childKey, + width: 100.0, + height: 100.0 + ) + ], + mainAxisAlignment: MainAxisAlignment.collapse ) - )); + ) + )); - RenderBox renderBox = tester.renderObjectOf(find.byKey(childKey)); - expect(renderBox.size.width, equals(0.0)); - expect(renderBox.size.height, equals(100.0)); + RenderBox renderBox = tester.renderObject(find.byKey(childKey)); + expect(renderBox.size.width, equals(0.0)); + expect(renderBox.size.height, equals(100.0)); - tester.pumpWidget(new Center( - child: new Container( - width: 0.0, - height: 0.0, - child: new Row( - children: [ - new Container( - key: childKey, - width: 100.0, - height: 100.0 - ) - ], - mainAxisAlignment: MainAxisAlignment.collapse - ) + tester.pumpWidget(new Center( + child: new Container( + width: 0.0, + height: 0.0, + child: new Row( + children: [ + new Container( + key: childKey, + width: 100.0, + height: 100.0 + ) + ], + mainAxisAlignment: MainAxisAlignment.collapse ) - )); + ) + )); - renderBox = tester.renderObjectOf(find.byKey(childKey)); - expect(renderBox.size.width, equals(100.0)); - expect(renderBox.size.height, equals(0.0)); - }); + renderBox = tester.renderObject(find.byKey(childKey)); + expect(renderBox.size.width, equals(100.0)); + expect(renderBox.size.height, equals(0.0)); }); } diff --git a/packages/flutter/test/widget/flow_test.dart b/packages/flutter/test/widget/flow_test.dart index 1c0338aefe..4306bcedda 100644 --- a/packages/flutter/test/widget/flow_test.dart +++ b/packages/flutter/test/widget/flow_test.dart @@ -32,59 +32,57 @@ class TestFlowDelegate extends FlowDelegate { } void main() { - test('Flow control test', () { - testWidgets((WidgetTester tester) { - AnimationController startOffset = new AnimationController.unbounded(); - List log = []; + testWidgets('Flow control test', (WidgetTester tester) { + AnimationController startOffset = new AnimationController.unbounded(); + List log = []; - Widget buildBox(int i) { - return new GestureDetector( - onTap: () { - log.add(i); - }, - child: new Container( - width: 100.0, - height: 100.0, - decoration: const BoxDecoration( - backgroundColor: const Color(0xFF0000FF) - ), - child: new Text('$i') - ) - ); - } - - tester.pumpWidget( - new Flow( - delegate: new TestFlowDelegate(startOffset: startOffset), - children: [ - buildBox(0), - buildBox(1), - buildBox(2), - buildBox(3), - buildBox(4), - buildBox(5), - buildBox(6), - ] + Widget buildBox(int i) { + return new GestureDetector( + onTap: () { + log.add(i); + }, + child: new Container( + width: 100.0, + height: 100.0, + decoration: const BoxDecoration( + backgroundColor: const Color(0xFF0000FF) + ), + child: new Text('$i') ) ); + } - tester.tap(find.text('0')); - expect(log, equals([0])); - tester.tap(find.text('1')); - expect(log, equals([0, 1])); - tester.tap(find.text('2')); - expect(log, equals([0, 1, 2])); + tester.pumpWidget( + new Flow( + delegate: new TestFlowDelegate(startOffset: startOffset), + children: [ + buildBox(0), + buildBox(1), + buildBox(2), + buildBox(3), + buildBox(4), + buildBox(5), + buildBox(6), + ] + ) + ); - log.clear(); - tester.tapAt(new Point(20.0, 90.0)); - expect(log, equals([1])); + tester.tap(find.text('0')); + expect(log, equals([0])); + tester.tap(find.text('1')); + expect(log, equals([0, 1])); + tester.tap(find.text('2')); + expect(log, equals([0, 1, 2])); - startOffset.value = 50.0; - tester.pump(); + log.clear(); + tester.tapAt(new Point(20.0, 90.0)); + expect(log, equals([1])); - log.clear(); - tester.tapAt(new Point(20.0, 90.0)); - expect(log, equals([0])); - }); + startOffset.value = 50.0; + tester.pump(); + + log.clear(); + tester.tapAt(new Point(20.0, 90.0)); + expect(log, equals([0])); }); } diff --git a/packages/flutter/test/widget/focus_test.dart b/packages/flutter/test/widget/focus_test.dart index 50896159a9..919db2380a 100644 --- a/packages/flutter/test/widget/focus_test.dart +++ b/packages/flutter/test/widget/focus_test.dart @@ -29,176 +29,170 @@ class TestFocusable extends StatelessWidget { } void main() { - test('Can have multiple focused children and they update accordingly', () { - testWidgets((WidgetTester tester) { - GlobalKey keyFocus = new GlobalKey(); - GlobalKey keyA = new GlobalKey(); - GlobalKey keyB = new GlobalKey(); - tester.pumpWidget( - new Focus( - key: keyFocus, - child: new Column( - children: [ - new TestFocusable( - key: keyA, - no: 'a', - yes: 'A FOCUSED' - ), - new TestFocusable( - key: keyB, - no: 'b', - yes: 'B FOCUSED' - ), - ] - ) + testWidgets('Can have multiple focused children and they update accordingly', (WidgetTester tester) { + GlobalKey keyFocus = new GlobalKey(); + GlobalKey keyA = new GlobalKey(); + GlobalKey keyB = new GlobalKey(); + tester.pumpWidget( + new Focus( + key: keyFocus, + child: new Column( + children: [ + new TestFocusable( + key: keyA, + no: 'a', + yes: 'A FOCUSED' + ), + new TestFocusable( + key: keyB, + no: 'b', + yes: 'B FOCUSED' + ), + ] ) - ); - expect(tester, doesNotHaveWidget(find.text('a'))); - expect(tester, hasWidget(find.text('A FOCUSED'))); - expect(tester, hasWidget(find.text('b'))); - expect(tester, doesNotHaveWidget(find.text('B FOCUSED'))); - tester.tap(find.text('A FOCUSED')); - tester.pump(); - expect(tester, doesNotHaveWidget(find.text('a'))); - expect(tester, hasWidget(find.text('A FOCUSED'))); - expect(tester, hasWidget(find.text('b'))); - expect(tester, doesNotHaveWidget(find.text('B FOCUSED'))); - tester.tap(find.text('A FOCUSED')); - tester.pump(); - expect(tester, doesNotHaveWidget(find.text('a'))); - expect(tester, hasWidget(find.text('A FOCUSED'))); - expect(tester, hasWidget(find.text('b'))); - expect(tester, doesNotHaveWidget(find.text('B FOCUSED'))); - tester.tap(find.text('b')); - tester.pump(); - expect(tester, hasWidget(find.text('a'))); - expect(tester, doesNotHaveWidget(find.text('A FOCUSED'))); - expect(tester, doesNotHaveWidget(find.text('b'))); - expect(tester, hasWidget(find.text('B FOCUSED'))); - tester.tap(find.text('a')); - tester.pump(); - expect(tester, doesNotHaveWidget(find.text('a'))); - expect(tester, hasWidget(find.text('A FOCUSED'))); - expect(tester, hasWidget(find.text('b'))); - expect(tester, doesNotHaveWidget(find.text('B FOCUSED'))); - }); + ) + ); + expect(find.text('a'), findsNothing); + expect(find.text('A FOCUSED'), findsOneWidget); + expect(find.text('b'), findsOneWidget); + expect(find.text('B FOCUSED'), findsNothing); + tester.tap(find.text('A FOCUSED')); + tester.pump(); + expect(find.text('a'), findsNothing); + expect(find.text('A FOCUSED'), findsOneWidget); + expect(find.text('b'), findsOneWidget); + expect(find.text('B FOCUSED'), findsNothing); + tester.tap(find.text('A FOCUSED')); + tester.pump(); + expect(find.text('a'), findsNothing); + expect(find.text('A FOCUSED'), findsOneWidget); + expect(find.text('b'), findsOneWidget); + expect(find.text('B FOCUSED'), findsNothing); + tester.tap(find.text('b')); + tester.pump(); + expect(find.text('a'), findsOneWidget); + expect(find.text('A FOCUSED'), findsNothing); + expect(find.text('b'), findsNothing); + expect(find.text('B FOCUSED'), findsOneWidget); + tester.tap(find.text('a')); + tester.pump(); + expect(find.text('a'), findsNothing); + expect(find.text('A FOCUSED'), findsOneWidget); + expect(find.text('b'), findsOneWidget); + expect(find.text('B FOCUSED'), findsNothing); }); - test('Can blur', () { - testWidgets((WidgetTester tester) { - GlobalKey keyFocus = new GlobalKey(); - GlobalKey keyA = new GlobalKey(); - tester.pumpWidget( - new Focus( - key: keyFocus, - child: new TestFocusable( - key: keyA, - no: 'a', - yes: 'A FOCUSED', - autofocus: false - ) + testWidgets('Can blur', (WidgetTester tester) { + GlobalKey keyFocus = new GlobalKey(); + GlobalKey keyA = new GlobalKey(); + tester.pumpWidget( + new Focus( + key: keyFocus, + child: new TestFocusable( + key: keyA, + no: 'a', + yes: 'A FOCUSED', + autofocus: false ) - ); + ) + ); - expect(tester, hasWidget(find.text('a'))); - expect(tester, doesNotHaveWidget(find.text('A FOCUSED'))); + expect(find.text('a'), findsOneWidget); + expect(find.text('A FOCUSED'), findsNothing); - Focus.moveTo(keyA); - tester.pump(); + Focus.moveTo(keyA); + tester.pump(); - expect(tester, doesNotHaveWidget(find.text('a'))); - expect(tester, hasWidget(find.text('A FOCUSED'))); + expect(find.text('a'), findsNothing); + expect(find.text('A FOCUSED'), findsOneWidget); - Focus.clear(keyA.currentContext); - tester.pump(); + Focus.clear(keyA.currentContext); + tester.pump(); - expect(tester, hasWidget(find.text('a'))); - expect(tester, doesNotHaveWidget(find.text('A FOCUSED'))); - }); + expect(find.text('a'), findsOneWidget); + expect(find.text('A FOCUSED'), findsNothing); }); - test('Can move focus to scope', () { - testWidgets((WidgetTester tester) { - GlobalKey keyParentFocus = new GlobalKey(); - GlobalKey keyChildFocus = new GlobalKey(); - GlobalKey keyA = new GlobalKey(); - tester.pumpWidget( - new Focus( - key: keyParentFocus, - child: new Row( - children: [ - new TestFocusable( - key: keyA, - no: 'a', - yes: 'A FOCUSED', - autofocus: false - ) - ] - ) + testWidgets('Can move focus to scope', (WidgetTester tester) { + GlobalKey keyParentFocus = new GlobalKey(); + GlobalKey keyChildFocus = new GlobalKey(); + GlobalKey keyA = new GlobalKey(); + tester.pumpWidget( + new Focus( + key: keyParentFocus, + child: new Row( + children: [ + new TestFocusable( + key: keyA, + no: 'a', + yes: 'A FOCUSED', + autofocus: false + ) + ] ) - ); + ) + ); - expect(tester, hasWidget(find.text('a'))); - expect(tester, doesNotHaveWidget(find.text('A FOCUSED'))); + expect(find.text('a'), findsOneWidget); + expect(find.text('A FOCUSED'), findsNothing); - Focus.moveTo(keyA); - tester.pump(); + Focus.moveTo(keyA); + tester.pump(); - expect(tester, doesNotHaveWidget(find.text('a'))); - expect(tester, hasWidget(find.text('A FOCUSED'))); + expect(find.text('a'), findsNothing); + expect(find.text('A FOCUSED'), findsOneWidget); - Focus.moveScopeTo(keyChildFocus, context: keyA.currentContext); + Focus.moveScopeTo(keyChildFocus, context: keyA.currentContext); - tester.pumpWidget( - new Focus( - key: keyParentFocus, - child: new Row( - children: [ - new TestFocusable( - key: keyA, - no: 'a', - yes: 'A FOCUSED', - autofocus: false - ), - new Focus( - key: keyChildFocus, - child: new Container( - width: 50.0, - height: 50.0 - ) + tester.pumpWidget( + new Focus( + key: keyParentFocus, + child: new Row( + children: [ + new TestFocusable( + key: keyA, + no: 'a', + yes: 'A FOCUSED', + autofocus: false + ), + new Focus( + key: keyChildFocus, + child: new Container( + width: 50.0, + height: 50.0 ) - ] - ) + ) + ] ) - ); + ) + ); - expect(tester, hasWidget(find.text('a'))); - expect(tester, doesNotHaveWidget(find.text('A FOCUSED'))); + expect(find.text('a'), findsOneWidget); + expect(find.text('A FOCUSED'), findsNothing); - tester.pumpWidget( - new Focus( - key: keyParentFocus, - child: new Row( - children: [ - new TestFocusable( - key: keyA, - no: 'a', - yes: 'A FOCUSED', - autofocus: false - ) - ] - ) + tester.pumpWidget( + new Focus( + key: keyParentFocus, + child: new Row( + children: [ + new TestFocusable( + key: keyA, + no: 'a', + yes: 'A FOCUSED', + autofocus: false + ) + ] ) - ); + ) + ); - // Focus has received the removal notification but we haven't rebuilt yet. - expect(tester, hasWidget(find.text('a'))); - expect(tester, doesNotHaveWidget(find.text('A FOCUSED'))); + // Focus has received the removal notification but we haven't rebuilt yet. + expect(find.text('a'), findsOneWidget); + expect(find.text('A FOCUSED'), findsNothing); - tester.pump(); + tester.pump(); - expect(tester, doesNotHaveWidget(find.text('a'))); - expect(tester, hasWidget(find.text('A FOCUSED'))); - }); + expect(find.text('a'), findsNothing); + expect(find.text('A FOCUSED'), findsOneWidget); }); } diff --git a/packages/flutter/test/widget/form_test.dart b/packages/flutter/test/widget/form_test.dart index bec7d7ec9c..b391330d31 100644 --- a/packages/flutter/test/widget/form_test.dart +++ b/packages/flutter/test/widget/form_test.dart @@ -26,9 +26,11 @@ class MockKeyboard implements mojom.Keyboard { } void main() { - WidgetsFlutterBinding.ensureInitialized(); // for serviceMocker MockKeyboard mockKeyboard = new MockKeyboard(); - serviceMocker.registerMockService(mojom.Keyboard.serviceName, mockKeyboard); + + setUpAll(() { + serviceMocker.registerMockService(mojom.Keyboard.serviceName, mockKeyboard); + }); void enterText(String testValue) { // Simulate entry of text through the keyboard. @@ -39,128 +41,122 @@ void main() { ..composingExtent = testValue.length); } - test('Setter callback is called', () { - testWidgets((WidgetTester tester) { - GlobalKey inputKey = new GlobalKey(); - String fieldValue; + testWidgets('Setter callback is called', (WidgetTester tester) { + GlobalKey inputKey = new GlobalKey(); + String fieldValue; - Widget builder() { - return new Center( - child: new Material( - child: new Form( - child: new Input( - key: inputKey, - formField: new FormField( - setter: (String val) { fieldValue = val; } - ) + Widget builder() { + return new Center( + child: new Material( + child: new Form( + child: new Input( + key: inputKey, + formField: new FormField( + setter: (String val) { fieldValue = val; } ) ) ) - ); - } + ) + ); + } + tester.pumpWidget(builder()); + + void checkText(String testValue) { + enterText(testValue); + + // Check that the FormField's setter was called. + expect(fieldValue, equals(testValue)); tester.pumpWidget(builder()); + } - void checkText(String testValue) { - enterText(testValue); - - // Check that the FormField's setter was called. - expect(fieldValue, equals(testValue)); - tester.pumpWidget(builder()); - } - - checkText('Test'); - checkText(''); - }); + checkText('Test'); + checkText(''); }); - test('Validator sets the error text', () { - testWidgets((WidgetTester tester) { - GlobalKey inputKey = new GlobalKey(); - String errorText(String input) => input + '/error'; + testWidgets('Validator sets the error text', (WidgetTester tester) { + GlobalKey inputKey = new GlobalKey(); + String errorText(String input) => input + '/error'; - Widget builder() { - return new Center( - child: new Material( - child: new Form( - child: new Input( - key: inputKey, - formField: new FormField( - validator: errorText - ) + Widget builder() { + return new Center( + child: new Material( + child: new Form( + child: new Input( + key: inputKey, + formField: new FormField( + validator: errorText ) ) ) - ); - } + ) + ); + } + tester.pumpWidget(builder()); + + void checkErrorText(String testValue) { + enterText(testValue); tester.pumpWidget(builder()); - void checkErrorText(String testValue) { - enterText(testValue); - tester.pumpWidget(builder()); + // Check for a new Text widget with our error text. + expect(find.text(errorText(testValue)), findsOneWidget); + } - // Check for a new Text widget with our error text. - expect(tester, hasWidget(find.text(errorText(testValue)))); - } - - checkErrorText('Test'); - checkErrorText(''); - }); + checkErrorText('Test'); + checkErrorText(''); }); - test('Multiple Inputs communicate', () { - testWidgets((WidgetTester tester) { - GlobalKey inputKey = new GlobalKey(); - GlobalKey focusKey = new GlobalKey(); - // Input 1's text value. - String fieldValue; - // Input 2's validator depends on a input 1's value. - String errorText(String input) => fieldValue.toString() + '/error'; + testWidgets('Multiple Inputs communicate', (WidgetTester tester) { + GlobalKey inputKey = new GlobalKey(); + GlobalKey focusKey = new GlobalKey(); + // Input 1's text value. + String fieldValue; + // Input 2's validator depends on a input 1's value. + String errorText(String input) => fieldValue.toString() + '/error'; - Widget builder() { - return new Center( - child: new Material( - child: new Form( - child: new Focus( - key: focusKey, - child: new Block( - children: [ - new Input( - key: inputKey, - formField: new FormField( - setter: (String val) { fieldValue = val; } - ) - ), - new Input( - formField: new FormField( - validator: errorText - ) + Widget builder() { + return new Center( + child: new Material( + child: new Form( + child: new Focus( + key: focusKey, + child: new Block( + children: [ + new Input( + key: inputKey, + formField: new FormField( + setter: (String val) { fieldValue = val; } ) - ] - ) + ), + new Input( + formField: new FormField( + validator: errorText + ) + ) + ] ) ) ) - ); - } + ) + ); + } + tester.pumpWidget(builder()); + Focus.moveTo(inputKey); + tester.pump(); + + void checkErrorText(String testValue) { + enterText(testValue); tester.pumpWidget(builder()); - Focus.moveTo(inputKey); - tester.pump(); - void checkErrorText(String testValue) { - enterText(testValue); - tester.pumpWidget(builder()); + expect(fieldValue, equals(testValue)); - expect(fieldValue, equals(testValue)); + // Check for a new Text widget with our error text. + expect(find.text(errorText(testValue)), findsOneWidget); + } - // Check for a new Text widget with our error text. - expect(tester, hasWidget(find.text(errorText(testValue)))); - } - - checkErrorText('Test'); - checkErrorText(''); - }); + checkErrorText('Test'); + checkErrorText(''); }); } diff --git a/packages/flutter/test/widget/fractionally_sized_box_test.dart b/packages/flutter/test/widget/fractionally_sized_box_test.dart index 7c2f7abd9f..a733f7e566 100644 --- a/packages/flutter/test/widget/fractionally_sized_box_test.dart +++ b/packages/flutter/test/widget/fractionally_sized_box_test.dart @@ -8,28 +8,26 @@ import 'package:flutter/widgets.dart'; import 'package:test/test.dart'; void main() { - test('FractionallySizedBox', () { - testWidgets((WidgetTester tester) { - GlobalKey inner = new GlobalKey(); - tester.pumpWidget(new OverflowBox( - minWidth: 0.0, - maxWidth: 100.0, - minHeight: 0.0, - maxHeight: 100.0, - alignment: const FractionalOffset(0.0, 0.0), - child: new Center( - child: new FractionallySizedBox( - width: 0.5, - height: 0.25, - child: new Container( - key: inner - ) + testWidgets('FractionallySizedBox', (WidgetTester tester) { + GlobalKey inner = new GlobalKey(); + tester.pumpWidget(new OverflowBox( + minWidth: 0.0, + maxWidth: 100.0, + minHeight: 0.0, + maxHeight: 100.0, + alignment: const FractionalOffset(0.0, 0.0), + child: new Center( + child: new FractionallySizedBox( + width: 0.5, + height: 0.25, + child: new Container( + key: inner ) ) - )); - RenderBox box = inner.currentContext.findRenderObject(); - expect(box.size, equals(const Size(50.0, 25.0))); - expect(box.localToGlobal(Point.origin), equals(const Point(25.0, 37.5))); - }); + ) + )); + RenderBox box = inner.currentContext.findRenderObject(); + expect(box.size, equals(const Size(50.0, 25.0))); + expect(box.localToGlobal(Point.origin), equals(const Point(25.0, 37.5))); }); } diff --git a/packages/flutter/test/widget/gesture_detector_test.dart b/packages/flutter/test/widget/gesture_detector_test.dart index f7502c4f35..e5ea58fd1b 100644 --- a/packages/flutter/test/widget/gesture_detector_test.dart +++ b/packages/flutter/test/widget/gesture_detector_test.dart @@ -7,196 +7,188 @@ import 'package:flutter/widgets.dart'; import 'package:test/test.dart'; void main() { - test('Uncontested scrolls start immediately', () { - testWidgets((WidgetTester tester) { - bool didStartDrag = false; - double updatedDragDelta; - bool didEndDrag = false; + testWidgets('Uncontested scrolls start immediately', (WidgetTester tester) { + bool didStartDrag = false; + double updatedDragDelta; + bool didEndDrag = false; - Widget widget = new GestureDetector( - onVerticalDragStart: (_) { - didStartDrag = true; + Widget widget = new GestureDetector( + onVerticalDragStart: (_) { + didStartDrag = true; + }, + onVerticalDragUpdate: (double scrollDelta) { + updatedDragDelta = scrollDelta; + }, + onVerticalDragEnd: (Velocity velocity) { + didEndDrag = true; + }, + child: new Container( + decoration: const BoxDecoration( + backgroundColor: const Color(0xFF00FF00) + ) + ) + ); + + tester.pumpWidget(widget); + expect(didStartDrag, isFalse); + expect(updatedDragDelta, isNull); + expect(didEndDrag, isFalse); + + Point firstLocation = new Point(10.0, 10.0); + TestGesture gesture = tester.startGesture(firstLocation, pointer: 7); + expect(didStartDrag, isTrue); + didStartDrag = false; + expect(updatedDragDelta, isNull); + expect(didEndDrag, isFalse); + + Point secondLocation = new Point(10.0, 9.0); + gesture.moveTo(secondLocation); + expect(didStartDrag, isFalse); + expect(updatedDragDelta, -1.0); + updatedDragDelta = null; + expect(didEndDrag, isFalse); + + gesture.up(); + expect(didStartDrag, isFalse); + expect(updatedDragDelta, isNull); + expect(didEndDrag, isTrue); + didEndDrag = false; + + tester.pumpWidget(new Container()); + }); + + testWidgets('Match two scroll gestures in succession', (WidgetTester tester) { + int gestureCount = 0; + double dragDistance = 0.0; + + Point downLocation = new Point(10.0, 10.0); + Point upLocation = new Point(10.0, 20.0); + + Widget widget = new GestureDetector( + onVerticalDragUpdate: (double delta) { dragDistance += delta; }, + onVerticalDragEnd: (Velocity velocity) { gestureCount += 1; }, + onHorizontalDragUpdate: (_) { fail("gesture should not match"); }, + onHorizontalDragEnd: (Velocity velocity) { fail("gesture should not match"); }, + child: new Container( + decoration: const BoxDecoration( + backgroundColor: const Color(0xFF00FF00) + ) + ) + ); + tester.pumpWidget(widget); + + TestGesture gesture = tester.startGesture(downLocation, pointer: 7); + gesture.moveTo(upLocation); + gesture.up(); + + gesture = tester.startGesture(downLocation, pointer: 7); + gesture.moveTo(upLocation); + gesture.up(); + + expect(gestureCount, 2); + expect(dragDistance, 20.0); + + tester.pumpWidget(new Container()); + }); + + testWidgets('Pan doesn\'t crash', (WidgetTester tester) { + bool didStartPan = false; + Offset panDelta; + bool didEndPan = false; + + tester.pumpWidget( + new GestureDetector( + onPanStart: (_) { + didStartPan = true; }, - onVerticalDragUpdate: (double scrollDelta) { - updatedDragDelta = scrollDelta; + onPanUpdate: (Offset delta) { + panDelta = delta; }, - onVerticalDragEnd: (Velocity velocity) { - didEndDrag = true; + onPanEnd: (_) { + didEndPan = true; }, child: new Container( decoration: const BoxDecoration( backgroundColor: const Color(0xFF00FF00) ) ) - ); + ) + ); - tester.pumpWidget(widget); - expect(didStartDrag, isFalse); - expect(updatedDragDelta, isNull); - expect(didEndDrag, isFalse); + expect(didStartPan, isFalse); + expect(panDelta, isNull); + expect(didEndPan, isFalse); - Point firstLocation = new Point(10.0, 10.0); - TestGesture gesture = tester.startGesture(firstLocation, pointer: 7); - expect(didStartDrag, isTrue); - didStartDrag = false; - expect(updatedDragDelta, isNull); - expect(didEndDrag, isFalse); + tester.scrollAt(new Point(10.0, 10.0), new Offset(20.0, 30.0)); - Point secondLocation = new Point(10.0, 9.0); - gesture.moveTo(secondLocation); - expect(didStartDrag, isFalse); - expect(updatedDragDelta, -1.0); - updatedDragDelta = null; - expect(didEndDrag, isFalse); - - gesture.up(); - expect(didStartDrag, isFalse); - expect(updatedDragDelta, isNull); - expect(didEndDrag, isTrue); - didEndDrag = false; - - tester.pumpWidget(new Container()); - }); + expect(didStartPan, isTrue); + expect(panDelta.dx, 20.0); + expect(panDelta.dy, 30.0); + expect(didEndPan, isTrue); }); - test('Match two scroll gestures in succession', () { - testWidgets((WidgetTester tester) { - int gestureCount = 0; - double dragDistance = 0.0; - - Point downLocation = new Point(10.0, 10.0); - Point upLocation = new Point(10.0, 20.0); - - Widget widget = new GestureDetector( - onVerticalDragUpdate: (double delta) { dragDistance += delta; }, - onVerticalDragEnd: (Velocity velocity) { gestureCount += 1; }, - onHorizontalDragUpdate: (_) { fail("gesture should not match"); }, - onHorizontalDragEnd: (Velocity velocity) { fail("gesture should not match"); }, - child: new Container( - decoration: const BoxDecoration( - backgroundColor: const Color(0xFF00FF00) - ) - ) - ); - tester.pumpWidget(widget); - - TestGesture gesture = tester.startGesture(downLocation, pointer: 7); - gesture.moveTo(upLocation); - gesture.up(); - - gesture = tester.startGesture(downLocation, pointer: 7); - gesture.moveTo(upLocation); - gesture.up(); - - expect(gestureCount, 2); - expect(dragDistance, 20.0); - - tester.pumpWidget(new Container()); - }); - }); - - test('Pan doesn\'t crash', () { - testWidgets((WidgetTester tester) { - bool didStartPan = false; - Offset panDelta; - bool didEndPan = false; + testWidgets('Translucent', (WidgetTester tester) { + bool didReceivePointerDown; + bool didTap; + void pumpWidgetTree(HitTestBehavior behavior) { tester.pumpWidget( - new GestureDetector( - onPanStart: (_) { - didStartPan = true; - }, - onPanUpdate: (Offset delta) { - panDelta = delta; - }, - onPanEnd: (_) { - didEndPan = true; - }, - child: new Container( - decoration: const BoxDecoration( - backgroundColor: const Color(0xFF00FF00) - ) - ) - ) - ); - - expect(didStartPan, isFalse); - expect(panDelta, isNull); - expect(didEndPan, isFalse); - - tester.scrollAt(new Point(10.0, 10.0), new Offset(20.0, 30.0)); - - expect(didStartPan, isTrue); - expect(panDelta.dx, 20.0); - expect(panDelta.dy, 30.0); - expect(didEndPan, isTrue); - }); - }); - - test('Translucent', () { - testWidgets((WidgetTester tester) { - bool didReceivePointerDown; - bool didTap; - - void pumpWidgetTree(HitTestBehavior behavior) { - tester.pumpWidget( - new Stack( - children: [ - new Listener( - onPointerDown: (_) { - didReceivePointerDown = true; - }, - child: new Container( - width: 100.0, - height: 100.0, - decoration: const BoxDecoration( - backgroundColor: const Color(0xFF00FF00) - ) - ) - ), - new Container( + new Stack( + children: [ + new Listener( + onPointerDown: (_) { + didReceivePointerDown = true; + }, + child: new Container( width: 100.0, height: 100.0, - child: new GestureDetector( - onTap: () { - didTap = true; - }, - behavior: behavior + decoration: const BoxDecoration( + backgroundColor: const Color(0xFF00FF00) ) ) - ] - ) - ); - } + ), + new Container( + width: 100.0, + height: 100.0, + child: new GestureDetector( + onTap: () { + didTap = true; + }, + behavior: behavior + ) + ) + ] + ) + ); + } - didReceivePointerDown = false; - didTap = false; - pumpWidgetTree(null); - tester.tapAt(new Point(10.0, 10.0)); - expect(didReceivePointerDown, isTrue); - expect(didTap, isTrue); + didReceivePointerDown = false; + didTap = false; + pumpWidgetTree(null); + tester.tapAt(new Point(10.0, 10.0)); + expect(didReceivePointerDown, isTrue); + expect(didTap, isTrue); - didReceivePointerDown = false; - didTap = false; - pumpWidgetTree(HitTestBehavior.deferToChild); - tester.tapAt(new Point(10.0, 10.0)); - expect(didReceivePointerDown, isTrue); - expect(didTap, isFalse); + didReceivePointerDown = false; + didTap = false; + pumpWidgetTree(HitTestBehavior.deferToChild); + tester.tapAt(new Point(10.0, 10.0)); + expect(didReceivePointerDown, isTrue); + expect(didTap, isFalse); - didReceivePointerDown = false; - didTap = false; - pumpWidgetTree(HitTestBehavior.opaque); - tester.tapAt(new Point(10.0, 10.0)); - expect(didReceivePointerDown, isFalse); - expect(didTap, isTrue); + didReceivePointerDown = false; + didTap = false; + pumpWidgetTree(HitTestBehavior.opaque); + tester.tapAt(new Point(10.0, 10.0)); + expect(didReceivePointerDown, isFalse); + expect(didTap, isTrue); - didReceivePointerDown = false; - didTap = false; - pumpWidgetTree(HitTestBehavior.translucent); - tester.tapAt(new Point(10.0, 10.0)); - expect(didReceivePointerDown, isTrue); - expect(didTap, isTrue); + didReceivePointerDown = false; + didTap = false; + pumpWidgetTree(HitTestBehavior.translucent); + tester.tapAt(new Point(10.0, 10.0)); + expect(didReceivePointerDown, isTrue); + expect(didTap, isTrue); - }); }); } diff --git a/packages/flutter/test/widget/heroes_test.dart b/packages/flutter/test/widget/heroes_test.dart index e99390d90d..650104ec57 100644 --- a/packages/flutter/test/widget/heroes_test.dart +++ b/packages/flutter/test/widget/heroes_test.dart @@ -6,8 +6,6 @@ import 'package:flutter_test/flutter_test.dart'; import 'package:flutter/material.dart'; import 'package:test/test.dart'; -import 'test_matchers.dart'; - Key firstKey = new Key('first'); Key secondKey = new Key('second'); Key thirdKey = new Key('third'); @@ -44,108 +42,106 @@ class ThreeRoute extends MaterialPageRoute { } void main() { - test('Heroes animate', () { - testWidgets((WidgetTester tester) { + testWidgets('Heroes animate', (WidgetTester tester) { - tester.pumpWidget(new MaterialApp(routes: routes)); + tester.pumpWidget(new MaterialApp(routes: routes)); - // the initial setup. + // the initial setup. - expect(find.byKey(firstKey), isOnStage(tester)); - expect(find.byKey(firstKey), isInCard(tester)); - expect(tester, doesNotHaveWidget(find.byKey(secondKey))); + expect(find.byKey(firstKey), isOnStage); + expect(find.byKey(firstKey), isInCard); + expect(find.byKey(secondKey), findsNothing); - tester.tap(find.text('two')); - tester.pump(); // begin navigation + tester.tap(find.text('two')); + tester.pump(); // begin navigation - // at this stage, the second route is off-stage, so that we can form the - // hero party. + // at this stage, the second route is off-stage, so that we can form the + // hero party. - expect(find.byKey(firstKey), isOnStage(tester)); - expect(find.byKey(firstKey), isInCard(tester)); - expect(find.byKey(secondKey), isOffStage(tester)); - expect(find.byKey(secondKey), isInCard(tester)); + expect(find.byKey(firstKey), isOnStage); + expect(find.byKey(firstKey), isInCard); + expect(find.byKey(secondKey), isOffStage); + expect(find.byKey(secondKey), isInCard); - tester.pump(); + tester.pump(); - // at this stage, the heroes have just gone on their journey, we are - // seeing them at t=16ms. The original page no longer contains the hero. + // at this stage, the heroes have just gone on their journey, we are + // seeing them at t=16ms. The original page no longer contains the hero. - expect(tester, doesNotHaveWidget(find.byKey(firstKey))); - expect(find.byKey(secondKey), isOnStage(tester)); - expect(find.byKey(secondKey), isNotInCard(tester)); + expect(find.byKey(firstKey), findsNothing); + expect(find.byKey(secondKey), isOnStage); + expect(find.byKey(secondKey), isNotInCard); - tester.pump(); + tester.pump(); - // t=32ms for the journey. Surely they are still at it. + // t=32ms for the journey. Surely they are still at it. - expect(tester, doesNotHaveWidget(find.byKey(firstKey))); - expect(find.byKey(secondKey), isOnStage(tester)); - expect(find.byKey(secondKey), isNotInCard(tester)); + expect(find.byKey(firstKey), findsNothing); + expect(find.byKey(secondKey), isOnStage); + expect(find.byKey(secondKey), isNotInCard); - tester.pump(new Duration(seconds: 1)); + tester.pump(new Duration(seconds: 1)); - // t=1.032s for the journey. The journey has ended (it ends this frame, in - // fact). The hero should now be in the new page, on-stage. + // t=1.032s for the journey. The journey has ended (it ends this frame, in + // fact). The hero should now be in the new page, on-stage. - expect(tester, doesNotHaveWidget(find.byKey(firstKey))); - expect(find.byKey(secondKey), isOnStage(tester)); - expect(find.byKey(secondKey), isInCard(tester)); + expect(find.byKey(firstKey), findsNothing); + expect(find.byKey(secondKey), isOnStage); + expect(find.byKey(secondKey), isInCard); - tester.pump(); + tester.pump(); - // Should not change anything. + // Should not change anything. - expect(tester, doesNotHaveWidget(find.byKey(firstKey))); - expect(find.byKey(secondKey), isOnStage(tester)); - expect(find.byKey(secondKey), isInCard(tester)); + expect(find.byKey(firstKey), findsNothing); + expect(find.byKey(secondKey), isOnStage); + expect(find.byKey(secondKey), isInCard); - // Now move on to view 3 + // Now move on to view 3 - tester.tap(find.text('three')); - tester.pump(); // begin navigation + tester.tap(find.text('three')); + tester.pump(); // begin navigation - // at this stage, the second route is off-stage, so that we can form the - // hero party. + // at this stage, the second route is off-stage, so that we can form the + // hero party. - expect(find.byKey(secondKey), isOnStage(tester)); - expect(find.byKey(secondKey), isInCard(tester)); - expect(find.byKey(thirdKey), isOffStage(tester)); - expect(find.byKey(thirdKey), isInCard(tester)); + expect(find.byKey(secondKey), isOnStage); + expect(find.byKey(secondKey), isInCard); + expect(find.byKey(thirdKey), isOffStage); + expect(find.byKey(thirdKey), isInCard); - tester.pump(); + tester.pump(); - // at this stage, the heroes have just gone on their journey, we are - // seeing them at t=16ms. The original page no longer contains the hero. + // at this stage, the heroes have just gone on their journey, we are + // seeing them at t=16ms. The original page no longer contains the hero. - expect(tester, doesNotHaveWidget(find.byKey(secondKey))); - expect(find.byKey(thirdKey), isOnStage(tester)); - expect(find.byKey(thirdKey), isNotInCard(tester)); + expect(find.byKey(secondKey), findsNothing); + expect(find.byKey(thirdKey), isOnStage); + expect(find.byKey(thirdKey), isNotInCard); - tester.pump(); + tester.pump(); - // t=32ms for the journey. Surely they are still at it. + // t=32ms for the journey. Surely they are still at it. - expect(tester, doesNotHaveWidget(find.byKey(secondKey))); - expect(find.byKey(thirdKey), isOnStage(tester)); - expect(find.byKey(thirdKey), isNotInCard(tester)); + expect(find.byKey(secondKey), findsNothing); + expect(find.byKey(thirdKey), isOnStage); + expect(find.byKey(thirdKey), isNotInCard); - tester.pump(new Duration(seconds: 1)); + tester.pump(new Duration(seconds: 1)); - // t=1.032s for the journey. The journey has ended (it ends this frame, in - // fact). The hero should now be in the new page, on-stage. + // t=1.032s for the journey. The journey has ended (it ends this frame, in + // fact). The hero should now be in the new page, on-stage. - expect(tester, doesNotHaveWidget(find.byKey(secondKey))); - expect(find.byKey(thirdKey), isOnStage(tester)); - expect(find.byKey(thirdKey), isInCard(tester)); + expect(find.byKey(secondKey), findsNothing); + expect(find.byKey(thirdKey), isOnStage); + expect(find.byKey(thirdKey), isInCard); - tester.pump(); + tester.pump(); - // Should not change anything. + // Should not change anything. - expect(tester, doesNotHaveWidget(find.byKey(secondKey))); - expect(find.byKey(thirdKey), isOnStage(tester)); - expect(find.byKey(thirdKey), isInCard(tester)); - }); + expect(find.byKey(secondKey), findsNothing); + expect(find.byKey(thirdKey), isOnStage); + expect(find.byKey(thirdKey), isInCard); }); } diff --git a/packages/flutter/test/widget/hyperlink_test.dart b/packages/flutter/test/widget/hyperlink_test.dart index dd978588a2..a2739cd1d5 100644 --- a/packages/flutter/test/widget/hyperlink_test.dart +++ b/packages/flutter/test/widget/hyperlink_test.dart @@ -8,66 +8,64 @@ import 'package:flutter/widgets.dart'; import 'package:test/test.dart'; void main() { - test('Can tap a hyperlink', () { - testWidgets((WidgetTester tester) { - bool didTapLeft = false; - TapGestureRecognizer tapLeft = new TapGestureRecognizer() - ..onTap = () { - didTapLeft = true; - }; + testWidgets('Can tap a hyperlink', (WidgetTester tester) { + bool didTapLeft = false; + TapGestureRecognizer tapLeft = new TapGestureRecognizer() + ..onTap = () { + didTapLeft = true; + }; - bool didTapRight = false; - TapGestureRecognizer tapRight = new TapGestureRecognizer() - ..onTap = () { - didTapRight = true; - }; + bool didTapRight = false; + TapGestureRecognizer tapRight = new TapGestureRecognizer() + ..onTap = () { + didTapRight = true; + }; - Key textKey = new Key('text'); + Key textKey = new Key('text'); - tester.pumpWidget( - new Center( - child: new RichText( - key: textKey, - text: new TextSpan( - children: [ - new TextSpan( - text: 'xxxxxxxx', - recognizer: tapLeft - ), - new TextSpan(text: 'yyyyyyyy'), - new TextSpan( - text: 'zzzzzzzzz', - recognizer: tapRight - ), - ] - ) + tester.pumpWidget( + new Center( + child: new RichText( + key: textKey, + text: new TextSpan( + children: [ + new TextSpan( + text: 'xxxxxxxx', + recognizer: tapLeft + ), + new TextSpan(text: 'yyyyyyyy'), + new TextSpan( + text: 'zzzzzzzzz', + recognizer: tapRight + ), + ] ) ) - ); + ) + ); - RenderBox box = tester.renderObjectOf(find.byKey(textKey)); + RenderBox box = tester.renderObject(find.byKey(textKey)); - expect(didTapLeft, isFalse); - expect(didTapRight, isFalse); + expect(didTapLeft, isFalse); + expect(didTapRight, isFalse); - tester.tapAt(box.localToGlobal(Point.origin) + new Offset(2.0, 2.0)); + tester.tapAt(box.localToGlobal(Point.origin) + new Offset(2.0, 2.0)); - expect(didTapLeft, isTrue); - expect(didTapRight, isFalse); + expect(didTapLeft, isTrue); + expect(didTapRight, isFalse); - didTapLeft = false; + didTapLeft = false; - tester.tapAt(box.localToGlobal(Point.origin) + new Offset(30.0, 2.0)); + tester.tapAt(box.localToGlobal(Point.origin) + new Offset(30.0, 2.0)); - expect(didTapLeft, isTrue); - expect(didTapRight, isFalse); + expect(didTapLeft, isTrue); + expect(didTapRight, isFalse); - didTapLeft = false; + didTapLeft = false; - tester.tapAt(box.localToGlobal(new Point(box.size.width, 0.0)) + new Offset(-2.0, 2.0)); + tester.tapAt(box.localToGlobal(new Point(box.size.width, 0.0)) + new Offset(-2.0, 2.0)); - expect(didTapLeft, isFalse); - expect(didTapRight, isTrue); - }); + expect(didTapLeft, isFalse); + expect(didTapRight, isTrue); }); } diff --git a/packages/flutter/test/widget/icon_test.dart b/packages/flutter/test/widget/icon_test.dart index 3f4ff20f25..2806b52c37 100644 --- a/packages/flutter/test/widget/icon_test.dart +++ b/packages/flutter/test/widget/icon_test.dart @@ -7,19 +7,17 @@ import 'package:flutter/material.dart'; import 'package:test/test.dart'; void main() { - test('Can set opacity for an Icon', () { - testWidgets((WidgetTester tester) { - tester.pumpWidget( - new IconTheme( - data: new IconThemeData( - color: Colors.green[500], - opacity: 0.5 - ), - child: new Icon(icon: Icons.add) - ) - ); - Text text = tester.widget(find.byType(Text)); - expect(text.style.color, equals(Colors.green[500].withOpacity(0.5))); - }); + testWidgets('Can set opacity for an Icon', (WidgetTester tester) { + tester.pumpWidget( + new IconTheme( + data: new IconThemeData( + color: Colors.green[500], + opacity: 0.5 + ), + child: new Icon(icon: Icons.add) + ) + ); + Text text = tester.widget(find.byType(Text)); + expect(text.style.color, equals(Colors.green[500].withOpacity(0.5))); }); } diff --git a/packages/flutter/test/widget/image_test.dart b/packages/flutter/test/widget/image_test.dart index b774a89dd0..0bba17cf1c 100644 --- a/packages/flutter/test/widget/image_test.dart +++ b/packages/flutter/test/widget/image_test.dart @@ -13,172 +13,156 @@ import 'package:flutter/widgets.dart'; import 'package:test/test.dart'; void main() { - test('Verify NetworkImage sets an ObjectKey on its ImageResource if it doesn\'t have a key', () { - testWidgets((WidgetTester tester) { - final String testUrl = 'https://foo.bar/baz1.png'; - tester.pumpWidget( - new NetworkImage( - scale: 1.0, - src: testUrl + testWidgets('Verify NetworkImage sets an ObjectKey on its ImageResource if it doesn\'t have a key', (WidgetTester tester) { + final String testUrl = 'https://foo.bar/baz1.png'; + tester.pumpWidget( + new NetworkImage( + scale: 1.0, + src: testUrl + ) + ); + + ImageResource imageResource = imageCache.load(testUrl, scale: 1.0); + expect(find.byKey(new ObjectKey(imageResource)), findsOneWidget); + }); + + testWidgets('Verify NetworkImage doesn\'t set an ObjectKey on its ImageResource if it has a key', (WidgetTester tester) { + final String testUrl = 'https://foo.bar/baz2.png'; + tester.pumpWidget( + new NetworkImage( + key: new GlobalKey(), + scale: 1.0, + src: testUrl + ) + ); + + ImageResource imageResource = imageCache.load(testUrl, scale: 1.0); + expect(find.byKey(new ObjectKey(imageResource)), findsNothing); + }); + + testWidgets('Verify AsyncImage sets an ObjectKey on its ImageResource if it doesn\'t have a key', (WidgetTester tester) { + ImageProvider imageProvider = new TestImageProvider(); + tester.pumpWidget(new AsyncImage(provider: imageProvider)); + + ImageResource imageResource = imageCache.loadProvider(imageProvider); + expect(find.byKey(new ObjectKey(imageResource)), findsOneWidget); + }); + + testWidgets('Verify AsyncImage doesn\'t set an ObjectKey on its ImageResource if it has a key', (WidgetTester tester) { + ImageProvider imageProvider = new TestImageProvider(); + tester.pumpWidget( + new AsyncImage( + key: new GlobalKey(), + provider: imageProvider + ) + ); + + ImageResource imageResource = imageCache.loadProvider(imageProvider); + expect(find.byKey(new ObjectKey(imageResource)), findsNothing); + }); + + testWidgets('Verify AssetImage sets an ObjectKey on its ImageResource if it doesn\'t have a key', (WidgetTester tester) { + final String name = 'foo'; + final AssetBundle assetBundle = new TestAssetBundle(); + tester.pumpWidget( + new AssetImage( + name: name, + bundle: assetBundle + ) + ); + + ImageResource imageResource = assetBundle.loadImage(name); + expect(find.byKey(new ObjectKey(imageResource)), findsOneWidget); + }); + + testWidgets('Verify AssetImage doesn\'t set an ObjectKey on its ImageResource if it has a key', (WidgetTester tester) { + final String name = 'foo'; + final AssetBundle assetBundle = new TestAssetBundle(); + tester.pumpWidget( + new AssetImage( + key: new GlobalKey(), + name: name, + bundle: assetBundle + ) + ); + + ImageResource imageResource = assetBundle.loadImage(name); + expect(find.byKey(new ObjectKey(imageResource)), findsNothing); + }); + + testWidgets('Verify AsyncImage resets its RenderImage when changing providers if it doesn\'t have a key', (WidgetTester tester) { + final GlobalKey key = new GlobalKey(); + TestImageProvider imageProvider1 = new TestImageProvider(); + tester.pumpWidget( + new Container( + key: key, + child: new AsyncImage( + provider: imageProvider1 ) - ); + ), + null, + EnginePhase.layout + ); + RenderImage renderImage = key.currentContext.findRenderObject(); + expect(renderImage.image, isNull); - ImageResource imageResource = imageCache.load(testUrl, scale: 1.0); - expect(tester, hasWidget(find.byKey(new ObjectKey(imageResource)))); - }); - }); + imageProvider1.complete(); + tester.flushMicrotasks(); // resolve the future from the image provider + tester.pump(null, EnginePhase.layout); - test('Verify NetworkImage doesn\'t set an ObjectKey on its ImageResource if it has a key', () { - testWidgets((WidgetTester tester) { - final String testUrl = 'https://foo.bar/baz2.png'; - tester.pumpWidget( - new NetworkImage( - key: new GlobalKey(), - scale: 1.0, - src: testUrl - ) - ); + renderImage = key.currentContext.findRenderObject(); + expect(renderImage.image, isNotNull); - ImageResource imageResource = imageCache.load(testUrl, scale: 1.0); - expect(tester, doesNotHaveWidget(find.byKey(new ObjectKey(imageResource)))); - }); - }); - - test('Verify AsyncImage sets an ObjectKey on its ImageResource if it doesn\'t have a key', () { - testWidgets((WidgetTester tester) { - ImageProvider imageProvider = new TestImageProvider(); - tester.pumpWidget(new AsyncImage(provider: imageProvider)); - - ImageResource imageResource = imageCache.loadProvider(imageProvider); - expect(tester, hasWidget(find.byKey(new ObjectKey(imageResource)))); - }); - }); - - test('Verify AsyncImage doesn\'t set an ObjectKey on its ImageResource if it has a key', () { - testWidgets((WidgetTester tester) { - ImageProvider imageProvider = new TestImageProvider(); - tester.pumpWidget( - new AsyncImage( - key: new GlobalKey(), - provider: imageProvider - ) - ); - - ImageResource imageResource = imageCache.loadProvider(imageProvider); - expect(tester, doesNotHaveWidget(find.byKey(new ObjectKey(imageResource)))); - }); - }); - - test('Verify AssetImage sets an ObjectKey on its ImageResource if it doesn\'t have a key', () { - testWidgets((WidgetTester tester) { - final String name = 'foo'; - final AssetBundle assetBundle = new TestAssetBundle(); - tester.pumpWidget( - new AssetImage( - name: name, - bundle: assetBundle - ) - ); - - ImageResource imageResource = assetBundle.loadImage(name); - expect(tester, hasWidget(find.byKey(new ObjectKey(imageResource)))); - }); - }); - - test('Verify AssetImage doesn\'t set an ObjectKey on its ImageResource if it has a key', () { - testWidgets((WidgetTester tester) { - final String name = 'foo'; - final AssetBundle assetBundle = new TestAssetBundle(); - tester.pumpWidget( - new AssetImage( - key: new GlobalKey(), - name: name, - bundle: assetBundle - ) - ); - - ImageResource imageResource = assetBundle.loadImage(name); - expect(tester, doesNotHaveWidget(find.byKey(new ObjectKey(imageResource)))); - }); - }); - - test('Verify AsyncImage resets its RenderImage when changing providers if it doesn\'t have a key', () { - testWidgets((WidgetTester tester) { - final GlobalKey key = new GlobalKey(); - TestImageProvider imageProvider1 = new TestImageProvider(); - tester.pumpWidget( - new Container( - key: key, - child: new AsyncImage( - provider: imageProvider1 - ) - ), - null, - EnginePhase.layout - ); - RenderImage renderImage = key.currentContext.findRenderObject(); - expect(renderImage.image, isNull); - - imageProvider1.complete(); - tester.flushMicrotasks(); // resolve the future from the image provider - tester.pump(null, EnginePhase.layout); - - renderImage = key.currentContext.findRenderObject(); - expect(renderImage.image, isNotNull); - - TestImageProvider imageProvider2 = new TestImageProvider(); - tester.pumpWidget( - new Container( - key: key, - child: new AsyncImage( - provider: imageProvider2 - ) - ), - null, - EnginePhase.layout - ); - - renderImage = key.currentContext.findRenderObject(); - expect(renderImage.image, isNull); - - }); - }); - - test('Verify AsyncImage doesn\'t reset its RenderImage when changing providers if it has a key', () { - testWidgets((WidgetTester tester) { - final GlobalKey key = new GlobalKey(); - TestImageProvider imageProvider1 = new TestImageProvider(); - tester.pumpWidget( - new AsyncImage( - key: key, - provider: imageProvider1 - ), - null, - EnginePhase.layout - ); - RenderImage renderImage = key.currentContext.findRenderObject(); - expect(renderImage.image, isNull); - - imageProvider1.complete(); - tester.flushMicrotasks(); // resolve the future from the image provider - tester.pump(null, EnginePhase.layout); - - renderImage = key.currentContext.findRenderObject(); - expect(renderImage.image, isNotNull); - - TestImageProvider imageProvider2 = new TestImageProvider(); - tester.pumpWidget( - new AsyncImage( - key: key, + TestImageProvider imageProvider2 = new TestImageProvider(); + tester.pumpWidget( + new Container( + key: key, + child: new AsyncImage( provider: imageProvider2 - ), - null, - EnginePhase.layout - ); + ) + ), + null, + EnginePhase.layout + ); - renderImage = key.currentContext.findRenderObject(); - expect(renderImage.image, isNotNull); - }); + renderImage = key.currentContext.findRenderObject(); + expect(renderImage.image, isNull); + + }); + + testWidgets('Verify AsyncImage doesn\'t reset its RenderImage when changing providers if it has a key', (WidgetTester tester) { + final GlobalKey key = new GlobalKey(); + TestImageProvider imageProvider1 = new TestImageProvider(); + tester.pumpWidget( + new AsyncImage( + key: key, + provider: imageProvider1 + ), + null, + EnginePhase.layout + ); + RenderImage renderImage = key.currentContext.findRenderObject(); + expect(renderImage.image, isNull); + + imageProvider1.complete(); + tester.flushMicrotasks(); // resolve the future from the image provider + tester.pump(null, EnginePhase.layout); + + renderImage = key.currentContext.findRenderObject(); + expect(renderImage.image, isNotNull); + + TestImageProvider imageProvider2 = new TestImageProvider(); + tester.pumpWidget( + new AsyncImage( + key: key, + provider: imageProvider2 + ), + null, + EnginePhase.layout + ); + + renderImage = key.currentContext.findRenderObject(); + expect(renderImage.image, isNotNull); }); } diff --git a/packages/flutter/test/widget/independent_widget_layout_test.dart b/packages/flutter/test/widget/independent_widget_layout_test.dart index 3702cdb879..258dca5443 100644 --- a/packages/flutter/test/widget/independent_widget_layout_test.dart +++ b/packages/flutter/test/widget/independent_widget_layout_test.dart @@ -109,55 +109,53 @@ class TriggerableState extends State { } void main() { - test('no crosstalk between widget build owners', () { - testWidgets((WidgetTester tester) { - Trigger trigger1 = new Trigger(); - Counter counter1 = new Counter(); - Trigger trigger2 = new Trigger(); - Counter counter2 = new Counter(); - OffscreenWidgetTree tree = new OffscreenWidgetTree(); - // Both counts should start at zero - expect(counter1.count, equals(0)); - expect(counter2.count, equals(0)); - // Lay out the "onscreen" in the default test binding - tester.pumpWidget(new TriggerableWidget(trigger: trigger1, counter: counter1)); - // Only the "onscreen" widget should have built - expect(counter1.count, equals(1)); - expect(counter2.count, equals(0)); - // Lay out the "offscreen" in a separate tree - tree.pumpWidget(new TriggerableWidget(trigger: trigger2, counter: counter2)); - // Now both widgets should have built - expect(counter1.count, equals(1)); - expect(counter2.count, equals(1)); - // Mark both as needing layout - trigger1.fire(); - trigger2.fire(); - // Marking as needing layout shouldn't immediately build anything - expect(counter1.count, equals(1)); - expect(counter2.count, equals(1)); - // Pump the "onscreen" layout - tester.pump(); - // Only the "onscreen" widget should have rebuilt - expect(counter1.count, equals(2)); - expect(counter2.count, equals(1)); - // Pump the "offscreen" layout - tree.pumpFrame(); - // Now both widgets should have rebuilt - expect(counter1.count, equals(2)); - expect(counter2.count, equals(2)); - // Mark both as needing layout, again - trigger1.fire(); - trigger2.fire(); - // Now pump the "offscreen" layout first - tree.pumpFrame(); - // Only the "offscreen" widget should have rebuilt - expect(counter1.count, equals(2)); - expect(counter2.count, equals(3)); - // Pump the "onscreen" layout - tester.pump(); - // Now both widgets should have rebuilt - expect(counter1.count, equals(3)); - expect(counter2.count, equals(3)); - }); + testWidgets('no crosstalk between widget build owners', (WidgetTester tester) { + Trigger trigger1 = new Trigger(); + Counter counter1 = new Counter(); + Trigger trigger2 = new Trigger(); + Counter counter2 = new Counter(); + OffscreenWidgetTree tree = new OffscreenWidgetTree(); + // Both counts should start at zero + expect(counter1.count, equals(0)); + expect(counter2.count, equals(0)); + // Lay out the "onscreen" in the default test binding + tester.pumpWidget(new TriggerableWidget(trigger: trigger1, counter: counter1)); + // Only the "onscreen" widget should have built + expect(counter1.count, equals(1)); + expect(counter2.count, equals(0)); + // Lay out the "offscreen" in a separate tree + tree.pumpWidget(new TriggerableWidget(trigger: trigger2, counter: counter2)); + // Now both widgets should have built + expect(counter1.count, equals(1)); + expect(counter2.count, equals(1)); + // Mark both as needing layout + trigger1.fire(); + trigger2.fire(); + // Marking as needing layout shouldn't immediately build anything + expect(counter1.count, equals(1)); + expect(counter2.count, equals(1)); + // Pump the "onscreen" layout + tester.pump(); + // Only the "onscreen" widget should have rebuilt + expect(counter1.count, equals(2)); + expect(counter2.count, equals(1)); + // Pump the "offscreen" layout + tree.pumpFrame(); + // Now both widgets should have rebuilt + expect(counter1.count, equals(2)); + expect(counter2.count, equals(2)); + // Mark both as needing layout, again + trigger1.fire(); + trigger2.fire(); + // Now pump the "offscreen" layout first + tree.pumpFrame(); + // Only the "offscreen" widget should have rebuilt + expect(counter1.count, equals(2)); + expect(counter2.count, equals(3)); + // Pump the "onscreen" layout + tester.pump(); + // Now both widgets should have rebuilt + expect(counter1.count, equals(3)); + expect(counter2.count, equals(3)); }); } diff --git a/packages/flutter/test/widget/inherited_test.dart b/packages/flutter/test/widget/inherited_test.dart index ac6292e07d..709d09e61f 100644 --- a/packages/flutter/test/widget/inherited_test.dart +++ b/packages/flutter/test/widget/inherited_test.dart @@ -19,63 +19,59 @@ class TestInherited extends InheritedWidget { } void main() { - test('Inherited notifies dependents', () { - testWidgets((WidgetTester tester) { - List log = []; + testWidgets('Inherited notifies dependents', (WidgetTester tester) { + List log = []; - Builder builder = new Builder( - builder: (BuildContext context) { - log.add(context.inheritFromWidgetOfExactType(TestInherited)); - return new Container(); - } - ); + Builder builder = new Builder( + builder: (BuildContext context) { + log.add(context.inheritFromWidgetOfExactType(TestInherited)); + return new Container(); + } + ); - TestInherited first = new TestInherited(child: builder); - tester.pumpWidget(first); + TestInherited first = new TestInherited(child: builder); + tester.pumpWidget(first); - expect(log, equals([first])); + expect(log, equals([first])); - TestInherited second = new TestInherited(child: builder, shouldNotify: false); - tester.pumpWidget(second); + TestInherited second = new TestInherited(child: builder, shouldNotify: false); + tester.pumpWidget(second); - expect(log, equals([first])); + expect(log, equals([first])); - TestInherited third = new TestInherited(child: builder, shouldNotify: true); - tester.pumpWidget(third); + TestInherited third = new TestInherited(child: builder, shouldNotify: true); + tester.pumpWidget(third); - expect(log, equals([first, third])); - }); + expect(log, equals([first, third])); }); - test('Update inherited when reparenting state', () { - testWidgets((WidgetTester tester) { - GlobalKey globalKey = new GlobalKey(); - List log = []; + testWidgets('Update inherited when reparenting state', (WidgetTester tester) { + GlobalKey globalKey = new GlobalKey(); + List log = []; - TestInherited build() { - return new TestInherited( - key: new UniqueKey(), - child: new Container( - key: globalKey, - child: new Builder( - builder: (BuildContext context) { - log.add(context.inheritFromWidgetOfExactType(TestInherited)); - return new Container(); - } - ) + TestInherited build() { + return new TestInherited( + key: new UniqueKey(), + child: new Container( + key: globalKey, + child: new Builder( + builder: (BuildContext context) { + log.add(context.inheritFromWidgetOfExactType(TestInherited)); + return new Container(); + } ) - ); - } + ) + ); + } - TestInherited first = build(); - tester.pumpWidget(first); + TestInherited first = build(); + tester.pumpWidget(first); - expect(log, equals([first])); + expect(log, equals([first])); - TestInherited second = build(); - tester.pumpWidget(second); + TestInherited second = build(); + tester.pumpWidget(second); - expect(log, equals([first, second])); - }); + expect(log, equals([first, second])); }); } diff --git a/packages/flutter/test/widget/init_state_test.dart b/packages/flutter/test/widget/init_state_test.dart index e0cd698c8c..6d05506c28 100644 --- a/packages/flutter/test/widget/init_state_test.dart +++ b/packages/flutter/test/widget/init_state_test.dart @@ -28,10 +28,8 @@ class TestWidgetState extends State { } void main() { - test('initState() is called when we are in the tree', () { - testWidgets((WidgetTester tester) { - tester.pumpWidget(new Container(child: new TestWidget())); - expect(ancestors, equals(['Container', 'RenderObjectToWidgetAdapter'])); - }); + testWidgets('initState() is called when we are in the tree', (WidgetTester tester) { + tester.pumpWidget(new Container(child: new TestWidget())); + expect(ancestors, equals(['Container', 'RenderObjectToWidgetAdapter'])); }); } diff --git a/packages/flutter/test/widget/input_test.dart b/packages/flutter/test/widget/input_test.dart index 3029566a25..4c4477a890 100644 --- a/packages/flutter/test/widget/input_test.dart +++ b/packages/flutter/test/widget/input_test.dart @@ -27,7 +27,6 @@ class MockKeyboard implements mojom.Keyboard { } void main() { - WidgetsFlutterBinding.ensureInitialized(); // for serviceMocker MockKeyboard mockKeyboard = new MockKeyboard(); serviceMocker.registerMockService(mojom.Keyboard.serviceName, mockKeyboard); @@ -40,126 +39,120 @@ void main() { ..composingExtent = testValue.length); } - test('Editable text has consistent size', () { - testWidgets((WidgetTester tester) { - GlobalKey inputKey = new GlobalKey(); - InputValue inputValue = InputValue.empty; + testWidgets('Editable text has consistent size', (WidgetTester tester) { + GlobalKey inputKey = new GlobalKey(); + InputValue inputValue = InputValue.empty; - Widget builder() { - return new Center( - child: new Material( - child: new Input( - value: inputValue, - key: inputKey, - hintText: 'Placeholder', - onChanged: (InputValue value) { inputValue = value; } - ) + Widget builder() { + return new Center( + child: new Material( + child: new Input( + value: inputValue, + key: inputKey, + hintText: 'Placeholder', + onChanged: (InputValue value) { inputValue = value; } ) - ); - } + ) + ); + } + + tester.pumpWidget(builder()); + + RenderBox findInputBox() => tester.renderObject(find.byKey(inputKey)); + + RenderBox inputBox = findInputBox(); + Size emptyInputSize = inputBox.size; + + void checkText(String testValue) { + enterText(testValue); + + // Check that the onChanged event handler fired. + expect(inputValue.text, equals(testValue)); tester.pumpWidget(builder()); + } - RenderBox findInputBox() => tester.renderObjectOf(find.byKey(inputKey)); + checkText(' '); + expect(findInputBox(), equals(inputBox)); + expect(inputBox.size, equals(emptyInputSize)); - RenderBox inputBox = findInputBox(); - Size emptyInputSize = inputBox.size; - - void checkText(String testValue) { - enterText(testValue); - - // Check that the onChanged event handler fired. - expect(inputValue.text, equals(testValue)); - - tester.pumpWidget(builder()); - } - - checkText(' '); - expect(findInputBox(), equals(inputBox)); - expect(inputBox.size, equals(emptyInputSize)); - - checkText('Test'); - expect(findInputBox(), equals(inputBox)); - expect(inputBox.size, equals(emptyInputSize)); - }); + checkText('Test'); + expect(findInputBox(), equals(inputBox)); + expect(inputBox.size, equals(emptyInputSize)); }); - test('Cursor blinks', () { - testWidgets((WidgetTester tester) { - GlobalKey inputKey = new GlobalKey(); + testWidgets('Cursor blinks', (WidgetTester tester) { + GlobalKey inputKey = new GlobalKey(); - Widget builder() { - return new Center( - child: new Material( - child: new Input( - key: inputKey, - hintText: 'Placeholder' - ) + Widget builder() { + return new Center( + child: new Material( + child: new Input( + key: inputKey, + hintText: 'Placeholder' ) - ); - } + ) + ); + } - tester.pumpWidget(builder()); + tester.pumpWidget(builder()); - RawInputLineState editableText = tester.stateOf(find.byType(RawInputLine)); + RawInputLineState editableText = tester.state(find.byType(RawInputLine)); - // Check that the cursor visibility toggles after each blink interval. - void checkCursorToggle() { - bool initialShowCursor = editableText.cursorCurrentlyVisible; - tester.async.elapse(editableText.cursorBlinkInterval); - expect(editableText.cursorCurrentlyVisible, equals(!initialShowCursor)); - tester.async.elapse(editableText.cursorBlinkInterval); - expect(editableText.cursorCurrentlyVisible, equals(initialShowCursor)); - tester.async.elapse(editableText.cursorBlinkInterval ~/ 10); - expect(editableText.cursorCurrentlyVisible, equals(initialShowCursor)); - tester.async.elapse(editableText.cursorBlinkInterval); - expect(editableText.cursorCurrentlyVisible, equals(!initialShowCursor)); - tester.async.elapse(editableText.cursorBlinkInterval); - expect(editableText.cursorCurrentlyVisible, equals(initialShowCursor)); - } + // Check that the cursor visibility toggles after each blink interval. + void checkCursorToggle() { + bool initialShowCursor = editableText.cursorCurrentlyVisible; + tester.pump(editableText.cursorBlinkInterval); + expect(editableText.cursorCurrentlyVisible, equals(!initialShowCursor)); + tester.pump(editableText.cursorBlinkInterval); + expect(editableText.cursorCurrentlyVisible, equals(initialShowCursor)); + tester.pump(editableText.cursorBlinkInterval ~/ 10); + expect(editableText.cursorCurrentlyVisible, equals(initialShowCursor)); + tester.pump(editableText.cursorBlinkInterval); + expect(editableText.cursorCurrentlyVisible, equals(!initialShowCursor)); + tester.pump(editableText.cursorBlinkInterval); + expect(editableText.cursorCurrentlyVisible, equals(initialShowCursor)); + } - checkCursorToggle(); + checkCursorToggle(); - // Try the test again with a nonempty EditableText. - mockKeyboard.client.updateEditingState(new mojom.EditingState() - ..text = 'X' - ..selectionBase = 1 - ..selectionExtent = 1); - checkCursorToggle(); - }); + // Try the test again with a nonempty EditableText. + mockKeyboard.client.updateEditingState(new mojom.EditingState() + ..text = 'X' + ..selectionBase = 1 + ..selectionExtent = 1); + checkCursorToggle(); }); - test('hideText control test', () { - testWidgets((WidgetTester tester) { - GlobalKey inputKey = new GlobalKey(); + testWidgets('hideText control test', (WidgetTester tester) { + GlobalKey inputKey = new GlobalKey(); - Widget builder() { - return new Center( - child: new Material( - child: new Input( - key: inputKey, - hideText: true, - hintText: 'Placeholder' - ) + Widget builder() { + return new Center( + child: new Material( + child: new Input( + key: inputKey, + hideText: true, + hintText: 'Placeholder' ) - ); - } + ) + ); + } - tester.pumpWidget(builder()); + tester.pumpWidget(builder()); - const String testValue = 'ABC'; - mockKeyboard.client.updateEditingState(new mojom.EditingState() - ..text = testValue - ..selectionBase = testValue.length - ..selectionExtent = testValue.length); + const String testValue = 'ABC'; + mockKeyboard.client.updateEditingState(new mojom.EditingState() + ..text = testValue + ..selectionBase = testValue.length + ..selectionExtent = testValue.length); - tester.pump(); - }); + tester.pump(); }); // Returns the first RenderEditableLine. RenderEditableLine findRenderEditableLine(WidgetTester tester) { - RenderObject root = tester.renderObjectOf(find.byType(RawInputLine)); + RenderObject root = tester.renderObject(find.byType(RawInputLine)); expect(root, isNotNull); RenderEditableLine renderLine; @@ -183,128 +176,124 @@ void main() { return endpoints[0].point; } - test('Can long press to select', () { - testWidgets((WidgetTester tester) { - GlobalKey inputKey = new GlobalKey(); - InputValue inputValue = InputValue.empty; + testWidgets('Can long press to select', (WidgetTester tester) { + GlobalKey inputKey = new GlobalKey(); + InputValue inputValue = InputValue.empty; - Widget builder() { - return new Overlay( - initialEntries: [ - new OverlayEntry( - builder: (BuildContext context) { - return new Center( - child: new Material( - child: new Input( - value: inputValue, - key: inputKey, - onChanged: (InputValue value) { inputValue = value; } - ) + Widget builder() { + return new Overlay( + initialEntries: [ + new OverlayEntry( + builder: (BuildContext context) { + return new Center( + child: new Material( + child: new Input( + value: inputValue, + key: inputKey, + onChanged: (InputValue value) { inputValue = value; } ) - ); - } - ) - ] - ); - } + ) + ); + } + ) + ] + ); + } - tester.pumpWidget(builder()); + tester.pumpWidget(builder()); - String testValue = 'abc def ghi'; - enterText(testValue); - expect(inputValue.text, testValue); + String testValue = 'abc def ghi'; + enterText(testValue); + expect(inputValue.text, testValue); - tester.pumpWidget(builder()); + tester.pumpWidget(builder()); - expect(inputValue.selection.isCollapsed, true); + expect(inputValue.selection.isCollapsed, true); - // Long press the 'e' to select 'def'. - Point ePos = textOffsetToPosition(tester, testValue.indexOf('e')); - TestGesture gesture = tester.startGesture(ePos, pointer: 7); - tester.pump(const Duration(seconds: 2)); - gesture.up(); - tester.pump(); + // Long press the 'e' to select 'def'. + Point ePos = textOffsetToPosition(tester, testValue.indexOf('e')); + TestGesture gesture = tester.startGesture(ePos, pointer: 7); + tester.pump(const Duration(seconds: 2)); + gesture.up(); + tester.pump(); - // 'def' is selected. - expect(inputValue.selection.baseOffset, testValue.indexOf('d')); - expect(inputValue.selection.extentOffset, testValue.indexOf('f')+1); - }); + // 'def' is selected. + expect(inputValue.selection.baseOffset, testValue.indexOf('d')); + expect(inputValue.selection.extentOffset, testValue.indexOf('f')+1); }); - test('Can drag handles to change selection', () { - testWidgets((WidgetTester tester) { - GlobalKey inputKey = new GlobalKey(); - InputValue inputValue = InputValue.empty; + testWidgets('Can drag handles to change selection', (WidgetTester tester) { + GlobalKey inputKey = new GlobalKey(); + InputValue inputValue = InputValue.empty; - Widget builder() { - return new Overlay( - initialEntries: [ - new OverlayEntry( - builder: (BuildContext context) { - return new Center( - child: new Material( - child: new Input( - value: inputValue, - key: inputKey, - onChanged: (InputValue value) { inputValue = value; } - ) + Widget builder() { + return new Overlay( + initialEntries: [ + new OverlayEntry( + builder: (BuildContext context) { + return new Center( + child: new Material( + child: new Input( + value: inputValue, + key: inputKey, + onChanged: (InputValue value) { inputValue = value; } ) - ); - } - ) - ] - ); - } + ) + ); + } + ) + ] + ); + } - tester.pumpWidget(builder()); + tester.pumpWidget(builder()); - String testValue = 'abc def ghi'; - enterText(testValue); + String testValue = 'abc def ghi'; + enterText(testValue); - tester.pumpWidget(builder()); + tester.pumpWidget(builder()); - // Long press the 'e' to select 'def'. - Point ePos = textOffsetToPosition(tester, testValue.indexOf('e')); - TestGesture gesture = tester.startGesture(ePos, pointer: 7); - tester.pump(const Duration(seconds: 2)); - gesture.up(); - tester.pump(); + // Long press the 'e' to select 'def'. + Point ePos = textOffsetToPosition(tester, testValue.indexOf('e')); + TestGesture gesture = tester.startGesture(ePos, pointer: 7); + tester.pump(const Duration(seconds: 2)); + gesture.up(); + tester.pump(); - TextSelection selection = inputValue.selection; + TextSelection selection = inputValue.selection; - RenderEditableLine renderLine = findRenderEditableLine(tester); - List endpoints = renderLine.getEndpointsForSelection( - selection); - expect(endpoints.length, 2); + RenderEditableLine renderLine = findRenderEditableLine(tester); + List endpoints = renderLine.getEndpointsForSelection( + selection); + expect(endpoints.length, 2); - // Drag the right handle 2 letters to the right. - // Note: use a small offset because the endpoint is on the very corner - // of the handle. - Point handlePos = endpoints[1].point + new Offset(1.0, 1.0); - Point newHandlePos = textOffsetToPosition(tester, selection.extentOffset+2); - gesture = tester.startGesture(handlePos, pointer: 7); - tester.pump(); - gesture.moveTo(newHandlePos); - tester.pump(); - gesture.up(); - tester.pump(); + // Drag the right handle 2 letters to the right. + // Note: use a small offset because the endpoint is on the very corner + // of the handle. + Point handlePos = endpoints[1].point + new Offset(1.0, 1.0); + Point newHandlePos = textOffsetToPosition(tester, selection.extentOffset+2); + gesture = tester.startGesture(handlePos, pointer: 7); + tester.pump(); + gesture.moveTo(newHandlePos); + tester.pump(); + gesture.up(); + tester.pump(); - expect(inputValue.selection.baseOffset, selection.baseOffset); - expect(inputValue.selection.extentOffset, selection.extentOffset+2); + expect(inputValue.selection.baseOffset, selection.baseOffset); + expect(inputValue.selection.extentOffset, selection.extentOffset+2); - // Drag the left handle 2 letters to the left. - handlePos = endpoints[0].point + new Offset(-1.0, 1.0); - newHandlePos = textOffsetToPosition(tester, selection.baseOffset-2); - gesture = tester.startGesture(handlePos, pointer: 7); - tester.pump(); - gesture.moveTo(newHandlePos); - tester.pump(); - gesture.up(); - tester.pumpWidget(builder()); + // Drag the left handle 2 letters to the left. + handlePos = endpoints[0].point + new Offset(-1.0, 1.0); + newHandlePos = textOffsetToPosition(tester, selection.baseOffset-2); + gesture = tester.startGesture(handlePos, pointer: 7); + tester.pump(); + gesture.moveTo(newHandlePos); + tester.pump(); + gesture.up(); + tester.pumpWidget(builder()); - expect(inputValue.selection.baseOffset, selection.baseOffset-2); - expect(inputValue.selection.extentOffset, selection.extentOffset+2); - }); + expect(inputValue.selection.baseOffset, selection.baseOffset-2); + expect(inputValue.selection.extentOffset, selection.extentOffset+2); }); } diff --git a/packages/flutter/test/widget/lazy_block_test.dart b/packages/flutter/test/widget/lazy_block_test.dart index ccb757f634..fc79b5cb61 100644 --- a/packages/flutter/test/widget/lazy_block_test.dart +++ b/packages/flutter/test/widget/lazy_block_test.dart @@ -4,31 +4,28 @@ import 'package:flutter_test/flutter_test.dart'; import 'package:flutter/material.dart'; -import 'package:test/test.dart'; void main() { - test('Block inside LazyBlock', () { - testWidgets((WidgetTester tester) { - tester.pumpWidget(new LazyBlock( - delegate: new LazyBlockChildren( - children: [ - new Block( - children: [ - new Text('1'), - new Text('2'), - new Text('3'), - ] - ), - new Block( - children: [ - new Text('4'), - new Text('5'), - new Text('6'), - ] - ), - ] - ) - )); - }); + testWidgets('Block inside LazyBlock', (WidgetTester tester) { + tester.pumpWidget(new LazyBlock( + delegate: new LazyBlockChildren( + children: [ + new Block( + children: [ + new Text('1'), + new Text('2'), + new Text('3'), + ] + ), + new Block( + children: [ + new Text('4'), + new Text('5'), + new Text('6'), + ] + ), + ] + ) + )); }); } diff --git a/packages/flutter/test/widget/lazy_block_viewport_test.dart b/packages/flutter/test/widget/lazy_block_viewport_test.dart index c4a2a03bd7..1ecb5dfe2d 100644 --- a/packages/flutter/test/widget/lazy_block_viewport_test.dart +++ b/packages/flutter/test/widget/lazy_block_viewport_test.dart @@ -10,300 +10,286 @@ import 'package:test/test.dart'; import 'test_widgets.dart'; void main() { - test('LazyBlockViewport mount/dismount smoke test', () { - testWidgets((WidgetTester tester) { - List callbackTracker = []; + testWidgets('LazyBlockViewport mount/dismount smoke test', (WidgetTester tester) { + List callbackTracker = []; - // the root view is 800x600 in the test environment - // so if our widget is 100 pixels tall, it should fit exactly 6 times. + // the root view is 800x600 in the test environment + // so if our widget is 100 pixels tall, it should fit exactly 6 times. - Widget builder() { - return new FlipWidget( - left: new LazyBlockViewport( - delegate: new LazyBlockBuilder(builder: (BuildContext context, int i) { - callbackTracker.add(i); - return new Container( - key: new ValueKey(i), - height: 100.0, - child: new Text("$i") - ); - }), - startOffset: 0.0 - ), - right: new Text('Not Today') - ); - } - - tester.pumpWidget(builder()); - - FlipWidgetState testWidget = tester.stateOf(find.byType(FlipWidget)); - - expect(callbackTracker, equals([0, 1, 2, 3, 4, 5])); - - callbackTracker.clear(); - testWidget.flip(); - tester.pump(); - - expect(callbackTracker, equals([])); - - callbackTracker.clear(); - testWidget.flip(); - tester.pump(); - - expect(callbackTracker, equals([0, 1, 2, 3, 4, 5])); - }); - }); - - test('LazyBlockViewport vertical', () { - testWidgets((WidgetTester tester) { - List callbackTracker = []; - - // the root view is 800x600 in the test environment - // so if our widget is 200 pixels tall, it should fit exactly 3 times. - // but if we are offset by 300 pixels, there will be 4, numbered 1-4. - - double offset = 300.0; - - IndexedBuilder itemBuilder = (BuildContext context, int i) { - callbackTracker.add(i); - return new Container( - key: new ValueKey(i), - width: 500.0, // this should be ignored - height: 200.0, - child: new Text("$i") - ); - }; - - Widget builder() { - return new FlipWidget( - left: new LazyBlockViewport( - delegate: new LazyBlockBuilder(builder: itemBuilder), - startOffset: offset - ), - right: new Text('Not Today') - ); - } - - tester.pumpWidget(builder()); - - // 0 is built to find its height - expect(callbackTracker, equals([0, 1, 2, 3, 4])); - callbackTracker.clear(); - - offset = 400.0; // now only 3 should fit, numbered 2-4. - - tester.pumpWidget(builder()); - - // We build all the children to find their new size. - expect(callbackTracker, equals([0, 1, 2, 3, 4])); - callbackTracker.clear(); - - tester.pumpWidget(builder()); - - // 0 isn't built because they're not visible. - expect(callbackTracker, equals([1, 2, 3, 4])); - callbackTracker.clear(); - }); - }); - - test('LazyBlockViewport horizontal', () { - testWidgets((WidgetTester tester) { - List callbackTracker = []; - - // the root view is 800x600 in the test environment - // so if our widget is 200 pixels wide, it should fit exactly 4 times. - // but if we are offset by 300 pixels, there will be 5, numbered 1-5. - - double offset = 300.0; - - IndexedBuilder itemBuilder = (BuildContext context, int i) { - callbackTracker.add(i); - return new Container( - key: new ValueKey(i), - height: 500.0, // this should be ignored - width: 200.0, - child: new Text("$i") - ); - }; - - Widget builder() { - return new FlipWidget( - left: new LazyBlockViewport( - delegate: new LazyBlockBuilder(builder: itemBuilder), - startOffset: offset, - mainAxis: Axis.horizontal - ), - right: new Text('Not Today') - ); - } - - tester.pumpWidget(builder()); - - // 0 is built to find its width - expect(callbackTracker, equals([0, 1, 2, 3, 4, 5])); - - callbackTracker.clear(); - - offset = 400.0; // now only 4 should fit, numbered 2-5. - - tester.pumpWidget(builder()); - - // We build all the children to find their new size. - expect(callbackTracker, equals([0, 1, 2, 3, 4, 5])); - callbackTracker.clear(); - - tester.pumpWidget(builder()); - - // 0 isn't built because they're not visible. - expect(callbackTracker, equals([1, 2, 3, 4, 5])); - callbackTracker.clear(); - }); - }); - - test('LazyBlockViewport reinvoke builders', () { - testWidgets((WidgetTester tester) { - List callbackTracker = []; - List text = []; - - IndexedBuilder itemBuilder = (BuildContext context, int i) { - callbackTracker.add(i); - return new Container( - key: new ValueKey(i), - width: 500.0, // this should be ignored - height: 220.0, - child: new Text("$i") - ); - }; - - void collectText(Widget widget) { - if (widget is Text) - text.add(widget.data); - }; - - Widget builder() { - return new LazyBlockViewport( - delegate: new LazyBlockBuilder(builder: itemBuilder), + Widget builder() { + return new FlipWidget( + left: new LazyBlockViewport( + delegate: new LazyBlockBuilder(builder: (BuildContext context, int i) { + callbackTracker.add(i); + return new Container( + key: new ValueKey(i), + height: 100.0, + child: new Text("$i") + ); + }), startOffset: 0.0 - ); - } + ), + right: new Text('Not Today') + ); + } - tester.pumpWidget(builder()); + tester.pumpWidget(builder()); - expect(callbackTracker, equals([0, 1, 2])); - callbackTracker.clear(); - tester.widgets.forEach(collectText); - expect(text, equals(['0', '1', '2'])); - text.clear(); + FlipWidgetState testWidget = tester.state(find.byType(FlipWidget)); - tester.pumpWidget(builder()); + expect(callbackTracker, equals([0, 1, 2, 3, 4, 5])); - expect(callbackTracker, equals([0, 1, 2])); - callbackTracker.clear(); - tester.widgets.forEach(collectText); - expect(text, equals(['0', '1', '2'])); - text.clear(); - }); + callbackTracker.clear(); + testWidget.flip(); + tester.pump(); + + expect(callbackTracker, equals([])); + + callbackTracker.clear(); + testWidget.flip(); + tester.pump(); + + expect(callbackTracker, equals([0, 1, 2, 3, 4, 5])); }); - test('LazyBlockViewport reinvoke builders', () { - testWidgets((WidgetTester tester) { - StateSetter setState; - ThemeData themeData = new ThemeData.light(); + testWidgets('LazyBlockViewport vertical', (WidgetTester tester) { + List callbackTracker = []; - IndexedBuilder itemBuilder = (BuildContext context, int i) { - return new Container( - key: new ValueKey(i), - width: 500.0, // this should be ignored - height: 220.0, - decoration: new BoxDecoration( - backgroundColor: Theme.of(context).primaryColor - ), - child: new Text("$i") - ); - }; + // the root view is 800x600 in the test environment + // so if our widget is 200 pixels tall, it should fit exactly 3 times. + // but if we are offset by 300 pixels, there will be 4, numbered 1-4. - Widget viewport = new LazyBlockViewport( + double offset = 300.0; + + IndexedBuilder itemBuilder = (BuildContext context, int i) { + callbackTracker.add(i); + return new Container( + key: new ValueKey(i), + width: 500.0, // this should be ignored + height: 200.0, + child: new Text("$i") + ); + }; + + Widget builder() { + return new FlipWidget( + left: new LazyBlockViewport( + delegate: new LazyBlockBuilder(builder: itemBuilder), + startOffset: offset + ), + right: new Text('Not Today') + ); + } + + tester.pumpWidget(builder()); + + // 0 is built to find its height + expect(callbackTracker, equals([0, 1, 2, 3, 4])); + callbackTracker.clear(); + + offset = 400.0; // now only 3 should fit, numbered 2-4. + + tester.pumpWidget(builder()); + + // We build all the children to find their new size. + expect(callbackTracker, equals([0, 1, 2, 3, 4])); + callbackTracker.clear(); + + tester.pumpWidget(builder()); + + // 0 isn't built because they're not visible. + expect(callbackTracker, equals([1, 2, 3, 4])); + callbackTracker.clear(); + }); + + testWidgets('LazyBlockViewport horizontal', (WidgetTester tester) { + List callbackTracker = []; + + // the root view is 800x600 in the test environment + // so if our widget is 200 pixels wide, it should fit exactly 4 times. + // but if we are offset by 300 pixels, there will be 5, numbered 1-5. + + double offset = 300.0; + + IndexedBuilder itemBuilder = (BuildContext context, int i) { + callbackTracker.add(i); + return new Container( + key: new ValueKey(i), + height: 500.0, // this should be ignored + width: 200.0, + child: new Text("$i") + ); + }; + + Widget builder() { + return new FlipWidget( + left: new LazyBlockViewport( + delegate: new LazyBlockBuilder(builder: itemBuilder), + startOffset: offset, + mainAxis: Axis.horizontal + ), + right: new Text('Not Today') + ); + } + + tester.pumpWidget(builder()); + + // 0 is built to find its width + expect(callbackTracker, equals([0, 1, 2, 3, 4, 5])); + + callbackTracker.clear(); + + offset = 400.0; // now only 4 should fit, numbered 2-5. + + tester.pumpWidget(builder()); + + // We build all the children to find their new size. + expect(callbackTracker, equals([0, 1, 2, 3, 4, 5])); + callbackTracker.clear(); + + tester.pumpWidget(builder()); + + // 0 isn't built because they're not visible. + expect(callbackTracker, equals([1, 2, 3, 4, 5])); + callbackTracker.clear(); + }); + + testWidgets('LazyBlockViewport reinvoke builders', (WidgetTester tester) { + List callbackTracker = []; + List text = []; + + IndexedBuilder itemBuilder = (BuildContext context, int i) { + callbackTracker.add(i); + return new Container( + key: new ValueKey(i), + width: 500.0, // this should be ignored + height: 220.0, + child: new Text("$i") + ); + }; + + void collectText(Widget widget) { + if (widget is Text) + text.add(widget.data); + }; + + Widget builder() { + return new LazyBlockViewport( + delegate: new LazyBlockBuilder(builder: itemBuilder), + startOffset: 0.0 + ); + } + + tester.pumpWidget(builder()); + + expect(callbackTracker, equals([0, 1, 2])); + callbackTracker.clear(); + tester.allWidgets.forEach(collectText); + expect(text, equals(['0', '1', '2'])); + text.clear(); + + tester.pumpWidget(builder()); + + expect(callbackTracker, equals([0, 1, 2])); + callbackTracker.clear(); + tester.allWidgets.forEach(collectText); + expect(text, equals(['0', '1', '2'])); + text.clear(); + }); + + testWidgets('LazyBlockViewport reinvoke builders', (WidgetTester tester) { + StateSetter setState; + ThemeData themeData = new ThemeData.light(); + + IndexedBuilder itemBuilder = (BuildContext context, int i) { + return new Container( + key: new ValueKey(i), + width: 500.0, // this should be ignored + height: 220.0, + decoration: new BoxDecoration( + backgroundColor: Theme.of(context).primaryColor + ), + child: new Text("$i") + ); + }; + + Widget viewport = new LazyBlockViewport( + delegate: new LazyBlockBuilder(builder: itemBuilder) + ); + + tester.pumpWidget( + new StatefulBuilder( + builder: (BuildContext context, StateSetter setter) { + setState = setter; + return new Theme(data: themeData, child: viewport); + } + ) + ); + + DecoratedBox widget = tester.firstWidget(find.byType(DecoratedBox)); + BoxDecoration decoraton = widget.decoration; + expect(decoraton.backgroundColor, equals(Colors.blue[500])); + + setState(() { + themeData = new ThemeData(primarySwatch: Colors.green); + }); + + tester.pump(); + + widget = tester.firstWidget(find.byType(DecoratedBox)); + decoraton = widget.decoration; + expect(decoraton.backgroundColor, equals(Colors.green[500])); + }); + + testWidgets('LazyBlockViewport padding', (WidgetTester tester) { + IndexedBuilder itemBuilder = (BuildContext context, int i) { + return new Container( + key: new ValueKey(i), + width: 500.0, // this should be ignored + height: 220.0, + decoration: new BoxDecoration( + backgroundColor: Colors.green[500] + ), + child: new Text("$i") + ); + }; + + tester.pumpWidget( + new LazyBlockViewport( + padding: new EdgeInsets.fromLTRB(7.0, 3.0, 5.0, 11.0), delegate: new LazyBlockBuilder(builder: itemBuilder) - ); + ) + ); - tester.pumpWidget( - new StatefulBuilder( - builder: (BuildContext context, StateSetter setter) { - setState = setter; - return new Theme(data: themeData, child: viewport); - } - ) - ); - - DecoratedBox widget = tester.widget(find.byType(DecoratedBox)); - BoxDecoration decoraton = widget.decoration; - expect(decoraton.backgroundColor, equals(Colors.blue[500])); - - setState(() { - themeData = new ThemeData(primarySwatch: Colors.green); - }); - - tester.pump(); - - widget = tester.widget(find.byType(DecoratedBox)); - decoraton = widget.decoration; - expect(decoraton.backgroundColor, equals(Colors.green[500])); - }); + RenderBox firstBox = tester.renderObject(find.text('0')); + Point upperLeft = firstBox.localToGlobal(Point.origin); + expect(upperLeft, equals(new Point(7.0, 3.0))); + expect(firstBox.size.width, equals(800.0 - 12.0)); }); - test('LazyBlockViewport padding', () { - testWidgets((WidgetTester tester) { - IndexedBuilder itemBuilder = (BuildContext context, int i) { - return new Container( - key: new ValueKey(i), - width: 500.0, // this should be ignored - height: 220.0, - decoration: new BoxDecoration( - backgroundColor: Colors.green[500] - ), - child: new Text("$i") - ); - }; + testWidgets('Underflow extents', (WidgetTester tester) { + double lastContentExtent; + double lastContainerExtent; + double lastMinScrollOffset; + void handleExtendsChanged(double contentExtent, double containerExtent, double minScrollOffset) { + lastContentExtent = contentExtent; + lastContainerExtent = containerExtent; + lastMinScrollOffset = minScrollOffset; + } - tester.pumpWidget( - new LazyBlockViewport( - padding: new EdgeInsets.fromLTRB(7.0, 3.0, 5.0, 11.0), - delegate: new LazyBlockBuilder(builder: itemBuilder) - ) - ); + tester.pumpWidget(new LazyBlockViewport( + onExtentsChanged: handleExtendsChanged, + delegate: new LazyBlockChildren( + children: [ + new Container(height: 100.0), + new Container(height: 100.0), + new Container(height: 100.0), + ] + ) + )); - RenderBox firstBox = tester.renderObjectOf(find.text('0')); - Point upperLeft = firstBox.localToGlobal(Point.origin); - expect(upperLeft, equals(new Point(7.0, 3.0))); - expect(firstBox.size.width, equals(800.0 - 12.0)); - }); - }); - - test('Underflow extents', () { - testWidgets((WidgetTester tester) { - double lastContentExtent; - double lastContainerExtent; - double lastMinScrollOffset; - void handleExtendsChanged(double contentExtent, double containerExtent, double minScrollOffset) { - lastContentExtent = contentExtent; - lastContainerExtent = containerExtent; - lastMinScrollOffset = minScrollOffset; - } - - tester.pumpWidget(new LazyBlockViewport( - onExtentsChanged: handleExtendsChanged, - delegate: new LazyBlockChildren( - children: [ - new Container(height: 100.0), - new Container(height: 100.0), - new Container(height: 100.0), - ] - ) - )); - - expect(lastContentExtent, equals(300.0)); - expect(lastContainerExtent, equals(600.0)); - expect(lastMinScrollOffset, equals(0.0)); - }); + expect(lastContentExtent, equals(300.0)); + expect(lastContainerExtent, equals(600.0)); + expect(lastMinScrollOffset, equals(0.0)); }); } diff --git a/packages/flutter/test/widget/listener_test.dart b/packages/flutter/test/widget/listener_test.dart index 3db7df9799..8ce725b239 100644 --- a/packages/flutter/test/widget/listener_test.dart +++ b/packages/flutter/test/widget/listener_test.dart @@ -7,39 +7,37 @@ import 'package:flutter/widgets.dart'; import 'package:test/test.dart'; void main() { - test('Events bubble up the tree', () { - testWidgets((WidgetTester tester) { - List log = new List(); + testWidgets('Events bubble up the tree', (WidgetTester tester) { + List log = new List(); - tester.pumpWidget( - new Listener( + tester.pumpWidget( + new Listener( + onPointerDown: (_) { + log.add('top'); + }, + child: new Listener( onPointerDown: (_) { - log.add('top'); + log.add('middle'); }, - child: new Listener( - onPointerDown: (_) { - log.add('middle'); - }, - child: new DecoratedBox( - decoration: const BoxDecoration(), - child: new Listener( - onPointerDown: (_) { - log.add('bottom'); - }, - child: new Text('X') - ) + child: new DecoratedBox( + decoration: const BoxDecoration(), + child: new Listener( + onPointerDown: (_) { + log.add('bottom'); + }, + child: new Text('X') ) ) ) - ); + ) + ); - tester.tap(find.text('X')); + tester.tap(find.text('X')); - expect(log, equals([ - 'bottom', - 'middle', - 'top', - ])); - }); + expect(log, equals([ + 'bottom', + 'middle', + 'top', + ])); }); } diff --git a/packages/flutter/test/widget/media_query_test.dart b/packages/flutter/test/widget/media_query_test.dart index 81ad5fe562..d230572cb8 100644 --- a/packages/flutter/test/widget/media_query_test.dart +++ b/packages/flutter/test/widget/media_query_test.dart @@ -9,20 +9,18 @@ import 'package:flutter/widgets.dart'; import 'package:test/test.dart'; void main() { - test('MediaQuery has a default', () { - testWidgets((WidgetTester tester) { - Size size; + testWidgets('MediaQuery has a default', (WidgetTester tester) { + Size size; - tester.pumpWidget( - new Builder( - builder: (BuildContext context) { - size = MediaQuery.of(context).size; - return new Container(); - } - ) - ); + tester.pumpWidget( + new Builder( + builder: (BuildContext context) { + size = MediaQuery.of(context).size; + return new Container(); + } + ) + ); - expect(size, equals(ui.window.size)); - }); + expect(size, equals(ui.window.size)); }); } diff --git a/packages/flutter/test/widget/modal_barrier_test.dart b/packages/flutter/test/widget/modal_barrier_test.dart index c6aa255724..9924236282 100644 --- a/packages/flutter/test/widget/modal_barrier_test.dart +++ b/packages/flutter/test/widget/modal_barrier_test.dart @@ -25,88 +25,82 @@ void main() { ); }); - test('ModalBarrier prevents interactions with widgets behind it', () { - testWidgets((WidgetTester tester) { - Widget subject = new Stack( - children: [ - tapTarget, - new ModalBarrier(dismissable: false), - ] - ); + testWidgets('ModalBarrier prevents interactions with widgets behind it', (WidgetTester tester) { + Widget subject = new Stack( + children: [ + tapTarget, + new ModalBarrier(dismissable: false), + ] + ); - tester.pumpWidget(subject); - tester.tap(find.text('target')); - tester.pumpWidget(subject); - expect(tapped, isFalse, - reason: 'because the tap is prevented by ModalBarrier'); - }); + tester.pumpWidget(subject); + tester.tap(find.text('target')); + tester.pumpWidget(subject); + expect(tapped, isFalse, + reason: 'because the tap is prevented by ModalBarrier'); }); - test('ModalBarrier does not prevent interactions with widgets in front of it', () { - testWidgets((WidgetTester tester) { - Widget subject = new Stack( - children: [ - new ModalBarrier(dismissable: false), - tapTarget, - ] - ); + testWidgets('ModalBarrier does not prevent interactions with widgets in front of it', (WidgetTester tester) { + Widget subject = new Stack( + children: [ + new ModalBarrier(dismissable: false), + tapTarget, + ] + ); - tester.pumpWidget(subject); - tester.tap(find.text('target')); - tester.pumpWidget(subject); - expect(tapped, isTrue, - reason: 'because the tap is not prevented by ModalBarrier'); - }); + tester.pumpWidget(subject); + tester.tap(find.text('target')); + tester.pumpWidget(subject); + expect(tapped, isTrue, + reason: 'because the tap is not prevented by ModalBarrier'); }); - test('ModalBarrier pops the Navigator when dismissed', () { - testWidgets((WidgetTester tester) { - final Map routes = { - '/': (BuildContext context) => new FirstWidget(), - '/modal': (BuildContext context) => new SecondWidget(), - }; + testWidgets('ModalBarrier pops the Navigator when dismissed', (WidgetTester tester) { + final Map routes = { + '/': (BuildContext context) => new FirstWidget(), + '/modal': (BuildContext context) => new SecondWidget(), + }; - tester.pumpWidget(new MaterialApp(routes: routes)); + tester.pumpWidget(new MaterialApp(routes: routes)); - // Initially the barrier is not visible - expect(tester, doesNotHaveWidget(find.byKey(const ValueKey('barrier')))); + // Initially the barrier is not visible + expect(find.byKey(const ValueKey('barrier')), findsNothing); - // Tapping on X routes to the barrier - tester.tap(find.text('X')); - tester.pump(); // begin transition - tester.pump(const Duration(seconds: 1)); // end transition + // Tapping on X routes to the barrier + tester.tap(find.text('X')); + tester.pump(); // begin transition + tester.pump(const Duration(seconds: 1)); // end transition - // Tap on the barrier to dismiss it - tester.tap(find.byKey(const ValueKey('barrier'))); - tester.pump(); // begin transition - tester.pump(const Duration(seconds: 1)); // end transition + // Tap on the barrier to dismiss it + tester.tap(find.byKey(const ValueKey('barrier'))); + tester.pump(); // begin transition + tester.pump(const Duration(seconds: 1)); // end transition - expect(tester, doesNotHaveWidget(find.byKey(const ValueKey('barrier'))), - reason: 'because the barrier was dismissed'); - }); + expect(find.byKey(const ValueKey('barrier')), findsNothing, + reason: 'because the barrier was dismissed'); }); } class FirstWidget extends StatelessWidget { @override Widget build(BuildContext context) { - return new GestureDetector( - onTap: () { - Navigator.pushNamed(context, '/modal'); - }, - child: new Container( - child: new Text('X') - ) - ); + return new GestureDetector( + onTap: () { + Navigator.pushNamed(context, '/modal'); + }, + child: new Container( + child: new Text('X') + ) + ); } } class SecondWidget extends StatelessWidget { @override Widget build(BuildContext context) { - return new ModalBarrier( - key: const ValueKey('barrier'), - dismissable: true - ); + return new ModalBarrier( + key: const ValueKey('barrier'), + dismissable: true + ); } } diff --git a/packages/flutter/test/widget/multichild_test.dart b/packages/flutter/test/widget/multichild_test.dart index ce43fa5ad5..717b439cf5 100644 --- a/packages/flutter/test/widget/multichild_test.dart +++ b/packages/flutter/test/widget/multichild_test.dart @@ -10,7 +10,7 @@ import 'package:test/test.dart'; import 'test_widgets.dart'; void checkTree(WidgetTester tester, List expectedDecorations) { - MultiChildRenderObjectElement element = tester.elementOf(find.byElementPredicate( + MultiChildRenderObjectElement element = tester.element(find.byElementPredicate( (Element element) => element is MultiChildRenderObjectElement )); expect(element, isNotNull); @@ -33,304 +33,298 @@ void checkTree(WidgetTester tester, List expectedDecorations) { } void main() { - test('MultiChildRenderObjectElement control test', () { - testWidgets((WidgetTester tester) { + testWidgets('MultiChildRenderObjectElement control test', (WidgetTester tester) { - tester.pumpWidget( - new Stack( - children: [ - new DecoratedBox(decoration: kBoxDecorationA), - new DecoratedBox(decoration: kBoxDecorationB), - new DecoratedBox(decoration: kBoxDecorationC), - ] - ) - ); + tester.pumpWidget( + new Stack( + children: [ + new DecoratedBox(decoration: kBoxDecorationA), + new DecoratedBox(decoration: kBoxDecorationB), + new DecoratedBox(decoration: kBoxDecorationC), + ] + ) + ); - checkTree(tester, [kBoxDecorationA, kBoxDecorationB, kBoxDecorationC]); + checkTree(tester, [kBoxDecorationA, kBoxDecorationB, kBoxDecorationC]); - tester.pumpWidget( - new Stack( - children: [ - new DecoratedBox(decoration: kBoxDecorationA), - new DecoratedBox(decoration: kBoxDecorationC), - ] - ) - ); + tester.pumpWidget( + new Stack( + children: [ + new DecoratedBox(decoration: kBoxDecorationA), + new DecoratedBox(decoration: kBoxDecorationC), + ] + ) + ); - checkTree(tester, [kBoxDecorationA, kBoxDecorationC]); + checkTree(tester, [kBoxDecorationA, kBoxDecorationC]); - tester.pumpWidget( - new Stack( - children: [ - new DecoratedBox(decoration: kBoxDecorationA), - new DecoratedBox(key: new Key('b'), decoration: kBoxDecorationB), - new DecoratedBox(decoration: kBoxDecorationC), - ] - ) - ); + tester.pumpWidget( + new Stack( + children: [ + new DecoratedBox(decoration: kBoxDecorationA), + new DecoratedBox(key: new Key('b'), decoration: kBoxDecorationB), + new DecoratedBox(decoration: kBoxDecorationC), + ] + ) + ); - checkTree(tester, [kBoxDecorationA, kBoxDecorationB, kBoxDecorationC]); + checkTree(tester, [kBoxDecorationA, kBoxDecorationB, kBoxDecorationC]); - tester.pumpWidget( - new Stack( - children: [ - new DecoratedBox(key: new Key('b'), decoration: kBoxDecorationB), - new DecoratedBox(decoration: kBoxDecorationC), - new DecoratedBox(key: new Key('a'), decoration: kBoxDecorationA), - ] - ) - ); + tester.pumpWidget( + new Stack( + children: [ + new DecoratedBox(key: new Key('b'), decoration: kBoxDecorationB), + new DecoratedBox(decoration: kBoxDecorationC), + new DecoratedBox(key: new Key('a'), decoration: kBoxDecorationA), + ] + ) + ); - checkTree(tester, [kBoxDecorationB, kBoxDecorationC, kBoxDecorationA]); + checkTree(tester, [kBoxDecorationB, kBoxDecorationC, kBoxDecorationA]); - tester.pumpWidget( - new Stack( - children: [ - new DecoratedBox(key: new Key('a'), decoration: kBoxDecorationA), - new DecoratedBox(decoration: kBoxDecorationC), - new DecoratedBox(key: new Key('b'), decoration: kBoxDecorationB), - ] - ) - ); + tester.pumpWidget( + new Stack( + children: [ + new DecoratedBox(key: new Key('a'), decoration: kBoxDecorationA), + new DecoratedBox(decoration: kBoxDecorationC), + new DecoratedBox(key: new Key('b'), decoration: kBoxDecorationB), + ] + ) + ); - checkTree(tester, [kBoxDecorationA, kBoxDecorationC, kBoxDecorationB]); + checkTree(tester, [kBoxDecorationA, kBoxDecorationC, kBoxDecorationB]); - tester.pumpWidget( - new Stack( - children: [ - new DecoratedBox(decoration: kBoxDecorationC), - ] - ) - ); + tester.pumpWidget( + new Stack( + children: [ + new DecoratedBox(decoration: kBoxDecorationC), + ] + ) + ); - checkTree(tester, [kBoxDecorationC]); + checkTree(tester, [kBoxDecorationC]); - tester.pumpWidget( - new Stack() - ); + tester.pumpWidget( + new Stack() + ); - checkTree(tester, []); + checkTree(tester, []); - }); }); - test('MultiChildRenderObjectElement with stateless widgets', () { - testWidgets((WidgetTester tester) { + testWidgets('MultiChildRenderObjectElement with stateless widgets', (WidgetTester tester) { - tester.pumpWidget( - new Stack( - children: [ - new DecoratedBox(decoration: kBoxDecorationA), - new DecoratedBox(decoration: kBoxDecorationB), - new DecoratedBox(decoration: kBoxDecorationC), - ] - ) - ); + tester.pumpWidget( + new Stack( + children: [ + new DecoratedBox(decoration: kBoxDecorationA), + new DecoratedBox(decoration: kBoxDecorationB), + new DecoratedBox(decoration: kBoxDecorationC), + ] + ) + ); - checkTree(tester, [kBoxDecorationA, kBoxDecorationB, kBoxDecorationC]); + checkTree(tester, [kBoxDecorationA, kBoxDecorationB, kBoxDecorationC]); - tester.pumpWidget( - new Stack( - children: [ - new DecoratedBox(decoration: kBoxDecorationA), - new Container( + tester.pumpWidget( + new Stack( + children: [ + new DecoratedBox(decoration: kBoxDecorationA), + new Container( + child: new DecoratedBox(decoration: kBoxDecorationB) + ), + new DecoratedBox(decoration: kBoxDecorationC), + ] + ) + ); + + checkTree(tester, [kBoxDecorationA, kBoxDecorationB, kBoxDecorationC]); + + tester.pumpWidget( + new Stack( + children: [ + new DecoratedBox(decoration: kBoxDecorationA), + new Container( + child: new Container( child: new DecoratedBox(decoration: kBoxDecorationB) - ), - new DecoratedBox(decoration: kBoxDecorationC), - ] - ) - ); + ) + ), + new DecoratedBox(decoration: kBoxDecorationC), + ] + ) + ); - checkTree(tester, [kBoxDecorationA, kBoxDecorationB, kBoxDecorationC]); + checkTree(tester, [kBoxDecorationA, kBoxDecorationB, kBoxDecorationC]); - tester.pumpWidget( - new Stack( - children: [ - new DecoratedBox(decoration: kBoxDecorationA), - new Container( - child: new Container( - child: new DecoratedBox(decoration: kBoxDecorationB) - ) - ), - new DecoratedBox(decoration: kBoxDecorationC), - ] - ) - ); - - checkTree(tester, [kBoxDecorationA, kBoxDecorationB, kBoxDecorationC]); - - tester.pumpWidget( - new Stack( - children: [ - new Container( - child: new Container( - child: new DecoratedBox(decoration: kBoxDecorationB) - ) - ), - new Container( - child: new DecoratedBox(decoration: kBoxDecorationA) - ), - new DecoratedBox(decoration: kBoxDecorationC), - ] - ) - ); - - checkTree(tester, [kBoxDecorationB, kBoxDecorationA, kBoxDecorationC]); - - tester.pumpWidget( - new Stack( - children: [ - new Container( + tester.pumpWidget( + new Stack( + children: [ + new Container( + child: new Container( child: new DecoratedBox(decoration: kBoxDecorationB) - ), - new Container( - child: new DecoratedBox(decoration: kBoxDecorationA) - ), - new DecoratedBox(decoration: kBoxDecorationC), - ] - ) - ); + ) + ), + new Container( + child: new DecoratedBox(decoration: kBoxDecorationA) + ), + new DecoratedBox(decoration: kBoxDecorationC), + ] + ) + ); - checkTree(tester, [kBoxDecorationB, kBoxDecorationA, kBoxDecorationC]); + checkTree(tester, [kBoxDecorationB, kBoxDecorationA, kBoxDecorationC]); - tester.pumpWidget( - new Stack( - children: [ - new Container( - key: new Key('b'), - child: new DecoratedBox(decoration: kBoxDecorationB) - ), - new Container( - key: new Key('a'), - child: new DecoratedBox(decoration: kBoxDecorationA) - ), - ] - ) - ); + tester.pumpWidget( + new Stack( + children: [ + new Container( + child: new DecoratedBox(decoration: kBoxDecorationB) + ), + new Container( + child: new DecoratedBox(decoration: kBoxDecorationA) + ), + new DecoratedBox(decoration: kBoxDecorationC), + ] + ) + ); - checkTree(tester, [kBoxDecorationB, kBoxDecorationA]); + checkTree(tester, [kBoxDecorationB, kBoxDecorationA, kBoxDecorationC]); - tester.pumpWidget( - new Stack( - children: [ - new Container( - key: new Key('a'), - child: new DecoratedBox(decoration: kBoxDecorationA) - ), - new Container( - key: new Key('b'), - child: new DecoratedBox(decoration: kBoxDecorationB) - ), - ] - ) - ); + tester.pumpWidget( + new Stack( + children: [ + new Container( + key: new Key('b'), + child: new DecoratedBox(decoration: kBoxDecorationB) + ), + new Container( + key: new Key('a'), + child: new DecoratedBox(decoration: kBoxDecorationA) + ), + ] + ) + ); - checkTree(tester, [kBoxDecorationA, kBoxDecorationB]); + checkTree(tester, [kBoxDecorationB, kBoxDecorationA]); - tester.pumpWidget( - new Stack() - ); + tester.pumpWidget( + new Stack( + children: [ + new Container( + key: new Key('a'), + child: new DecoratedBox(decoration: kBoxDecorationA) + ), + new Container( + key: new Key('b'), + child: new DecoratedBox(decoration: kBoxDecorationB) + ), + ] + ) + ); - checkTree(tester, []); - }); + checkTree(tester, [kBoxDecorationA, kBoxDecorationB]); + + tester.pumpWidget( + new Stack() + ); + + checkTree(tester, []); }); - test('MultiChildRenderObjectElement with stateful widgets', () { - testWidgets((WidgetTester tester) { - tester.pumpWidget( - new Stack( - children: [ - new DecoratedBox(decoration: kBoxDecorationA), - new DecoratedBox(decoration: kBoxDecorationB), - ] - ) - ); + testWidgets('MultiChildRenderObjectElement with stateful widgets', (WidgetTester tester) { + tester.pumpWidget( + new Stack( + children: [ + new DecoratedBox(decoration: kBoxDecorationA), + new DecoratedBox(decoration: kBoxDecorationB), + ] + ) + ); - checkTree(tester, [kBoxDecorationA, kBoxDecorationB]); + checkTree(tester, [kBoxDecorationA, kBoxDecorationB]); - tester.pumpWidget( - new Stack( - children: [ - new FlipWidget( - left: new DecoratedBox(decoration: kBoxDecorationA), - right: new DecoratedBox(decoration: kBoxDecorationB) - ), - new DecoratedBox(decoration: kBoxDecorationC), - ] - ) - ); + tester.pumpWidget( + new Stack( + children: [ + new FlipWidget( + left: new DecoratedBox(decoration: kBoxDecorationA), + right: new DecoratedBox(decoration: kBoxDecorationB) + ), + new DecoratedBox(decoration: kBoxDecorationC), + ] + ) + ); - checkTree(tester, [kBoxDecorationA, kBoxDecorationC]); + checkTree(tester, [kBoxDecorationA, kBoxDecorationC]); - flipStatefulWidget(tester); - tester.pump(); + flipStatefulWidget(tester); + tester.pump(); - checkTree(tester, [kBoxDecorationB, kBoxDecorationC]); + checkTree(tester, [kBoxDecorationB, kBoxDecorationC]); - tester.pumpWidget( - new Stack( - children: [ - new FlipWidget( - left: new DecoratedBox(decoration: kBoxDecorationA), - right: new DecoratedBox(decoration: kBoxDecorationB) - ), - ] - ) - ); + tester.pumpWidget( + new Stack( + children: [ + new FlipWidget( + left: new DecoratedBox(decoration: kBoxDecorationA), + right: new DecoratedBox(decoration: kBoxDecorationB) + ), + ] + ) + ); - checkTree(tester, [kBoxDecorationB]); + checkTree(tester, [kBoxDecorationB]); - flipStatefulWidget(tester); - tester.pump(); + flipStatefulWidget(tester); + tester.pump(); - checkTree(tester, [kBoxDecorationA]); + checkTree(tester, [kBoxDecorationA]); - tester.pumpWidget( - new Stack( - children: [ - new FlipWidget( - key: new Key('flip'), - left: new DecoratedBox(decoration: kBoxDecorationA), - right: new DecoratedBox(decoration: kBoxDecorationB) - ), - ] - ) - ); + tester.pumpWidget( + new Stack( + children: [ + new FlipWidget( + key: new Key('flip'), + left: new DecoratedBox(decoration: kBoxDecorationA), + right: new DecoratedBox(decoration: kBoxDecorationB) + ), + ] + ) + ); - tester.pumpWidget( - new Stack( - children: [ - new DecoratedBox(key: new Key('c'), decoration: kBoxDecorationC), - new FlipWidget( - key: new Key('flip'), - left: new DecoratedBox(decoration: kBoxDecorationA), - right: new DecoratedBox(decoration: kBoxDecorationB) - ), - ] - ) - ); + tester.pumpWidget( + new Stack( + children: [ + new DecoratedBox(key: new Key('c'), decoration: kBoxDecorationC), + new FlipWidget( + key: new Key('flip'), + left: new DecoratedBox(decoration: kBoxDecorationA), + right: new DecoratedBox(decoration: kBoxDecorationB) + ), + ] + ) + ); - checkTree(tester, [kBoxDecorationC, kBoxDecorationA]); + checkTree(tester, [kBoxDecorationC, kBoxDecorationA]); - flipStatefulWidget(tester); - tester.pump(); + flipStatefulWidget(tester); + tester.pump(); - checkTree(tester, [kBoxDecorationC, kBoxDecorationB]); + checkTree(tester, [kBoxDecorationC, kBoxDecorationB]); - tester.pumpWidget( - new Stack( - children: [ - new FlipWidget( - key: new Key('flip'), - left: new DecoratedBox(decoration: kBoxDecorationA), - right: new DecoratedBox(decoration: kBoxDecorationB) - ), - new DecoratedBox(key: new Key('c'), decoration: kBoxDecorationC), - ] - ) - ); + tester.pumpWidget( + new Stack( + children: [ + new FlipWidget( + key: new Key('flip'), + left: new DecoratedBox(decoration: kBoxDecorationA), + right: new DecoratedBox(decoration: kBoxDecorationB) + ), + new DecoratedBox(key: new Key('c'), decoration: kBoxDecorationC), + ] + ) + ); - checkTree(tester, [kBoxDecorationB, kBoxDecorationC]); - }); + checkTree(tester, [kBoxDecorationB, kBoxDecorationC]); }); } diff --git a/packages/flutter/test/widget/navigator_test.dart b/packages/flutter/test/widget/navigator_test.dart index cf165571d1..dcdc95466b 100644 --- a/packages/flutter/test/widget/navigator_test.dart +++ b/packages/flutter/test/widget/navigator_test.dart @@ -9,7 +9,7 @@ import 'package:test/test.dart'; class FirstWidget extends StatelessWidget { @override Widget build(BuildContext context) { - return new GestureDetector( + return new GestureDetector( onTap: () { Navigator.pushNamed(context, '/second'); }, @@ -68,53 +68,49 @@ class ThirdWidget extends StatelessWidget { } void main() { - test('Can navigator navigate to and from a stateful widget', () { - testWidgets((WidgetTester tester) { - final Map routes = { - '/': (BuildContext context) => new FirstWidget(), - '/second': (BuildContext context) => new SecondWidget(), - }; + testWidgets('Can navigator navigate to and from a stateful widget', (WidgetTester tester) { + final Map routes = { + '/': (BuildContext context) => new FirstWidget(), + '/second': (BuildContext context) => new SecondWidget(), + }; - tester.pumpWidget(new MaterialApp(routes: routes)); + tester.pumpWidget(new MaterialApp(routes: routes)); - expect(tester, hasWidget(find.text('X'))); - expect(tester, doesNotHaveWidget(find.text('Y'))); + expect(find.text('X'), findsOneWidget); + expect(find.text('Y'), findsNothing); - tester.tap(find.text('X')); - tester.pump(const Duration(milliseconds: 10)); + tester.tap(find.text('X')); + tester.pump(const Duration(milliseconds: 10)); - expect(tester, hasWidget(find.text('X'))); - expect(tester, hasWidget(find.text('Y'))); + expect(find.text('X'), findsOneWidget); + expect(find.text('Y'), findsOneWidget); - tester.pump(const Duration(milliseconds: 10)); - tester.pump(const Duration(milliseconds: 10)); - tester.pump(const Duration(seconds: 1)); + tester.pump(const Duration(milliseconds: 10)); + tester.pump(const Duration(milliseconds: 10)); + tester.pump(const Duration(seconds: 1)); - tester.tap(find.text('Y')); - tester.pump(const Duration(milliseconds: 10)); - tester.pump(const Duration(milliseconds: 10)); - tester.pump(const Duration(milliseconds: 10)); - tester.pump(const Duration(seconds: 1)); + tester.tap(find.text('Y')); + tester.pump(const Duration(milliseconds: 10)); + tester.pump(const Duration(milliseconds: 10)); + tester.pump(const Duration(milliseconds: 10)); + tester.pump(const Duration(seconds: 1)); - expect(tester, hasWidget(find.text('X'))); - expect(tester, doesNotHaveWidget(find.text('Y'))); - }); + expect(find.text('X'), findsOneWidget); + expect(find.text('Y'), findsNothing); }); - test('Navigator.openTransaction fails gracefully when not found in context', () { - testWidgets((WidgetTester tester) { - Key targetKey = new Key('foo'); - dynamic exception; - Widget widget = new ThirdWidget( - targetKey: targetKey, - onException: (dynamic e) { - exception = e; - } - ); - tester.pumpWidget(widget); - tester.tap(find.byKey(targetKey)); - expect(exception, new isInstanceOf()); - expect('$exception', startsWith('openTransaction called with a context')); - }); + testWidgets('Navigator.openTransaction fails gracefully when not found in context', (WidgetTester tester) { + Key targetKey = new Key('foo'); + dynamic exception; + Widget widget = new ThirdWidget( + targetKey: targetKey, + onException: (dynamic e) { + exception = e; + } + ); + tester.pumpWidget(widget); + tester.tap(find.byKey(targetKey)); + expect(exception, new isInstanceOf()); + expect('$exception', startsWith('openTransaction called with a context')); }); } diff --git a/packages/flutter/test/widget/overflow_box_test.dart b/packages/flutter/test/widget/overflow_box_test.dart index 3afe436fc0..582a80458e 100644 --- a/packages/flutter/test/widget/overflow_box_test.dart +++ b/packages/flutter/test/widget/overflow_box_test.dart @@ -8,32 +8,30 @@ import 'package:flutter/widgets.dart'; import 'package:test/test.dart'; void main() { - test('OverflowBox control test', () { - testWidgets((WidgetTester tester) { - GlobalKey inner = new GlobalKey(); - tester.pumpWidget(new Align( - alignment: const FractionalOffset(1.0, 1.0), - child: new SizedBox( - width: 10.0, - height: 20.0, - child: new OverflowBox( - minWidth: 0.0, - maxWidth: 100.0, - minHeight: 0.0, - maxHeight: 50.0, - child: new Container( - key: inner - ) + testWidgets('OverflowBox control test', (WidgetTester tester) { + GlobalKey inner = new GlobalKey(); + tester.pumpWidget(new Align( + alignment: const FractionalOffset(1.0, 1.0), + child: new SizedBox( + width: 10.0, + height: 20.0, + child: new OverflowBox( + minWidth: 0.0, + maxWidth: 100.0, + minHeight: 0.0, + maxHeight: 50.0, + child: new Container( + key: inner ) ) - )); - RenderBox box = inner.currentContext.findRenderObject(); - expect(box.localToGlobal(Point.origin), equals(const Point(745.0, 565.0))); - expect(box.size, equals(const Size(100.0, 50.0))); - }); + ) + )); + RenderBox box = inner.currentContext.findRenderObject(); + expect(box.localToGlobal(Point.origin), equals(const Point(745.0, 565.0))); + expect(box.size, equals(const Size(100.0, 50.0))); }); - test('OverflowBox implements debugFillDescription', () { + testWidgets('OverflowBox implements debugFillDescription', (WidgetTester tester) { List description = []; new OverflowBox( minWidth: 1.0, diff --git a/packages/flutter/test/widget/page_forward_transitions_test.dart b/packages/flutter/test/widget/page_forward_transitions_test.dart index bc090c4c46..bec0b5b66e 100644 --- a/packages/flutter/test/widget/page_forward_transitions_test.dart +++ b/packages/flutter/test/widget/page_forward_transitions_test.dart @@ -49,129 +49,127 @@ void main() { final Duration kTwoTenthsOfTheTransitionDuration = kMaterialPageRouteTransitionDuration * 0.2; final Duration kFourTenthsOfTheTransitionDuration = kMaterialPageRouteTransitionDuration * 0.4; - test('Check onstage/offstage handling around transitions', () { - testWidgets((WidgetTester tester) { + testWidgets('Check onstage/offstage handling around transitions', (WidgetTester tester) { - GlobalKey insideKey = new GlobalKey(); + GlobalKey insideKey = new GlobalKey(); - String state() { - String result = ''; - if (tester.exists(find.text('A'))) - result += 'A'; - if (tester.exists(find.text('B'))) - result += 'B'; - if (tester.exists(find.text('C'))) - result += 'C'; - if (tester.exists(find.text('D'))) - result += 'D'; - if (tester.exists(find.text('E'))) - result += 'E'; - if (tester.exists(find.text('F'))) - result += 'F'; - if (tester.exists(find.text('G'))) - result += 'G'; - return result; - } + String state() { + String result = ''; + if (tester.any(find.text('A'))) + result += 'A'; + if (tester.any(find.text('B'))) + result += 'B'; + if (tester.any(find.text('C'))) + result += 'C'; + if (tester.any(find.text('D'))) + result += 'D'; + if (tester.any(find.text('E'))) + result += 'E'; + if (tester.any(find.text('F'))) + result += 'F'; + if (tester.any(find.text('G'))) + result += 'G'; + return result; + } - tester.pumpWidget( - new MaterialApp( - onGenerateRoute: (RouteSettings settings) { - switch (settings.name) { - case '/': - return new TestRoute( - settings: settings, - child: new Builder( - key: insideKey, - builder: (BuildContext context) { - PageRoute route = ModalRoute.of(context); - return new Column( - children: [ - new TestTransition( - childFirstHalf: new Text('A'), - childSecondHalf: new Text('B'), - animation: route.animation - ), - new TestTransition( - childFirstHalf: new Text('C'), - childSecondHalf: new Text('D'), - animation: route.forwardAnimation - ), - ] - ); - } - ) - ); - case '/2': return new TestRoute(settings: settings, child: new Text('E')); - case '/3': return new TestRoute (settings: settings, child: new Text('F')); - case '/4': return new TestRoute (settings: settings, child: new Text('G')); - } + tester.pumpWidget( + new MaterialApp( + onGenerateRoute: (RouteSettings settings) { + switch (settings.name) { + case '/': + return new TestRoute( + settings: settings, + child: new Builder( + key: insideKey, + builder: (BuildContext context) { + PageRoute route = ModalRoute.of(context); + return new Column( + children: [ + new TestTransition( + childFirstHalf: new Text('A'), + childSecondHalf: new Text('B'), + animation: route.animation + ), + new TestTransition( + childFirstHalf: new Text('C'), + childSecondHalf: new Text('D'), + animation: route.forwardAnimation + ), + ] + ); + } + ) + ); + case '/2': return new TestRoute(settings: settings, child: new Text('E')); + case '/3': return new TestRoute (settings: settings, child: new Text('F')); + case '/4': return new TestRoute (settings: settings, child: new Text('G')); } - ) - ); + } + ) + ); - NavigatorState navigator = insideKey.currentContext.ancestorStateOfType(const TypeMatcher()); + NavigatorState navigator = insideKey.currentContext.ancestorStateOfType(const TypeMatcher()); - expect(state(), equals('BC')); // transition ->1 is at 1.0 + expect(state(), equals('BC')); // transition ->1 is at 1.0 - navigator.openTransaction((NavigatorTransaction transaction) => transaction.pushNamed('/2')); - expect(state(), equals('BC')); // transition 1->2 is not yet built - tester.pump(); - expect(state(), equals('BCE')); // transition 1->2 is at 0.0 + navigator.openTransaction((NavigatorTransaction transaction) => transaction.pushNamed('/2')); + expect(state(), equals('BC')); // transition 1->2 is not yet built + tester.pump(); + expect(state(), equals('BCE')); // transition 1->2 is at 0.0 - tester.pump(kFourTenthsOfTheTransitionDuration); - expect(state(), equals('BCE')); // transition 1->2 is at 0.4 + tester.pump(kFourTenthsOfTheTransitionDuration); + expect(state(), equals('BCE')); // transition 1->2 is at 0.4 - tester.pump(kFourTenthsOfTheTransitionDuration); - expect(state(), equals('BDE')); // transition 1->2 is at 0.8 + tester.pump(kFourTenthsOfTheTransitionDuration); + expect(state(), equals('BDE')); // transition 1->2 is at 0.8 - tester.pump(kFourTenthsOfTheTransitionDuration); - expect(state(), equals('E')); // transition 1->2 is at 1.0 + tester.pump(kFourTenthsOfTheTransitionDuration); + expect(state(), equals('E')); // transition 1->2 is at 1.0 - navigator.openTransaction((NavigatorTransaction transaction) => transaction.pop()); - expect(state(), equals('E')); // transition 1<-2 is at 1.0, just reversed - tester.pump(); - expect(state(), equals('BDE')); // transition 1<-2 is at 1.0 + navigator.openTransaction((NavigatorTransaction transaction) => transaction.pop()); + expect(state(), equals('E')); // transition 1<-2 is at 1.0, just reversed + tester.pump(); + expect(state(), equals('BDE')); // transition 1<-2 is at 1.0 - tester.pump(kFourTenthsOfTheTransitionDuration); - expect(state(), equals('BDE')); // transition 1<-2 is at 0.6 + tester.pump(kFourTenthsOfTheTransitionDuration); + expect(state(), equals('BDE')); // transition 1<-2 is at 0.6 - navigator.openTransaction((NavigatorTransaction transaction) => transaction.pushNamed('/3')); - expect(state(), equals('BDE')); // transition 1<-2 is at 0.6 - tester.pump(); - expect(state(), equals('BDEF')); // transition 1<-2 is at 0.6, 1->3 is at 0.0 + navigator.openTransaction((NavigatorTransaction transaction) => transaction.pushNamed('/3')); + expect(state(), equals('BDE')); // transition 1<-2 is at 0.6 + tester.pump(); + expect(state(), equals('BDEF')); // transition 1<-2 is at 0.6, 1->3 is at 0.0 - tester.pump(kFourTenthsOfTheTransitionDuration); - expect(state(), equals('BCEF')); // transition 1<-2 is at 0.2, 1->3 is at 0.4 + tester.pump(kFourTenthsOfTheTransitionDuration); + expect(state(), equals('BCEF')); // transition 1<-2 is at 0.2, 1->3 is at 0.4 - tester.pump(kFourTenthsOfTheTransitionDuration); - expect(state(), equals('BDF')); // transition 1<-2 is done, 1->3 is at 0.8 + tester.pump(kFourTenthsOfTheTransitionDuration); + expect(state(), equals('BDF')); // transition 1<-2 is done, 1->3 is at 0.8 - navigator.openTransaction((NavigatorTransaction transaction) => transaction.pop()); - expect(state(), equals('BDF')); // transition 1<-3 is at 0.8, just reversed - tester.pump(); - expect(state(), equals('BDF')); // transition 1<-3 is at 0.8 + navigator.openTransaction((NavigatorTransaction transaction) => transaction.pop()); + expect(state(), equals('BDF')); // transition 1<-3 is at 0.8, just reversed + tester.pump(); + expect(state(), equals('BDF')); // transition 1<-3 is at 0.8 - tester.pump(kTwoTenthsOfTheTransitionDuration); // notice that dT=0.2 here, not 0.4 - expect(state(), equals('BDF')); // transition 1<-3 is at 0.6 + tester.pump(kTwoTenthsOfTheTransitionDuration); // notice that dT=0.2 here, not 0.4 + expect(state(), equals('BDF')); // transition 1<-3 is at 0.6 - tester.pump(kFourTenthsOfTheTransitionDuration); - expect(state(), equals('BCF')); // transition 1<-3 is at 0.2 + tester.pump(kFourTenthsOfTheTransitionDuration); + expect(state(), equals('BCF')); // transition 1<-3 is at 0.2 - navigator.openTransaction((NavigatorTransaction transaction) => transaction.pushNamed('/4')); - expect(state(), equals('BCF')); // transition 1<-3 is at 0.2, 1->4 is not yet built - tester.pump(); - expect(state(), equals('BCFG')); // transition 1<-3 is at 0.2, 1->4 is at 0.0 + navigator.openTransaction((NavigatorTransaction transaction) => transaction.pushNamed('/4')); + expect(state(), equals('BCF')); // transition 1<-3 is at 0.2, 1->4 is not yet built + tester.pump(); + expect(state(), equals('BCFG')); // transition 1<-3 is at 0.2, 1->4 is at 0.0 - tester.pump(kFourTenthsOfTheTransitionDuration); - expect(state(), equals('BCG')); // transition 1<-3 is done, 1->4 is at 0.4 + tester.pump(kFourTenthsOfTheTransitionDuration); + expect(state(), equals('BCG')); // transition 1<-3 is done, 1->4 is at 0.4 - tester.pump(kFourTenthsOfTheTransitionDuration); - expect(state(), equals('BDG')); // transition 1->4 is at 0.8 + tester.pump(kFourTenthsOfTheTransitionDuration); + expect(state(), equals('BDG')); // transition 1->4 is at 0.8 - tester.pump(kFourTenthsOfTheTransitionDuration); - expect(state(), equals('G')); // transition 1->4 is done + tester.pump(kFourTenthsOfTheTransitionDuration); + expect(state(), equals('G')); // transition 1->4 is done - }); }); } diff --git a/packages/flutter/test/widget/page_transitions_test.dart b/packages/flutter/test/widget/page_transitions_test.dart index 8a5c77bd06..3f2b1d6cbb 100644 --- a/packages/flutter/test/widget/page_transitions_test.dart +++ b/packages/flutter/test/widget/page_transitions_test.dart @@ -6,8 +6,6 @@ import 'package:flutter_test/flutter_test.dart'; import 'package:flutter/material.dart'; import 'package:test/test.dart'; -import 'test_matchers.dart'; - class TestOverlayRoute extends OverlayRoute { @override List get builders => [ _build ]; @@ -15,87 +13,85 @@ class TestOverlayRoute extends OverlayRoute { } void main() { - test('Check onstage/offstage handling around transitions', () { - testWidgets((WidgetTester tester) { - GlobalKey containerKey1 = new GlobalKey(); - GlobalKey containerKey2 = new GlobalKey(); - final Map routes = { - '/': (_) => new Container(key: containerKey1, child: new Text('Home')), - '/settings': (_) => new Container(key: containerKey2, child: new Text('Settings')), - }; + testWidgets('Check onstage/offstage handling around transitions', (WidgetTester tester) { + GlobalKey containerKey1 = new GlobalKey(); + GlobalKey containerKey2 = new GlobalKey(); + final Map routes = { + '/': (_) => new Container(key: containerKey1, child: new Text('Home')), + '/settings': (_) => new Container(key: containerKey2, child: new Text('Settings')), + }; - tester.pumpWidget(new MaterialApp(routes: routes)); + tester.pumpWidget(new MaterialApp(routes: routes)); - expect(find.text('Home'), isOnStage(tester)); - expect(tester, doesNotHaveWidget(find.text('Settings'))); - expect(tester, doesNotHaveWidget(find.text('Overlay'))); + expect(find.text('Home'), isOnStage); + expect(find.text('Settings'), findsNothing); + expect(find.text('Overlay'), findsNothing); - expect(Navigator.canPop(containerKey1.currentContext), isFalse); - Navigator.pushNamed(containerKey1.currentContext, '/settings'); - expect(Navigator.canPop(containerKey1.currentContext), isTrue); + expect(Navigator.canPop(containerKey1.currentContext), isFalse); + Navigator.pushNamed(containerKey1.currentContext, '/settings'); + expect(Navigator.canPop(containerKey1.currentContext), isTrue); - tester.pump(); + tester.pump(); - expect(find.text('Home'), isOnStage(tester)); - expect(find.text('Settings'), isOffStage(tester)); - expect(tester, doesNotHaveWidget(find.text('Overlay'))); + expect(find.text('Home'), isOnStage); + expect(find.text('Settings'), isOffStage); + expect(find.text('Overlay'), findsNothing); - tester.pump(const Duration(milliseconds: 16)); + tester.pump(const Duration(milliseconds: 16)); - expect(find.text('Home'), isOnStage(tester)); - expect(find.text('Settings'), isOnStage(tester)); - expect(tester, doesNotHaveWidget(find.text('Overlay'))); + expect(find.text('Home'), isOnStage); + expect(find.text('Settings'), isOnStage); + expect(find.text('Overlay'), findsNothing); - tester.pump(const Duration(seconds: 1)); + tester.pump(const Duration(seconds: 1)); - expect(tester, doesNotHaveWidget(find.text('Home'))); - expect(find.text('Settings'), isOnStage(tester)); - expect(tester, doesNotHaveWidget(find.text('Overlay'))); + expect(find.text('Home'), findsNothing); + expect(find.text('Settings'), isOnStage); + expect(find.text('Overlay'), findsNothing); - Navigator.push(containerKey2.currentContext, new TestOverlayRoute()); + Navigator.push(containerKey2.currentContext, new TestOverlayRoute()); - tester.pump(); + tester.pump(); - expect(tester, doesNotHaveWidget(find.text('Home'))); - expect(find.text('Settings'), isOnStage(tester)); - expect(find.text('Overlay'), isOnStage(tester)); + expect(find.text('Home'), findsNothing); + expect(find.text('Settings'), isOnStage); + expect(find.text('Overlay'), isOnStage); - tester.pump(const Duration(seconds: 1)); + tester.pump(const Duration(seconds: 1)); - expect(tester, doesNotHaveWidget(find.text('Home'))); - expect(find.text('Settings'), isOnStage(tester)); - expect(find.text('Overlay'), isOnStage(tester)); + expect(find.text('Home'), findsNothing); + expect(find.text('Settings'), isOnStage); + expect(find.text('Overlay'), isOnStage); - expect(Navigator.canPop(containerKey2.currentContext), isTrue); - Navigator.pop(containerKey2.currentContext); - tester.pump(); + expect(Navigator.canPop(containerKey2.currentContext), isTrue); + Navigator.pop(containerKey2.currentContext); + tester.pump(); - expect(tester, doesNotHaveWidget(find.text('Home'))); - expect(find.text('Settings'), isOnStage(tester)); - expect(tester, doesNotHaveWidget(find.text('Overlay'))); + expect(find.text('Home'), findsNothing); + expect(find.text('Settings'), isOnStage); + expect(find.text('Overlay'), findsNothing); - tester.pump(const Duration(seconds: 1)); + tester.pump(const Duration(seconds: 1)); - expect(tester, doesNotHaveWidget(find.text('Home'))); - expect(find.text('Settings'), isOnStage(tester)); - expect(tester, doesNotHaveWidget(find.text('Overlay'))); + expect(find.text('Home'), findsNothing); + expect(find.text('Settings'), isOnStage); + expect(find.text('Overlay'), findsNothing); - expect(Navigator.canPop(containerKey2.currentContext), isTrue); - Navigator.pop(containerKey2.currentContext); - tester.pump(); + expect(Navigator.canPop(containerKey2.currentContext), isTrue); + Navigator.pop(containerKey2.currentContext); + tester.pump(); - expect(find.text('Home'), isOnStage(tester)); - expect(find.text('Settings'), isOnStage(tester)); - expect(tester, doesNotHaveWidget(find.text('Overlay'))); + expect(find.text('Home'), isOnStage); + expect(find.text('Settings'), isOnStage); + expect(find.text('Overlay'), findsNothing); - tester.pump(const Duration(seconds: 1)); + tester.pump(const Duration(seconds: 1)); - expect(find.text('Home'), isOnStage(tester)); - expect(tester, doesNotHaveWidget(find.text('Settings'))); - expect(tester, doesNotHaveWidget(find.text('Overlay'))); + expect(find.text('Home'), isOnStage); + expect(find.text('Settings'), findsNothing); + expect(find.text('Overlay'), findsNothing); - expect(Navigator.canPop(containerKey1.currentContext), isFalse); + expect(Navigator.canPop(containerKey1.currentContext), isFalse); - }); }); } diff --git a/packages/flutter/test/widget/pageable_list_test.dart b/packages/flutter/test/widget/pageable_list_test.dart index 42ea759451..1d80590892 100644 --- a/packages/flutter/test/widget/pageable_list_test.dart +++ b/packages/flutter/test/widget/pageable_list_test.dart @@ -59,195 +59,179 @@ void pageRight(WidgetTester tester) { } void main() { - test('PageableList with itemsWrap: false', () { - testWidgets((WidgetTester tester) { - currentPage = null; - tester.pumpWidget(buildFrame()); - expect(currentPage, isNull); - pageLeft(tester); - expect(currentPage, equals(1)); + testWidgets('PageableList with itemsWrap: false', (WidgetTester tester) { + currentPage = null; + tester.pumpWidget(buildFrame()); + expect(currentPage, isNull); + pageLeft(tester); + expect(currentPage, equals(1)); - expect(tester, doesNotHaveWidget(find.text('0'))); - expect(tester, hasWidget(find.text('1'))); - expect(tester, doesNotHaveWidget(find.text('2'))); - expect(tester, doesNotHaveWidget(find.text('3'))); - expect(tester, doesNotHaveWidget(find.text('4'))); - expect(tester, doesNotHaveWidget(find.text('5'))); + expect(find.text('0'), findsNothing); + expect(find.text('1'), findsOneWidget); + expect(find.text('2'), findsNothing); + expect(find.text('3'), findsNothing); + expect(find.text('4'), findsNothing); + expect(find.text('5'), findsNothing); - pageRight(tester); - expect(currentPage, equals(0)); + pageRight(tester); + expect(currentPage, equals(0)); - expect(tester, hasWidget(find.text('0'))); - expect(tester, doesNotHaveWidget(find.text('1'))); - expect(tester, doesNotHaveWidget(find.text('2'))); - expect(tester, doesNotHaveWidget(find.text('3'))); - expect(tester, doesNotHaveWidget(find.text('4'))); - expect(tester, doesNotHaveWidget(find.text('5'))); + expect(find.text('0'), findsOneWidget); + expect(find.text('1'), findsNothing); + expect(find.text('2'), findsNothing); + expect(find.text('3'), findsNothing); + expect(find.text('4'), findsNothing); + expect(find.text('5'), findsNothing); - pageRight(tester); - expect(currentPage, equals(0)); - }); + pageRight(tester); + expect(currentPage, equals(0)); }); - test('PageableList with end scroll anchor', () { - testWidgets((WidgetTester tester) { - currentPage = 5; - tester.pumpWidget(buildFrame(scrollAnchor: ViewportAnchor.end)); - pageRight(tester); - expect(currentPage, equals(4)); + testWidgets('PageableList with end scroll anchor', (WidgetTester tester) { + currentPage = 5; + tester.pumpWidget(buildFrame(scrollAnchor: ViewportAnchor.end)); + pageRight(tester); + expect(currentPage, equals(4)); - expect(tester, doesNotHaveWidget(find.text('0'))); - expect(tester, doesNotHaveWidget(find.text('1'))); - expect(tester, doesNotHaveWidget(find.text('2'))); - expect(tester, doesNotHaveWidget(find.text('3'))); - expect(tester, hasWidget(find.text('4'))); - expect(tester, doesNotHaveWidget(find.text('5'))); + expect(find.text('0'), findsNothing); + expect(find.text('1'), findsNothing); + expect(find.text('2'), findsNothing); + expect(find.text('3'), findsNothing); + expect(find.text('4'), findsOneWidget); + expect(find.text('5'), findsNothing); - pageLeft(tester); - expect(currentPage, equals(5)); + pageLeft(tester); + expect(currentPage, equals(5)); - expect(tester, doesNotHaveWidget(find.text('0'))); - expect(tester, doesNotHaveWidget(find.text('1'))); - expect(tester, doesNotHaveWidget(find.text('2'))); - expect(tester, doesNotHaveWidget(find.text('3'))); - expect(tester, doesNotHaveWidget(find.text('4'))); - expect(tester, hasWidget(find.text('5'))); + expect(find.text('0'), findsNothing); + expect(find.text('1'), findsNothing); + expect(find.text('2'), findsNothing); + expect(find.text('3'), findsNothing); + expect(find.text('4'), findsNothing); + expect(find.text('5'), findsOneWidget); - pageLeft(tester); - expect(currentPage, equals(5)); + pageLeft(tester); + expect(currentPage, equals(5)); - expect(tester, doesNotHaveWidget(find.text('0'))); - expect(tester, doesNotHaveWidget(find.text('1'))); - expect(tester, doesNotHaveWidget(find.text('2'))); - expect(tester, doesNotHaveWidget(find.text('3'))); - expect(tester, doesNotHaveWidget(find.text('4'))); - expect(tester, hasWidget(find.text('5'))); - }); + expect(find.text('0'), findsNothing); + expect(find.text('1'), findsNothing); + expect(find.text('2'), findsNothing); + expect(find.text('3'), findsNothing); + expect(find.text('4'), findsNothing); + expect(find.text('5'), findsOneWidget); }); - test('PageableList with itemsWrap: true', () { - testWidgets((WidgetTester tester) { - currentPage = null; - tester.pumpWidget(buildFrame(itemsWrap: true)); - expect(currentPage, isNull); - pageLeft(tester); - expect(currentPage, equals(1)); - pageRight(tester); - expect(currentPage, equals(0)); - pageRight(tester); - expect(currentPage, equals(5)); - }); + testWidgets('PageableList with itemsWrap: true', (WidgetTester tester) { + currentPage = null; + tester.pumpWidget(buildFrame(itemsWrap: true)); + expect(currentPage, isNull); + pageLeft(tester); + expect(currentPage, equals(1)); + pageRight(tester); + expect(currentPage, equals(0)); + pageRight(tester); + expect(currentPage, equals(5)); }); - test('PageableList with end and itemsWrap: true', () { - testWidgets((WidgetTester tester) { - currentPage = 5; - tester.pumpWidget(buildFrame(itemsWrap: true, scrollAnchor: ViewportAnchor.end)); - pageRight(tester); - expect(currentPage, equals(4)); + testWidgets('PageableList with end and itemsWrap: true', (WidgetTester tester) { + currentPage = 5; + tester.pumpWidget(buildFrame(itemsWrap: true, scrollAnchor: ViewportAnchor.end)); + pageRight(tester); + expect(currentPage, equals(4)); - expect(tester, doesNotHaveWidget(find.text('0'))); - expect(tester, doesNotHaveWidget(find.text('1'))); - expect(tester, doesNotHaveWidget(find.text('2'))); - expect(tester, doesNotHaveWidget(find.text('3'))); - expect(tester, hasWidget(find.text('4'))); - expect(tester, doesNotHaveWidget(find.text('5'))); + expect(find.text('0'), findsNothing); + expect(find.text('1'), findsNothing); + expect(find.text('2'), findsNothing); + expect(find.text('3'), findsNothing); + expect(find.text('4'), findsOneWidget); + expect(find.text('5'), findsNothing); - pageLeft(tester); - expect(currentPage, equals(5)); + pageLeft(tester); + expect(currentPage, equals(5)); - expect(tester, doesNotHaveWidget(find.text('0'))); - expect(tester, doesNotHaveWidget(find.text('1'))); - expect(tester, doesNotHaveWidget(find.text('2'))); - expect(tester, doesNotHaveWidget(find.text('3'))); - expect(tester, doesNotHaveWidget(find.text('4'))); - expect(tester, hasWidget(find.text('5'))); + expect(find.text('0'), findsNothing); + expect(find.text('1'), findsNothing); + expect(find.text('2'), findsNothing); + expect(find.text('3'), findsNothing); + expect(find.text('4'), findsNothing); + expect(find.text('5'), findsOneWidget); - pageLeft(tester); - expect(currentPage, equals(0)); + pageLeft(tester); + expect(currentPage, equals(0)); - expect(tester, hasWidget(find.text('0'))); - expect(tester, doesNotHaveWidget(find.text('1'))); - expect(tester, doesNotHaveWidget(find.text('2'))); - expect(tester, doesNotHaveWidget(find.text('3'))); - expect(tester, doesNotHaveWidget(find.text('4'))); - expect(tester, doesNotHaveWidget(find.text('5'))); + expect(find.text('0'), findsOneWidget); + expect(find.text('1'), findsNothing); + expect(find.text('2'), findsNothing); + expect(find.text('3'), findsNothing); + expect(find.text('4'), findsNothing); + expect(find.text('5'), findsNothing); - pageLeft(tester); - expect(currentPage, equals(1)); + pageLeft(tester); + expect(currentPage, equals(1)); - expect(tester, doesNotHaveWidget(find.text('0'))); - expect(tester, hasWidget(find.text('1'))); - expect(tester, doesNotHaveWidget(find.text('2'))); - expect(tester, doesNotHaveWidget(find.text('3'))); - expect(tester, doesNotHaveWidget(find.text('4'))); - expect(tester, doesNotHaveWidget(find.text('5'))); - }); + expect(find.text('0'), findsNothing); + expect(find.text('1'), findsOneWidget); + expect(find.text('2'), findsNothing); + expect(find.text('3'), findsNothing); + expect(find.text('4'), findsNothing); + expect(find.text('5'), findsNothing); }); - test('PageableList with two items', () { - testWidgets((WidgetTester tester) { - currentPage = null; - tester.pumpWidget(buildFrame(itemsWrap: true, pages: [0, 1])); - expect(currentPage, isNull); - pageLeft(tester); - expect(currentPage, equals(1)); - pageRight(tester); - expect(currentPage, equals(0)); - pageRight(tester); - expect(currentPage, equals(1)); - }); + testWidgets('PageableList with two items', (WidgetTester tester) { + currentPage = null; + tester.pumpWidget(buildFrame(itemsWrap: true, pages: [0, 1])); + expect(currentPage, isNull); + pageLeft(tester); + expect(currentPage, equals(1)); + pageRight(tester); + expect(currentPage, equals(0)); + pageRight(tester); + expect(currentPage, equals(1)); }); - test('PageableList with one item', () { - testWidgets((WidgetTester tester) { - currentPage = null; - tester.pumpWidget(buildFrame(itemsWrap: true, pages: [0])); - expect(currentPage, isNull); - pageLeft(tester); - expect(currentPage, equals(0)); - pageRight(tester); - expect(currentPage, equals(0)); - pageRight(tester); - expect(currentPage, equals(0)); - }); + testWidgets('PageableList with one item', (WidgetTester tester) { + currentPage = null; + tester.pumpWidget(buildFrame(itemsWrap: true, pages: [0])); + expect(currentPage, isNull); + pageLeft(tester); + expect(currentPage, equals(0)); + pageRight(tester); + expect(currentPage, equals(0)); + pageRight(tester); + expect(currentPage, equals(0)); }); - test('PageableList with no items', () { - testWidgets((WidgetTester tester) { - currentPage = null; - tester.pumpWidget(buildFrame(itemsWrap: true, pages: [])); - expect(currentPage, isNull); - }); + testWidgets('PageableList with no items', (WidgetTester tester) { + currentPage = null; + tester.pumpWidget(buildFrame(itemsWrap: true, pages: [])); + expect(currentPage, isNull); }); - test('PageableList resize parent', () { - testWidgets((WidgetTester tester) { - tester.pumpWidget(new Container()); - currentPage = null; + testWidgets('PageableList resize parent', (WidgetTester tester) { + tester.pumpWidget(new Container()); + currentPage = null; - tester.pumpWidget(buildFrame(itemsWrap: true)); - expect(currentPage, isNull); - pageRight(tester); - expect(currentPage, equals(5)); + tester.pumpWidget(buildFrame(itemsWrap: true)); + expect(currentPage, isNull); + pageRight(tester); + expect(currentPage, equals(5)); - RenderBox box = globalKeys[5].currentContext.findRenderObject(); - expect(box.size.width, equals(pageSize.width)); - expect(box.size.height, equals(pageSize.height)); + RenderBox box = globalKeys[5].currentContext.findRenderObject(); + expect(box.size.width, equals(pageSize.width)); + expect(box.size.height, equals(pageSize.height)); - pageSize = new Size(pageSize.height, pageSize.width); - tester.pumpWidget(buildFrame(itemsWrap: true)); + pageSize = new Size(pageSize.height, pageSize.width); + tester.pumpWidget(buildFrame(itemsWrap: true)); - expect(tester, doesNotHaveWidget(find.text('0'))); - expect(tester, doesNotHaveWidget(find.text('1'))); - expect(tester, doesNotHaveWidget(find.text('2'))); - expect(tester, doesNotHaveWidget(find.text('3'))); - expect(tester, doesNotHaveWidget(find.text('4'))); - expect(tester, hasWidget(find.text('5'))); + expect(find.text('0'), findsNothing); + expect(find.text('1'), findsNothing); + expect(find.text('2'), findsNothing); + expect(find.text('3'), findsNothing); + expect(find.text('4'), findsNothing); + expect(find.text('5'), findsOneWidget); - box = globalKeys[5].currentContext.findRenderObject(); - expect(box.size.width, equals(pageSize.width)); - expect(box.size.height, equals(pageSize.height)); - }); + box = globalKeys[5].currentContext.findRenderObject(); + expect(box.size.width, equals(pageSize.width)); + expect(box.size.height, equals(pageSize.height)); }); } diff --git a/packages/flutter/test/widget/parent_data_test.dart b/packages/flutter/test/widget/parent_data_test.dart index 956371ab80..8006ecfa57 100644 --- a/packages/flutter/test/widget/parent_data_test.dart +++ b/packages/flutter/test/widget/parent_data_test.dart @@ -19,7 +19,7 @@ class TestParentData { } void checkTree(WidgetTester tester, List expectedParentData) { - MultiChildRenderObjectElement element = tester.elementOf( + MultiChildRenderObjectElement element = tester.element( find.byElementPredicate((Element element) => element is MultiChildRenderObjectElement) ); expect(element, isNotNull); @@ -49,301 +49,295 @@ void checkTree(WidgetTester tester, List expectedParentData) { final TestParentData kNonPositioned = new TestParentData(); void main() { - test('ParentDataWidget control test', () { - testWidgets((WidgetTester tester) { + testWidgets('ParentDataWidget control test', (WidgetTester tester) { - tester.pumpWidget( - new Stack( - children: [ - new DecoratedBox(decoration: kBoxDecorationA), - new Positioned( - top: 10.0, - left: 10.0, - child: new DecoratedBox(decoration: kBoxDecorationB) - ), - new DecoratedBox(decoration: kBoxDecorationC), - ] - ) - ); + tester.pumpWidget( + new Stack( + children: [ + new DecoratedBox(decoration: kBoxDecorationA), + new Positioned( + top: 10.0, + left: 10.0, + child: new DecoratedBox(decoration: kBoxDecorationB) + ), + new DecoratedBox(decoration: kBoxDecorationC), + ] + ) + ); - checkTree(tester, [ - kNonPositioned, - new TestParentData(top: 10.0, left: 10.0), - kNonPositioned, - ]); + checkTree(tester, [ + kNonPositioned, + new TestParentData(top: 10.0, left: 10.0), + kNonPositioned, + ]); - tester.pumpWidget( - new Stack( - children: [ - new Positioned( - bottom: 5.0, - right: 7.0, - child: new DecoratedBox(decoration: kBoxDecorationA) - ), - new Positioned( - top: 10.0, - left: 10.0, - child: new DecoratedBox(decoration: kBoxDecorationB) - ), - new DecoratedBox(decoration: kBoxDecorationC), - ] - ) - ); + tester.pumpWidget( + new Stack( + children: [ + new Positioned( + bottom: 5.0, + right: 7.0, + child: new DecoratedBox(decoration: kBoxDecorationA) + ), + new Positioned( + top: 10.0, + left: 10.0, + child: new DecoratedBox(decoration: kBoxDecorationB) + ), + new DecoratedBox(decoration: kBoxDecorationC), + ] + ) + ); - checkTree(tester, [ - new TestParentData(bottom: 5.0, right: 7.0), - new TestParentData(top: 10.0, left: 10.0), - kNonPositioned, - ]); + checkTree(tester, [ + new TestParentData(bottom: 5.0, right: 7.0), + new TestParentData(top: 10.0, left: 10.0), + kNonPositioned, + ]); - DecoratedBox kDecoratedBoxA = new DecoratedBox(decoration: kBoxDecorationA); - DecoratedBox kDecoratedBoxB = new DecoratedBox(decoration: kBoxDecorationB); - DecoratedBox kDecoratedBoxC = new DecoratedBox(decoration: kBoxDecorationC); + DecoratedBox kDecoratedBoxA = new DecoratedBox(decoration: kBoxDecorationA); + DecoratedBox kDecoratedBoxB = new DecoratedBox(decoration: kBoxDecorationB); + DecoratedBox kDecoratedBoxC = new DecoratedBox(decoration: kBoxDecorationC); - tester.pumpWidget( - new Stack( - children: [ - new Positioned( - bottom: 5.0, - right: 7.0, - child: kDecoratedBoxA - ), - new Positioned( - top: 10.0, - left: 10.0, - child: kDecoratedBoxB - ), - kDecoratedBoxC, - ] - ) - ); + tester.pumpWidget( + new Stack( + children: [ + new Positioned( + bottom: 5.0, + right: 7.0, + child: kDecoratedBoxA + ), + new Positioned( + top: 10.0, + left: 10.0, + child: kDecoratedBoxB + ), + kDecoratedBoxC, + ] + ) + ); - checkTree(tester, [ - new TestParentData(bottom: 5.0, right: 7.0), - new TestParentData(top: 10.0, left: 10.0), - kNonPositioned, - ]); + checkTree(tester, [ + new TestParentData(bottom: 5.0, right: 7.0), + new TestParentData(top: 10.0, left: 10.0), + kNonPositioned, + ]); - tester.pumpWidget( - new Stack( - children: [ - new Positioned( - bottom: 6.0, - right: 8.0, - child: kDecoratedBoxA - ), - new Positioned( - left: 10.0, - right: 10.0, - child: kDecoratedBoxB - ), - kDecoratedBoxC, - ] - ) - ); + tester.pumpWidget( + new Stack( + children: [ + new Positioned( + bottom: 6.0, + right: 8.0, + child: kDecoratedBoxA + ), + new Positioned( + left: 10.0, + right: 10.0, + child: kDecoratedBoxB + ), + kDecoratedBoxC, + ] + ) + ); - checkTree(tester, [ - new TestParentData(bottom: 6.0, right: 8.0), - new TestParentData(left: 10.0, right: 10.0), - kNonPositioned, - ]); + checkTree(tester, [ + new TestParentData(bottom: 6.0, right: 8.0), + new TestParentData(left: 10.0, right: 10.0), + kNonPositioned, + ]); - tester.pumpWidget( - new Stack( - children: [ - kDecoratedBoxA, - new Positioned( - left: 11.0, - right: 12.0, - child: new Container(child: kDecoratedBoxB) - ), - kDecoratedBoxC, - ] - ) - ); + tester.pumpWidget( + new Stack( + children: [ + kDecoratedBoxA, + new Positioned( + left: 11.0, + right: 12.0, + child: new Container(child: kDecoratedBoxB) + ), + kDecoratedBoxC, + ] + ) + ); - checkTree(tester, [ - kNonPositioned, - new TestParentData(left: 11.0, right: 12.0), - kNonPositioned, - ]); + checkTree(tester, [ + kNonPositioned, + new TestParentData(left: 11.0, right: 12.0), + kNonPositioned, + ]); - tester.pumpWidget( - new Stack( - children: [ - kDecoratedBoxA, - new Positioned( - right: 10.0, - child: new Container(child: kDecoratedBoxB) - ), - new Container( - child: new Positioned( - top: 8.0, - child: kDecoratedBoxC - ) + tester.pumpWidget( + new Stack( + children: [ + kDecoratedBoxA, + new Positioned( + right: 10.0, + child: new Container(child: kDecoratedBoxB) + ), + new Container( + child: new Positioned( + top: 8.0, + child: kDecoratedBoxC ) - ] - ) - ); - - checkTree(tester, [ - kNonPositioned, - new TestParentData(right: 10.0), - new TestParentData(top: 8.0), - ]); - - tester.pumpWidget( - new Stack( - children: [ - new Positioned( - right: 10.0, - child: new FlipWidget(left: kDecoratedBoxA, right: kDecoratedBoxB) - ), - ] - ) - ); - - checkTree(tester, [ - new TestParentData(right: 10.0), - ]); - - flipStatefulWidget(tester); - tester.pump(); - - checkTree(tester, [ - new TestParentData(right: 10.0), - ]); - - tester.pumpWidget( - new Stack( - children: [ - new Positioned( - top: 7.0, - child: new FlipWidget(left: kDecoratedBoxA, right: kDecoratedBoxB) - ), - ] - ) - ); - - checkTree(tester, [ - new TestParentData(top: 7.0), - ]); - - flipStatefulWidget(tester); - tester.pump(); - - checkTree(tester, [ - new TestParentData(top: 7.0), - ]); - - tester.pumpWidget( - new Stack() - ); - - checkTree(tester, []); - }); - }); - - test('ParentDataWidget conflicting data', () { - testWidgets((WidgetTester tester) { - tester.pumpWidget( - new Stack( - children: [ - new Positioned( - top: 5.0, - bottom: 8.0, - child: new Positioned( - top: 6.0, - left: 7.0, - child: new DecoratedBox(decoration: kBoxDecorationB) - ) - ) - ] - ) - ); - expect(tester.takeException(), isNotNull); - - tester.pumpWidget(new Stack()); - - checkTree(tester, []); - - tester.pumpWidget( - new Container( - child: new Flex( - children: [ - new Positioned( - top: 6.0, - left: 7.0, - child: new DecoratedBox(decoration: kBoxDecorationB) - ) - ] ) - ) - ); - expect(tester.takeException(), isNotNull); + ] + ) + ); - tester.pumpWidget( - new Stack() - ); + checkTree(tester, [ + kNonPositioned, + new TestParentData(right: 10.0), + new TestParentData(top: 8.0), + ]); - checkTree(tester, []); - }); + tester.pumpWidget( + new Stack( + children: [ + new Positioned( + right: 10.0, + child: new FlipWidget(left: kDecoratedBoxA, right: kDecoratedBoxB) + ), + ] + ) + ); + + checkTree(tester, [ + new TestParentData(right: 10.0), + ]); + + flipStatefulWidget(tester); + tester.pump(); + + checkTree(tester, [ + new TestParentData(right: 10.0), + ]); + + tester.pumpWidget( + new Stack( + children: [ + new Positioned( + top: 7.0, + child: new FlipWidget(left: kDecoratedBoxA, right: kDecoratedBoxB) + ), + ] + ) + ); + + checkTree(tester, [ + new TestParentData(top: 7.0), + ]); + + flipStatefulWidget(tester); + tester.pump(); + + checkTree(tester, [ + new TestParentData(top: 7.0), + ]); + + tester.pumpWidget( + new Stack() + ); + + checkTree(tester, []); }); - test('ParentDataWidget interacts with global keys', () { - testWidgets((WidgetTester tester) { - GlobalKey key = new GlobalKey(); + testWidgets('ParentDataWidget conflicting data', (WidgetTester tester) { + tester.pumpWidget( + new Stack( + children: [ + new Positioned( + top: 5.0, + bottom: 8.0, + child: new Positioned( + top: 6.0, + left: 7.0, + child: new DecoratedBox(decoration: kBoxDecorationB) + ) + ) + ] + ) + ); + expect(tester.takeException(), isNotNull); - tester.pumpWidget( - new Stack( + tester.pumpWidget(new Stack()); + + checkTree(tester, []); + + tester.pumpWidget( + new Container( + child: new Flex( children: [ new Positioned( - top: 10.0, - left: 10.0, + top: 6.0, + left: 7.0, + child: new DecoratedBox(decoration: kBoxDecorationB) + ) + ] + ) + ) + ); + expect(tester.takeException(), isNotNull); + + tester.pumpWidget( + new Stack() + ); + + checkTree(tester, []); + }); + + testWidgets('ParentDataWidget interacts with global keys', (WidgetTester tester) { + GlobalKey key = new GlobalKey(); + + tester.pumpWidget( + new Stack( + children: [ + new Positioned( + top: 10.0, + left: 10.0, + child: new DecoratedBox(key: key, decoration: kBoxDecorationA) + ) + ] + ) + ); + + checkTree(tester, [ + new TestParentData(top: 10.0, left: 10.0), + ]); + + tester.pumpWidget( + new Stack( + children: [ + new Positioned( + top: 10.0, + left: 10.0, + child: new DecoratedBox( + decoration: kBoxDecorationB, child: new DecoratedBox(key: key, decoration: kBoxDecorationA) ) - ] - ) - ); + ) + ] + ) + ); - checkTree(tester, [ - new TestParentData(top: 10.0, left: 10.0), - ]); + checkTree(tester, [ + new TestParentData(top: 10.0, left: 10.0), + ]); - tester.pumpWidget( - new Stack( - children: [ - new Positioned( - top: 10.0, - left: 10.0, - child: new DecoratedBox( - decoration: kBoxDecorationB, - child: new DecoratedBox(key: key, decoration: kBoxDecorationA) - ) - ) - ] - ) - ); + tester.pumpWidget( + new Stack( + children: [ + new Positioned( + top: 10.0, + left: 10.0, + child: new DecoratedBox(key: key, decoration: kBoxDecorationA) + ) + ] + ) + ); - checkTree(tester, [ - new TestParentData(top: 10.0, left: 10.0), - ]); - - tester.pumpWidget( - new Stack( - children: [ - new Positioned( - top: 10.0, - left: 10.0, - child: new DecoratedBox(key: key, decoration: kBoxDecorationA) - ) - ] - ) - ); - - checkTree(tester, [ - new TestParentData(top: 10.0, left: 10.0), - ]); - }); + checkTree(tester, [ + new TestParentData(top: 10.0, left: 10.0), + ]); }); } diff --git a/packages/flutter/test/widget/positioned_test.dart b/packages/flutter/test/widget/positioned_test.dart index 57c075007b..e5e78d5eda 100644 --- a/packages/flutter/test/widget/positioned_test.dart +++ b/packages/flutter/test/widget/positioned_test.dart @@ -9,69 +9,67 @@ import 'package:test/test.dart'; void main() { - test('Can animate position data', () { - testWidgets((WidgetTester tester) { + testWidgets('Can animate position data', (WidgetTester tester) { - final RelativeRectTween rect = new RelativeRectTween( - begin: new RelativeRect.fromRect( - new Rect.fromLTRB(10.0, 20.0, 20.0, 30.0), - new Rect.fromLTRB(0.0, 10.0, 100.0, 110.0) - ), - end: new RelativeRect.fromRect( - new Rect.fromLTRB(80.0, 90.0, 90.0, 100.0), - new Rect.fromLTRB(0.0, 10.0, 100.0, 110.0) - ) - ); - final AnimationController controller = new AnimationController( - duration: const Duration(seconds: 10) - ); - final List sizes = []; - final List positions = []; - final GlobalKey key = new GlobalKey(); + final RelativeRectTween rect = new RelativeRectTween( + begin: new RelativeRect.fromRect( + new Rect.fromLTRB(10.0, 20.0, 20.0, 30.0), + new Rect.fromLTRB(0.0, 10.0, 100.0, 110.0) + ), + end: new RelativeRect.fromRect( + new Rect.fromLTRB(80.0, 90.0, 90.0, 100.0), + new Rect.fromLTRB(0.0, 10.0, 100.0, 110.0) + ) + ); + final AnimationController controller = new AnimationController( + duration: const Duration(seconds: 10) + ); + final List sizes = []; + final List positions = []; + final GlobalKey key = new GlobalKey(); - void recordMetrics() { - RenderBox box = key.currentContext.findRenderObject(); - BoxParentData boxParentData = box.parentData; - sizes.add(box.size); - positions.add(boxParentData.offset); - } + void recordMetrics() { + RenderBox box = key.currentContext.findRenderObject(); + BoxParentData boxParentData = box.parentData; + sizes.add(box.size); + positions.add(boxParentData.offset); + } - tester.pumpWidget( - new Center( - child: new Container( - height: 100.0, - width: 100.0, - child: new Stack( - children: [ - new PositionedTransition( - rect: rect.animate(controller), - child: new Container( - key: key - ) + tester.pumpWidget( + new Center( + child: new Container( + height: 100.0, + width: 100.0, + child: new Stack( + children: [ + new PositionedTransition( + rect: rect.animate(controller), + child: new Container( + key: key ) - ] - ) + ) + ] ) ) - ); // t=0 - recordMetrics(); - controller.forward(); - tester.pump(); // t=0 again - recordMetrics(); - tester.pump(const Duration(seconds: 1)); // t=1 - recordMetrics(); - tester.pump(const Duration(seconds: 1)); // t=2 - recordMetrics(); - tester.pump(const Duration(seconds: 3)); // t=5 - recordMetrics(); - tester.pump(const Duration(seconds: 5)); // t=10 - recordMetrics(); + ) + ); // t=0 + recordMetrics(); + controller.forward(); + tester.pump(); // t=0 again + recordMetrics(); + tester.pump(const Duration(seconds: 1)); // t=1 + recordMetrics(); + tester.pump(const Duration(seconds: 1)); // t=2 + recordMetrics(); + tester.pump(const Duration(seconds: 3)); // t=5 + recordMetrics(); + tester.pump(const Duration(seconds: 5)); // t=10 + recordMetrics(); - expect(sizes, equals([const Size(10.0, 10.0), const Size(10.0, 10.0), const Size(10.0, 10.0), const Size(10.0, 10.0), const Size(10.0, 10.0), const Size(10.0, 10.0)])); - expect(positions, equals([const Offset(10.0, 10.0), const Offset(10.0, 10.0), const Offset(17.0, 17.0), const Offset(24.0, 24.0), const Offset(45.0, 45.0), const Offset(80.0, 80.0)])); + expect(sizes, equals([const Size(10.0, 10.0), const Size(10.0, 10.0), const Size(10.0, 10.0), const Size(10.0, 10.0), const Size(10.0, 10.0), const Size(10.0, 10.0)])); + expect(positions, equals([const Offset(10.0, 10.0), const Offset(10.0, 10.0), const Offset(17.0, 17.0), const Offset(24.0, 24.0), const Offset(45.0, 45.0), const Offset(80.0, 80.0)])); - controller.stop(); - }); + controller.stop(); }); } diff --git a/packages/flutter/test/widget/raw_keyboard_listener_test.dart b/packages/flutter/test/widget/raw_keyboard_listener_test.dart index b0a05e10ef..b40b8c0d1d 100644 --- a/packages/flutter/test/widget/raw_keyboard_listener_test.dart +++ b/packages/flutter/test/widget/raw_keyboard_listener_test.dart @@ -4,13 +4,10 @@ import 'package:flutter_test/flutter_test.dart'; import 'package:flutter/widgets.dart'; -import 'package:test/test.dart'; void main() { - test('Can dispose without keyboard', () { - testWidgets((WidgetTester tester) { - tester.pumpWidget(new RawKeyboardListener(child: new Container())); - tester.pumpWidget(new Container()); - }); + testWidgets('Can dispose without keyboard', (WidgetTester tester) { + tester.pumpWidget(new RawKeyboardListener(child: new Container())); + tester.pumpWidget(new Container()); }); } diff --git a/packages/flutter/test/widget/remember_scroll_position_test.dart b/packages/flutter/test/widget/remember_scroll_position_test.dart index 159e21117d..cb94bef514 100644 --- a/packages/flutter/test/widget/remember_scroll_position_test.dart +++ b/packages/flutter/test/widget/remember_scroll_position_test.dart @@ -22,89 +22,87 @@ class ThePositiveNumbers extends StatelessWidget { } void main() { - test('whether we remember our scroll position', () { - testWidgets((WidgetTester tester) { - GlobalKey navigatorKey = new GlobalKey(); - tester.pumpWidget(new Navigator( - key: navigatorKey, - onGenerateRoute: (RouteSettings settings) { - if (settings.name == '/') - return new MaterialPageRoute(builder: (_) => new Container(child: new ThePositiveNumbers())); - else if (settings.name == '/second') - return new MaterialPageRoute(builder: (_) => new Container(child: new ThePositiveNumbers())); - return null; - } - )); + testWidgets('whether we remember our scroll position', (WidgetTester tester) { + GlobalKey navigatorKey = new GlobalKey(); + tester.pumpWidget(new Navigator( + key: navigatorKey, + onGenerateRoute: (RouteSettings settings) { + if (settings.name == '/') + return new MaterialPageRoute(builder: (_) => new Container(child: new ThePositiveNumbers())); + else if (settings.name == '/second') + return new MaterialPageRoute(builder: (_) => new Container(child: new ThePositiveNumbers())); + return null; + } + )); - // we're 600 pixels high, each item is 100 pixels high, scroll position is - // zero, so we should have exactly 6 items, 0..5. - expect(tester, hasWidget(find.text('0'))); - expect(tester, hasWidget(find.text('1'))); - expect(tester, hasWidget(find.text('2'))); - expect(tester, hasWidget(find.text('3'))); - expect(tester, hasWidget(find.text('4'))); - expect(tester, hasWidget(find.text('5'))); - expect(tester, doesNotHaveWidget(find.text('6'))); - expect(tester, doesNotHaveWidget(find.text('10'))); - expect(tester, doesNotHaveWidget(find.text('100'))); + // we're 600 pixels high, each item is 100 pixels high, scroll position is + // zero, so we should have exactly 6 items, 0..5. + expect(find.text('0'), findsOneWidget); + expect(find.text('1'), findsOneWidget); + expect(find.text('2'), findsOneWidget); + expect(find.text('3'), findsOneWidget); + expect(find.text('4'), findsOneWidget); + expect(find.text('5'), findsOneWidget); + expect(find.text('6'), findsNothing); + expect(find.text('10'), findsNothing); + expect(find.text('100'), findsNothing); - ScrollableState targetState = tester.stateOf(find.byType(ScrollableLazyList)); - targetState.scrollTo(1000.0); - tester.pump(new Duration(seconds: 1)); + ScrollableState targetState = tester.state(find.byType(ScrollableLazyList)); + targetState.scrollTo(1000.0); + tester.pump(new Duration(seconds: 1)); - // we're 600 pixels high, each item is 100 pixels high, scroll position is - // 1000, so we should have exactly 6 items, 10..15. + // we're 600 pixels high, each item is 100 pixels high, scroll position is + // 1000, so we should have exactly 6 items, 10..15. - expect(tester, doesNotHaveWidget(find.text('0'))); - expect(tester, doesNotHaveWidget(find.text('8'))); - expect(tester, doesNotHaveWidget(find.text('9'))); - expect(tester, hasWidget(find.text('10'))); - expect(tester, hasWidget(find.text('11'))); - expect(tester, hasWidget(find.text('12'))); - expect(tester, hasWidget(find.text('13'))); - expect(tester, hasWidget(find.text('14'))); - expect(tester, hasWidget(find.text('15'))); - expect(tester, doesNotHaveWidget(find.text('16'))); - expect(tester, doesNotHaveWidget(find.text('100'))); + expect(find.text('0'), findsNothing); + expect(find.text('8'), findsNothing); + expect(find.text('9'), findsNothing); + expect(find.text('10'), findsOneWidget); + expect(find.text('11'), findsOneWidget); + expect(find.text('12'), findsOneWidget); + expect(find.text('13'), findsOneWidget); + expect(find.text('14'), findsOneWidget); + expect(find.text('15'), findsOneWidget); + expect(find.text('16'), findsNothing); + expect(find.text('100'), findsNothing); - navigatorKey.currentState.openTransaction( - (NavigatorTransaction transaction) => transaction.pushNamed('/second') - ); - tester.pump(); // navigating always takes two frames - tester.pump(new Duration(seconds: 1)); + navigatorKey.currentState.openTransaction( + (NavigatorTransaction transaction) => transaction.pushNamed('/second') + ); + tester.pump(); // navigating always takes two frames + tester.pump(new Duration(seconds: 1)); - // same as the first list again - expect(tester, hasWidget(find.text('0'))); - expect(tester, hasWidget(find.text('1'))); - expect(tester, hasWidget(find.text('2'))); - expect(tester, hasWidget(find.text('3'))); - expect(tester, hasWidget(find.text('4'))); - expect(tester, hasWidget(find.text('5'))); - expect(tester, doesNotHaveWidget(find.text('6'))); - expect(tester, doesNotHaveWidget(find.text('10'))); - expect(tester, doesNotHaveWidget(find.text('100'))); + // same as the first list again + expect(find.text('0'), findsOneWidget); + expect(find.text('1'), findsOneWidget); + expect(find.text('2'), findsOneWidget); + expect(find.text('3'), findsOneWidget); + expect(find.text('4'), findsOneWidget); + expect(find.text('5'), findsOneWidget); + expect(find.text('6'), findsNothing); + expect(find.text('10'), findsNothing); + expect(find.text('100'), findsNothing); - navigatorKey.currentState.openTransaction( - (NavigatorTransaction transaction) => transaction.pop() - ); - tester.pump(); // navigating always takes two frames - tester.pump(new Duration(seconds: 1)); + navigatorKey.currentState.openTransaction( + (NavigatorTransaction transaction) => transaction.pop() + ); + tester.pump(); // navigating always takes two frames + tester.pump(new Duration(seconds: 1)); - // we're 600 pixels high, each item is 100 pixels high, scroll position is - // 1000, so we should have exactly 6 items, 10..15. + // we're 600 pixels high, each item is 100 pixels high, scroll position is + // 1000, so we should have exactly 6 items, 10..15. - expect(tester, doesNotHaveWidget(find.text('0'))); - expect(tester, doesNotHaveWidget(find.text('8'))); - expect(tester, doesNotHaveWidget(find.text('9'))); - expect(tester, hasWidget(find.text('10'))); - expect(tester, hasWidget(find.text('11'))); - expect(tester, hasWidget(find.text('12'))); - expect(tester, hasWidget(find.text('13'))); - expect(tester, hasWidget(find.text('14'))); - expect(tester, hasWidget(find.text('15'))); - expect(tester, doesNotHaveWidget(find.text('16'))); - expect(tester, doesNotHaveWidget(find.text('100'))); + expect(find.text('0'), findsNothing); + expect(find.text('8'), findsNothing); + expect(find.text('9'), findsNothing); + expect(find.text('10'), findsOneWidget); + expect(find.text('11'), findsOneWidget); + expect(find.text('12'), findsOneWidget); + expect(find.text('13'), findsOneWidget); + expect(find.text('14'), findsOneWidget); + expect(find.text('15'), findsOneWidget); + expect(find.text('16'), findsNothing); + expect(find.text('100'), findsNothing); - }); }); } diff --git a/packages/flutter/test/widget/render_object_widget_test.dart b/packages/flutter/test/widget/render_object_widget_test.dart index 4d1a725a66..a89dc07b63 100644 --- a/packages/flutter/test/widget/render_object_widget_test.dart +++ b/packages/flutter/test/widget/render_object_widget_test.dart @@ -42,178 +42,170 @@ class TestOrientedBox extends SingleChildRenderObjectWidget { } void main() { - test('RenderObjectWidget smoke test', () { - testElementTree((ElementTreeTester tester) { - tester.pumpWidget(new DecoratedBox(decoration: kBoxDecorationA)); + testWidgets('RenderObjectWidget smoke test', (WidgetTester tester) { + tester.pumpWidget(new DecoratedBox(decoration: kBoxDecorationA)); + SingleChildRenderObjectElement element = + tester.element(find.byElementType(SingleChildRenderObjectElement)); + expect(element, isNotNull); + expect(element.renderObject is RenderDecoratedBox, isTrue); + RenderDecoratedBox renderObject = element.renderObject; + expect(renderObject.decoration, equals(kBoxDecorationA)); + expect(renderObject.position, equals(DecorationPosition.background)); + + tester.pumpWidget(new DecoratedBox(decoration: kBoxDecorationB)); + element = tester.element(find.byElementType(SingleChildRenderObjectElement)); + expect(element, isNotNull); + expect(element.renderObject is RenderDecoratedBox, isTrue); + renderObject = element.renderObject; + expect(renderObject.decoration, equals(kBoxDecorationB)); + expect(renderObject.position, equals(DecorationPosition.background)); + }); + + testWidgets('RenderObjectWidget can add and remove children', (WidgetTester tester) { + + void checkFullTree() { SingleChildRenderObjectElement element = - tester.findElement((Element element) => element is SingleChildRenderObjectElement); + tester.firstElement(find.byElementType(SingleChildRenderObjectElement)); expect(element, isNotNull); expect(element.renderObject is RenderDecoratedBox, isTrue); RenderDecoratedBox renderObject = element.renderObject; expect(renderObject.decoration, equals(kBoxDecorationA)); expect(renderObject.position, equals(DecorationPosition.background)); + expect(renderObject.child, isNotNull); + expect(renderObject.child is RenderDecoratedBox, isTrue); + RenderDecoratedBox child = renderObject.child; + expect(child.decoration, equals(kBoxDecorationB)); + expect(child.position, equals(DecorationPosition.background)); + expect(child.child, isNull); + } - tester.pumpWidget(new DecoratedBox(decoration: kBoxDecorationB)); - element = tester.findElement((Element element) => element is SingleChildRenderObjectElement); + void childBareTree() { + SingleChildRenderObjectElement element = + tester.element(find.byElementType(SingleChildRenderObjectElement)); expect(element, isNotNull); expect(element.renderObject is RenderDecoratedBox, isTrue); - renderObject = element.renderObject; - expect(renderObject.decoration, equals(kBoxDecorationB)); + RenderDecoratedBox renderObject = element.renderObject; + expect(renderObject.decoration, equals(kBoxDecorationA)); expect(renderObject.position, equals(DecorationPosition.background)); - }); - }); + expect(renderObject.child, isNull); + } - test('RenderObjectWidget can add and remove children', () { - testElementTree((ElementTreeTester tester) { + tester.pumpWidget(new DecoratedBox( + decoration: kBoxDecorationA, + child: new DecoratedBox( + decoration: kBoxDecorationB + ) + )); - void checkFullTree() { - SingleChildRenderObjectElement element = - tester.findElement((Element element) => element is SingleChildRenderObjectElement); - expect(element, isNotNull); - expect(element.renderObject is RenderDecoratedBox, isTrue); - RenderDecoratedBox renderObject = element.renderObject; - expect(renderObject.decoration, equals(kBoxDecorationA)); - expect(renderObject.position, equals(DecorationPosition.background)); - expect(renderObject.child, isNotNull); - expect(renderObject.child is RenderDecoratedBox, isTrue); - RenderDecoratedBox child = renderObject.child; - expect(child.decoration, equals(kBoxDecorationB)); - expect(child.position, equals(DecorationPosition.background)); - expect(child.child, isNull); - } + checkFullTree(); - void childBareTree() { - SingleChildRenderObjectElement element = - tester.findElement((Element element) => element is SingleChildRenderObjectElement); - expect(element, isNotNull); - expect(element.renderObject is RenderDecoratedBox, isTrue); - RenderDecoratedBox renderObject = element.renderObject; - expect(renderObject.decoration, equals(kBoxDecorationA)); - expect(renderObject.position, equals(DecorationPosition.background)); - expect(renderObject.child, isNull); - } - - tester.pumpWidget(new DecoratedBox( - decoration: kBoxDecorationA, + tester.pumpWidget(new DecoratedBox( + decoration: kBoxDecorationA, + child: new TestWidget( child: new DecoratedBox( decoration: kBoxDecorationB ) - )); + ) + )); - checkFullTree(); + checkFullTree(); - tester.pumpWidget(new DecoratedBox( - decoration: kBoxDecorationA, + tester.pumpWidget(new DecoratedBox( + decoration: kBoxDecorationA, + child: new DecoratedBox( + decoration: kBoxDecorationB + ) + )); + + checkFullTree(); + + tester.pumpWidget(new DecoratedBox( + decoration: kBoxDecorationA + )); + + childBareTree(); + + tester.pumpWidget(new DecoratedBox( + decoration: kBoxDecorationA, + child: new TestWidget( child: new TestWidget( child: new DecoratedBox( decoration: kBoxDecorationB ) ) - )); + ) + )); - checkFullTree(); + checkFullTree(); - tester.pumpWidget(new DecoratedBox( - decoration: kBoxDecorationA, - child: new DecoratedBox( - decoration: kBoxDecorationB - ) - )); + tester.pumpWidget(new DecoratedBox( + decoration: kBoxDecorationA + )); - checkFullTree(); - - tester.pumpWidget(new DecoratedBox( - decoration: kBoxDecorationA - )); - - childBareTree(); - - tester.pumpWidget(new DecoratedBox( - decoration: kBoxDecorationA, - child: new TestWidget( - child: new TestWidget( - child: new DecoratedBox( - decoration: kBoxDecorationB - ) - ) - ) - )); - - checkFullTree(); - - tester.pumpWidget(new DecoratedBox( - decoration: kBoxDecorationA - )); - - childBareTree(); - }); + childBareTree(); }); - test('Detached render tree is intact', () { - testElementTree((ElementTreeTester tester) { + testWidgets('Detached render tree is intact', (WidgetTester tester) { - tester.pumpWidget(new DecoratedBox( - decoration: kBoxDecorationA, + tester.pumpWidget(new DecoratedBox( + decoration: kBoxDecorationA, + child: new DecoratedBox( + decoration: kBoxDecorationB, child: new DecoratedBox( - decoration: kBoxDecorationB, - child: new DecoratedBox( - decoration: kBoxDecorationC - ) + decoration: kBoxDecorationC ) - )); + ) + )); - SingleChildRenderObjectElement element = - tester.findElement((Element element) => element is SingleChildRenderObjectElement); - expect(element.renderObject is RenderDecoratedBox, isTrue); - RenderDecoratedBox parent = element.renderObject; - expect(parent.child is RenderDecoratedBox, isTrue); - RenderDecoratedBox child = parent.child; - expect(child.decoration, equals(kBoxDecorationB)); - expect(child.child is RenderDecoratedBox, isTrue); - RenderDecoratedBox grandChild = child.child; - expect(grandChild.decoration, equals(kBoxDecorationC)); - expect(grandChild.child, isNull); + SingleChildRenderObjectElement element = + tester.firstElement(find.byElementType(SingleChildRenderObjectElement)); + expect(element.renderObject is RenderDecoratedBox, isTrue); + RenderDecoratedBox parent = element.renderObject; + expect(parent.child is RenderDecoratedBox, isTrue); + RenderDecoratedBox child = parent.child; + expect(child.decoration, equals(kBoxDecorationB)); + expect(child.child is RenderDecoratedBox, isTrue); + RenderDecoratedBox grandChild = child.child; + expect(grandChild.decoration, equals(kBoxDecorationC)); + expect(grandChild.child, isNull); - tester.pumpWidget(new DecoratedBox( - decoration: kBoxDecorationA - )); + tester.pumpWidget(new DecoratedBox( + decoration: kBoxDecorationA + )); - element = - tester.findElement((Element element) => element is SingleChildRenderObjectElement); - expect(element.renderObject is RenderDecoratedBox, isTrue); - expect(element.renderObject, equals(parent)); - expect(parent.child, isNull); + element = + tester.element(find.byElementType(SingleChildRenderObjectElement)); + expect(element.renderObject is RenderDecoratedBox, isTrue); + expect(element.renderObject, equals(parent)); + expect(parent.child, isNull); - expect(child.parent, isNull); - expect(child.decoration, equals(kBoxDecorationB)); - expect(child.child, equals(grandChild)); - expect(grandChild.parent, equals(child)); - expect(grandChild.decoration, equals(kBoxDecorationC)); - expect(grandChild.child, isNull); - }); + expect(child.parent, isNull); + expect(child.decoration, equals(kBoxDecorationB)); + expect(child.child, equals(grandChild)); + expect(grandChild.parent, equals(child)); + expect(grandChild.decoration, equals(kBoxDecorationC)); + expect(grandChild.child, isNull); }); - test('Can watch inherited widgets', () { - testElementTree((ElementTreeTester tester) { - Key boxKey = new UniqueKey(); - TestOrientedBox box = new TestOrientedBox(key: boxKey); + testWidgets('Can watch inherited widgets', (WidgetTester tester) { + Key boxKey = new UniqueKey(); + TestOrientedBox box = new TestOrientedBox(key: boxKey); - tester.pumpWidget(new MediaQuery( - data: new MediaQueryData(size: const Size(400.0, 300.0)), - child: box - )); + tester.pumpWidget(new MediaQuery( + data: new MediaQueryData(size: const Size(400.0, 300.0)), + child: box + )); - RenderDecoratedBox renderBox = tester.findElementByKey(boxKey).renderObject; - BoxDecoration decoration = renderBox.decoration; - expect(decoration.backgroundColor, equals(new Color(0xFF00FF00))); + RenderDecoratedBox renderBox = tester.renderObject(find.byKey(boxKey)); + BoxDecoration decoration = renderBox.decoration; + expect(decoration.backgroundColor, equals(new Color(0xFF00FF00))); - tester.pumpWidget(new MediaQuery( - data: new MediaQueryData(size: const Size(300.0, 400.0)), - child: box - )); + tester.pumpWidget(new MediaQuery( + data: new MediaQueryData(size: const Size(300.0, 400.0)), + child: box + )); - decoration = renderBox.decoration; - expect(decoration.backgroundColor, equals(new Color(0xFF0000FF))); - }); + decoration = renderBox.decoration; + expect(decoration.backgroundColor, equals(new Color(0xFF0000FF))); }); } diff --git a/packages/flutter/test/widget/reparent_state_test.dart b/packages/flutter/test/widget/reparent_state_test.dart index 3ac68bcb85..bdc0a16208 100644 --- a/packages/flutter/test/widget/reparent_state_test.dart +++ b/packages/flutter/test/widget/reparent_state_test.dart @@ -50,294 +50,282 @@ class DeactivateLoggerState extends State { } void main() { - test('can reparent state', () { - testWidgets((WidgetTester tester) { - GlobalKey left = new GlobalKey(); - GlobalKey right = new GlobalKey(); + testWidgets('can reparent state', (WidgetTester tester) { + GlobalKey left = new GlobalKey(); + GlobalKey right = new GlobalKey(); - StateMarker grandchild = new StateMarker(); - tester.pumpWidget( - new Stack( - children: [ - new Container( - child: new StateMarker(key: left) - ), - new Container( - child: new StateMarker( - key: right, - child: grandchild - ) - ), - ] - ) - ); - - StateMarkerState leftState = left.currentState; - leftState.marker = "left"; - StateMarkerState rightState = right.currentState; - rightState.marker = "right"; - - StateMarkerState grandchildState = tester.stateOf(find.byConfig(grandchild)); - expect(grandchildState, isNotNull); - grandchildState.marker = "grandchild"; - - StateMarker newGrandchild = new StateMarker(); - tester.pumpWidget( - new Stack( - children: [ - new Container( - child: new StateMarker( - key: right, - child: newGrandchild - ) - ), - new Container( - child: new StateMarker(key: left) - ), - ] - ) - ); - - expect(left.currentState, equals(leftState)); - expect(leftState.marker, equals("left")); - expect(right.currentState, equals(rightState)); - expect(rightState.marker, equals("right")); - - StateMarkerState newGrandchildState = tester.stateOf(find.byConfig(newGrandchild)); - expect(newGrandchildState, isNotNull); - expect(newGrandchildState, equals(grandchildState)); - expect(newGrandchildState.marker, equals("grandchild")); - - tester.pumpWidget( - new Center( - child: new Container( + StateMarker grandchild = new StateMarker(); + tester.pumpWidget( + new Stack( + children: [ + new Container( + child: new StateMarker(key: left) + ), + new Container( child: new StateMarker( - key: left, - child: new Container() - ) - ) - ) - ); - - expect(left.currentState, equals(leftState)); - expect(leftState.marker, equals("left")); - expect(right.currentState, isNull); - }); - }); - - test('can reparent state with multichild widgets', () { - testWidgets((WidgetTester tester) { - GlobalKey left = new GlobalKey(); - GlobalKey right = new GlobalKey(); - - StateMarker grandchild = new StateMarker(); - tester.pumpWidget( - new Stack( - children: [ - new StateMarker(key: left), - new StateMarker( key: right, child: grandchild ) - ] - ) - ); + ), + ] + ) + ); - StateMarkerState leftState = left.currentState; - leftState.marker = "left"; - StateMarkerState rightState = right.currentState; - rightState.marker = "right"; + StateMarkerState leftState = left.currentState; + leftState.marker = "left"; + StateMarkerState rightState = right.currentState; + rightState.marker = "right"; - StateMarkerState grandchildState = tester.stateOf(find.byConfig(grandchild)); - expect(grandchildState, isNotNull); - grandchildState.marker = "grandchild"; + StateMarkerState grandchildState = tester.state(find.byConfig(grandchild)); + expect(grandchildState, isNotNull); + grandchildState.marker = "grandchild"; - StateMarker newGrandchild = new StateMarker(); - tester.pumpWidget( - new Stack( - children: [ - new StateMarker( - key: right, - child: newGrandchild - ), - new StateMarker(key: left) - ] - ) - ); - - expect(left.currentState, equals(leftState)); - expect(leftState.marker, equals("left")); - expect(right.currentState, equals(rightState)); - expect(rightState.marker, equals("right")); - - StateMarkerState newGrandchildState = tester.stateOf(find.byConfig(newGrandchild)); - expect(newGrandchildState, isNotNull); - expect(newGrandchildState, equals(grandchildState)); - expect(newGrandchildState.marker, equals("grandchild")); - - tester.pumpWidget( - new Center( - child: new Container( - child: new StateMarker( - key: left, - child: new Container() - ) - ) - ) - ); - - expect(left.currentState, equals(leftState)); - expect(leftState.marker, equals("left")); - expect(right.currentState, isNull); - }); - }); - - test('can with scrollable list', () { - testWidgets((WidgetTester tester) { - GlobalKey key = new GlobalKey(); - - tester.pumpWidget(new StateMarker(key: key)); - - StateMarkerState keyState = key.currentState; - keyState.marker = "marked"; - - tester.pumpWidget(new ScrollableList( - itemExtent: 100.0, + StateMarker newGrandchild = new StateMarker(); + tester.pumpWidget( + new Stack( children: [ new Container( - key: new Key('container'), - height: 100.0, - child: new StateMarker(key: key) + child: new StateMarker( + key: right, + child: newGrandchild + ) + ), + new Container( + child: new StateMarker(key: left) + ), + ] + ) + ); + + expect(left.currentState, equals(leftState)); + expect(leftState.marker, equals("left")); + expect(right.currentState, equals(rightState)); + expect(rightState.marker, equals("right")); + + StateMarkerState newGrandchildState = tester.state(find.byConfig(newGrandchild)); + expect(newGrandchildState, isNotNull); + expect(newGrandchildState, equals(grandchildState)); + expect(newGrandchildState.marker, equals("grandchild")); + + tester.pumpWidget( + new Center( + child: new Container( + child: new StateMarker( + key: left, + child: new Container() + ) + ) + ) + ); + + expect(left.currentState, equals(leftState)); + expect(leftState.marker, equals("left")); + expect(right.currentState, isNull); + }); + + testWidgets('can reparent state with multichild widgets', (WidgetTester tester) { + GlobalKey left = new GlobalKey(); + GlobalKey right = new GlobalKey(); + + StateMarker grandchild = new StateMarker(); + tester.pumpWidget( + new Stack( + children: [ + new StateMarker(key: left), + new StateMarker( + key: right, + child: grandchild ) ] - )); + ) + ); - expect(key.currentState, equals(keyState)); - expect(keyState.marker, equals("marked")); + StateMarkerState leftState = left.currentState; + leftState.marker = "left"; + StateMarkerState rightState = right.currentState; + rightState.marker = "right"; - tester.pumpWidget(new StateMarker(key: key)); + StateMarkerState grandchildState = tester.state(find.byConfig(grandchild)); + expect(grandchildState, isNotNull); + grandchildState.marker = "grandchild"; - expect(key.currentState, equals(keyState)); - expect(keyState.marker, equals("marked")); - }); + StateMarker newGrandchild = new StateMarker(); + tester.pumpWidget( + new Stack( + children: [ + new StateMarker( + key: right, + child: newGrandchild + ), + new StateMarker(key: left) + ] + ) + ); + + expect(left.currentState, equals(leftState)); + expect(leftState.marker, equals("left")); + expect(right.currentState, equals(rightState)); + expect(rightState.marker, equals("right")); + + StateMarkerState newGrandchildState = tester.state(find.byConfig(newGrandchild)); + expect(newGrandchildState, isNotNull); + expect(newGrandchildState, equals(grandchildState)); + expect(newGrandchildState.marker, equals("grandchild")); + + tester.pumpWidget( + new Center( + child: new Container( + child: new StateMarker( + key: left, + child: new Container() + ) + ) + ) + ); + + expect(left.currentState, equals(leftState)); + expect(leftState.marker, equals("left")); + expect(right.currentState, isNull); }); - test('Reparent during update children', () { - testWidgets((WidgetTester tester) { - GlobalKey key = new GlobalKey(); + testWidgets('can with scrollable list', (WidgetTester tester) { + GlobalKey key = new GlobalKey(); - tester.pumpWidget(new Stack( - children: [ - new StateMarker(key: key), - new Container(width: 100.0, height: 100.0), - ] - )); + tester.pumpWidget(new StateMarker(key: key)); - StateMarkerState keyState = key.currentState; - keyState.marker = "marked"; + StateMarkerState keyState = key.currentState; + keyState.marker = "marked"; - tester.pumpWidget(new Stack( - children: [ - new Container(width: 100.0, height: 100.0), - new StateMarker(key: key), - ] - )); + tester.pumpWidget(new ScrollableList( + itemExtent: 100.0, + children: [ + new Container( + key: new Key('container'), + height: 100.0, + child: new StateMarker(key: key) + ) + ] + )); - expect(key.currentState, equals(keyState)); - expect(keyState.marker, equals("marked")); + expect(key.currentState, equals(keyState)); + expect(keyState.marker, equals("marked")); - tester.pumpWidget(new Stack( - children: [ - new StateMarker(key: key), - new Container(width: 100.0, height: 100.0), - ] - )); + tester.pumpWidget(new StateMarker(key: key)); - expect(key.currentState, equals(keyState)); - expect(keyState.marker, equals("marked")); - }); + expect(key.currentState, equals(keyState)); + expect(keyState.marker, equals("marked")); }); - test('Reparent to child during update children', () { - testWidgets((WidgetTester tester) { - GlobalKey key = new GlobalKey(); + testWidgets('Reparent during update children', (WidgetTester tester) { + GlobalKey key = new GlobalKey(); - tester.pumpWidget(new Stack( - children: [ - new Container(width: 100.0, height: 100.0), - new StateMarker(key: key), - new Container(width: 100.0, height: 100.0), - ] - )); + tester.pumpWidget(new Stack( + children: [ + new StateMarker(key: key), + new Container(width: 100.0, height: 100.0), + ] + )); - StateMarkerState keyState = key.currentState; - keyState.marker = "marked"; + StateMarkerState keyState = key.currentState; + keyState.marker = "marked"; - tester.pumpWidget(new Stack( - children: [ - new Container(width: 100.0, height: 100.0, child: new StateMarker(key: key)), - new Container(width: 100.0, height: 100.0), - ] - )); + tester.pumpWidget(new Stack( + children: [ + new Container(width: 100.0, height: 100.0), + new StateMarker(key: key), + ] + )); - expect(key.currentState, equals(keyState)); - expect(keyState.marker, equals("marked")); + expect(key.currentState, equals(keyState)); + expect(keyState.marker, equals("marked")); - tester.pumpWidget(new Stack( - children: [ - new Container(width: 100.0, height: 100.0), - new StateMarker(key: key), - new Container(width: 100.0, height: 100.0), - ] - )); + tester.pumpWidget(new Stack( + children: [ + new StateMarker(key: key), + new Container(width: 100.0, height: 100.0), + ] + )); - expect(key.currentState, equals(keyState)); - expect(keyState.marker, equals("marked")); - - tester.pumpWidget(new Stack( - children: [ - new Container(width: 100.0, height: 100.0), - new Container(width: 100.0, height: 100.0, child: new StateMarker(key: key)), - ] - )); - - expect(key.currentState, equals(keyState)); - expect(keyState.marker, equals("marked")); - - tester.pumpWidget(new Stack( - children: [ - new Container(width: 100.0, height: 100.0), - new StateMarker(key: key), - new Container(width: 100.0, height: 100.0), - ] - )); - - expect(key.currentState, equals(keyState)); - expect(keyState.marker, equals("marked")); - }); + expect(key.currentState, equals(keyState)); + expect(keyState.marker, equals("marked")); }); - test('Deactivate implies build', () { - testWidgets((WidgetTester tester) { - GlobalKey key = new GlobalKey(); - List log = []; - DeactivateLogger logger = new DeactivateLogger(key: key, log: log); + testWidgets('Reparent to child during update children', (WidgetTester tester) { + GlobalKey key = new GlobalKey(); - tester.pumpWidget( - new Container(key: new UniqueKey(), child: logger) - ); + tester.pumpWidget(new Stack( + children: [ + new Container(width: 100.0, height: 100.0), + new StateMarker(key: key), + new Container(width: 100.0, height: 100.0), + ] + )); - expect(log, equals(['build'])); + StateMarkerState keyState = key.currentState; + keyState.marker = "marked"; - tester.pumpWidget( - new Container(key: new UniqueKey(), child: logger) - ); + tester.pumpWidget(new Stack( + children: [ + new Container(width: 100.0, height: 100.0, child: new StateMarker(key: key)), + new Container(width: 100.0, height: 100.0), + ] + )); - expect(log, equals(['build', 'deactivate', 'build'])); - log.clear(); + expect(key.currentState, equals(keyState)); + expect(keyState.marker, equals("marked")); - tester.pump(); - expect(log, isEmpty); - }); + tester.pumpWidget(new Stack( + children: [ + new Container(width: 100.0, height: 100.0), + new StateMarker(key: key), + new Container(width: 100.0, height: 100.0), + ] + )); + + expect(key.currentState, equals(keyState)); + expect(keyState.marker, equals("marked")); + + tester.pumpWidget(new Stack( + children: [ + new Container(width: 100.0, height: 100.0), + new Container(width: 100.0, height: 100.0, child: new StateMarker(key: key)), + ] + )); + + expect(key.currentState, equals(keyState)); + expect(keyState.marker, equals("marked")); + + tester.pumpWidget(new Stack( + children: [ + new Container(width: 100.0, height: 100.0), + new StateMarker(key: key), + new Container(width: 100.0, height: 100.0), + ] + )); + + expect(key.currentState, equals(keyState)); + expect(keyState.marker, equals("marked")); + }); + + testWidgets('Deactivate implies build', (WidgetTester tester) { + GlobalKey key = new GlobalKey(); + List log = []; + DeactivateLogger logger = new DeactivateLogger(key: key, log: log); + + tester.pumpWidget( + new Container(key: new UniqueKey(), child: logger) + ); + + expect(log, equals(['build'])); + + tester.pumpWidget( + new Container(key: new UniqueKey(), child: logger) + ); + + expect(log, equals(['build', 'deactivate', 'build'])); + log.clear(); + + tester.pump(); + expect(log, isEmpty); }); } diff --git a/packages/flutter/test/widget/rotated_box_test.dart b/packages/flutter/test/widget/rotated_box_test.dart index bf19ab66f1..87ecad55e9 100644 --- a/packages/flutter/test/widget/rotated_box_test.dart +++ b/packages/flutter/test/widget/rotated_box_test.dart @@ -7,52 +7,50 @@ import 'package:flutter/material.dart'; import 'package:test/test.dart'; void main() { - test('Rotated box control test', () { - testWidgets((WidgetTester tester) { - List log = []; - Key rotatedBoxKey = new UniqueKey(); + testWidgets('Rotated box control test', (WidgetTester tester) { + List log = []; + Key rotatedBoxKey = new UniqueKey(); - tester.pumpWidget( - new Center( - child: new RotatedBox( - key: rotatedBoxKey, - quarterTurns: 1, - child: new Row( - mainAxisAlignment: MainAxisAlignment.collapse, - children: [ - new GestureDetector( - onTap: () { log.add('left'); }, - child: new Container( - width: 100.0, - height: 40.0, - decoration: new BoxDecoration(backgroundColor: Colors.blue[500]) - ) - ), - new GestureDetector( - onTap: () { log.add('right'); }, - child: new Container( - width: 75.0, - height: 65.0, - decoration: new BoxDecoration(backgroundColor: Colors.blue[500]) - ) - ), - ] - ) + tester.pumpWidget( + new Center( + child: new RotatedBox( + key: rotatedBoxKey, + quarterTurns: 1, + child: new Row( + mainAxisAlignment: MainAxisAlignment.collapse, + children: [ + new GestureDetector( + onTap: () { log.add('left'); }, + child: new Container( + width: 100.0, + height: 40.0, + decoration: new BoxDecoration(backgroundColor: Colors.blue[500]) + ) + ), + new GestureDetector( + onTap: () { log.add('right'); }, + child: new Container( + width: 75.0, + height: 65.0, + decoration: new BoxDecoration(backgroundColor: Colors.blue[500]) + ) + ), + ] ) ) - ); + ) + ); - RenderBox box = tester.elementTreeTester.findElementByKey(rotatedBoxKey).renderObject; - expect(box.size.width, equals(65.0)); - expect(box.size.height, equals(175.0)); + RenderBox box = tester.renderObject(find.byKey(rotatedBoxKey)); + expect(box.size.width, equals(65.0)); + expect(box.size.height, equals(175.0)); - tester.tapAt(new Point(420.0, 280.0)); - expect(log, equals(['left'])); - log.clear(); + tester.tapAt(new Point(420.0, 280.0)); + expect(log, equals(['left'])); + log.clear(); - tester.tapAt(new Point(380.0, 320.0)); - expect(log, equals(['right'])); - log.clear(); - }); + tester.tapAt(new Point(380.0, 320.0)); + expect(log, equals(['right'])); + log.clear(); }); } diff --git a/packages/flutter/test/widget/routes_test.dart b/packages/flutter/test/widget/routes_test.dart index d6f083894a..b7b7ddcd75 100644 --- a/packages/flutter/test/widget/routes_test.dart +++ b/packages/flutter/test/widget/routes_test.dart @@ -90,299 +90,293 @@ void runNavigatorTest( } void main() { - test('Route management - push, replace, pop', () { - testWidgets((WidgetTester tester) { - GlobalKey navigatorKey = new GlobalKey(); - tester.pumpWidget(new Navigator( - key: navigatorKey, - onGenerateRoute: (_) => new TestRoute('initial') - )); - NavigatorState host = navigatorKey.currentState; - runNavigatorTest( - tester, - host, - (NavigatorTransaction transaction) { - }, - [ - 'initial: install', - 'initial: didPush', - 'initial: didChangeNext null', - ] - ); - TestRoute second; - runNavigatorTest( - tester, - host, - (NavigatorTransaction transaction) { - transaction.push(second = new TestRoute('second')); - }, - [ - 'second: install', - 'second: didPush', - 'second: didChangeNext null', - 'initial: didChangeNext second', - ] - ); - runNavigatorTest( - tester, - host, - (NavigatorTransaction transaction) { - transaction.push(new TestRoute('third')); - }, - [ - 'third: install', - 'third: didPush', - 'third: didChangeNext null', - 'second: didChangeNext third', - ] - ); - runNavigatorTest( - tester, - host, - (NavigatorTransaction transaction) { - transaction.replace(oldRoute: second, newRoute: new TestRoute('two')); - }, - [ - 'two: install', - 'two: didReplace second', - 'two: didChangeNext third', - 'initial: didChangeNext two', - 'second: dispose', - ] - ); - runNavigatorTest( - tester, - host, - (NavigatorTransaction transaction) { - transaction.pop('hello'); - }, - [ - 'third: didPop hello', - 'third: dispose', - 'two: didPopNext third', - ] - ); - runNavigatorTest( - tester, - host, - (NavigatorTransaction transaction) { - transaction.pop('good bye'); - }, - [ - 'two: didPop good bye', - 'two: dispose', - 'initial: didPopNext two', - ] - ); - tester.pumpWidget(new Container()); - expect(results, equals(['initial: dispose'])); - expect(routes.isEmpty, isTrue); - results.clear(); - }); + testWidgets('Route management - push, replace, pop', (WidgetTester tester) { + GlobalKey navigatorKey = new GlobalKey(); + tester.pumpWidget(new Navigator( + key: navigatorKey, + onGenerateRoute: (_) => new TestRoute('initial') + )); + NavigatorState host = navigatorKey.currentState; + runNavigatorTest( + tester, + host, + (NavigatorTransaction transaction) { + }, + [ + 'initial: install', + 'initial: didPush', + 'initial: didChangeNext null', + ] + ); + TestRoute second; + runNavigatorTest( + tester, + host, + (NavigatorTransaction transaction) { + transaction.push(second = new TestRoute('second')); + }, + [ + 'second: install', + 'second: didPush', + 'second: didChangeNext null', + 'initial: didChangeNext second', + ] + ); + runNavigatorTest( + tester, + host, + (NavigatorTransaction transaction) { + transaction.push(new TestRoute('third')); + }, + [ + 'third: install', + 'third: didPush', + 'third: didChangeNext null', + 'second: didChangeNext third', + ] + ); + runNavigatorTest( + tester, + host, + (NavigatorTransaction transaction) { + transaction.replace(oldRoute: second, newRoute: new TestRoute('two')); + }, + [ + 'two: install', + 'two: didReplace second', + 'two: didChangeNext third', + 'initial: didChangeNext two', + 'second: dispose', + ] + ); + runNavigatorTest( + tester, + host, + (NavigatorTransaction transaction) { + transaction.pop('hello'); + }, + [ + 'third: didPop hello', + 'third: dispose', + 'two: didPopNext third', + ] + ); + runNavigatorTest( + tester, + host, + (NavigatorTransaction transaction) { + transaction.pop('good bye'); + }, + [ + 'two: didPop good bye', + 'two: dispose', + 'initial: didPopNext two', + ] + ); + tester.pumpWidget(new Container()); + expect(results, equals(['initial: dispose'])); + expect(routes.isEmpty, isTrue); + results.clear(); }); - test('Route management - push, remove, pop', () { - testWidgets((WidgetTester tester) { - GlobalKey navigatorKey = new GlobalKey(); - tester.pumpWidget(new Navigator( - key: navigatorKey, - onGenerateRoute: (_) => new TestRoute('first') - )); - NavigatorState host = navigatorKey.currentState; - runNavigatorTest( - tester, - host, - (NavigatorTransaction transaction) { - }, - [ - 'first: install', - 'first: didPush', - 'first: didChangeNext null', - ] - ); - TestRoute second; - runNavigatorTest( - tester, - host, - (NavigatorTransaction transaction) { - transaction.push(second = new TestRoute('second')); - }, - [ - 'second: install', - 'second: didPush', - 'second: didChangeNext null', - 'first: didChangeNext second', - ] - ); - runNavigatorTest( - tester, - host, - (NavigatorTransaction transaction) { - transaction.push(new TestRoute('third')); - }, - [ - 'third: install', - 'third: didPush', - 'third: didChangeNext null', - 'second: didChangeNext third', - ] - ); - runNavigatorTest( - tester, - host, - (NavigatorTransaction transaction) { - transaction.removeRouteBefore(second); - }, - [ - 'first: dispose', - ] - ); - runNavigatorTest( - tester, - host, - (NavigatorTransaction transaction) { - transaction.pop('good bye'); - }, - [ - 'third: didPop good bye', - 'third: dispose', - 'second: didPopNext third', - ] - ); - runNavigatorTest( - tester, - host, - (NavigatorTransaction transaction) { - transaction.push(new TestRoute('three')); - }, - [ - 'three: install', - 'three: didPush', - 'three: didChangeNext null', - 'second: didChangeNext three', - ] - ); - TestRoute four; - runNavigatorTest( - tester, - host, - (NavigatorTransaction transaction) { - transaction.push(four = new TestRoute('four')); - }, - [ - 'four: install', - 'four: didPush', - 'four: didChangeNext null', - 'three: didChangeNext four', - ] - ); - runNavigatorTest( - tester, - host, - (NavigatorTransaction transaction) { - transaction.removeRouteBefore(four); - }, - [ - 'second: didChangeNext four', - 'three: dispose', - ] - ); - runNavigatorTest( - tester, - host, - (NavigatorTransaction transaction) { - transaction.pop('the end'); - }, - [ - 'four: didPop the end', - 'four: dispose', - 'second: didPopNext four', - ] - ); - tester.pumpWidget(new Container()); - expect(results, equals(['second: dispose'])); - expect(routes.isEmpty, isTrue); - results.clear(); - }); + testWidgets('Route management - push, remove, pop', (WidgetTester tester) { + GlobalKey navigatorKey = new GlobalKey(); + tester.pumpWidget(new Navigator( + key: navigatorKey, + onGenerateRoute: (_) => new TestRoute('first') + )); + NavigatorState host = navigatorKey.currentState; + runNavigatorTest( + tester, + host, + (NavigatorTransaction transaction) { + }, + [ + 'first: install', + 'first: didPush', + 'first: didChangeNext null', + ] + ); + TestRoute second; + runNavigatorTest( + tester, + host, + (NavigatorTransaction transaction) { + transaction.push(second = new TestRoute('second')); + }, + [ + 'second: install', + 'second: didPush', + 'second: didChangeNext null', + 'first: didChangeNext second', + ] + ); + runNavigatorTest( + tester, + host, + (NavigatorTransaction transaction) { + transaction.push(new TestRoute('third')); + }, + [ + 'third: install', + 'third: didPush', + 'third: didChangeNext null', + 'second: didChangeNext third', + ] + ); + runNavigatorTest( + tester, + host, + (NavigatorTransaction transaction) { + transaction.removeRouteBefore(second); + }, + [ + 'first: dispose', + ] + ); + runNavigatorTest( + tester, + host, + (NavigatorTransaction transaction) { + transaction.pop('good bye'); + }, + [ + 'third: didPop good bye', + 'third: dispose', + 'second: didPopNext third', + ] + ); + runNavigatorTest( + tester, + host, + (NavigatorTransaction transaction) { + transaction.push(new TestRoute('three')); + }, + [ + 'three: install', + 'three: didPush', + 'three: didChangeNext null', + 'second: didChangeNext three', + ] + ); + TestRoute four; + runNavigatorTest( + tester, + host, + (NavigatorTransaction transaction) { + transaction.push(four = new TestRoute('four')); + }, + [ + 'four: install', + 'four: didPush', + 'four: didChangeNext null', + 'three: didChangeNext four', + ] + ); + runNavigatorTest( + tester, + host, + (NavigatorTransaction transaction) { + transaction.removeRouteBefore(four); + }, + [ + 'second: didChangeNext four', + 'three: dispose', + ] + ); + runNavigatorTest( + tester, + host, + (NavigatorTransaction transaction) { + transaction.pop('the end'); + }, + [ + 'four: didPop the end', + 'four: dispose', + 'second: didPopNext four', + ] + ); + tester.pumpWidget(new Container()); + expect(results, equals(['second: dispose'])); + expect(routes.isEmpty, isTrue); + results.clear(); }); - test('Route management - push, replace, popUntil', () { - testWidgets((WidgetTester tester) { - GlobalKey navigatorKey = new GlobalKey(); - tester.pumpWidget(new Navigator( - key: navigatorKey, - onGenerateRoute: (_) => new TestRoute('A') - )); - NavigatorState host = navigatorKey.currentState; - runNavigatorTest( - tester, - host, - (NavigatorTransaction transaction) { - }, - [ - 'A: install', - 'A: didPush', - 'A: didChangeNext null', - ] - ); - runNavigatorTest( - tester, - host, - (NavigatorTransaction transaction) { - transaction.push(new TestRoute('B')); - }, - [ - 'B: install', - 'B: didPush', - 'B: didChangeNext null', - 'A: didChangeNext B', - ] - ); - TestRoute routeC; - runNavigatorTest( - tester, - host, - (NavigatorTransaction transaction) { - transaction.push(routeC = new TestRoute('C')); - }, - [ - 'C: install', - 'C: didPush', - 'C: didChangeNext null', - 'B: didChangeNext C', - ] - ); - TestRoute routeB; - runNavigatorTest( - tester, - host, - (NavigatorTransaction transaction) { - transaction.replaceRouteBefore(anchorRoute: routeC, newRoute: routeB = new TestRoute('b')); - }, - [ - 'b: install', - 'b: didReplace B', - 'b: didChangeNext C', - 'A: didChangeNext b', - 'B: dispose', - ] - ); - runNavigatorTest( - tester, - host, - (NavigatorTransaction transaction) { - transaction.popUntil(routeB); - }, - [ - 'C: didPop null', - 'C: dispose', - 'b: didPopNext C', - ] - ); - tester.pumpWidget(new Container()); - expect(results, equals(['A: dispose', 'b: dispose'])); - expect(routes.isEmpty, isTrue); - results.clear(); - }); + testWidgets('Route management - push, replace, popUntil', (WidgetTester tester) { + GlobalKey navigatorKey = new GlobalKey(); + tester.pumpWidget(new Navigator( + key: navigatorKey, + onGenerateRoute: (_) => new TestRoute('A') + )); + NavigatorState host = navigatorKey.currentState; + runNavigatorTest( + tester, + host, + (NavigatorTransaction transaction) { + }, + [ + 'A: install', + 'A: didPush', + 'A: didChangeNext null', + ] + ); + runNavigatorTest( + tester, + host, + (NavigatorTransaction transaction) { + transaction.push(new TestRoute('B')); + }, + [ + 'B: install', + 'B: didPush', + 'B: didChangeNext null', + 'A: didChangeNext B', + ] + ); + TestRoute routeC; + runNavigatorTest( + tester, + host, + (NavigatorTransaction transaction) { + transaction.push(routeC = new TestRoute('C')); + }, + [ + 'C: install', + 'C: didPush', + 'C: didChangeNext null', + 'B: didChangeNext C', + ] + ); + TestRoute routeB; + runNavigatorTest( + tester, + host, + (NavigatorTransaction transaction) { + transaction.replaceRouteBefore(anchorRoute: routeC, newRoute: routeB = new TestRoute('b')); + }, + [ + 'b: install', + 'b: didReplace B', + 'b: didChangeNext C', + 'A: didChangeNext b', + 'B: dispose', + ] + ); + runNavigatorTest( + tester, + host, + (NavigatorTransaction transaction) { + transaction.popUntil(routeB); + }, + [ + 'C: didPop null', + 'C: dispose', + 'b: didPopNext C', + ] + ); + tester.pumpWidget(new Container()); + expect(results, equals(['A: dispose', 'b: dispose'])); + expect(routes.isEmpty, isTrue); + results.clear(); }); } diff --git a/packages/flutter/test/widget/scroll_behavior_test.dart b/packages/flutter/test/widget/scroll_behavior_test.dart index 096be78ceb..30f65d9b04 100644 --- a/packages/flutter/test/widget/scroll_behavior_test.dart +++ b/packages/flutter/test/widget/scroll_behavior_test.dart @@ -7,11 +7,11 @@ import 'package:test/test.dart'; void main() { test('BoundedBehavior min scroll offset', () { - BoundedBehavior behavior = new BoundedBehavior( - contentExtent: 150.0, - containerExtent: 75.0, - minScrollOffset: -100.0 - ); + BoundedBehavior behavior = new BoundedBehavior( + contentExtent: 150.0, + containerExtent: 75.0, + minScrollOffset: -100.0 + ); expect(behavior.minScrollOffset, equals(-100.0)); expect(behavior.maxScrollOffset, equals(-25.0)); diff --git a/packages/flutter/test/widget/scroll_events_test.dart b/packages/flutter/test/widget/scroll_events_test.dart index b5bab6b4f9..827852d3ec 100644 --- a/packages/flutter/test/widget/scroll_events_test.dart +++ b/packages/flutter/test/widget/scroll_events_test.dart @@ -23,136 +23,124 @@ Widget _buildScroller({Key key, List log}) { } void main() { - test('Scroll event drag', () { - testWidgets((WidgetTester tester) { - List log = []; - tester.pumpWidget(_buildScroller(log: log)); + testWidgets('Scroll event drag', (WidgetTester tester) { + List log = []; + tester.pumpWidget(_buildScroller(log: log)); - expect(log, equals([])); - TestGesture gesture = tester.startGesture(new Point(100.0, 100.0)); - expect(log, equals(['scrollstart'])); - tester.pump(const Duration(seconds: 1)); - expect(log, equals(['scrollstart'])); - gesture.moveBy(new Offset(-10.0, -10.0)); - expect(log, equals(['scrollstart', 'scroll'])); - tester.pump(const Duration(seconds: 1)); - expect(log, equals(['scrollstart', 'scroll'])); - gesture.up(); - expect(log, equals(['scrollstart', 'scroll'])); - tester.pump(const Duration(seconds: 1)); - expect(log, equals(['scrollstart', 'scroll', 'scrollend'])); - }); + expect(log, equals([])); + TestGesture gesture = tester.startGesture(new Point(100.0, 100.0)); + expect(log, equals(['scrollstart'])); + tester.pump(const Duration(seconds: 1)); + expect(log, equals(['scrollstart'])); + gesture.moveBy(new Offset(-10.0, -10.0)); + expect(log, equals(['scrollstart', 'scroll'])); + tester.pump(const Duration(seconds: 1)); + expect(log, equals(['scrollstart', 'scroll'])); + gesture.up(); + expect(log, equals(['scrollstart', 'scroll'])); + tester.pump(const Duration(seconds: 1)); + expect(log, equals(['scrollstart', 'scroll', 'scrollend'])); }); - test('Scroll scrollTo animation', () { - testWidgets((WidgetTester tester) { - GlobalKey> scrollKey = new GlobalKey>(); - List log = []; - tester.pumpWidget(_buildScroller(key: scrollKey, log: log)); + testWidgets('Scroll scrollTo animation', (WidgetTester tester) { + GlobalKey> scrollKey = new GlobalKey>(); + List log = []; + tester.pumpWidget(_buildScroller(key: scrollKey, log: log)); - expect(log, equals([])); - scrollKey.currentState.scrollTo(100.0, duration: const Duration(seconds: 1)); - expect(log, equals(['scrollstart'])); - tester.pump(const Duration(milliseconds: 100)); - expect(log, equals(['scrollstart'])); - tester.pump(const Duration(milliseconds: 100)); - expect(log, equals(['scrollstart', 'scroll'])); - tester.pump(const Duration(milliseconds: 1500)); - expect(log, equals(['scrollstart', 'scroll', 'scroll', 'scrollend'])); - }); + expect(log, equals([])); + scrollKey.currentState.scrollTo(100.0, duration: const Duration(seconds: 1)); + expect(log, equals(['scrollstart'])); + tester.pump(const Duration(milliseconds: 100)); + expect(log, equals(['scrollstart'])); + tester.pump(const Duration(milliseconds: 100)); + expect(log, equals(['scrollstart', 'scroll'])); + tester.pump(const Duration(milliseconds: 1500)); + expect(log, equals(['scrollstart', 'scroll', 'scroll', 'scrollend'])); }); - test('Scroll scrollTo no animation', () { - testWidgets((WidgetTester tester) { - GlobalKey> scrollKey = new GlobalKey>(); - List log = []; - tester.pumpWidget(_buildScroller(key: scrollKey, log: log)); + testWidgets('Scroll scrollTo no animation', (WidgetTester tester) { + GlobalKey> scrollKey = new GlobalKey>(); + List log = []; + tester.pumpWidget(_buildScroller(key: scrollKey, log: log)); - expect(log, equals([])); - scrollKey.currentState.scrollTo(100.0); - expect(log, equals(['scrollstart', 'scroll', 'scrollend'])); - }); + expect(log, equals([])); + scrollKey.currentState.scrollTo(100.0); + expect(log, equals(['scrollstart', 'scroll', 'scrollend'])); }); - test('Scroll during animation', () { - testWidgets((WidgetTester tester) { - GlobalKey> scrollKey = new GlobalKey>(); - List log = []; - tester.pumpWidget(_buildScroller(key: scrollKey, log: log)); + testWidgets('Scroll during animation', (WidgetTester tester) { + GlobalKey> scrollKey = new GlobalKey>(); + List log = []; + tester.pumpWidget(_buildScroller(key: scrollKey, log: log)); - expect(log, equals([])); - scrollKey.currentState.scrollTo(100.0, duration: const Duration(seconds: 1)); - expect(log, equals(['scrollstart'])); - tester.pump(const Duration(milliseconds: 100)); - expect(log, equals(['scrollstart'])); - tester.pump(const Duration(milliseconds: 100)); - expect(log, equals(['scrollstart', 'scroll'])); - scrollKey.currentState.scrollTo(100.0); - expect(log, equals(['scrollstart', 'scroll', 'scroll'])); - tester.pump(const Duration(milliseconds: 100)); - expect(log, equals(['scrollstart', 'scroll', 'scroll', 'scrollend'])); - tester.pump(const Duration(milliseconds: 1500)); - expect(log, equals(['scrollstart', 'scroll', 'scroll', 'scrollend'])); - }); + expect(log, equals([])); + scrollKey.currentState.scrollTo(100.0, duration: const Duration(seconds: 1)); + expect(log, equals(['scrollstart'])); + tester.pump(const Duration(milliseconds: 100)); + expect(log, equals(['scrollstart'])); + tester.pump(const Duration(milliseconds: 100)); + expect(log, equals(['scrollstart', 'scroll'])); + scrollKey.currentState.scrollTo(100.0); + expect(log, equals(['scrollstart', 'scroll', 'scroll'])); + tester.pump(const Duration(milliseconds: 100)); + expect(log, equals(['scrollstart', 'scroll', 'scroll', 'scrollend'])); + tester.pump(const Duration(milliseconds: 1500)); + expect(log, equals(['scrollstart', 'scroll', 'scroll', 'scrollend'])); }); - test('Scroll during animation', () { - testWidgets((WidgetTester tester) { - GlobalKey> scrollKey = new GlobalKey>(); - List log = []; - tester.pumpWidget(_buildScroller(key: scrollKey, log: log)); + testWidgets('Scroll during animation', (WidgetTester tester) { + GlobalKey> scrollKey = new GlobalKey>(); + List log = []; + tester.pumpWidget(_buildScroller(key: scrollKey, log: log)); - expect(log, equals([])); - scrollKey.currentState.scrollTo(100.0, duration: const Duration(seconds: 1)); - expect(log, equals(['scrollstart'])); - tester.pump(const Duration(milliseconds: 100)); - expect(log, equals(['scrollstart'])); - tester.pump(const Duration(milliseconds: 100)); - expect(log, equals(['scrollstart', 'scroll'])); - scrollKey.currentState.scrollTo(100.0, duration: const Duration(seconds: 1)); - expect(log, equals(['scrollstart', 'scroll'])); - tester.pump(const Duration(milliseconds: 100)); - expect(log, equals(['scrollstart', 'scroll'])); - tester.pump(const Duration(milliseconds: 1500)); - expect(log, equals(['scrollstart', 'scroll', 'scroll', 'scrollend'])); - }); + expect(log, equals([])); + scrollKey.currentState.scrollTo(100.0, duration: const Duration(seconds: 1)); + expect(log, equals(['scrollstart'])); + tester.pump(const Duration(milliseconds: 100)); + expect(log, equals(['scrollstart'])); + tester.pump(const Duration(milliseconds: 100)); + expect(log, equals(['scrollstart', 'scroll'])); + scrollKey.currentState.scrollTo(100.0, duration: const Duration(seconds: 1)); + expect(log, equals(['scrollstart', 'scroll'])); + tester.pump(const Duration(milliseconds: 100)); + expect(log, equals(['scrollstart', 'scroll'])); + tester.pump(const Duration(milliseconds: 1500)); + expect(log, equals(['scrollstart', 'scroll', 'scroll', 'scrollend'])); }); - test('fling, fling generates one start/end pair', () { - testWidgets((WidgetTester tester) { - GlobalKey> scrollKey = new GlobalKey>(); - List log = []; - tester.pumpWidget(_buildScroller(key: scrollKey, log: log)); + testWidgets('fling, fling generates two start/end pairs', (WidgetTester tester) { + GlobalKey> scrollKey = new GlobalKey>(); + List log = []; + tester.pumpWidget(_buildScroller(key: scrollKey, log: log)); - expect(log, equals([])); - tester.flingFrom(new Point(100.0, 100.0), new Offset(-50.0, -50.0), 500.0); - tester.pump(new Duration(seconds: 1)); - log.removeWhere((String value) => value == 'scroll'); - expect(log, equals(['scrollstart'])); - tester.flingFrom(new Point(100.0, 100.0), new Offset(-50.0, -50.0), 500.0); - tester.pump(new Duration(seconds: 1)); - tester.pump(new Duration(seconds: 1)); - log.removeWhere((String value) => value == 'scroll'); - expect(log, equals(['scrollstart', 'scrollend'])); - }); + expect(log, equals([])); + tester.flingFrom(new Point(100.0, 100.0), new Offset(-50.0, -50.0), 500.0); + tester.pump(new Duration(seconds: 1)); + log.removeWhere((String value) => value == 'scroll'); + expect(log, equals(['scrollstart'])); + tester.flingFrom(new Point(100.0, 100.0), new Offset(-50.0, -50.0), 500.0); + log.removeWhere((String value) => value == 'scroll'); + expect(log, equals(['scrollstart', 'scrollend', 'scrollstart'])); + tester.pump(new Duration(seconds: 1)); + tester.pump(new Duration(seconds: 1)); + log.removeWhere((String value) => value == 'scroll'); + expect(log, equals(['scrollstart', 'scrollend', 'scrollstart', 'scrollend'])); }); - test('fling up ends', () { - testWidgets((WidgetTester tester) { - GlobalKey> scrollKey = new GlobalKey>(); - List log = []; - tester.pumpWidget(_buildScroller(key: scrollKey, log: log)); + testWidgets('fling up ends', (WidgetTester tester) { + GlobalKey> scrollKey = new GlobalKey>(); + List log = []; + tester.pumpWidget(_buildScroller(key: scrollKey, log: log)); - expect(log, equals([])); - tester.flingFrom(new Point(100.0, 100.0), new Offset(50.0, 50.0), 500.0); - tester.pump(new Duration(seconds: 1)); - tester.pump(new Duration(seconds: 1)); - tester.pump(new Duration(seconds: 1)); - expect(log.first, equals('scrollstart')); - expect(log.last, equals('scrollend')); - log.removeWhere((String value) => value == 'scroll'); - expect(log.length, equals(2)); - expect(scrollKey.currentState.scrollOffset, equals(0.0)); - }); + expect(log, equals([])); + tester.flingFrom(new Point(100.0, 100.0), new Offset(50.0, 50.0), 500.0); + tester.pump(new Duration(seconds: 1)); + tester.pump(new Duration(seconds: 1)); + tester.pump(new Duration(seconds: 1)); + expect(log.first, equals('scrollstart')); + expect(log.last, equals('scrollend')); + log.removeWhere((String value) => value == 'scroll'); + expect(log.length, equals(2)); + expect(scrollKey.currentState.scrollOffset, equals(0.0)); }); } diff --git a/packages/flutter/test/widget/scroll_interaction_test.dart b/packages/flutter/test/widget/scroll_interaction_test.dart index e81dcff141..e652237c5d 100644 --- a/packages/flutter/test/widget/scroll_interaction_test.dart +++ b/packages/flutter/test/widget/scroll_interaction_test.dart @@ -7,33 +7,30 @@ import 'package:flutter/widgets.dart'; import 'package:test/test.dart'; void main() { - test('Scroll flings twice in a row does not crash', () { - testWidgets((WidgetTester tester) { - tester.pumpWidget(new Block( - children: [ - new Container(height: 100000.0) - ] - )); + testWidgets('Scroll flings twice in a row does not crash', (WidgetTester tester) { + tester.pumpWidget(new Block( + children: [ + new Container(height: 100000.0) + ] + )); - ScrollableState scrollable = - tester.stateOf/*>*/(find.byType(ScrollableViewport)); + ScrollableState scrollable = + tester.state/*>*/(find.byType(ScrollableViewport)); - expect(scrollable.scrollOffset, equals(0.0)); + expect(scrollable.scrollOffset, equals(0.0)); - tester.flingFrom(new Point(200.0, 300.0), new Offset(0.0, -200.0), 500.0); - tester.pump(); - tester.pump(const Duration(seconds: 5)); + tester.flingFrom(new Point(200.0, 300.0), new Offset(0.0, -200.0), 500.0); + tester.pump(); + tester.pump(const Duration(seconds: 5)); - expect(scrollable.scrollOffset, greaterThan(0.0)); + expect(scrollable.scrollOffset, greaterThan(0.0)); - double oldOffset = scrollable.scrollOffset; + double oldOffset = scrollable.scrollOffset; - tester.flingFrom(new Point(200.0, 300.0), new Offset(0.0, -200.0), 500.0); - tester.pump(); - tester.pump(const Duration(seconds: 5)); + tester.flingFrom(new Point(200.0, 300.0), new Offset(0.0, -200.0), 500.0); + tester.pump(); + tester.pump(const Duration(seconds: 5)); - expect(scrollable.scrollOffset, greaterThan(oldOffset)); - - }); + expect(scrollable.scrollOffset, greaterThan(oldOffset)); }); } diff --git a/packages/flutter/test/widget/scrollable_lazy_list_test.dart b/packages/flutter/test/widget/scrollable_lazy_list_test.dart index 4103c57e14..4962bdbadd 100644 --- a/packages/flutter/test/widget/scrollable_lazy_list_test.dart +++ b/packages/flutter/test/widget/scrollable_lazy_list_test.dart @@ -9,199 +9,191 @@ import 'package:test/test.dart'; import 'test_widgets.dart'; void main() { - test('HomogeneousViewport mount/dismount smoke test', () { - testWidgets((WidgetTester tester) { - List callbackTracker = []; + testWidgets('HomogeneousViewport mount/dismount smoke test', (WidgetTester tester) { + List callbackTracker = []; - // the root view is 800x600 in the test environment - // so if our widget is 100 pixels tall, it should fit exactly 6 times. + // the root view is 800x600 in the test environment + // so if our widget is 100 pixels tall, it should fit exactly 6 times. - Widget builder() { - return new FlipWidget( - left: new ScrollableLazyList( - itemBuilder: (BuildContext context, int start, int count) { - List result = []; - for (int index = start; index < start + count; index += 1) { - callbackTracker.add(index); - result.add(new Container( - key: new ValueKey(index), - height: 100.0, - child: new Text("$index") - )); - } - return result; - }, - itemExtent: 100.0 - ), - right: new Text('Not Today') - ); + Widget builder() { + return new FlipWidget( + left: new ScrollableLazyList( + itemBuilder: (BuildContext context, int start, int count) { + List result = []; + for (int index = start; index < start + count; index += 1) { + callbackTracker.add(index); + result.add(new Container( + key: new ValueKey(index), + height: 100.0, + child: new Text("$index") + )); + } + return result; + }, + itemExtent: 100.0 + ), + right: new Text('Not Today') + ); + } + + tester.pumpWidget(builder()); + + FlipWidgetState testWidget = tester.state(find.byType(FlipWidget)); + + expect(callbackTracker, equals([0, 1, 2, 3, 4, 5])); + + callbackTracker.clear(); + testWidget.flip(); + tester.pump(); + + expect(callbackTracker, equals([])); + + callbackTracker.clear(); + testWidget.flip(); + tester.pump(); + + expect(callbackTracker, equals([0, 1, 2, 3, 4, 5])); + }); + + testWidgets('HomogeneousViewport vertical', (WidgetTester tester) { + List callbackTracker = []; + + // the root view is 800x600 in the test environment + // so if our widget is 200 pixels tall, it should fit exactly 3 times. + // but if we are offset by 300 pixels, there will be 4, numbered 1-4. + + ItemListBuilder itemBuilder = (BuildContext context, int start, int count) { + List result = []; + for (int index = start; index < start + count; index += 1) { + callbackTracker.add(index); + result.add(new Container( + key: new ValueKey(index), + width: 500.0, // this should be ignored + height: 400.0, // should be overridden by itemExtent + child: new Text("$index") + )); } + return result; + }; - tester.pumpWidget(builder()); - - FlipWidgetState testWidget = tester.stateOf(find.byType(FlipWidget)); - - expect(callbackTracker, equals([0, 1, 2, 3, 4, 5])); - - callbackTracker.clear(); - testWidget.flip(); - tester.pump(); - - expect(callbackTracker, equals([])); - - callbackTracker.clear(); - testWidget.flip(); - tester.pump(); - - expect(callbackTracker, equals([0, 1, 2, 3, 4, 5])); - }); - }); - - test('HomogeneousViewport vertical', () { - testWidgets((WidgetTester tester) { - List callbackTracker = []; - - // the root view is 800x600 in the test environment - // so if our widget is 200 pixels tall, it should fit exactly 3 times. - // but if we are offset by 300 pixels, there will be 4, numbered 1-4. - - ItemListBuilder itemBuilder = (BuildContext context, int start, int count) { - List result = []; - for (int index = start; index < start + count; index += 1) { - callbackTracker.add(index); - result.add(new Container( - key: new ValueKey(index), - width: 500.0, // this should be ignored - height: 400.0, // should be overridden by itemExtent - child: new Text("$index") - )); - } - return result; - }; - - GlobalKey> scrollableKey = new GlobalKey>(); - FlipWidget testWidget = new FlipWidget( - left: new ScrollableLazyList( - key: scrollableKey, - itemBuilder: itemBuilder, - itemExtent: 200.0, - initialScrollOffset: 300.0 - ), - right: new Text('Not Today') - ); - - tester.pumpWidget(testWidget); - - expect(callbackTracker, equals([1, 2, 3, 4])); - - callbackTracker.clear(); - - scrollableKey.currentState.scrollTo(400.0); - // now only 3 should fit, numbered 2-4. - - tester.pumpWidget(testWidget); - - expect(callbackTracker, equals([2, 3, 4])); - - callbackTracker.clear(); - }); - }); - - test('HomogeneousViewport horizontal', () { - testWidgets((WidgetTester tester) { - List callbackTracker = []; - - // the root view is 800x600 in the test environment - // so if our widget is 200 pixels wide, it should fit exactly 4 times. - // but if we are offset by 300 pixels, there will be 5, numbered 1-5. - - ItemListBuilder itemBuilder = (BuildContext context, int start, int count) { - List result = []; - for (int index = start; index < start + count; index += 1) { - callbackTracker.add(index); - result.add(new Container( - key: new ValueKey(index), - width: 400.0, // this should be overridden by itemExtent - height: 500.0, // this should be ignored - child: new Text("$index") - )); - } - return result; - }; - - GlobalKey> scrollableKey = new GlobalKey>(); - FlipWidget testWidget = new FlipWidget( - left: new ScrollableLazyList( - key: scrollableKey, - itemBuilder: itemBuilder, - itemExtent: 200.0, - initialScrollOffset: 300.0, - scrollDirection: Axis.horizontal - ), - right: new Text('Not Today') - ); - - tester.pumpWidget(testWidget); - - expect(callbackTracker, equals([1, 2, 3, 4, 5])); - - callbackTracker.clear(); - - scrollableKey.currentState.scrollTo(400.0); - // now only 4 should fit, numbered 2-5. - - tester.pumpWidget(testWidget); - - expect(callbackTracker, equals([2, 3, 4, 5])); - - callbackTracker.clear(); - }); - }); - - test('ScrollableLazyList 10 items, 2-3 items visible', () { - testWidgets((WidgetTester tester) { - List callbackTracker = []; - - // The root view is 800x600 in the test environment and our list - // items are 300 tall. Scrolling should cause two or three items - // to be built. - - ItemListBuilder itemBuilder = (BuildContext context, int start, int count) { - List result = []; - for (int index = start; index < start + count; index += 1) { - callbackTracker.add(index); - result.add(new Text('$index', key: new ValueKey(index))); - } - return result; - }; - - GlobalKey> scrollableKey = new GlobalKey>(); - Widget testWidget = new ScrollableLazyList( + GlobalKey> scrollableKey = new GlobalKey>(); + FlipWidget testWidget = new FlipWidget( + left: new ScrollableLazyList( key: scrollableKey, itemBuilder: itemBuilder, - itemExtent: 300.0, - itemCount: 10 - ); + itemExtent: 200.0, + initialScrollOffset: 300.0 + ), + right: new Text('Not Today') + ); - tester.pumpWidget(testWidget); - expect(callbackTracker, equals([0, 1])); - callbackTracker.clear(); + tester.pumpWidget(testWidget); - scrollableKey.currentState.scrollTo(150.0); - tester.pumpWidget(testWidget); - expect(callbackTracker, equals([0, 1, 2])); - callbackTracker.clear(); + expect(callbackTracker, equals([1, 2, 3, 4])); - scrollableKey.currentState.scrollTo(600.0); - tester.pumpWidget(testWidget); - expect(callbackTracker, equals([2, 3])); - callbackTracker.clear(); + callbackTracker.clear(); - scrollableKey.currentState.scrollTo(750.0); - tester.pumpWidget(testWidget); - expect(callbackTracker, equals([2, 3, 4])); - callbackTracker.clear(); - }); + scrollableKey.currentState.scrollTo(400.0); + // now only 3 should fit, numbered 2-4. + + tester.pumpWidget(testWidget); + + expect(callbackTracker, equals([2, 3, 4])); + + callbackTracker.clear(); + }); + + testWidgets('HomogeneousViewport horizontal', (WidgetTester tester) { + List callbackTracker = []; + + // the root view is 800x600 in the test environment + // so if our widget is 200 pixels wide, it should fit exactly 4 times. + // but if we are offset by 300 pixels, there will be 5, numbered 1-5. + + ItemListBuilder itemBuilder = (BuildContext context, int start, int count) { + List result = []; + for (int index = start; index < start + count; index += 1) { + callbackTracker.add(index); + result.add(new Container( + key: new ValueKey(index), + width: 400.0, // this should be overridden by itemExtent + height: 500.0, // this should be ignored + child: new Text("$index") + )); + } + return result; + }; + + GlobalKey> scrollableKey = new GlobalKey>(); + FlipWidget testWidget = new FlipWidget( + left: new ScrollableLazyList( + key: scrollableKey, + itemBuilder: itemBuilder, + itemExtent: 200.0, + initialScrollOffset: 300.0, + scrollDirection: Axis.horizontal + ), + right: new Text('Not Today') + ); + + tester.pumpWidget(testWidget); + + expect(callbackTracker, equals([1, 2, 3, 4, 5])); + + callbackTracker.clear(); + + scrollableKey.currentState.scrollTo(400.0); + // now only 4 should fit, numbered 2-5. + + tester.pumpWidget(testWidget); + + expect(callbackTracker, equals([2, 3, 4, 5])); + + callbackTracker.clear(); + }); + + testWidgets('ScrollableLazyList 10 items, 2-3 items visible', (WidgetTester tester) { + List callbackTracker = []; + + // The root view is 800x600 in the test environment and our list + // items are 300 tall. Scrolling should cause two or three items + // to be built. + + ItemListBuilder itemBuilder = (BuildContext context, int start, int count) { + List result = []; + for (int index = start; index < start + count; index += 1) { + callbackTracker.add(index); + result.add(new Text('$index', key: new ValueKey(index))); + } + return result; + }; + + GlobalKey> scrollableKey = new GlobalKey>(); + Widget testWidget = new ScrollableLazyList( + key: scrollableKey, + itemBuilder: itemBuilder, + itemExtent: 300.0, + itemCount: 10 + ); + + tester.pumpWidget(testWidget); + expect(callbackTracker, equals([0, 1])); + callbackTracker.clear(); + + scrollableKey.currentState.scrollTo(150.0); + tester.pumpWidget(testWidget); + expect(callbackTracker, equals([0, 1, 2])); + callbackTracker.clear(); + + scrollableKey.currentState.scrollTo(600.0); + tester.pumpWidget(testWidget); + expect(callbackTracker, equals([2, 3])); + callbackTracker.clear(); + + scrollableKey.currentState.scrollTo(750.0); + tester.pumpWidget(testWidget); + expect(callbackTracker, equals([2, 3, 4])); + callbackTracker.clear(); }); } diff --git a/packages/flutter/test/widget/scrollable_list_hit_testing_test.dart b/packages/flutter/test/widget/scrollable_list_hit_testing_test.dart index d9df3e8ec3..dbca5b7329 100644 --- a/packages/flutter/test/widget/scrollable_list_hit_testing_test.dart +++ b/packages/flutter/test/widget/scrollable_list_hit_testing_test.dart @@ -10,97 +10,15 @@ import 'package:test/test.dart'; const List items = const [0, 1, 2, 3, 4, 5]; void main() { - test('Tap item after scroll - horizontal', () { - testWidgets((WidgetTester tester) { - List tapped = []; - tester.pumpWidget(new Center( - child: new Container( - height: 50.0, - child: new ScrollableList( - key: new GlobalKey(), - itemExtent: 290.0, - scrollDirection: Axis.horizontal, - children: items.map((int item) { - return new Container( - child: new GestureDetector( - onTap: () { tapped.add(item); }, - child: new Text('$item') - ) - ); - }) - ) - ) - )); - tester.scroll(find.text('2'), const Offset(-280.0, 0.0)); - tester.pump(const Duration(seconds: 1)); - // screen is 800px wide, and has the following items: - // -280..10 = 0 - // 10..300 = 1 - // 300..590 = 2 - // 590..880 = 3 - expect(tester, hasWidget(find.text('0'))); - expect(tester, hasWidget(find.text('1'))); - expect(tester, hasWidget(find.text('2'))); - expect(tester, hasWidget(find.text('3'))); - expect(tester, doesNotHaveWidget(find.text('4'))); - expect(tester, doesNotHaveWidget(find.text('5'))); - expect(tapped, equals([])); - tester.tap(find.text('2')); - expect(tapped, equals([2])); - }); - }); - - test('Tap item after scroll - vertical', () { - testWidgets((WidgetTester tester) { - List tapped = []; - tester.pumpWidget(new Center( - child: new Container( - width: 50.0, - child: new ScrollableList( - key: new GlobalKey(), - itemExtent: 290.0, - scrollDirection: Axis.vertical, - children: items.map((int item) { - return new Container( - child: new GestureDetector( - onTap: () { tapped.add(item); }, - child: new Text('$item') - ) - ); - }) - ) - ) - )); - tester.scroll(find.text('1'), const Offset(0.0, -280.0)); - tester.pump(const Duration(seconds: 1)); - // screen is 600px tall, and has the following items: - // -280..10 = 0 - // 10..300 = 1 - // 300..590 = 2 - // 590..880 = 3 - expect(tester, hasWidget(find.text('0'))); - expect(tester, hasWidget(find.text('1'))); - expect(tester, hasWidget(find.text('2'))); - expect(tester, hasWidget(find.text('3'))); - expect(tester, doesNotHaveWidget(find.text('4'))); - expect(tester, doesNotHaveWidget(find.text('5'))); - expect(tapped, equals([])); - tester.tap(find.text('1')); - expect(tapped, equals([1])); - tester.tap(find.text('3')); - expect(tapped, equals([1])); // the center of the third item is off-screen so it shouldn't get hit - }); - }); - - test('Padding scroll anchor start', () { - testWidgets((WidgetTester tester) { - List tapped = []; - - tester.pumpWidget( - new ScrollableList( + testWidgets('Tap item after scroll - horizontal', (WidgetTester tester) { + List tapped = []; + tester.pumpWidget(new Center( + child: new Container( + height: 50.0, + child: new ScrollableList( key: new GlobalKey(), itemExtent: 290.0, - padding: new EdgeInsets.fromLTRB(5.0, 20.0, 15.0, 10.0), + scrollDirection: Axis.horizontal, children: items.map((int item) { return new Container( child: new GestureDetector( @@ -110,32 +28,35 @@ void main() { ); }) ) - ); - tester.tapAt(new Point(200.0, 19.0)); - expect(tapped, equals([])); - tester.tapAt(new Point(200.0, 21.0)); - expect(tapped, equals([0])); - tester.tapAt(new Point(4.0, 400.0)); - expect(tapped, equals([0])); - tester.tapAt(new Point(6.0, 400.0)); - expect(tapped, equals([0, 1])); - tester.tapAt(new Point(800.0 - 14.0, 400.0)); - expect(tapped, equals([0, 1])); - tester.tapAt(new Point(800.0 - 16.0, 400.0)); - expect(tapped, equals([0, 1, 1])); - }); + ) + )); + tester.scroll(find.text('2'), const Offset(-280.0, 0.0)); + tester.pump(const Duration(seconds: 1)); + // screen is 800px wide, and has the following items: + // -280..10 = 0 + // 10..300 = 1 + // 300..590 = 2 + // 590..880 = 3 + expect(find.text('0'), findsOneWidget); + expect(find.text('1'), findsOneWidget); + expect(find.text('2'), findsOneWidget); + expect(find.text('3'), findsOneWidget); + expect(find.text('4'), findsNothing); + expect(find.text('5'), findsNothing); + expect(tapped, equals([])); + tester.tap(find.text('2')); + expect(tapped, equals([2])); }); - test('Padding scroll anchor end', () { - testWidgets((WidgetTester tester) { - List tapped = []; - - tester.pumpWidget( - new ScrollableList( + testWidgets('Tap item after scroll - vertical', (WidgetTester tester) { + List tapped = []; + tester.pumpWidget(new Center( + child: new Container( + width: 50.0, + child: new ScrollableList( key: new GlobalKey(), itemExtent: 290.0, - scrollAnchor: ViewportAnchor.end, - padding: new EdgeInsets.fromLTRB(5.0, 20.0, 15.0, 10.0), + scrollDirection: Axis.vertical, children: items.map((int item) { return new Container( child: new GestureDetector( @@ -145,19 +66,90 @@ void main() { ); }) ) - ); - tester.tapAt(new Point(200.0, 600.0 - 9.0)); - expect(tapped, equals([])); - tester.tapAt(new Point(200.0, 600.0 - 11.0)); - expect(tapped, equals([5])); - tester.tapAt(new Point(4.0, 200.0)); - expect(tapped, equals([5])); - tester.tapAt(new Point(6.0, 200.0)); - expect(tapped, equals([5, 4])); - tester.tapAt(new Point(800.0 - 14.0, 200.0)); - expect(tapped, equals([5, 4])); - tester.tapAt(new Point(800.0 - 16.0, 200.0)); - expect(tapped, equals([5, 4, 4])); - }); + ) + )); + tester.scroll(find.text('1'), const Offset(0.0, -280.0)); + tester.pump(const Duration(seconds: 1)); + // screen is 600px tall, and has the following items: + // -280..10 = 0 + // 10..300 = 1 + // 300..590 = 2 + // 590..880 = 3 + expect(find.text('0'), findsOneWidget); + expect(find.text('1'), findsOneWidget); + expect(find.text('2'), findsOneWidget); + expect(find.text('3'), findsOneWidget); + expect(find.text('4'), findsNothing); + expect(find.text('5'), findsNothing); + expect(tapped, equals([])); + tester.tap(find.text('1')); + expect(tapped, equals([1])); + tester.tap(find.text('3')); + expect(tapped, equals([1])); // the center of the third item is off-screen so it shouldn't get hit + }); + + testWidgets('Padding scroll anchor start', (WidgetTester tester) { + List tapped = []; + + tester.pumpWidget( + new ScrollableList( + key: new GlobalKey(), + itemExtent: 290.0, + padding: new EdgeInsets.fromLTRB(5.0, 20.0, 15.0, 10.0), + children: items.map((int item) { + return new Container( + child: new GestureDetector( + onTap: () { tapped.add(item); }, + child: new Text('$item') + ) + ); + }) + ) + ); + tester.tapAt(new Point(200.0, 19.0)); + expect(tapped, equals([])); + tester.tapAt(new Point(200.0, 21.0)); + expect(tapped, equals([0])); + tester.tapAt(new Point(4.0, 400.0)); + expect(tapped, equals([0])); + tester.tapAt(new Point(6.0, 400.0)); + expect(tapped, equals([0, 1])); + tester.tapAt(new Point(800.0 - 14.0, 400.0)); + expect(tapped, equals([0, 1])); + tester.tapAt(new Point(800.0 - 16.0, 400.0)); + expect(tapped, equals([0, 1, 1])); + }); + + testWidgets('Padding scroll anchor end', (WidgetTester tester) { + List tapped = []; + + tester.pumpWidget( + new ScrollableList( + key: new GlobalKey(), + itemExtent: 290.0, + scrollAnchor: ViewportAnchor.end, + padding: new EdgeInsets.fromLTRB(5.0, 20.0, 15.0, 10.0), + children: items.map((int item) { + return new Container( + child: new GestureDetector( + onTap: () { tapped.add(item); }, + child: new Text('$item') + ) + ); + }) + ) + ); + tester.tapAt(new Point(200.0, 600.0 - 9.0)); + expect(tapped, equals([])); + tester.tapAt(new Point(200.0, 600.0 - 11.0)); + expect(tapped, equals([5])); + tester.tapAt(new Point(4.0, 200.0)); + expect(tapped, equals([5])); + tester.tapAt(new Point(6.0, 200.0)); + expect(tapped, equals([5, 4])); + tester.tapAt(new Point(800.0 - 14.0, 200.0)); + expect(tapped, equals([5, 4])); + tester.tapAt(new Point(800.0 - 16.0, 200.0)); + expect(tapped, equals([5, 4, 4])); }); } diff --git a/packages/flutter/test/widget/scrollable_list_horizontal_test.dart b/packages/flutter/test/widget/scrollable_list_horizontal_test.dart index e47cbbcfef..205a95b1e9 100644 --- a/packages/flutter/test/widget/scrollable_list_horizontal_test.dart +++ b/packages/flutter/test/widget/scrollable_list_horizontal_test.dart @@ -28,226 +28,222 @@ Widget buildFrame(ViewportAnchor scrollAnchor) { } void main() { - test('Drag horizontally with scroll anchor at top', () { - testWidgets((WidgetTester tester) { - tester.pumpWidget(buildFrame(ViewportAnchor.start)); + testWidgets('Drag horizontally with scroll anchor at top', (WidgetTester tester) { + tester.pumpWidget(buildFrame(ViewportAnchor.start)); - tester.pump(const Duration(seconds: 1)); - tester.scroll(find.text('1'), const Offset(-300.0, 0.0)); - tester.pump(const Duration(seconds: 1)); - // screen is 800px wide, and has the following items: - // -10..280 = 1 - // 280..570 = 2 - // 570..860 = 3 - expect(tester, doesNotHaveWidget(find.text('0'))); - expect(tester, hasWidget(find.text('1'))); - expect(tester, hasWidget(find.text('2'))); - expect(tester, hasWidget(find.text('3'))); - expect(tester, doesNotHaveWidget(find.text('4'))); - expect(tester, doesNotHaveWidget(find.text('5'))); + tester.pump(const Duration(seconds: 1)); + tester.scroll(find.text('1'), const Offset(-300.0, 0.0)); + tester.pump(const Duration(seconds: 1)); + // screen is 800px wide, and has the following items: + // -10..280 = 1 + // 280..570 = 2 + // 570..860 = 3 + expect(find.text('0'), findsNothing); + expect(find.text('1'), findsOneWidget); + expect(find.text('2'), findsOneWidget); + expect(find.text('3'), findsOneWidget); + expect(find.text('4'), findsNothing); + expect(find.text('5'), findsNothing); - // the center of item 3 is visible, so this works; - // if item 3 was a bit wider, such that its center was past the 800px mark, this would fail, - // because it wouldn't be hit tested when scrolling from its center, as scroll() does. - tester.pump(const Duration(seconds: 1)); - tester.scroll(find.text('3'), const Offset(-290.0, 0.0)); - tester.pump(const Duration(seconds: 1)); - // screen is 800px wide, and has the following items: - // -10..280 = 2 - // 280..570 = 3 - // 570..860 = 4 - expect(tester, doesNotHaveWidget(find.text('0'))); - expect(tester, doesNotHaveWidget(find.text('1'))); - expect(tester, hasWidget(find.text('2'))); - expect(tester, hasWidget(find.text('3'))); - expect(tester, hasWidget(find.text('4'))); - expect(tester, doesNotHaveWidget(find.text('5'))); + // the center of item 3 is visible, so this works; + // if item 3 was a bit wider, such that its center was past the 800px mark, this would fail, + // because it wouldn't be hit tested when scrolling from its center, as scroll() does. + tester.pump(const Duration(seconds: 1)); + tester.scroll(find.text('3'), const Offset(-290.0, 0.0)); + tester.pump(const Duration(seconds: 1)); + // screen is 800px wide, and has the following items: + // -10..280 = 2 + // 280..570 = 3 + // 570..860 = 4 + expect(find.text('0'), findsNothing); + expect(find.text('1'), findsNothing); + expect(find.text('2'), findsOneWidget); + expect(find.text('3'), findsOneWidget); + expect(find.text('4'), findsOneWidget); + expect(find.text('5'), findsNothing); - tester.pump(const Duration(seconds: 1)); - tester.scroll(find.text('3'), const Offset(0.0, -290.0)); - tester.pump(const Duration(seconds: 1)); - // unchanged - expect(tester, doesNotHaveWidget(find.text('0'))); - expect(tester, doesNotHaveWidget(find.text('1'))); - expect(tester, hasWidget(find.text('2'))); - expect(tester, hasWidget(find.text('3'))); - expect(tester, hasWidget(find.text('4'))); - expect(tester, doesNotHaveWidget(find.text('5'))); + tester.pump(const Duration(seconds: 1)); + tester.scroll(find.text('3'), const Offset(0.0, -290.0)); + tester.pump(const Duration(seconds: 1)); + // unchanged + expect(find.text('0'), findsNothing); + expect(find.text('1'), findsNothing); + expect(find.text('2'), findsOneWidget); + expect(find.text('3'), findsOneWidget); + expect(find.text('4'), findsOneWidget); + expect(find.text('5'), findsNothing); - tester.pump(const Duration(seconds: 1)); - tester.scroll(find.text('3'), const Offset(-290.0, 0.0)); - tester.pump(const Duration(seconds: 1)); - // screen is 800px wide, and has the following items: - // -10..280 = 3 - // 280..570 = 4 - // 570..860 = 5 - expect(tester, doesNotHaveWidget(find.text('0'))); - expect(tester, doesNotHaveWidget(find.text('1'))); - expect(tester, doesNotHaveWidget(find.text('2'))); - expect(tester, hasWidget(find.text('3'))); - expect(tester, hasWidget(find.text('4'))); - expect(tester, hasWidget(find.text('5'))); + tester.pump(const Duration(seconds: 1)); + tester.scroll(find.text('3'), const Offset(-290.0, 0.0)); + tester.pump(const Duration(seconds: 1)); + // screen is 800px wide, and has the following items: + // -10..280 = 3 + // 280..570 = 4 + // 570..860 = 5 + expect(find.text('0'), findsNothing); + expect(find.text('1'), findsNothing); + expect(find.text('2'), findsNothing); + expect(find.text('3'), findsOneWidget); + expect(find.text('4'), findsOneWidget); + expect(find.text('5'), findsOneWidget); - tester.pump(const Duration(seconds: 1)); - // at this point we can drag 60 pixels further before we hit the friction zone - // then, every pixel we drag is equivalent to half a pixel of movement - // to move item 3 entirely off screen therefore takes: - // 60 + (290-60)*2 = 520 pixels - // plus a couple more to be sure - tester.scroll(find.text('3'), const Offset(-522.0, 0.0)); - tester.pump(); // just after release - // screen is 800px wide, and has the following items: - // -11..279 = 4 - // 279..569 = 5 - expect(tester, doesNotHaveWidget(find.text('0'))); - expect(tester, doesNotHaveWidget(find.text('1'))); - expect(tester, doesNotHaveWidget(find.text('2'))); - expect(tester, doesNotHaveWidget(find.text('3'))); - expect(tester, hasWidget(find.text('4'))); - expect(tester, hasWidget(find.text('5'))); - tester.pump(const Duration(seconds: 1)); // a second after release - // screen is 800px wide, and has the following items: - // -70..220 = 3 - // 220..510 = 4 - // 510..800 = 5 - expect(tester, doesNotHaveWidget(find.text('0'))); - expect(tester, doesNotHaveWidget(find.text('1'))); - expect(tester, doesNotHaveWidget(find.text('2'))); - expect(tester, hasWidget(find.text('3'))); - expect(tester, hasWidget(find.text('4'))); - expect(tester, hasWidget(find.text('5'))); + tester.pump(const Duration(seconds: 1)); + // at this point we can drag 60 pixels further before we hit the friction zone + // then, every pixel we drag is equivalent to half a pixel of movement + // to move item 3 entirely off screen therefore takes: + // 60 + (290-60)*2 = 520 pixels + // plus a couple more to be sure + tester.scroll(find.text('3'), const Offset(-522.0, 0.0)); + tester.pump(); // just after release + // screen is 800px wide, and has the following items: + // -11..279 = 4 + // 279..569 = 5 + expect(find.text('0'), findsNothing); + expect(find.text('1'), findsNothing); + expect(find.text('2'), findsNothing); + expect(find.text('3'), findsNothing); + expect(find.text('4'), findsOneWidget); + expect(find.text('5'), findsOneWidget); + tester.pump(const Duration(seconds: 1)); // a second after release + // screen is 800px wide, and has the following items: + // -70..220 = 3 + // 220..510 = 4 + // 510..800 = 5 + expect(find.text('0'), findsNothing); + expect(find.text('1'), findsNothing); + expect(find.text('2'), findsNothing); + expect(find.text('3'), findsOneWidget); + expect(find.text('4'), findsOneWidget); + expect(find.text('5'), findsOneWidget); - tester.pumpWidget(new Container()); - tester.pumpWidget(buildFrame(ViewportAnchor.start), const Duration(seconds: 1)); - tester.scroll(find.text('2'), const Offset(-280.0, 0.0)); - tester.pump(const Duration(seconds: 1)); - // screen is 800px wide, and has the following items: - // -280..10 = 0 - // 10..300 = 1 - // 300..590 = 2 - // 590..880 = 3 - expect(tester, hasWidget(find.text('0'))); - expect(tester, hasWidget(find.text('1'))); - expect(tester, hasWidget(find.text('2'))); - expect(tester, hasWidget(find.text('3'))); - expect(tester, doesNotHaveWidget(find.text('4'))); - expect(tester, doesNotHaveWidget(find.text('5'))); - tester.pump(const Duration(seconds: 1)); - tester.scroll(find.text('2'), const Offset(-290.0, 0.0)); - tester.pump(const Duration(seconds: 1)); - // screen is 800px wide, and has the following items: - // -280..10 = 1 - // 10..300 = 2 - // 300..590 = 3 - // 590..880 = 4 - expect(tester, doesNotHaveWidget(find.text('0'))); - expect(tester, hasWidget(find.text('1'))); - expect(tester, hasWidget(find.text('2'))); - expect(tester, hasWidget(find.text('3'))); - expect(tester, hasWidget(find.text('4'))); - expect(tester, doesNotHaveWidget(find.text('5'))); - }); + tester.pumpWidget(new Container()); + tester.pumpWidget(buildFrame(ViewportAnchor.start), const Duration(seconds: 1)); + tester.scroll(find.text('2'), const Offset(-280.0, 0.0)); + tester.pump(const Duration(seconds: 1)); + // screen is 800px wide, and has the following items: + // -280..10 = 0 + // 10..300 = 1 + // 300..590 = 2 + // 590..880 = 3 + expect(find.text('0'), findsOneWidget); + expect(find.text('1'), findsOneWidget); + expect(find.text('2'), findsOneWidget); + expect(find.text('3'), findsOneWidget); + expect(find.text('4'), findsNothing); + expect(find.text('5'), findsNothing); + tester.pump(const Duration(seconds: 1)); + tester.scroll(find.text('2'), const Offset(-290.0, 0.0)); + tester.pump(const Duration(seconds: 1)); + // screen is 800px wide, and has the following items: + // -280..10 = 1 + // 10..300 = 2 + // 300..590 = 3 + // 590..880 = 4 + expect(find.text('0'), findsNothing); + expect(find.text('1'), findsOneWidget); + expect(find.text('2'), findsOneWidget); + expect(find.text('3'), findsOneWidget); + expect(find.text('4'), findsOneWidget); + expect(find.text('5'), findsNothing); }); - test('Drag horizontally with scroll anchor at end', () { - testWidgets((WidgetTester tester) { - tester.pumpWidget(buildFrame(ViewportAnchor.end)); + testWidgets('Drag horizontally with scroll anchor at end', (WidgetTester tester) { + tester.pumpWidget(buildFrame(ViewportAnchor.end)); - tester.pump(const Duration(seconds: 1)); - // screen is 800px wide, and has the following items: - // -70..220 = 3 - // 220..510 = 4 - // 510..800 = 5 - expect(tester, doesNotHaveWidget(find.text('0'))); - expect(tester, doesNotHaveWidget(find.text('1'))); - expect(tester, doesNotHaveWidget(find.text('2'))); - expect(tester, hasWidget(find.text('3'))); - expect(tester, hasWidget(find.text('4'))); - expect(tester, hasWidget(find.text('5'))); + tester.pump(const Duration(seconds: 1)); + // screen is 800px wide, and has the following items: + // -70..220 = 3 + // 220..510 = 4 + // 510..800 = 5 + expect(find.text('0'), findsNothing); + expect(find.text('1'), findsNothing); + expect(find.text('2'), findsNothing); + expect(find.text('3'), findsOneWidget); + expect(find.text('4'), findsOneWidget); + expect(find.text('5'), findsOneWidget); - tester.scroll(find.text('5'), const Offset(300.0, 0.0)); - tester.pump(const Duration(seconds: 1)); - // screen is 800px wide, and has the following items: - // -80..210 = 2 - // 230..520 = 3 - // 520..810 = 4 - expect(tester, doesNotHaveWidget(find.text('0'))); - expect(tester, doesNotHaveWidget(find.text('1'))); - expect(tester, hasWidget(find.text('2'))); - expect(tester, hasWidget(find.text('3'))); - expect(tester, hasWidget(find.text('4'))); - expect(tester, doesNotHaveWidget(find.text('5'))); + tester.scroll(find.text('5'), const Offset(300.0, 0.0)); + tester.pump(const Duration(seconds: 1)); + // screen is 800px wide, and has the following items: + // -80..210 = 2 + // 230..520 = 3 + // 520..810 = 4 + expect(find.text('0'), findsNothing); + expect(find.text('1'), findsNothing); + expect(find.text('2'), findsOneWidget); + expect(find.text('3'), findsOneWidget); + expect(find.text('4'), findsOneWidget); + expect(find.text('5'), findsNothing); - // the center of item 3 is visible, so this works; - // if item 3 was a bit wider, such that its center was past the 800px mark, this would fail, - // because it wouldn't be hit tested when scrolling from its center, as scroll() does. - tester.pump(const Duration(seconds: 1)); - tester.scroll(find.text('3'), const Offset(290.0, 0.0)); - tester.pump(const Duration(seconds: 1)); - // screen is 800px wide, and has the following items: - // -10..280 = 1 - // 280..570 = 2 - // 570..860 = 3 - expect(tester, doesNotHaveWidget(find.text('0'))); - expect(tester, hasWidget(find.text('1'))); - expect(tester, hasWidget(find.text('2'))); - expect(tester, hasWidget(find.text('3'))); - expect(tester, doesNotHaveWidget(find.text('4'))); - expect(tester, doesNotHaveWidget(find.text('5'))); + // the center of item 3 is visible, so this works; + // if item 3 was a bit wider, such that its center was past the 800px mark, this would fail, + // because it wouldn't be hit tested when scrolling from its center, as scroll() does. + tester.pump(const Duration(seconds: 1)); + tester.scroll(find.text('3'), const Offset(290.0, 0.0)); + tester.pump(const Duration(seconds: 1)); + // screen is 800px wide, and has the following items: + // -10..280 = 1 + // 280..570 = 2 + // 570..860 = 3 + expect(find.text('0'), findsNothing); + expect(find.text('1'), findsOneWidget); + expect(find.text('2'), findsOneWidget); + expect(find.text('3'), findsOneWidget); + expect(find.text('4'), findsNothing); + expect(find.text('5'), findsNothing); - tester.pump(const Duration(seconds: 1)); - tester.scroll(find.text('3'), const Offset(0.0, 290.0)); - tester.pump(const Duration(seconds: 1)); - // unchanged - expect(tester, doesNotHaveWidget(find.text('0'))); - expect(tester, hasWidget(find.text('1'))); - expect(tester, hasWidget(find.text('2'))); - expect(tester, hasWidget(find.text('3'))); - expect(tester, doesNotHaveWidget(find.text('4'))); - expect(tester, doesNotHaveWidget(find.text('5'))); + tester.pump(const Duration(seconds: 1)); + tester.scroll(find.text('3'), const Offset(0.0, 290.0)); + tester.pump(const Duration(seconds: 1)); + // unchanged + expect(find.text('0'), findsNothing); + expect(find.text('1'), findsOneWidget); + expect(find.text('2'), findsOneWidget); + expect(find.text('3'), findsOneWidget); + expect(find.text('4'), findsNothing); + expect(find.text('5'), findsNothing); - tester.pump(const Duration(seconds: 1)); - tester.scroll(find.text('2'), const Offset(290.0, 0.0)); - tester.pump(const Duration(seconds: 1)); - // screen is 800px wide, and has the following items: - // -10..280 = 0 - // 280..570 = 1 - // 570..860 = 2 - expect(tester, hasWidget(find.text('0'))); - expect(tester, hasWidget(find.text('1'))); - expect(tester, hasWidget(find.text('2'))); - expect(tester, doesNotHaveWidget(find.text('3'))); - expect(tester, doesNotHaveWidget(find.text('4'))); - expect(tester, doesNotHaveWidget(find.text('5'))); + tester.pump(const Duration(seconds: 1)); + tester.scroll(find.text('2'), const Offset(290.0, 0.0)); + tester.pump(const Duration(seconds: 1)); + // screen is 800px wide, and has the following items: + // -10..280 = 0 + // 280..570 = 1 + // 570..860 = 2 + expect(find.text('0'), findsOneWidget); + expect(find.text('1'), findsOneWidget); + expect(find.text('2'), findsOneWidget); + expect(find.text('3'), findsNothing); + expect(find.text('4'), findsNothing); + expect(find.text('5'), findsNothing); - tester.pump(const Duration(seconds: 1)); - // at this point we can drag 60 pixels further before we hit the friction zone - // then, every pixel we drag is equivalent to half a pixel of movement - // to move item 3 entirely off screen therefore takes: - // 60 + (290-60)*2 = 520 pixels - // plus a couple more to be sure - tester.scroll(find.text('1'), const Offset(522.0, 0.0)); - tester.pump(); // just after release - // screen is 800px wide, and has the following items: - // 280..570 = 0 - // 570..860 = 1 - expect(tester, hasWidget(find.text('0'))); - expect(tester, hasWidget(find.text('1'))); - expect(tester, doesNotHaveWidget(find.text('2'))); - expect(tester, doesNotHaveWidget(find.text('3'))); - expect(tester, doesNotHaveWidget(find.text('4'))); - expect(tester, doesNotHaveWidget(find.text('5'))); - tester.pump(const Duration(seconds: 1)); // a second after release - // screen is 800px wide, and has the following items: - // 0..290 = 0 - // 290..580 = 1 - // 580..870 = 2 - expect(tester, hasWidget(find.text('0'))); - expect(tester, hasWidget(find.text('1'))); - expect(tester, hasWidget(find.text('2'))); - expect(tester, doesNotHaveWidget(find.text('3'))); - expect(tester, doesNotHaveWidget(find.text('4'))); - expect(tester, doesNotHaveWidget(find.text('5'))); - }); + tester.pump(const Duration(seconds: 1)); + // at this point we can drag 60 pixels further before we hit the friction zone + // then, every pixel we drag is equivalent to half a pixel of movement + // to move item 3 entirely off screen therefore takes: + // 60 + (290-60)*2 = 520 pixels + // plus a couple more to be sure + tester.scroll(find.text('1'), const Offset(522.0, 0.0)); + tester.pump(); // just after release + // screen is 800px wide, and has the following items: + // 280..570 = 0 + // 570..860 = 1 + expect(find.text('0'), findsOneWidget); + expect(find.text('1'), findsOneWidget); + expect(find.text('2'), findsNothing); + expect(find.text('3'), findsNothing); + expect(find.text('4'), findsNothing); + expect(find.text('5'), findsNothing); + tester.pump(const Duration(seconds: 1)); // a second after release + // screen is 800px wide, and has the following items: + // 0..290 = 0 + // 290..580 = 1 + // 580..870 = 2 + expect(find.text('0'), findsOneWidget); + expect(find.text('1'), findsOneWidget); + expect(find.text('2'), findsOneWidget); + expect(find.text('3'), findsNothing); + expect(find.text('4'), findsNothing); + expect(find.text('5'), findsNothing); }); } diff --git a/packages/flutter/test/widget/scrollable_list_vertical_test.dart b/packages/flutter/test/widget/scrollable_list_vertical_test.dart index 858051d971..d3a53e2a52 100644 --- a/packages/flutter/test/widget/scrollable_list_vertical_test.dart +++ b/packages/flutter/test/widget/scrollable_list_vertical_test.dart @@ -10,100 +10,96 @@ const List items = const [0, 1, 2, 3, 4, 5]; Widget buildFrame() { return new ScrollableList( - itemExtent: 290.0, - scrollDirection: Axis.vertical, - children: items.map((int item) { - return new Container( - child: new Text('$item') - ); - }) + itemExtent: 290.0, + scrollDirection: Axis.vertical, + children: items.map((int item) { + return new Container( + child: new Text('$item') + ); + }) ); } void main() { - test('Drag vertically', () { - testWidgets((WidgetTester tester) { - tester.pumpWidget(buildFrame()); + testWidgets('Drag vertically', (WidgetTester tester) { + tester.pumpWidget(buildFrame()); - tester.pump(); - tester.scroll(find.text('1'), const Offset(0.0, -300.0)); - tester.pump(); - // screen is 600px high, and has the following items: - // -10..280 = 1 - // 280..570 = 2 - // 570..860 = 3 - expect(tester, doesNotHaveWidget(find.text('0'))); - expect(tester, hasWidget(find.text('1'))); - expect(tester, hasWidget(find.text('2'))); - expect(tester, hasWidget(find.text('3'))); - expect(tester, doesNotHaveWidget(find.text('4'))); - expect(tester, doesNotHaveWidget(find.text('5'))); + tester.pump(); + tester.scroll(find.text('1'), const Offset(0.0, -300.0)); + tester.pump(); + // screen is 600px high, and has the following items: + // -10..280 = 1 + // 280..570 = 2 + // 570..860 = 3 + expect(find.text('0'), findsNothing); + expect(find.text('1'), findsOneWidget); + expect(find.text('2'), findsOneWidget); + expect(find.text('3'), findsOneWidget); + expect(find.text('4'), findsNothing); + expect(find.text('5'), findsNothing); - tester.pump(); - tester.scroll(find.text('2'), const Offset(0.0, -290.0)); - tester.pump(); - // screen is 600px high, and has the following items: - // -10..280 = 2 - // 280..570 = 3 - // 570..860 = 4 - expect(tester, doesNotHaveWidget(find.text('0'))); - expect(tester, doesNotHaveWidget(find.text('1'))); - expect(tester, hasWidget(find.text('2'))); - expect(tester, hasWidget(find.text('3'))); - expect(tester, hasWidget(find.text('4'))); - expect(tester, doesNotHaveWidget(find.text('5'))); + tester.pump(); + tester.scroll(find.text('2'), const Offset(0.0, -290.0)); + tester.pump(); + // screen is 600px high, and has the following items: + // -10..280 = 2 + // 280..570 = 3 + // 570..860 = 4 + expect(find.text('0'), findsNothing); + expect(find.text('1'), findsNothing); + expect(find.text('2'), findsOneWidget); + expect(find.text('3'), findsOneWidget); + expect(find.text('4'), findsOneWidget); + expect(find.text('5'), findsNothing); - tester.pump(); - tester.scroll(find.text('3'), const Offset(-300.0, 0.0)); - tester.pump(); - // nothing should have changed - expect(tester, doesNotHaveWidget(find.text('0'))); - expect(tester, doesNotHaveWidget(find.text('1'))); - expect(tester, hasWidget(find.text('2'))); - expect(tester, hasWidget(find.text('3'))); - expect(tester, hasWidget(find.text('4'))); - expect(tester, doesNotHaveWidget(find.text('5'))); - }); + tester.pump(); + tester.scroll(find.text('3'), const Offset(-300.0, 0.0)); + tester.pump(); + // nothing should have changed + expect(find.text('0'), findsNothing); + expect(find.text('1'), findsNothing); + expect(find.text('2'), findsOneWidget); + expect(find.text('3'), findsOneWidget); + expect(find.text('4'), findsOneWidget); + expect(find.text('5'), findsNothing); }); - test('Drag vertically', () { - testWidgets((WidgetTester tester) { - tester.pumpWidget( - new ScrollableList( - itemExtent: 290.0, - padding: new EdgeInsets.only(top: 250.0), - scrollDirection: Axis.vertical, - children: items.map((int item) { - return new Container( - child: new Text('$item') - ); - }) - ) - ); + testWidgets('Drag vertically', (WidgetTester tester) { + tester.pumpWidget( + new ScrollableList( + itemExtent: 290.0, + padding: new EdgeInsets.only(top: 250.0), + scrollDirection: Axis.vertical, + children: items.map((int item) { + return new Container( + child: new Text('$item') + ); + }) + ) + ); - tester.pump(); - // screen is 600px high, and has the following items: - // 250..540 = 0 - // 540..830 = 1 - expect(tester, hasWidget(find.text('0'))); - expect(tester, hasWidget(find.text('1'))); - expect(tester, doesNotHaveWidget(find.text('2'))); - expect(tester, doesNotHaveWidget(find.text('3'))); - expect(tester, doesNotHaveWidget(find.text('4'))); - expect(tester, doesNotHaveWidget(find.text('5'))); + tester.pump(); + // screen is 600px high, and has the following items: + // 250..540 = 0 + // 540..830 = 1 + expect(find.text('0'), findsOneWidget); + expect(find.text('1'), findsOneWidget); + expect(find.text('2'), findsNothing); + expect(find.text('3'), findsNothing); + expect(find.text('4'), findsNothing); + expect(find.text('5'), findsNothing); - tester.scroll(find.text('0'), const Offset(0.0, -300.0)); - tester.pump(); - // screen is 600px high, and has the following items: - // -50..240 = 0 - // 240..530 = 1 - // 530..820 = 2 - expect(tester, hasWidget(find.text('0'))); - expect(tester, hasWidget(find.text('1'))); - expect(tester, hasWidget(find.text('2'))); - expect(tester, doesNotHaveWidget(find.text('3'))); - expect(tester, doesNotHaveWidget(find.text('4'))); - expect(tester, doesNotHaveWidget(find.text('5'))); - }); + tester.scroll(find.text('0'), const Offset(0.0, -300.0)); + tester.pump(); + // screen is 600px high, and has the following items: + // -50..240 = 0 + // 240..530 = 1 + // 530..820 = 2 + expect(find.text('0'), findsOneWidget); + expect(find.text('1'), findsOneWidget); + expect(find.text('2'), findsOneWidget); + expect(find.text('3'), findsNothing); + expect(find.text('4'), findsNothing); + expect(find.text('5'), findsNothing); }); } diff --git a/packages/flutter/test/widget/scrollable_list_with_inherited_test.dart b/packages/flutter/test/widget/scrollable_list_with_inherited_test.dart index e9d99c9ac7..1bc5bc73ce 100644 --- a/packages/flutter/test/widget/scrollable_list_with_inherited_test.dart +++ b/packages/flutter/test/widget/scrollable_list_with_inherited_test.dart @@ -28,19 +28,17 @@ Widget buildFrame() { } void main() { - test('LazyBlock is a build function (smoketest)', () { - testWidgets((WidgetTester tester) { - tester.pumpWidget(buildFrame()); - expect(tester, hasWidget(find.text('0'))); - expect(tester, hasWidget(find.text('1'))); - expect(tester, hasWidget(find.text('2'))); - expect(tester, hasWidget(find.text('3'))); - items.removeAt(2); - tester.pumpWidget(buildFrame()); - expect(tester, hasWidget(find.text('0'))); - expect(tester, hasWidget(find.text('1'))); - expect(tester, doesNotHaveWidget(find.text('2'))); - expect(tester, hasWidget(find.text('3'))); - }); + testWidgets('LazyBlock is a build function (smoketest)', (WidgetTester tester) { + tester.pumpWidget(buildFrame()); + expect(find.text('0'), findsOneWidget); + expect(find.text('1'), findsOneWidget); + expect(find.text('2'), findsOneWidget); + expect(find.text('3'), findsOneWidget); + items.removeAt(2); + tester.pumpWidget(buildFrame()); + expect(find.text('0'), findsOneWidget); + expect(find.text('1'), findsOneWidget); + expect(find.text('2'), findsNothing); + expect(find.text('3'), findsOneWidget); }); } diff --git a/packages/flutter/test/widget/semantics_1_test.dart b/packages/flutter/test/widget/semantics_1_test.dart index 4ab1d0c6f1..83a0f20cb2 100644 --- a/packages/flutter/test/widget/semantics_1_test.dart +++ b/packages/flutter/test/widget/semantics_1_test.dart @@ -11,240 +11,238 @@ import 'package:test/test.dart'; import 'test_semantics.dart'; void main() { - test('Semantics 1', () { - testWidgets((WidgetTester tester) { - TestSemanticsListener client = new TestSemanticsListener(); + testWidgets('Semantics 1', (WidgetTester tester) { + TestSemanticsListener client = new TestSemanticsListener(); - // smoketest - tester.pumpWidget( - new Container( - child: new Semantics( - label: 'test1', - child: new Container() - ) + // smoketest + tester.pumpWidget( + new Container( + child: new Semantics( + label: 'test1', + child: new Container() ) - ); - expect(client.updates.length, equals(2)); - expect(client.updates[0].id, equals(0)); - expect(client.updates[0].flags.canBeTapped, isFalse); - expect(client.updates[0].flags.canBeLongPressed, isFalse); - expect(client.updates[0].flags.canBeScrolledHorizontally, isFalse); - expect(client.updates[0].flags.canBeScrolledVertically, isFalse); - expect(client.updates[0].flags.hasCheckedState, isFalse); - expect(client.updates[0].flags.isChecked, isFalse); - expect(client.updates[0].strings.label, equals('test1')); - expect(client.updates[0].geometry.transform, isNull); - expect(client.updates[0].geometry.left, equals(0.0)); - expect(client.updates[0].geometry.top, equals(0.0)); - expect(client.updates[0].geometry.width, equals(800.0)); - expect(client.updates[0].geometry.height, equals(600.0)); - expect(client.updates[0].children.length, equals(0)); - expect(client.updates[1], isNull); - client.updates.clear(); + ) + ); + expect(client.updates.length, equals(2)); + expect(client.updates[0].id, equals(0)); + expect(client.updates[0].flags.canBeTapped, isFalse); + expect(client.updates[0].flags.canBeLongPressed, isFalse); + expect(client.updates[0].flags.canBeScrolledHorizontally, isFalse); + expect(client.updates[0].flags.canBeScrolledVertically, isFalse); + expect(client.updates[0].flags.hasCheckedState, isFalse); + expect(client.updates[0].flags.isChecked, isFalse); + expect(client.updates[0].strings.label, equals('test1')); + expect(client.updates[0].geometry.transform, isNull); + expect(client.updates[0].geometry.left, equals(0.0)); + expect(client.updates[0].geometry.top, equals(0.0)); + expect(client.updates[0].geometry.width, equals(800.0)); + expect(client.updates[0].geometry.height, equals(600.0)); + expect(client.updates[0].children.length, equals(0)); + expect(client.updates[1], isNull); + client.updates.clear(); - // control for forking - tester.pumpWidget( - new Column( - children: [ - new Container( - height: 10.0, - child: new Semantics(label: 'child1') - ), - new Container( - height: 10.0, - child: new IgnorePointer( - ignoring: true, - child: new Semantics(label: 'child2') - ) - ), - ], - crossAxisAlignment: CrossAxisAlignment.stretch - ) - ); - expect(client.updates.length, equals(2)); - expect(client.updates[0].id, equals(0)); - expect(client.updates[0].flags.canBeTapped, isFalse); - expect(client.updates[0].flags.canBeLongPressed, isFalse); - expect(client.updates[0].flags.canBeScrolledHorizontally, isFalse); - expect(client.updates[0].flags.canBeScrolledVertically, isFalse); - expect(client.updates[0].flags.hasCheckedState, isFalse); - expect(client.updates[0].flags.isChecked, isFalse); - expect(client.updates[0].strings.label, equals('child1')); - expect(client.updates[0].geometry.transform, isNull); - expect(client.updates[0].geometry.left, equals(0.0)); - expect(client.updates[0].geometry.top, equals(0.0)); - expect(client.updates[0].geometry.width, equals(800.0)); - expect(client.updates[0].geometry.height, equals(600.0)); - expect(client.updates[0].children.length, equals(0)); - expect(client.updates[1], isNull); - client.updates.clear(); + // control for forking + tester.pumpWidget( + new Column( + children: [ + new Container( + height: 10.0, + child: new Semantics(label: 'child1') + ), + new Container( + height: 10.0, + child: new IgnorePointer( + ignoring: true, + child: new Semantics(label: 'child2') + ) + ), + ], + crossAxisAlignment: CrossAxisAlignment.stretch + ) + ); + expect(client.updates.length, equals(2)); + expect(client.updates[0].id, equals(0)); + expect(client.updates[0].flags.canBeTapped, isFalse); + expect(client.updates[0].flags.canBeLongPressed, isFalse); + expect(client.updates[0].flags.canBeScrolledHorizontally, isFalse); + expect(client.updates[0].flags.canBeScrolledVertically, isFalse); + expect(client.updates[0].flags.hasCheckedState, isFalse); + expect(client.updates[0].flags.isChecked, isFalse); + expect(client.updates[0].strings.label, equals('child1')); + expect(client.updates[0].geometry.transform, isNull); + expect(client.updates[0].geometry.left, equals(0.0)); + expect(client.updates[0].geometry.top, equals(0.0)); + expect(client.updates[0].geometry.width, equals(800.0)); + expect(client.updates[0].geometry.height, equals(600.0)); + expect(client.updates[0].children.length, equals(0)); + expect(client.updates[1], isNull); + client.updates.clear(); - // forking semantics - tester.pumpWidget( - new Column( - children: [ - new Container( - height: 10.0, - child: new Semantics(label: 'child1') - ), - new Container( - height: 10.0, - child: new IgnorePointer( - ignoring: false, - child: new Semantics(label: 'child2') - ) - ), - ], - crossAxisAlignment: CrossAxisAlignment.stretch - ) - ); - expect(client.updates.length, equals(2)); - expect(client.updates[0].id, equals(0)); - expect(client.updates[0].flags.canBeTapped, isFalse); - expect(client.updates[0].flags.canBeLongPressed, isFalse); - expect(client.updates[0].flags.canBeScrolledHorizontally, isFalse); - expect(client.updates[0].flags.canBeScrolledVertically, isFalse); - expect(client.updates[0].flags.hasCheckedState, isFalse); - expect(client.updates[0].flags.isChecked, isFalse); - expect(client.updates[0].strings.label, equals('')); - expect(client.updates[0].geometry.transform, isNull); - expect(client.updates[0].geometry.left, equals(0.0)); - expect(client.updates[0].geometry.top, equals(0.0)); - expect(client.updates[0].geometry.width, equals(800.0)); - expect(client.updates[0].geometry.height, equals(600.0)); - expect(client.updates[0].children.length, equals(2)); - expect(client.updates[0].children[0].id, equals(1)); - expect(client.updates[0].children[0].flags.canBeTapped, isFalse); - expect(client.updates[0].children[0].flags.canBeLongPressed, isFalse); - expect(client.updates[0].children[0].flags.canBeScrolledHorizontally, isFalse); - expect(client.updates[0].children[0].flags.canBeScrolledVertically, isFalse); - expect(client.updates[0].children[0].flags.hasCheckedState, isFalse); - expect(client.updates[0].children[0].flags.isChecked, isFalse); - expect(client.updates[0].children[0].strings.label, equals('child1')); - expect(client.updates[0].children[0].geometry.transform, isNull); - expect(client.updates[0].children[0].geometry.left, equals(0.0)); - expect(client.updates[0].children[0].geometry.top, equals(0.0)); - expect(client.updates[0].children[0].geometry.width, equals(800.0)); - expect(client.updates[0].children[0].geometry.height, equals(10.0)); - expect(client.updates[0].children[0].children.length, equals(0)); - expect(client.updates[0].children[1].id, equals(2)); - expect(client.updates[0].children[1].flags.canBeTapped, isFalse); - expect(client.updates[0].children[1].flags.canBeLongPressed, isFalse); - expect(client.updates[0].children[1].flags.canBeScrolledHorizontally, isFalse); - expect(client.updates[0].children[1].flags.canBeScrolledVertically, isFalse); - expect(client.updates[0].children[1].flags.hasCheckedState, isFalse); - expect(client.updates[0].children[1].flags.isChecked, isFalse); - expect(client.updates[0].children[1].strings.label, equals('child2')); - expect(client.updates[0].children[1].geometry.transform, equals([1.0,0.0,0.0,0.0, 0.0,1.0,0.0,0.0, 0.0,0.0,1.0,0.0, 0.0,10.0,0.0,1.0])); - expect(client.updates[0].children[1].geometry.left, equals(0.0)); - expect(client.updates[0].children[1].geometry.top, equals(0.0)); - expect(client.updates[0].children[1].geometry.width, equals(800.0)); - expect(client.updates[0].children[1].geometry.height, equals(10.0)); - expect(client.updates[0].children[1].children.length, equals(0)); - expect(client.updates[1], isNull); - client.updates.clear(); + // forking semantics + tester.pumpWidget( + new Column( + children: [ + new Container( + height: 10.0, + child: new Semantics(label: 'child1') + ), + new Container( + height: 10.0, + child: new IgnorePointer( + ignoring: false, + child: new Semantics(label: 'child2') + ) + ), + ], + crossAxisAlignment: CrossAxisAlignment.stretch + ) + ); + expect(client.updates.length, equals(2)); + expect(client.updates[0].id, equals(0)); + expect(client.updates[0].flags.canBeTapped, isFalse); + expect(client.updates[0].flags.canBeLongPressed, isFalse); + expect(client.updates[0].flags.canBeScrolledHorizontally, isFalse); + expect(client.updates[0].flags.canBeScrolledVertically, isFalse); + expect(client.updates[0].flags.hasCheckedState, isFalse); + expect(client.updates[0].flags.isChecked, isFalse); + expect(client.updates[0].strings.label, equals('')); + expect(client.updates[0].geometry.transform, isNull); + expect(client.updates[0].geometry.left, equals(0.0)); + expect(client.updates[0].geometry.top, equals(0.0)); + expect(client.updates[0].geometry.width, equals(800.0)); + expect(client.updates[0].geometry.height, equals(600.0)); + expect(client.updates[0].children.length, equals(2)); + expect(client.updates[0].children[0].id, equals(1)); + expect(client.updates[0].children[0].flags.canBeTapped, isFalse); + expect(client.updates[0].children[0].flags.canBeLongPressed, isFalse); + expect(client.updates[0].children[0].flags.canBeScrolledHorizontally, isFalse); + expect(client.updates[0].children[0].flags.canBeScrolledVertically, isFalse); + expect(client.updates[0].children[0].flags.hasCheckedState, isFalse); + expect(client.updates[0].children[0].flags.isChecked, isFalse); + expect(client.updates[0].children[0].strings.label, equals('child1')); + expect(client.updates[0].children[0].geometry.transform, isNull); + expect(client.updates[0].children[0].geometry.left, equals(0.0)); + expect(client.updates[0].children[0].geometry.top, equals(0.0)); + expect(client.updates[0].children[0].geometry.width, equals(800.0)); + expect(client.updates[0].children[0].geometry.height, equals(10.0)); + expect(client.updates[0].children[0].children.length, equals(0)); + expect(client.updates[0].children[1].id, equals(2)); + expect(client.updates[0].children[1].flags.canBeTapped, isFalse); + expect(client.updates[0].children[1].flags.canBeLongPressed, isFalse); + expect(client.updates[0].children[1].flags.canBeScrolledHorizontally, isFalse); + expect(client.updates[0].children[1].flags.canBeScrolledVertically, isFalse); + expect(client.updates[0].children[1].flags.hasCheckedState, isFalse); + expect(client.updates[0].children[1].flags.isChecked, isFalse); + expect(client.updates[0].children[1].strings.label, equals('child2')); + expect(client.updates[0].children[1].geometry.transform, equals([1.0,0.0,0.0,0.0, 0.0,1.0,0.0,0.0, 0.0,0.0,1.0,0.0, 0.0,10.0,0.0,1.0])); + expect(client.updates[0].children[1].geometry.left, equals(0.0)); + expect(client.updates[0].children[1].geometry.top, equals(0.0)); + expect(client.updates[0].children[1].geometry.width, equals(800.0)); + expect(client.updates[0].children[1].geometry.height, equals(10.0)); + expect(client.updates[0].children[1].children.length, equals(0)); + expect(client.updates[1], isNull); + client.updates.clear(); - // toggle a branch off - tester.pumpWidget( - new Column( - children: [ - new Container( - height: 10.0, - child: new Semantics(label: 'child1') - ), - new Container( - height: 10.0, - child: new IgnorePointer( - ignoring: true, - child: new Semantics(label: 'child2') - ) - ), - ], - crossAxisAlignment: CrossAxisAlignment.stretch - ) - ); - expect(client.updates.length, equals(2)); - expect(client.updates[0].id, equals(0)); - expect(client.updates[0].flags.canBeTapped, isFalse); - expect(client.updates[0].flags.canBeLongPressed, isFalse); - expect(client.updates[0].flags.canBeScrolledHorizontally, isFalse); - expect(client.updates[0].flags.canBeScrolledVertically, isFalse); - expect(client.updates[0].flags.hasCheckedState, isFalse); - expect(client.updates[0].flags.isChecked, isFalse); - expect(client.updates[0].strings.label, equals('child1')); - expect(client.updates[0].geometry.transform, isNull); - expect(client.updates[0].geometry.left, equals(0.0)); - expect(client.updates[0].geometry.top, equals(0.0)); - expect(client.updates[0].geometry.width, equals(800.0)); - expect(client.updates[0].geometry.height, equals(600.0)); - expect(client.updates[0].children.length, equals(0)); - expect(client.updates[1], isNull); - client.updates.clear(); + // toggle a branch off + tester.pumpWidget( + new Column( + children: [ + new Container( + height: 10.0, + child: new Semantics(label: 'child1') + ), + new Container( + height: 10.0, + child: new IgnorePointer( + ignoring: true, + child: new Semantics(label: 'child2') + ) + ), + ], + crossAxisAlignment: CrossAxisAlignment.stretch + ) + ); + expect(client.updates.length, equals(2)); + expect(client.updates[0].id, equals(0)); + expect(client.updates[0].flags.canBeTapped, isFalse); + expect(client.updates[0].flags.canBeLongPressed, isFalse); + expect(client.updates[0].flags.canBeScrolledHorizontally, isFalse); + expect(client.updates[0].flags.canBeScrolledVertically, isFalse); + expect(client.updates[0].flags.hasCheckedState, isFalse); + expect(client.updates[0].flags.isChecked, isFalse); + expect(client.updates[0].strings.label, equals('child1')); + expect(client.updates[0].geometry.transform, isNull); + expect(client.updates[0].geometry.left, equals(0.0)); + expect(client.updates[0].geometry.top, equals(0.0)); + expect(client.updates[0].geometry.width, equals(800.0)); + expect(client.updates[0].geometry.height, equals(600.0)); + expect(client.updates[0].children.length, equals(0)); + expect(client.updates[1], isNull); + client.updates.clear(); - // toggle a branch back on - tester.pumpWidget( - new Column( - children: [ - new Container( - height: 10.0, - child: new Semantics(label: 'child1') - ), - new Container( - height: 10.0, - child: new IgnorePointer( - ignoring: false, - child: new Semantics(label: 'child2') - ) - ), - ], - crossAxisAlignment: CrossAxisAlignment.stretch - ) - ); - expect(client.updates.length, equals(2)); - expect(client.updates[0].id, equals(0)); - expect(client.updates[0].flags.canBeTapped, isFalse); - expect(client.updates[0].flags.canBeLongPressed, isFalse); - expect(client.updates[0].flags.canBeScrolledHorizontally, isFalse); - expect(client.updates[0].flags.canBeScrolledVertically, isFalse); - expect(client.updates[0].flags.hasCheckedState, isFalse); - expect(client.updates[0].flags.isChecked, isFalse); - expect(client.updates[0].strings.label, equals('')); - expect(client.updates[0].geometry.transform, isNull); - expect(client.updates[0].geometry.left, equals(0.0)); - expect(client.updates[0].geometry.top, equals(0.0)); - expect(client.updates[0].geometry.width, equals(800.0)); - expect(client.updates[0].geometry.height, equals(600.0)); - expect(client.updates[0].children.length, equals(2)); - expect(client.updates[0].children[0].id, equals(3)); - expect(client.updates[0].children[0].flags.canBeTapped, isFalse); - expect(client.updates[0].children[0].flags.canBeLongPressed, isFalse); - expect(client.updates[0].children[0].flags.canBeScrolledHorizontally, isFalse); - expect(client.updates[0].children[0].flags.canBeScrolledVertically, isFalse); - expect(client.updates[0].children[0].flags.hasCheckedState, isFalse); - expect(client.updates[0].children[0].flags.isChecked, isFalse); - expect(client.updates[0].children[0].strings.label, equals('child1')); - expect(client.updates[0].children[0].geometry.transform, isNull); - expect(client.updates[0].children[0].geometry.left, equals(0.0)); - expect(client.updates[0].children[0].geometry.top, equals(0.0)); - expect(client.updates[0].children[0].geometry.width, equals(800.0)); - expect(client.updates[0].children[0].geometry.height, equals(10.0)); - expect(client.updates[0].children[0].children.length, equals(0)); - expect(client.updates[0].children[1].id, equals(2)); - expect(client.updates[0].children[1].flags.canBeTapped, isFalse); - expect(client.updates[0].children[1].flags.canBeLongPressed, isFalse); - expect(client.updates[0].children[1].flags.canBeScrolledHorizontally, isFalse); - expect(client.updates[0].children[1].flags.canBeScrolledVertically, isFalse); - expect(client.updates[0].children[1].flags.hasCheckedState, isFalse); - expect(client.updates[0].children[1].flags.isChecked, isFalse); - expect(client.updates[0].children[1].strings.label, equals('child2')); - expect(client.updates[0].children[1].geometry.transform, equals([1.0,0.0,0.0,0.0, 0.0,1.0,0.0,0.0, 0.0,0.0,1.0,0.0, 0.0,10.0,0.0,1.0])); - expect(client.updates[0].children[1].geometry.left, equals(0.0)); - expect(client.updates[0].children[1].geometry.top, equals(0.0)); - expect(client.updates[0].children[1].geometry.width, equals(800.0)); - expect(client.updates[0].children[1].geometry.height, equals(10.0)); - expect(client.updates[0].children[1].children.length, equals(0)); - expect(client.updates[1], isNull); - client.updates.clear(); - }); + // toggle a branch back on + tester.pumpWidget( + new Column( + children: [ + new Container( + height: 10.0, + child: new Semantics(label: 'child1') + ), + new Container( + height: 10.0, + child: new IgnorePointer( + ignoring: false, + child: new Semantics(label: 'child2') + ) + ), + ], + crossAxisAlignment: CrossAxisAlignment.stretch + ) + ); + expect(client.updates.length, equals(2)); + expect(client.updates[0].id, equals(0)); + expect(client.updates[0].flags.canBeTapped, isFalse); + expect(client.updates[0].flags.canBeLongPressed, isFalse); + expect(client.updates[0].flags.canBeScrolledHorizontally, isFalse); + expect(client.updates[0].flags.canBeScrolledVertically, isFalse); + expect(client.updates[0].flags.hasCheckedState, isFalse); + expect(client.updates[0].flags.isChecked, isFalse); + expect(client.updates[0].strings.label, equals('')); + expect(client.updates[0].geometry.transform, isNull); + expect(client.updates[0].geometry.left, equals(0.0)); + expect(client.updates[0].geometry.top, equals(0.0)); + expect(client.updates[0].geometry.width, equals(800.0)); + expect(client.updates[0].geometry.height, equals(600.0)); + expect(client.updates[0].children.length, equals(2)); + expect(client.updates[0].children[0].id, equals(3)); + expect(client.updates[0].children[0].flags.canBeTapped, isFalse); + expect(client.updates[0].children[0].flags.canBeLongPressed, isFalse); + expect(client.updates[0].children[0].flags.canBeScrolledHorizontally, isFalse); + expect(client.updates[0].children[0].flags.canBeScrolledVertically, isFalse); + expect(client.updates[0].children[0].flags.hasCheckedState, isFalse); + expect(client.updates[0].children[0].flags.isChecked, isFalse); + expect(client.updates[0].children[0].strings.label, equals('child1')); + expect(client.updates[0].children[0].geometry.transform, isNull); + expect(client.updates[0].children[0].geometry.left, equals(0.0)); + expect(client.updates[0].children[0].geometry.top, equals(0.0)); + expect(client.updates[0].children[0].geometry.width, equals(800.0)); + expect(client.updates[0].children[0].geometry.height, equals(10.0)); + expect(client.updates[0].children[0].children.length, equals(0)); + expect(client.updates[0].children[1].id, equals(2)); + expect(client.updates[0].children[1].flags.canBeTapped, isFalse); + expect(client.updates[0].children[1].flags.canBeLongPressed, isFalse); + expect(client.updates[0].children[1].flags.canBeScrolledHorizontally, isFalse); + expect(client.updates[0].children[1].flags.canBeScrolledVertically, isFalse); + expect(client.updates[0].children[1].flags.hasCheckedState, isFalse); + expect(client.updates[0].children[1].flags.isChecked, isFalse); + expect(client.updates[0].children[1].strings.label, equals('child2')); + expect(client.updates[0].children[1].geometry.transform, equals([1.0,0.0,0.0,0.0, 0.0,1.0,0.0,0.0, 0.0,0.0,1.0,0.0, 0.0,10.0,0.0,1.0])); + expect(client.updates[0].children[1].geometry.left, equals(0.0)); + expect(client.updates[0].children[1].geometry.top, equals(0.0)); + expect(client.updates[0].children[1].geometry.width, equals(800.0)); + expect(client.updates[0].children[1].geometry.height, equals(10.0)); + expect(client.updates[0].children[1].children.length, equals(0)); + expect(client.updates[1], isNull); + client.updates.clear(); }); } diff --git a/packages/flutter/test/widget/semantics_2_test.dart b/packages/flutter/test/widget/semantics_2_test.dart index 7cbcce0208..6761f34147 100644 --- a/packages/flutter/test/widget/semantics_2_test.dart +++ b/packages/flutter/test/widget/semantics_2_test.dart @@ -11,180 +11,178 @@ import 'package:test/test.dart'; import 'test_semantics.dart'; void main() { - test('Semantics 2', () { - testWidgets((WidgetTester tester) { - TestSemanticsListener client = new TestSemanticsListener(); + testWidgets('Semantics 2', (WidgetTester tester) { + TestSemanticsListener client = new TestSemanticsListener(); - // this test is the same as the test in Semantics 1, but - // starting with the second branch being ignored and then - // switching to not ignoring it. + // this test is the same as the test in Semantics 1, but + // starting with the second branch being ignored and then + // switching to not ignoring it. - // forking semantics - tester.pumpWidget( - new Column( - children: [ - new Container( - height: 10.0, - child: new Semantics(label: 'child1') - ), - new Container( - height: 10.0, - child: new IgnorePointer( - ignoring: false, - child: new Semantics(label: 'child2') - ) - ), - ], - crossAxisAlignment: CrossAxisAlignment.stretch - ) - ); - expect(client.updates.length, equals(2)); - expect(client.updates[0].id, equals(0)); - expect(client.updates[0].flags.canBeTapped, isFalse); - expect(client.updates[0].flags.canBeLongPressed, isFalse); - expect(client.updates[0].flags.canBeScrolledHorizontally, isFalse); - expect(client.updates[0].flags.canBeScrolledVertically, isFalse); - expect(client.updates[0].flags.hasCheckedState, isFalse); - expect(client.updates[0].flags.isChecked, isFalse); - expect(client.updates[0].strings.label, equals('')); - expect(client.updates[0].geometry.transform, isNull); - expect(client.updates[0].geometry.left, equals(0.0)); - expect(client.updates[0].geometry.top, equals(0.0)); - expect(client.updates[0].geometry.width, equals(800.0)); - expect(client.updates[0].geometry.height, equals(600.0)); - expect(client.updates[0].children.length, equals(2)); - expect(client.updates[0].children[0].id, equals(1)); - expect(client.updates[0].children[0].flags.canBeTapped, isFalse); - expect(client.updates[0].children[0].flags.canBeLongPressed, isFalse); - expect(client.updates[0].children[0].flags.canBeScrolledHorizontally, isFalse); - expect(client.updates[0].children[0].flags.canBeScrolledVertically, isFalse); - expect(client.updates[0].children[0].flags.hasCheckedState, isFalse); - expect(client.updates[0].children[0].flags.isChecked, isFalse); - expect(client.updates[0].children[0].strings.label, equals('child1')); - expect(client.updates[0].children[0].geometry.transform, isNull); - expect(client.updates[0].children[0].geometry.left, equals(0.0)); - expect(client.updates[0].children[0].geometry.top, equals(0.0)); - expect(client.updates[0].children[0].geometry.width, equals(800.0)); - expect(client.updates[0].children[0].geometry.height, equals(10.0)); - expect(client.updates[0].children[0].children.length, equals(0)); - expect(client.updates[0].children[1].id, equals(2)); - expect(client.updates[0].children[1].flags.canBeTapped, isFalse); - expect(client.updates[0].children[1].flags.canBeLongPressed, isFalse); - expect(client.updates[0].children[1].flags.canBeScrolledHorizontally, isFalse); - expect(client.updates[0].children[1].flags.canBeScrolledVertically, isFalse); - expect(client.updates[0].children[1].flags.hasCheckedState, isFalse); - expect(client.updates[0].children[1].flags.isChecked, isFalse); - expect(client.updates[0].children[1].strings.label, equals('child2')); - expect(client.updates[0].children[1].geometry.transform, equals([1.0,0.0,0.0,0.0, 0.0,1.0,0.0,0.0, 0.0,0.0,1.0,0.0, 0.0,10.0,0.0,1.0])); - expect(client.updates[0].children[1].geometry.left, equals(0.0)); - expect(client.updates[0].children[1].geometry.top, equals(0.0)); - expect(client.updates[0].children[1].geometry.width, equals(800.0)); - expect(client.updates[0].children[1].geometry.height, equals(10.0)); - expect(client.updates[0].children[1].children.length, equals(0)); - expect(client.updates[1], isNull); - client.updates.clear(); + // forking semantics + tester.pumpWidget( + new Column( + children: [ + new Container( + height: 10.0, + child: new Semantics(label: 'child1') + ), + new Container( + height: 10.0, + child: new IgnorePointer( + ignoring: false, + child: new Semantics(label: 'child2') + ) + ), + ], + crossAxisAlignment: CrossAxisAlignment.stretch + ) + ); + expect(client.updates.length, equals(2)); + expect(client.updates[0].id, equals(0)); + expect(client.updates[0].flags.canBeTapped, isFalse); + expect(client.updates[0].flags.canBeLongPressed, isFalse); + expect(client.updates[0].flags.canBeScrolledHorizontally, isFalse); + expect(client.updates[0].flags.canBeScrolledVertically, isFalse); + expect(client.updates[0].flags.hasCheckedState, isFalse); + expect(client.updates[0].flags.isChecked, isFalse); + expect(client.updates[0].strings.label, equals('')); + expect(client.updates[0].geometry.transform, isNull); + expect(client.updates[0].geometry.left, equals(0.0)); + expect(client.updates[0].geometry.top, equals(0.0)); + expect(client.updates[0].geometry.width, equals(800.0)); + expect(client.updates[0].geometry.height, equals(600.0)); + expect(client.updates[0].children.length, equals(2)); + expect(client.updates[0].children[0].id, equals(1)); + expect(client.updates[0].children[0].flags.canBeTapped, isFalse); + expect(client.updates[0].children[0].flags.canBeLongPressed, isFalse); + expect(client.updates[0].children[0].flags.canBeScrolledHorizontally, isFalse); + expect(client.updates[0].children[0].flags.canBeScrolledVertically, isFalse); + expect(client.updates[0].children[0].flags.hasCheckedState, isFalse); + expect(client.updates[0].children[0].flags.isChecked, isFalse); + expect(client.updates[0].children[0].strings.label, equals('child1')); + expect(client.updates[0].children[0].geometry.transform, isNull); + expect(client.updates[0].children[0].geometry.left, equals(0.0)); + expect(client.updates[0].children[0].geometry.top, equals(0.0)); + expect(client.updates[0].children[0].geometry.width, equals(800.0)); + expect(client.updates[0].children[0].geometry.height, equals(10.0)); + expect(client.updates[0].children[0].children.length, equals(0)); + expect(client.updates[0].children[1].id, equals(2)); + expect(client.updates[0].children[1].flags.canBeTapped, isFalse); + expect(client.updates[0].children[1].flags.canBeLongPressed, isFalse); + expect(client.updates[0].children[1].flags.canBeScrolledHorizontally, isFalse); + expect(client.updates[0].children[1].flags.canBeScrolledVertically, isFalse); + expect(client.updates[0].children[1].flags.hasCheckedState, isFalse); + expect(client.updates[0].children[1].flags.isChecked, isFalse); + expect(client.updates[0].children[1].strings.label, equals('child2')); + expect(client.updates[0].children[1].geometry.transform, equals([1.0,0.0,0.0,0.0, 0.0,1.0,0.0,0.0, 0.0,0.0,1.0,0.0, 0.0,10.0,0.0,1.0])); + expect(client.updates[0].children[1].geometry.left, equals(0.0)); + expect(client.updates[0].children[1].geometry.top, equals(0.0)); + expect(client.updates[0].children[1].geometry.width, equals(800.0)); + expect(client.updates[0].children[1].geometry.height, equals(10.0)); + expect(client.updates[0].children[1].children.length, equals(0)); + expect(client.updates[1], isNull); + client.updates.clear(); - // toggle a branch off - tester.pumpWidget( - new Column( - children: [ - new Container( - height: 10.0, - child: new Semantics(label: 'child1') - ), - new Container( - height: 10.0, - child: new IgnorePointer( - ignoring: true, - child: new Semantics(label: 'child2') - ) - ), - ], - crossAxisAlignment: CrossAxisAlignment.stretch - ) - ); - expect(client.updates.length, equals(2)); - expect(client.updates[0].id, equals(0)); - expect(client.updates[0].flags.canBeTapped, isFalse); - expect(client.updates[0].flags.canBeLongPressed, isFalse); - expect(client.updates[0].flags.canBeScrolledHorizontally, isFalse); - expect(client.updates[0].flags.canBeScrolledVertically, isFalse); - expect(client.updates[0].flags.hasCheckedState, isFalse); - expect(client.updates[0].flags.isChecked, isFalse); - expect(client.updates[0].strings.label, equals('child1')); - expect(client.updates[0].geometry.transform, isNull); - expect(client.updates[0].geometry.left, equals(0.0)); - expect(client.updates[0].geometry.top, equals(0.0)); - expect(client.updates[0].geometry.width, equals(800.0)); - expect(client.updates[0].geometry.height, equals(600.0)); - expect(client.updates[0].children.length, equals(0)); - expect(client.updates[1], isNull); - client.updates.clear(); + // toggle a branch off + tester.pumpWidget( + new Column( + children: [ + new Container( + height: 10.0, + child: new Semantics(label: 'child1') + ), + new Container( + height: 10.0, + child: new IgnorePointer( + ignoring: true, + child: new Semantics(label: 'child2') + ) + ), + ], + crossAxisAlignment: CrossAxisAlignment.stretch + ) + ); + expect(client.updates.length, equals(2)); + expect(client.updates[0].id, equals(0)); + expect(client.updates[0].flags.canBeTapped, isFalse); + expect(client.updates[0].flags.canBeLongPressed, isFalse); + expect(client.updates[0].flags.canBeScrolledHorizontally, isFalse); + expect(client.updates[0].flags.canBeScrolledVertically, isFalse); + expect(client.updates[0].flags.hasCheckedState, isFalse); + expect(client.updates[0].flags.isChecked, isFalse); + expect(client.updates[0].strings.label, equals('child1')); + expect(client.updates[0].geometry.transform, isNull); + expect(client.updates[0].geometry.left, equals(0.0)); + expect(client.updates[0].geometry.top, equals(0.0)); + expect(client.updates[0].geometry.width, equals(800.0)); + expect(client.updates[0].geometry.height, equals(600.0)); + expect(client.updates[0].children.length, equals(0)); + expect(client.updates[1], isNull); + client.updates.clear(); - // toggle a branch back on - tester.pumpWidget( - new Column( - children: [ - new Container( - height: 10.0, - child: new Semantics(label: 'child1') - ), - new Container( - height: 10.0, - child: new IgnorePointer( - ignoring: false, - child: new Semantics(label: 'child2') - ) - ), - ], - crossAxisAlignment: CrossAxisAlignment.stretch - ) - ); - expect(client.updates.length, equals(2)); - expect(client.updates[0].id, equals(0)); - expect(client.updates[0].flags.canBeTapped, isFalse); - expect(client.updates[0].flags.canBeLongPressed, isFalse); - expect(client.updates[0].flags.canBeScrolledHorizontally, isFalse); - expect(client.updates[0].flags.canBeScrolledVertically, isFalse); - expect(client.updates[0].flags.hasCheckedState, isFalse); - expect(client.updates[0].flags.isChecked, isFalse); - expect(client.updates[0].strings.label, equals('')); - expect(client.updates[0].geometry.transform, isNull); - expect(client.updates[0].geometry.left, equals(0.0)); - expect(client.updates[0].geometry.top, equals(0.0)); - expect(client.updates[0].geometry.width, equals(800.0)); - expect(client.updates[0].geometry.height, equals(600.0)); - expect(client.updates[0].children.length, equals(2)); - expect(client.updates[0].children[0].id, equals(3)); - expect(client.updates[0].children[0].flags.canBeTapped, isFalse); - expect(client.updates[0].children[0].flags.canBeLongPressed, isFalse); - expect(client.updates[0].children[0].flags.canBeScrolledHorizontally, isFalse); - expect(client.updates[0].children[0].flags.canBeScrolledVertically, isFalse); - expect(client.updates[0].children[0].flags.hasCheckedState, isFalse); - expect(client.updates[0].children[0].flags.isChecked, isFalse); - expect(client.updates[0].children[0].strings.label, equals('child1')); - expect(client.updates[0].children[0].geometry.transform, isNull); - expect(client.updates[0].children[0].geometry.left, equals(0.0)); - expect(client.updates[0].children[0].geometry.top, equals(0.0)); - expect(client.updates[0].children[0].geometry.width, equals(800.0)); - expect(client.updates[0].children[0].geometry.height, equals(10.0)); - expect(client.updates[0].children[0].children.length, equals(0)); - expect(client.updates[0].children[1].id, equals(2)); - expect(client.updates[0].children[1].flags.canBeTapped, isFalse); - expect(client.updates[0].children[1].flags.canBeLongPressed, isFalse); - expect(client.updates[0].children[1].flags.canBeScrolledHorizontally, isFalse); - expect(client.updates[0].children[1].flags.canBeScrolledVertically, isFalse); - expect(client.updates[0].children[1].flags.hasCheckedState, isFalse); - expect(client.updates[0].children[1].flags.isChecked, isFalse); - expect(client.updates[0].children[1].strings.label, equals('child2')); - expect(client.updates[0].children[1].geometry.transform, equals([1.0,0.0,0.0,0.0, 0.0,1.0,0.0,0.0, 0.0,0.0,1.0,0.0, 0.0,10.0,0.0,1.0])); - expect(client.updates[0].children[1].geometry.left, equals(0.0)); - expect(client.updates[0].children[1].geometry.top, equals(0.0)); - expect(client.updates[0].children[1].geometry.width, equals(800.0)); - expect(client.updates[0].children[1].geometry.height, equals(10.0)); - expect(client.updates[0].children[1].children.length, equals(0)); - expect(client.updates[1], isNull); - client.updates.clear(); - }); + // toggle a branch back on + tester.pumpWidget( + new Column( + children: [ + new Container( + height: 10.0, + child: new Semantics(label: 'child1') + ), + new Container( + height: 10.0, + child: new IgnorePointer( + ignoring: false, + child: new Semantics(label: 'child2') + ) + ), + ], + crossAxisAlignment: CrossAxisAlignment.stretch + ) + ); + expect(client.updates.length, equals(2)); + expect(client.updates[0].id, equals(0)); + expect(client.updates[0].flags.canBeTapped, isFalse); + expect(client.updates[0].flags.canBeLongPressed, isFalse); + expect(client.updates[0].flags.canBeScrolledHorizontally, isFalse); + expect(client.updates[0].flags.canBeScrolledVertically, isFalse); + expect(client.updates[0].flags.hasCheckedState, isFalse); + expect(client.updates[0].flags.isChecked, isFalse); + expect(client.updates[0].strings.label, equals('')); + expect(client.updates[0].geometry.transform, isNull); + expect(client.updates[0].geometry.left, equals(0.0)); + expect(client.updates[0].geometry.top, equals(0.0)); + expect(client.updates[0].geometry.width, equals(800.0)); + expect(client.updates[0].geometry.height, equals(600.0)); + expect(client.updates[0].children.length, equals(2)); + expect(client.updates[0].children[0].id, equals(3)); + expect(client.updates[0].children[0].flags.canBeTapped, isFalse); + expect(client.updates[0].children[0].flags.canBeLongPressed, isFalse); + expect(client.updates[0].children[0].flags.canBeScrolledHorizontally, isFalse); + expect(client.updates[0].children[0].flags.canBeScrolledVertically, isFalse); + expect(client.updates[0].children[0].flags.hasCheckedState, isFalse); + expect(client.updates[0].children[0].flags.isChecked, isFalse); + expect(client.updates[0].children[0].strings.label, equals('child1')); + expect(client.updates[0].children[0].geometry.transform, isNull); + expect(client.updates[0].children[0].geometry.left, equals(0.0)); + expect(client.updates[0].children[0].geometry.top, equals(0.0)); + expect(client.updates[0].children[0].geometry.width, equals(800.0)); + expect(client.updates[0].children[0].geometry.height, equals(10.0)); + expect(client.updates[0].children[0].children.length, equals(0)); + expect(client.updates[0].children[1].id, equals(2)); + expect(client.updates[0].children[1].flags.canBeTapped, isFalse); + expect(client.updates[0].children[1].flags.canBeLongPressed, isFalse); + expect(client.updates[0].children[1].flags.canBeScrolledHorizontally, isFalse); + expect(client.updates[0].children[1].flags.canBeScrolledVertically, isFalse); + expect(client.updates[0].children[1].flags.hasCheckedState, isFalse); + expect(client.updates[0].children[1].flags.isChecked, isFalse); + expect(client.updates[0].children[1].strings.label, equals('child2')); + expect(client.updates[0].children[1].geometry.transform, equals([1.0,0.0,0.0,0.0, 0.0,1.0,0.0,0.0, 0.0,0.0,1.0,0.0, 0.0,10.0,0.0,1.0])); + expect(client.updates[0].children[1].geometry.left, equals(0.0)); + expect(client.updates[0].children[1].geometry.top, equals(0.0)); + expect(client.updates[0].children[1].geometry.width, equals(800.0)); + expect(client.updates[0].children[1].geometry.height, equals(10.0)); + expect(client.updates[0].children[1].children.length, equals(0)); + expect(client.updates[1], isNull); + client.updates.clear(); }); } diff --git a/packages/flutter/test/widget/semantics_3_test.dart b/packages/flutter/test/widget/semantics_3_test.dart index e496d5ea10..0e5a054067 100644 --- a/packages/flutter/test/widget/semantics_3_test.dart +++ b/packages/flutter/test/widget/semantics_3_test.dart @@ -10,143 +10,141 @@ import 'package:test/test.dart'; import 'test_semantics.dart'; void main() { - test('Semantics 3', () { - testWidgets((WidgetTester tester) { - TestSemanticsListener client = new TestSemanticsListener(); + testWidgets('Semantics 3', (WidgetTester tester) { + TestSemanticsListener client = new TestSemanticsListener(); - // implicit annotators - tester.pumpWidget( - new Container( - child: new Semantics( - label: 'test', - child: new Container( - child: new Semantics( - checked: true - ) - ) - ) - ) - ); - expect(client.updates.length, equals(2)); - expect(client.updates[0].id, equals(0)); - expect(client.updates[0].flags.canBeTapped, isFalse); - expect(client.updates[0].flags.canBeLongPressed, isFalse); - expect(client.updates[0].flags.canBeScrolledHorizontally, isFalse); - expect(client.updates[0].flags.canBeScrolledVertically, isFalse); - expect(client.updates[0].flags.hasCheckedState, isTrue); - expect(client.updates[0].flags.isChecked, isTrue); - expect(client.updates[0].strings.label, equals('test')); - expect(client.updates[0].geometry.transform, isNull); - expect(client.updates[0].geometry.left, equals(0.0)); - expect(client.updates[0].geometry.top, equals(0.0)); - expect(client.updates[0].geometry.width, equals(800.0)); - expect(client.updates[0].geometry.height, equals(600.0)); - expect(client.updates[0].children.length, equals(0)); - expect(client.updates[1], isNull); - client.updates.clear(); - - // remove one - tester.pumpWidget( - new Container( + // implicit annotators + tester.pumpWidget( + new Container( + child: new Semantics( + label: 'test', child: new Container( child: new Semantics( checked: true ) ) ) - ); - expect(client.updates.length, equals(2)); - expect(client.updates[0].id, equals(0)); - expect(client.updates[0].flags.canBeTapped, isFalse); - expect(client.updates[0].flags.canBeLongPressed, isFalse); - expect(client.updates[0].flags.canBeScrolledHorizontally, isFalse); - expect(client.updates[0].flags.canBeScrolledVertically, isFalse); - expect(client.updates[0].flags.hasCheckedState, isTrue); - expect(client.updates[0].flags.isChecked, isTrue); - expect(client.updates[0].strings.label, equals('')); - expect(client.updates[0].geometry.transform, isNull); - expect(client.updates[0].geometry.left, equals(0.0)); - expect(client.updates[0].geometry.top, equals(0.0)); - expect(client.updates[0].geometry.width, equals(800.0)); - expect(client.updates[0].geometry.height, equals(600.0)); - expect(client.updates[0].children.length, equals(0)); - expect(client.updates[1], isNull); - client.updates.clear(); + ) + ); + expect(client.updates.length, equals(2)); + expect(client.updates[0].id, equals(0)); + expect(client.updates[0].flags.canBeTapped, isFalse); + expect(client.updates[0].flags.canBeLongPressed, isFalse); + expect(client.updates[0].flags.canBeScrolledHorizontally, isFalse); + expect(client.updates[0].flags.canBeScrolledVertically, isFalse); + expect(client.updates[0].flags.hasCheckedState, isTrue); + expect(client.updates[0].flags.isChecked, isTrue); + expect(client.updates[0].strings.label, equals('test')); + expect(client.updates[0].geometry.transform, isNull); + expect(client.updates[0].geometry.left, equals(0.0)); + expect(client.updates[0].geometry.top, equals(0.0)); + expect(client.updates[0].geometry.width, equals(800.0)); + expect(client.updates[0].geometry.height, equals(600.0)); + expect(client.updates[0].children.length, equals(0)); + expect(client.updates[1], isNull); + client.updates.clear(); - // change what it says - tester.pumpWidget( - new Container( + // remove one + tester.pumpWidget( + new Container( + child: new Container( + child: new Semantics( + checked: true + ) + ) + ) + ); + expect(client.updates.length, equals(2)); + expect(client.updates[0].id, equals(0)); + expect(client.updates[0].flags.canBeTapped, isFalse); + expect(client.updates[0].flags.canBeLongPressed, isFalse); + expect(client.updates[0].flags.canBeScrolledHorizontally, isFalse); + expect(client.updates[0].flags.canBeScrolledVertically, isFalse); + expect(client.updates[0].flags.hasCheckedState, isTrue); + expect(client.updates[0].flags.isChecked, isTrue); + expect(client.updates[0].strings.label, equals('')); + expect(client.updates[0].geometry.transform, isNull); + expect(client.updates[0].geometry.left, equals(0.0)); + expect(client.updates[0].geometry.top, equals(0.0)); + expect(client.updates[0].geometry.width, equals(800.0)); + expect(client.updates[0].geometry.height, equals(600.0)); + expect(client.updates[0].children.length, equals(0)); + expect(client.updates[1], isNull); + client.updates.clear(); + + // change what it says + tester.pumpWidget( + new Container( + child: new Container( + child: new Semantics( + label: 'test' + ) + ) + ) + ); + expect(client.updates.length, equals(2)); + expect(client.updates[0].id, equals(0)); + expect(client.updates[0].flags.canBeTapped, isFalse); + expect(client.updates[0].flags.canBeLongPressed, isFalse); + expect(client.updates[0].flags.canBeScrolledHorizontally, isFalse); + expect(client.updates[0].flags.canBeScrolledVertically, isFalse); + expect(client.updates[0].flags.hasCheckedState, isFalse); + expect(client.updates[0].flags.isChecked, isFalse); + expect(client.updates[0].strings.label, equals('test')); + expect(client.updates[0].geometry.transform, isNull); + expect(client.updates[0].geometry.left, equals(0.0)); + expect(client.updates[0].geometry.top, equals(0.0)); + expect(client.updates[0].geometry.width, equals(800.0)); + expect(client.updates[0].geometry.height, equals(600.0)); + expect(client.updates[0].children.length, equals(0)); + expect(client.updates[1], isNull); + client.updates.clear(); + + // add a node + tester.pumpWidget( + new Container( + child: new Semantics( + checked: true, child: new Container( child: new Semantics( label: 'test' ) ) ) - ); - expect(client.updates.length, equals(2)); - expect(client.updates[0].id, equals(0)); - expect(client.updates[0].flags.canBeTapped, isFalse); - expect(client.updates[0].flags.canBeLongPressed, isFalse); - expect(client.updates[0].flags.canBeScrolledHorizontally, isFalse); - expect(client.updates[0].flags.canBeScrolledVertically, isFalse); - expect(client.updates[0].flags.hasCheckedState, isFalse); - expect(client.updates[0].flags.isChecked, isFalse); - expect(client.updates[0].strings.label, equals('test')); - expect(client.updates[0].geometry.transform, isNull); - expect(client.updates[0].geometry.left, equals(0.0)); - expect(client.updates[0].geometry.top, equals(0.0)); - expect(client.updates[0].geometry.width, equals(800.0)); - expect(client.updates[0].geometry.height, equals(600.0)); - expect(client.updates[0].children.length, equals(0)); - expect(client.updates[1], isNull); - client.updates.clear(); + ) + ); + expect(client.updates.length, equals(2)); + expect(client.updates[0].id, equals(0)); + expect(client.updates[0].flags.canBeTapped, isFalse); + expect(client.updates[0].flags.canBeLongPressed, isFalse); + expect(client.updates[0].flags.canBeScrolledHorizontally, isFalse); + expect(client.updates[0].flags.canBeScrolledVertically, isFalse); + expect(client.updates[0].flags.hasCheckedState, isTrue); + expect(client.updates[0].flags.isChecked, isTrue); + expect(client.updates[0].strings.label, equals('test')); + expect(client.updates[0].geometry.transform, isNull); + expect(client.updates[0].geometry.left, equals(0.0)); + expect(client.updates[0].geometry.top, equals(0.0)); + expect(client.updates[0].geometry.width, equals(800.0)); + expect(client.updates[0].geometry.height, equals(600.0)); + expect(client.updates[0].children.length, equals(0)); + expect(client.updates[1], isNull); + client.updates.clear(); - // add a node - tester.pumpWidget( - new Container( - child: new Semantics( - checked: true, - child: new Container( - child: new Semantics( - label: 'test' - ) + // make no changes + tester.pumpWidget( + new Container( + child: new Semantics( + checked: true, + child: new Container( + child: new Semantics( + label: 'test' ) ) ) - ); - expect(client.updates.length, equals(2)); - expect(client.updates[0].id, equals(0)); - expect(client.updates[0].flags.canBeTapped, isFalse); - expect(client.updates[0].flags.canBeLongPressed, isFalse); - expect(client.updates[0].flags.canBeScrolledHorizontally, isFalse); - expect(client.updates[0].flags.canBeScrolledVertically, isFalse); - expect(client.updates[0].flags.hasCheckedState, isTrue); - expect(client.updates[0].flags.isChecked, isTrue); - expect(client.updates[0].strings.label, equals('test')); - expect(client.updates[0].geometry.transform, isNull); - expect(client.updates[0].geometry.left, equals(0.0)); - expect(client.updates[0].geometry.top, equals(0.0)); - expect(client.updates[0].geometry.width, equals(800.0)); - expect(client.updates[0].geometry.height, equals(600.0)); - expect(client.updates[0].children.length, equals(0)); - expect(client.updates[1], isNull); - client.updates.clear(); + ) + ); + expect(client.updates.length, equals(0)); - // make no changes - tester.pumpWidget( - new Container( - child: new Semantics( - checked: true, - child: new Container( - child: new Semantics( - label: 'test' - ) - ) - ) - ) - ); - expect(client.updates.length, equals(0)); - - }); }); } diff --git a/packages/flutter/test/widget/semantics_4_test.dart b/packages/flutter/test/widget/semantics_4_test.dart index 50aa43e1a0..77ae48620a 100644 --- a/packages/flutter/test/widget/semantics_4_test.dart +++ b/packages/flutter/test/widget/semantics_4_test.dart @@ -10,111 +10,109 @@ import 'package:test/test.dart'; import 'test_semantics.dart'; void main() { - test('Semantics 4', () { - testWidgets((WidgetTester tester) { - TestSemanticsListener client = new TestSemanticsListener(); + testWidgets('Semantics 4', (WidgetTester tester) { + TestSemanticsListener client = new TestSemanticsListener(); - // O - // / \ O=root - // L L L=node with label - // / \ C=node with checked - // C C* *=node removed next pass - // - tester.pumpWidget( - new Stack( - children: [ - new Semantics( - label: 'L1' - ), - new Semantics( - label: 'L2', - child: new Stack( - children: [ - new Semantics( - checked: true - ), - new Semantics( - checked: false - ) - ] - ) + // O + // / \ O=root + // L L L=node with label + // / \ C=node with checked + // C C* *=node removed next pass + // + tester.pumpWidget( + new Stack( + children: [ + new Semantics( + label: 'L1' + ), + new Semantics( + label: 'L2', + child: new Stack( + children: [ + new Semantics( + checked: true + ), + new Semantics( + checked: false + ) + ] ) - ] - ) - ); - expect(client.updates.length, equals(2)); - expect(client.updates[0].id, equals(0)); - expect(client.updates[0].children.length, equals(2)); - expect(client.updates[0].children[0].id, equals(1)); - expect(client.updates[0].children[0].children.length, equals(0)); - expect(client.updates[0].children[1].id, equals(2)); - expect(client.updates[0].children[1].children.length, equals(2)); - expect(client.updates[0].children[1].children[0].id, equals(3)); - expect(client.updates[0].children[1].children[0].children.length, equals(0)); - expect(client.updates[0].children[1].children[1].id, equals(4)); - expect(client.updates[0].children[1].children[1].children.length, equals(0)); - expect(client.updates[1], isNull); - client.updates.clear(); + ) + ] + ) + ); + expect(client.updates.length, equals(2)); + expect(client.updates[0].id, equals(0)); + expect(client.updates[0].children.length, equals(2)); + expect(client.updates[0].children[0].id, equals(1)); + expect(client.updates[0].children[0].children.length, equals(0)); + expect(client.updates[0].children[1].id, equals(2)); + expect(client.updates[0].children[1].children.length, equals(2)); + expect(client.updates[0].children[1].children[0].id, equals(3)); + expect(client.updates[0].children[1].children[0].children.length, equals(0)); + expect(client.updates[0].children[1].children[1].id, equals(4)); + expect(client.updates[0].children[1].children[1].children.length, equals(0)); + expect(client.updates[1], isNull); + client.updates.clear(); - // O O=root - // / \ L=node with label - // L* LC C=node with checked - // *=node removed next pass - // - tester.pumpWidget( - new Stack( - children: [ - new Semantics( - label: 'L1' - ), - new Semantics( - label: 'L2', - child: new Stack( - children: [ - new Semantics( - checked: true - ), - new Semantics() - ] - ) + // O O=root + // / \ L=node with label + // L* LC C=node with checked + // *=node removed next pass + // + tester.pumpWidget( + new Stack( + children: [ + new Semantics( + label: 'L1' + ), + new Semantics( + label: 'L2', + child: new Stack( + children: [ + new Semantics( + checked: true + ), + new Semantics() + ] ) - ] - ) - ); - expect(client.updates.length, equals(2)); - expect(client.updates[0].id, equals(2)); - expect(client.updates[0].children.length, equals(0)); - expect(client.updates[1], isNull); - client.updates.clear(); + ) + ] + ) + ); + expect(client.updates.length, equals(2)); + expect(client.updates[0].id, equals(2)); + expect(client.updates[0].children.length, equals(0)); + expect(client.updates[1], isNull); + client.updates.clear(); - // O=root - // OLC L=node with label - // C=node with checked - // - tester.pumpWidget( - new Stack( - children: [ - new Semantics(), - new Semantics( - label: 'L2', - child: new Stack( - children: [ - new Semantics( - checked: true - ), - new Semantics() - ] - ) + // O=root + // OLC L=node with label + // C=node with checked + // + tester.pumpWidget( + new Stack( + children: [ + new Semantics(), + new Semantics( + label: 'L2', + child: new Stack( + children: [ + new Semantics( + checked: true + ), + new Semantics() + ] ) - ] - ) - ); - expect(client.updates.length, equals(2)); - expect(client.updates[0].id, equals(0)); - expect(client.updates[0].children.length, equals(0)); - expect(client.updates[1], isNull); - client.updates.clear(); + ) + ] + ) + ); + expect(client.updates.length, equals(2)); + expect(client.updates[0].id, equals(0)); + expect(client.updates[0].children.length, equals(0)); + expect(client.updates[1], isNull); + client.updates.clear(); - }); }); } diff --git a/packages/flutter/test/widget/semantics_5_test.dart b/packages/flutter/test/widget/semantics_5_test.dart index 91f73db2eb..dff548c0f1 100644 --- a/packages/flutter/test/widget/semantics_5_test.dart +++ b/packages/flutter/test/widget/semantics_5_test.dart @@ -10,40 +10,38 @@ import 'package:test/test.dart'; import 'test_semantics.dart'; void main() { - test('Semantics 5', () { - testWidgets((WidgetTester tester) { - TestSemanticsListener client = new TestSemanticsListener(); + testWidgets('Semantics 5', (WidgetTester tester) { + TestSemanticsListener client = new TestSemanticsListener(); - tester.pumpWidget( - new Stack( - children: [ - new Semantics( - // this tests that empty nodes disappear - ), - new Semantics( - // this tests whether you can have a container with no other semantics - container: true - ), - new Semantics( - label: 'label' // (force a fork) - ), - ] - ) - ); - expect(client.updates.length, equals(2)); - expect(client.updates[0].id, equals(0)); - expect(client.updates[0].flags.hasCheckedState, isFalse); - expect(client.updates[0].strings.label, equals('')); - expect(client.updates[0].children.length, equals(2)); - expect(client.updates[0].children[0].id, equals(1)); - expect(client.updates[0].children[0].flags.hasCheckedState, isFalse); - expect(client.updates[0].children[0].strings.label, equals('')); - expect(client.updates[0].children[1].id, equals(2)); - expect(client.updates[0].children[1].flags.hasCheckedState, isFalse); - expect(client.updates[0].children[1].strings.label, equals('label')); - expect(client.updates[1], isNull); - client.updates.clear(); + tester.pumpWidget( + new Stack( + children: [ + new Semantics( + // this tests that empty nodes disappear + ), + new Semantics( + // this tests whether you can have a container with no other semantics + container: true + ), + new Semantics( + label: 'label' // (force a fork) + ), + ] + ) + ); + expect(client.updates.length, equals(2)); + expect(client.updates[0].id, equals(0)); + expect(client.updates[0].flags.hasCheckedState, isFalse); + expect(client.updates[0].strings.label, equals('')); + expect(client.updates[0].children.length, equals(2)); + expect(client.updates[0].children[0].id, equals(1)); + expect(client.updates[0].children[0].flags.hasCheckedState, isFalse); + expect(client.updates[0].children[0].strings.label, equals('')); + expect(client.updates[0].children[1].id, equals(2)); + expect(client.updates[0].children[1].flags.hasCheckedState, isFalse); + expect(client.updates[0].children[1].strings.label, equals('label')); + expect(client.updates[1], isNull); + client.updates.clear(); - }); }); } diff --git a/packages/flutter/test/widget/semantics_6_test.dart b/packages/flutter/test/widget/semantics_6_test.dart index 96ef4dac3c..1dfe1b7593 100644 --- a/packages/flutter/test/widget/semantics_6_test.dart +++ b/packages/flutter/test/widget/semantics_6_test.dart @@ -8,13 +8,27 @@ import 'package:flutter_test/flutter_test.dart'; import 'package:test/test.dart'; void main() { - test('Semantics 6 - SemanticsDebugger smoke test', () { - testWidgets((WidgetTester tester) { + testWidgets('Semantics 6 - SemanticsDebugger smoke test', (WidgetTester tester) { - // This is a smoketest to verify that adding a debugger doesn't crash. + // This is a smoketest to verify that adding a debugger doesn't crash. - tester.pumpWidget( - new Stack( + tester.pumpWidget( + new Stack( + children: [ + new Semantics(), + new Semantics( + container: true + ), + new Semantics( + label: 'label' + ), + ] + ) + ); + + tester.pumpWidget( + new SemanticsDebugger( + child: new Stack( children: [ new Semantics(), new Semantics( @@ -25,26 +39,10 @@ void main() { ), ] ) - ); + ) + ); - tester.pumpWidget( - new SemanticsDebugger( - child: new Stack( - children: [ - new Semantics(), - new Semantics( - container: true - ), - new Semantics( - label: 'label' - ), - ] - ) - ) - ); + expect(true, isTrue); // expect that we reach here without crashing - expect(true, isTrue); // expect that we reach here without crashing - - }); }); } diff --git a/packages/flutter/test/widget/semantics_7_test.dart b/packages/flutter/test/widget/semantics_7_test.dart index 2b65a29355..4803725583 100644 --- a/packages/flutter/test/widget/semantics_7_test.dart +++ b/packages/flutter/test/widget/semantics_7_test.dart @@ -11,163 +11,161 @@ import 'test_semantics.dart'; import 'package:sky_services/semantics/semantics.mojom.dart' as mojom; void main() { - test('Semantics 7 - Merging', () { - testWidgets((WidgetTester tester) { - TestSemanticsListener client = new TestSemanticsListener(); + testWidgets('Semantics 7 - Merging', (WidgetTester tester) { + TestSemanticsListener client = new TestSemanticsListener(); - String label; + String label; - label = '1'; - tester.pumpWidget( - new Stack( - children: [ - new MergeSemantics( + label = '1'; + tester.pumpWidget( + new Stack( + children: [ + new MergeSemantics( + child: new Semantics( + checked: true, + container: true, child: new Semantics( - checked: true, container: true, - child: new Semantics( - container: true, + label: label + ) + ) + ), + new MergeSemantics( + child: new Stack( + children: [ + new Semantics( + checked: true + ), + new Semantics( label: label ) - ) - ), - new MergeSemantics( - child: new Stack( - children: [ - new Semantics( - checked: true - ), - new Semantics( - label: label - ) - ] - ) - ), - ] - ) - ); - expect(client.updates.length, equals(2)); - expect(client.updates[0].id, equals(0)); - expect(client.updates[0].flags.canBeTapped, isFalse); - expect(client.updates[0].flags.canBeLongPressed, isFalse); - expect(client.updates[0].flags.canBeScrolledHorizontally, isFalse); - expect(client.updates[0].flags.canBeScrolledVertically, isFalse); - expect(client.updates[0].flags.hasCheckedState, isFalse); - expect(client.updates[0].flags.isChecked, isFalse); - expect(client.updates[0].strings.label, equals('')); - expect(client.updates[0].geometry.transform, isNull); - expect(client.updates[0].geometry.left, equals(0.0)); - expect(client.updates[0].geometry.top, equals(0.0)); - expect(client.updates[0].geometry.width, equals(800.0)); - expect(client.updates[0].geometry.height, equals(600.0)); - expect(client.updates[0].children.length, equals(2)); - expect(client.updates[0].children[0].id, equals(1)); - expect(client.updates[0].children[0].flags.canBeTapped, isFalse); - expect(client.updates[0].children[0].flags.canBeLongPressed, isFalse); - expect(client.updates[0].children[0].flags.canBeScrolledHorizontally, isFalse); - expect(client.updates[0].children[0].flags.canBeScrolledVertically, isFalse); - expect(client.updates[0].children[0].flags.hasCheckedState, isTrue); - expect(client.updates[0].children[0].flags.isChecked, isTrue); - expect(client.updates[0].children[0].strings.label, equals(label)); - expect(client.updates[0].children[0].geometry.transform, isNull); - expect(client.updates[0].children[0].geometry.left, equals(0.0)); - expect(client.updates[0].children[0].geometry.top, equals(0.0)); - expect(client.updates[0].children[0].geometry.width, equals(800.0)); - expect(client.updates[0].children[0].geometry.height, equals(600.0)); - expect(client.updates[0].children[0].children.length, equals(0)); - // IDs 2 and 3 are used up by the nodes that get merged in - expect(client.updates[0].children[1].id, equals(4)); - expect(client.updates[0].children[1].flags.canBeTapped, isFalse); - expect(client.updates[0].children[1].flags.canBeLongPressed, isFalse); - expect(client.updates[0].children[1].flags.canBeScrolledHorizontally, isFalse); - expect(client.updates[0].children[1].flags.canBeScrolledVertically, isFalse); - expect(client.updates[0].children[1].flags.hasCheckedState, isTrue); - expect(client.updates[0].children[1].flags.isChecked, isTrue); - expect(client.updates[0].children[1].strings.label, equals(label)); - expect(client.updates[0].children[1].geometry.transform, isNull); - expect(client.updates[0].children[1].geometry.left, equals(0.0)); - expect(client.updates[0].children[1].geometry.top, equals(0.0)); - expect(client.updates[0].children[1].geometry.width, equals(800.0)); - expect(client.updates[0].children[1].geometry.height, equals(600.0)); - expect(client.updates[0].children[1].children.length, equals(0)); - // IDs 5 and 6 are used up by the nodes that get merged in - expect(client.updates[1], isNull); - client.updates.clear(); + ] + ) + ), + ] + ) + ); + expect(client.updates.length, equals(2)); + expect(client.updates[0].id, equals(0)); + expect(client.updates[0].flags.canBeTapped, isFalse); + expect(client.updates[0].flags.canBeLongPressed, isFalse); + expect(client.updates[0].flags.canBeScrolledHorizontally, isFalse); + expect(client.updates[0].flags.canBeScrolledVertically, isFalse); + expect(client.updates[0].flags.hasCheckedState, isFalse); + expect(client.updates[0].flags.isChecked, isFalse); + expect(client.updates[0].strings.label, equals('')); + expect(client.updates[0].geometry.transform, isNull); + expect(client.updates[0].geometry.left, equals(0.0)); + expect(client.updates[0].geometry.top, equals(0.0)); + expect(client.updates[0].geometry.width, equals(800.0)); + expect(client.updates[0].geometry.height, equals(600.0)); + expect(client.updates[0].children.length, equals(2)); + expect(client.updates[0].children[0].id, equals(1)); + expect(client.updates[0].children[0].flags.canBeTapped, isFalse); + expect(client.updates[0].children[0].flags.canBeLongPressed, isFalse); + expect(client.updates[0].children[0].flags.canBeScrolledHorizontally, isFalse); + expect(client.updates[0].children[0].flags.canBeScrolledVertically, isFalse); + expect(client.updates[0].children[0].flags.hasCheckedState, isTrue); + expect(client.updates[0].children[0].flags.isChecked, isTrue); + expect(client.updates[0].children[0].strings.label, equals(label)); + expect(client.updates[0].children[0].geometry.transform, isNull); + expect(client.updates[0].children[0].geometry.left, equals(0.0)); + expect(client.updates[0].children[0].geometry.top, equals(0.0)); + expect(client.updates[0].children[0].geometry.width, equals(800.0)); + expect(client.updates[0].children[0].geometry.height, equals(600.0)); + expect(client.updates[0].children[0].children.length, equals(0)); + // IDs 2 and 3 are used up by the nodes that get merged in + expect(client.updates[0].children[1].id, equals(4)); + expect(client.updates[0].children[1].flags.canBeTapped, isFalse); + expect(client.updates[0].children[1].flags.canBeLongPressed, isFalse); + expect(client.updates[0].children[1].flags.canBeScrolledHorizontally, isFalse); + expect(client.updates[0].children[1].flags.canBeScrolledVertically, isFalse); + expect(client.updates[0].children[1].flags.hasCheckedState, isTrue); + expect(client.updates[0].children[1].flags.isChecked, isTrue); + expect(client.updates[0].children[1].strings.label, equals(label)); + expect(client.updates[0].children[1].geometry.transform, isNull); + expect(client.updates[0].children[1].geometry.left, equals(0.0)); + expect(client.updates[0].children[1].geometry.top, equals(0.0)); + expect(client.updates[0].children[1].geometry.width, equals(800.0)); + expect(client.updates[0].children[1].geometry.height, equals(600.0)); + expect(client.updates[0].children[1].children.length, equals(0)); + // IDs 5 and 6 are used up by the nodes that get merged in + expect(client.updates[1], isNull); + client.updates.clear(); - label = '2'; - tester.pumpWidget( - new Stack( - children: [ - new MergeSemantics( + label = '2'; + tester.pumpWidget( + new Stack( + children: [ + new MergeSemantics( + child: new Semantics( + checked: true, + container: true, child: new Semantics( - checked: true, container: true, - child: new Semantics( - container: true, + label: label + ) + ) + ), + new MergeSemantics( + child: new Stack( + children: [ + new Semantics( + checked: true + ), + new Semantics( label: label ) - ) - ), - new MergeSemantics( - child: new Stack( - children: [ - new Semantics( - checked: true - ), - new Semantics( - label: label - ) - ] - ) - ), - ] - ) - ); - expect(client.updates.length, equals(3)); - expect(client.updates[2], isNull); + ] + ) + ), + ] + ) + ); + expect(client.updates.length, equals(3)); + expect(client.updates[2], isNull); - // The order of the nodes is undefined, so allow both orders. - mojom.SemanticsNode a, b; - if (client.updates[0].id == 1) { - a = client.updates[0]; - b = client.updates[1]; - } else { - a = client.updates[1]; - b = client.updates[0]; - } - - expect(a.id, equals(1)); - expect(a.flags.canBeTapped, isFalse); - expect(a.flags.canBeLongPressed, isFalse); - expect(a.flags.canBeScrolledHorizontally, isFalse); - expect(a.flags.canBeScrolledVertically, isFalse); - expect(a.flags.hasCheckedState, isTrue); - expect(a.flags.isChecked, isTrue); - expect(a.strings.label, equals(label)); - expect(a.geometry.transform, isNull); - expect(a.geometry.left, equals(0.0)); - expect(a.geometry.top, equals(0.0)); - expect(a.geometry.width, equals(800.0)); - expect(a.geometry.height, equals(600.0)); - expect(a.children.length, equals(0)); + // The order of the nodes is undefined, so allow both orders. + mojom.SemanticsNode a, b; + if (client.updates[0].id == 1) { + a = client.updates[0]; + b = client.updates[1]; + } else { + a = client.updates[1]; + b = client.updates[0]; + } - expect(b.id, equals(4)); - expect(b.flags.canBeTapped, isFalse); - expect(b.flags.canBeLongPressed, isFalse); - expect(b.flags.canBeScrolledHorizontally, isFalse); - expect(b.flags.canBeScrolledVertically, isFalse); - expect(b.flags.hasCheckedState, isTrue); - expect(b.flags.isChecked, isTrue); - expect(b.strings.label, equals(label)); - expect(b.geometry.transform, isNull); - expect(b.geometry.left, equals(0.0)); - expect(b.geometry.top, equals(0.0)); - expect(b.geometry.width, equals(800.0)); - expect(b.geometry.height, equals(600.0)); - expect(b.children.length, equals(0)); + expect(a.id, equals(1)); + expect(a.flags.canBeTapped, isFalse); + expect(a.flags.canBeLongPressed, isFalse); + expect(a.flags.canBeScrolledHorizontally, isFalse); + expect(a.flags.canBeScrolledVertically, isFalse); + expect(a.flags.hasCheckedState, isTrue); + expect(a.flags.isChecked, isTrue); + expect(a.strings.label, equals(label)); + expect(a.geometry.transform, isNull); + expect(a.geometry.left, equals(0.0)); + expect(a.geometry.top, equals(0.0)); + expect(a.geometry.width, equals(800.0)); + expect(a.geometry.height, equals(600.0)); + expect(a.children.length, equals(0)); - client.updates.clear(); + expect(b.id, equals(4)); + expect(b.flags.canBeTapped, isFalse); + expect(b.flags.canBeLongPressed, isFalse); + expect(b.flags.canBeScrolledHorizontally, isFalse); + expect(b.flags.canBeScrolledVertically, isFalse); + expect(b.flags.hasCheckedState, isTrue); + expect(b.flags.isChecked, isTrue); + expect(b.strings.label, equals(label)); + expect(b.geometry.transform, isNull); + expect(b.geometry.left, equals(0.0)); + expect(b.geometry.top, equals(0.0)); + expect(b.geometry.width, equals(800.0)); + expect(b.geometry.height, equals(600.0)); + expect(b.children.length, equals(0)); + + client.updates.clear(); - }); }); } diff --git a/packages/flutter/test/widget/semantics_8_test.dart b/packages/flutter/test/widget/semantics_8_test.dart index ec5dbf04e7..bcfb12d15d 100644 --- a/packages/flutter/test/widget/semantics_8_test.dart +++ b/packages/flutter/test/widget/semantics_8_test.dart @@ -10,87 +10,85 @@ import 'package:test/test.dart'; import 'test_semantics.dart'; void main() { - test('Semantics 8 - Merging with reset', () { - testWidgets((WidgetTester tester) { - TestSemanticsListener client = new TestSemanticsListener(); + testWidgets('Semantics 8 - Merging with reset', (WidgetTester tester) { + TestSemanticsListener client = new TestSemanticsListener(); - tester.pumpWidget( - new MergeSemantics( + tester.pumpWidget( + new MergeSemantics( + child: new Semantics( + container: true, child: new Semantics( container: true, - child: new Semantics( - container: true, - child: new Stack( - children: [ - new Semantics( - checked: true - ), - new Semantics( - label: 'label' - ) - ] - ) + child: new Stack( + children: [ + new Semantics( + checked: true + ), + new Semantics( + label: 'label' + ) + ] ) ) ) - ); - expect(client.updates.length, equals(2)); - expect(client.updates[0].id, equals(0)); - expect(client.updates[0].flags.canBeTapped, isFalse); - expect(client.updates[0].flags.canBeLongPressed, isFalse); - expect(client.updates[0].flags.canBeScrolledHorizontally, isFalse); - expect(client.updates[0].flags.canBeScrolledVertically, isFalse); - expect(client.updates[0].flags.hasCheckedState, isTrue); - expect(client.updates[0].flags.isChecked, isTrue); - expect(client.updates[0].strings.label, equals('label')); - expect(client.updates[0].geometry.transform, isNull); - expect(client.updates[0].geometry.left, equals(0.0)); - expect(client.updates[0].geometry.top, equals(0.0)); - expect(client.updates[0].geometry.width, equals(800.0)); - expect(client.updates[0].geometry.height, equals(600.0)); - expect(client.updates[0].children.length, equals(0)); - expect(client.updates[1], isNull); - client.updates.clear(); + ) + ); + expect(client.updates.length, equals(2)); + expect(client.updates[0].id, equals(0)); + expect(client.updates[0].flags.canBeTapped, isFalse); + expect(client.updates[0].flags.canBeLongPressed, isFalse); + expect(client.updates[0].flags.canBeScrolledHorizontally, isFalse); + expect(client.updates[0].flags.canBeScrolledVertically, isFalse); + expect(client.updates[0].flags.hasCheckedState, isTrue); + expect(client.updates[0].flags.isChecked, isTrue); + expect(client.updates[0].strings.label, equals('label')); + expect(client.updates[0].geometry.transform, isNull); + expect(client.updates[0].geometry.left, equals(0.0)); + expect(client.updates[0].geometry.top, equals(0.0)); + expect(client.updates[0].geometry.width, equals(800.0)); + expect(client.updates[0].geometry.height, equals(600.0)); + expect(client.updates[0].children.length, equals(0)); + expect(client.updates[1], isNull); + client.updates.clear(); - // switch the order of the inner Semantics node to trigger a reset - tester.pumpWidget( - new MergeSemantics( + // switch the order of the inner Semantics node to trigger a reset + tester.pumpWidget( + new MergeSemantics( + child: new Semantics( + container: true, child: new Semantics( container: true, - child: new Semantics( - container: true, - child: new Stack( - children: [ - new Semantics( - label: 'label' - ), - new Semantics( - checked: true - ) - ] - ) + child: new Stack( + children: [ + new Semantics( + label: 'label' + ), + new Semantics( + checked: true + ) + ] ) ) ) - ); - expect(client.updates.length, equals(2)); - expect(client.updates[0].id, equals(0)); - expect(client.updates[0].flags.canBeTapped, isFalse); - expect(client.updates[0].flags.canBeLongPressed, isFalse); - expect(client.updates[0].flags.canBeScrolledHorizontally, isFalse); - expect(client.updates[0].flags.canBeScrolledVertically, isFalse); - expect(client.updates[0].flags.hasCheckedState, isTrue); - expect(client.updates[0].flags.isChecked, isTrue); - expect(client.updates[0].strings.label, equals('label')); - expect(client.updates[0].geometry.transform, isNull); - expect(client.updates[0].geometry.left, equals(0.0)); - expect(client.updates[0].geometry.top, equals(0.0)); - expect(client.updates[0].geometry.width, equals(800.0)); - expect(client.updates[0].geometry.height, equals(600.0)); - expect(client.updates[0].children.length, equals(0)); - expect(client.updates[1], isNull); - client.updates.clear(); + ) + ); + expect(client.updates.length, equals(2)); + expect(client.updates[0].id, equals(0)); + expect(client.updates[0].flags.canBeTapped, isFalse); + expect(client.updates[0].flags.canBeLongPressed, isFalse); + expect(client.updates[0].flags.canBeScrolledHorizontally, isFalse); + expect(client.updates[0].flags.canBeScrolledVertically, isFalse); + expect(client.updates[0].flags.hasCheckedState, isTrue); + expect(client.updates[0].flags.isChecked, isTrue); + expect(client.updates[0].strings.label, equals('label')); + expect(client.updates[0].geometry.transform, isNull); + expect(client.updates[0].geometry.left, equals(0.0)); + expect(client.updates[0].geometry.top, equals(0.0)); + expect(client.updates[0].geometry.width, equals(800.0)); + expect(client.updates[0].geometry.height, equals(600.0)); + expect(client.updates[0].children.length, equals(0)); + expect(client.updates[1], isNull); + client.updates.clear(); - }); }); } diff --git a/packages/flutter/test/widget/set_state_2_test.dart b/packages/flutter/test/widget/set_state_2_test.dart index af6e3370b1..58f11ddbab 100644 --- a/packages/flutter/test/widget/set_state_2_test.dart +++ b/packages/flutter/test/widget/set_state_2_test.dart @@ -7,53 +7,51 @@ import 'package:flutter/widgets.dart'; import 'package:test/test.dart'; void main() { - test('setState() overbuild test', () { - testWidgets((WidgetTester tester) { - List log = []; - Builder inner = new Builder( - builder: (BuildContext context) { - log.add('inner'); - return new Text('inner'); - } - ); - int value = 0; - tester.pumpWidget(new Builder( - builder: (BuildContext context) { - log.add('outer'); - return new StatefulBuilder( - builder: (BuildContext context, StateSetter setState) { - log.add('stateful'); - return new GestureDetector( - onTap: () { - setState(() { - value += 1; - }); - }, - child: new Builder( - builder: (BuildContext context) { - log.add('middle $value'); - return inner; - } - ) - ); - } - ); - } - )); - log.add('---'); - tester.tap(find.text('inner'));; - tester.pump(); - log.add('---'); - expect(log, equals([ - 'outer', - 'stateful', - 'middle 0', - 'inner', - '---', - 'stateful', - 'middle 1', - '---', - ])); - }); + testWidgets('setState() overbuild test', (WidgetTester tester) { + List log = []; + Builder inner = new Builder( + builder: (BuildContext context) { + log.add('inner'); + return new Text('inner'); + } + ); + int value = 0; + tester.pumpWidget(new Builder( + builder: (BuildContext context) { + log.add('outer'); + return new StatefulBuilder( + builder: (BuildContext context, StateSetter setState) { + log.add('stateful'); + return new GestureDetector( + onTap: () { + setState(() { + value += 1; + }); + }, + child: new Builder( + builder: (BuildContext context) { + log.add('middle $value'); + return inner; + } + ) + ); + } + ); + } + )); + log.add('---'); + tester.tap(find.text('inner'));; + tester.pump(); + log.add('---'); + expect(log, equals([ + 'outer', + 'stateful', + 'middle 0', + 'inner', + '---', + 'stateful', + 'middle 1', + '---', + ])); }); } diff --git a/packages/flutter/test/widget/set_state_3_test.dart b/packages/flutter/test/widget/set_state_3_test.dart index 78599de6f9..2b36030362 100644 --- a/packages/flutter/test/widget/set_state_3_test.dart +++ b/packages/flutter/test/widget/set_state_3_test.dart @@ -4,7 +4,6 @@ import 'package:flutter_test/flutter_test.dart'; import 'package:flutter/widgets.dart'; -import 'package:test/test.dart'; ChangerState changer; @@ -52,12 +51,10 @@ class LeafState extends State { } void main() { - test('three-way setState() smoke test', () { - testWidgets((WidgetTester tester) { - tester.pumpWidget(new Changer(new Wrapper(new Leaf()))); - tester.pumpWidget(new Changer(new Wrapper(new Leaf()))); - changer.test(); - tester.pump(); - }); + testWidgets('three-way setState() smoke test', (WidgetTester tester) { + tester.pumpWidget(new Changer(new Wrapper(new Leaf()))); + tester.pumpWidget(new Changer(new Wrapper(new Leaf()))); + changer.test(); + tester.pump(); }); } diff --git a/packages/flutter/test/widget/set_state_test.dart b/packages/flutter/test/widget/set_state_test.dart index f34af52614..54ac8bb8d5 100644 --- a/packages/flutter/test/widget/set_state_test.dart +++ b/packages/flutter/test/widget/set_state_test.dart @@ -4,7 +4,6 @@ import 'package:flutter_test/flutter_test.dart'; import 'package:flutter/widgets.dart'; -import 'package:test/test.dart'; class Inside extends StatefulWidget { @override @@ -61,14 +60,12 @@ class OutsideState extends State { } void main() { - test('setState() smoke test', () { - testWidgets((WidgetTester tester) { - tester.pumpWidget(new Outside()); - Point location = tester.getCenter(find.text('INSIDE')); - TestGesture gesture = tester.startGesture(location); - tester.pump(); - gesture.up(); - tester.pump(); - }); + testWidgets('setState() smoke test', (WidgetTester tester) { + tester.pumpWidget(new Outside()); + Point location = tester.getCenter(find.text('INSIDE')); + TestGesture gesture = tester.startGesture(location); + tester.pump(); + gesture.up(); + tester.pump(); }); } diff --git a/packages/flutter/test/widget/shader_mask_test.dart b/packages/flutter/test/widget/shader_mask_test.dart index 34670477ae..bdc3a28ad6 100644 --- a/packages/flutter/test/widget/shader_mask_test.dart +++ b/packages/flutter/test/widget/shader_mask_test.dart @@ -6,7 +6,6 @@ import 'dart:ui' show Shader; import 'package:flutter_test/flutter_test.dart'; import 'package:flutter/widgets.dart'; -import 'package:test/test.dart'; Shader createShader(Rect bounds) { return new LinearGradient( @@ -19,10 +18,8 @@ Shader createShader(Rect bounds) { void main() { - test('Can be constructed', () { - testWidgets((WidgetTester tester) { - Widget child = new Container(width: 100.0, height: 100.0); - tester.pumpWidget(new ShaderMask(child: child, shaderCallback: createShader)); - }); + testWidgets('Can be constructed', (WidgetTester tester) { + Widget child = new Container(width: 100.0, height: 100.0); + tester.pumpWidget(new ShaderMask(child: child, shaderCallback: createShader)); }); } diff --git a/packages/flutter/test/widget/snap_scrolling_test.dart b/packages/flutter/test/widget/snap_scrolling_test.dart index 01984f1c8d..bbb1544256 100644 --- a/packages/flutter/test/widget/snap_scrolling_test.dart +++ b/packages/flutter/test/widget/snap_scrolling_test.dart @@ -52,60 +52,58 @@ Future fling(double velocity) { } void main() { - test('ScrollableList snap scrolling, fling(0.8)', () { - testWidgets((WidgetTester tester) { - tester.pumpWidget(buildFrame()); + testWidgets('ScrollableList snap scrolling, fling(0.8)', (WidgetTester tester) { + tester.pumpWidget(buildFrame()); - scrollOffset = 0.0; - tester.pump(); - expect(scrollOffset, 0.0); + scrollOffset = 0.0; + tester.pump(); + expect(scrollOffset, 0.0); - Duration dt = const Duration(seconds: 2); + Duration dt = const Duration(seconds: 2); - fling(0.8); - tester.pump(); // Start the scheduler at 0.0 - tester.pump(dt); + fling(0.8); + tester.pump(); // Start the scheduler at 0.0 + tester.pump(dt); + expect(scrollOffset, closeTo(200.0, 1.0)); + + scrollOffset = 0.0; + tester.pump(); + expect(scrollOffset, 0.0); + + fling(2.0); + tester.pump(); + tester.pump(dt); + expect(scrollOffset, closeTo(400.0, 1.0)); + + scrollOffset = 400.0; + tester.pump(); + expect(scrollOffset, 400.0); + + fling(-0.8); + tester.pump(); + tester.pump(dt); + expect(scrollOffset, closeTo(0.0, 1.0)); + + scrollOffset = 800.0; + tester.pump(); + expect(scrollOffset, 800.0); + + fling(-2.0); + tester.pump(); + tester.pump(dt); + expect(scrollOffset, closeTo(200.0, 1.0)); + + scrollOffset = 800.0; + tester.pump(); + expect(scrollOffset, 800.0); + + bool completed = false; + fling(-2.0).then((_) { + completed = true; expect(scrollOffset, closeTo(200.0, 1.0)); - - scrollOffset = 0.0; - tester.pump(); - expect(scrollOffset, 0.0); - - fling(2.0); - tester.pump(); - tester.pump(dt); - expect(scrollOffset, closeTo(400.0, 1.0)); - - scrollOffset = 400.0; - tester.pump(); - expect(scrollOffset, 400.0); - - fling(-0.8); - tester.pump(); - tester.pump(dt); - expect(scrollOffset, closeTo(0.0, 1.0)); - - scrollOffset = 800.0; - tester.pump(); - expect(scrollOffset, 800.0); - - fling(-2.0); - tester.pump(); - tester.pump(dt); - expect(scrollOffset, closeTo(200.0, 1.0)); - - scrollOffset = 800.0; - tester.pump(); - expect(scrollOffset, 800.0); - - bool completed = false; - fling(-2.0).then((_) { - completed = true; - expect(scrollOffset, closeTo(200.0, 1.0)); - }); - tester.pump(); - tester.pump(dt); - expect(completed, true); }); + tester.pump(); + tester.pump(dt); + expect(completed, true); }); } diff --git a/packages/flutter/test/widget/stack_test.dart b/packages/flutter/test/widget/stack_test.dart index b55a931905..e898144fb4 100644 --- a/packages/flutter/test/widget/stack_test.dart +++ b/packages/flutter/test/widget/stack_test.dart @@ -10,268 +10,248 @@ import 'package:test/test.dart'; import '../rendering/rendering_tester.dart'; void main() { - test('Can construct an empty Stack', () { - testWidgets((WidgetTester tester) { - tester.pumpWidget(new Stack()); - }); + testWidgets('Can construct an empty Stack', (WidgetTester tester) { + tester.pumpWidget(new Stack()); }); - test('Can construct an empty Centered Stack', () { - testWidgets((WidgetTester tester) { - tester.pumpWidget(new Center(child: new Stack())); - }); + testWidgets('Can construct an empty Centered Stack', (WidgetTester tester) { + tester.pumpWidget(new Center(child: new Stack())); }); - test('Can change position data', () { - testElementTree((ElementTreeTester tester) { - Key key = new Key('container'); + testWidgets('Can change position data', (WidgetTester tester) { + Key key = new Key('container'); - tester.pumpWidget( - new Stack( - children: [ - new Positioned( - left: 10.0, - child: new Container( - key: key, - width: 10.0, - height: 10.0 - ) + tester.pumpWidget( + new Stack( + children: [ + new Positioned( + left: 10.0, + child: new Container( + key: key, + width: 10.0, + height: 10.0 ) - ] - ) - ); - - Element container; - StackParentData parentData; - - container = tester.findElementByKey(key); - parentData = container.renderObject.parentData; - expect(parentData.top, isNull); - expect(parentData.right, isNull); - expect(parentData.bottom, isNull); - expect(parentData.left, equals(10.0)); - expect(parentData.width, isNull); - expect(parentData.height, isNull); - - tester.pumpWidget( - new Stack( - children: [ - new Positioned( - right: 10.0, - child: new Container( - key: key, - width: 10.0, - height: 10.0 - ) - ) - ] - ) - ); - - container = tester.findElementByKey(key); - parentData = container.renderObject.parentData; - expect(parentData.top, isNull); - expect(parentData.right, equals(10.0)); - expect(parentData.bottom, isNull); - expect(parentData.left, isNull); - expect(parentData.width, isNull); - expect(parentData.height, isNull); - }); - }); - - test('Can remove parent data', () { - testElementTree((ElementTreeTester tester) { - Key key = new Key('container'); - Container container = new Container(key: key, width: 10.0, height: 10.0); - - tester.pumpWidget(new Stack(children: [ new Positioned(left: 10.0, child: container) ])); - Element containerElement = tester.findElementByKey(key); - - StackParentData parentData; - parentData = containerElement.renderObject.parentData; - expect(parentData.top, isNull); - expect(parentData.right, isNull); - expect(parentData.bottom, isNull); - expect(parentData.left, equals(10.0)); - expect(parentData.width, isNull); - expect(parentData.height, isNull); - - tester.pumpWidget(new Stack(children: [ container ])); - containerElement = tester.findElementByKey(key); - - parentData = containerElement.renderObject.parentData; - expect(parentData.top, isNull); - expect(parentData.right, isNull); - expect(parentData.bottom, isNull); - expect(parentData.left, isNull); - expect(parentData.width, isNull); - expect(parentData.height, isNull); - }); - }); - - test('Can align non-positioned children', () { - testElementTree((ElementTreeTester tester) { - Key child0Key = new Key('child0'); - Key child1Key = new Key('child1'); - - tester.pumpWidget( - new Center( - child: new Stack( - children: [ - new Container(key: child0Key, width: 20.0, height: 20.0), - new Container(key: child1Key, width: 10.0, height: 10.0) - ], - alignment: const FractionalOffset(0.5, 0.5) ) - ) - ); + ] + ) + ); - Element child0 = tester.findElementByKey(child0Key); - final StackParentData child0RenderObjectParentData = child0.renderObject.parentData; - expect(child0RenderObjectParentData.offset, equals(const Offset(0.0, 0.0))); + Element container; + StackParentData parentData; - Element child1 = tester.findElementByKey(child1Key); - final StackParentData child1RenderObjectParentData = child1.renderObject.parentData; - expect(child1RenderObjectParentData.offset, equals(const Offset(5.0, 5.0))); - }); - }); + container = tester.element(find.byKey(key)); + parentData = container.renderObject.parentData; + expect(parentData.top, isNull); + expect(parentData.right, isNull); + expect(parentData.bottom, isNull); + expect(parentData.left, equals(10.0)); + expect(parentData.width, isNull); + expect(parentData.height, isNull); - test('Can construct an empty IndexedStack', () { - testWidgets((WidgetTester tester) { - tester.pumpWidget(new IndexedStack()); - }); - }); - - test('Can construct an empty Centered IndexedStack', () { - testWidgets((WidgetTester tester) { - tester.pumpWidget(new Center(child: new IndexedStack())); - }); - }); - - test('Can construct an IndexedStack', () { - testWidgets((WidgetTester tester) { - int itemCount = 3; - List itemsPainted; - - Widget buildFrame(int index) { - itemsPainted = []; - List items = new List.generate(itemCount, (int i) { - return new CustomPaint( - child: new Text('$i'), - painter: new TestCallbackPainter( - onPaint: () { itemsPainted.add(i); } + tester.pumpWidget( + new Stack( + children: [ + new Positioned( + right: 10.0, + child: new Container( + key: key, + width: 10.0, + height: 10.0 ) - ); - }); - return new Center(child: new IndexedStack(children: items, index: index)); - } + ) + ] + ) + ); - tester.pumpWidget(buildFrame(0)); - expect(tester, hasWidget(find.text('0'))); - expect(tester, hasWidget(find.text('1'))); - expect(tester, hasWidget(find.text('2'))); - expect(itemsPainted, equals([0])); - - tester.pumpWidget(buildFrame(1)); - expect(itemsPainted, equals([1])); - - tester.pumpWidget(buildFrame(2)); - expect(itemsPainted, equals([2])); - }); + container = tester.element(find.byKey(key)); + parentData = container.renderObject.parentData; + expect(parentData.top, isNull); + expect(parentData.right, equals(10.0)); + expect(parentData.bottom, isNull); + expect(parentData.left, isNull); + expect(parentData.width, isNull); + expect(parentData.height, isNull); }); - test('Can hit test an IndexedStack', () { - testWidgets((WidgetTester tester) { - Key key = new Key('indexedStack'); - int itemCount = 3; - List itemsTapped; + testWidgets('Can remove parent data', (WidgetTester tester) { + Key key = new Key('container'); + Container container = new Container(key: key, width: 10.0, height: 10.0); - Widget buildFrame(int index) { - itemsTapped = []; - List items = new List.generate(itemCount, (int i) { - return new GestureDetector(child: new Text('$i'), onTap: () { itemsTapped.add(i); }); - }); - return new Center(child: new IndexedStack(children: items, key: key, index: index)); - } + tester.pumpWidget(new Stack(children: [ new Positioned(left: 10.0, child: container) ])); + Element containerElement = tester.element(find.byKey(key)); - tester.pumpWidget(buildFrame(0)); - expect(itemsTapped, isEmpty); - tester.tap(find.byKey(key)); - expect(itemsTapped, [0]); + StackParentData parentData; + parentData = containerElement.renderObject.parentData; + expect(parentData.top, isNull); + expect(parentData.right, isNull); + expect(parentData.bottom, isNull); + expect(parentData.left, equals(10.0)); + expect(parentData.width, isNull); + expect(parentData.height, isNull); - tester.pumpWidget(buildFrame(2)); - expect(itemsTapped, isEmpty); - tester.tap(find.byKey(key)); - expect(itemsTapped, [2]); - }); + tester.pumpWidget(new Stack(children: [ container ])); + containerElement = tester.element(find.byKey(key)); + + parentData = containerElement.renderObject.parentData; + expect(parentData.top, isNull); + expect(parentData.right, isNull); + expect(parentData.bottom, isNull); + expect(parentData.left, isNull); + expect(parentData.width, isNull); + expect(parentData.height, isNull); }); - test('Can set width and height', () { - testElementTree((ElementTreeTester tester) { - Key key = new Key('container'); + testWidgets('Can align non-positioned children', (WidgetTester tester) { + Key child0Key = new Key('child0'); + Key child1Key = new Key('child1'); - BoxDecoration kBoxDecoration = new BoxDecoration( - backgroundColor: new Color(0xFF00FF00) - ); - - tester.pumpWidget( - new Stack( + tester.pumpWidget( + new Center( + child: new Stack( children: [ - new Positioned( - left: 10.0, - width: 11.0, - height: 12.0, - child: new DecoratedBox(key: key, decoration: kBoxDecoration) - ) - ] + new Container(key: child0Key, width: 20.0, height: 20.0), + new Container(key: child1Key, width: 10.0, height: 10.0) + ], + alignment: const FractionalOffset(0.5, 0.5) ) - ); + ) + ); - Element box; - RenderBox renderBox; - StackParentData parentData; + Element child0 = tester.element(find.byKey(child0Key)); + final StackParentData child0RenderObjectParentData = child0.renderObject.parentData; + expect(child0RenderObjectParentData.offset, equals(const Offset(0.0, 0.0))); - box = tester.findElementByKey(key); - renderBox = box.renderObject; - parentData = renderBox.parentData; - expect(parentData.top, isNull); - expect(parentData.right, isNull); - expect(parentData.bottom, isNull); - expect(parentData.left, equals(10.0)); - expect(parentData.width, equals(11.0)); - expect(parentData.height, equals(12.0)); - expect(parentData.offset.dx, equals(10.0)); - expect(parentData.offset.dy, equals(0.0)); - expect(renderBox.size.width, equals(11.0)); - expect(renderBox.size.height, equals(12.0)); + Element child1 = tester.element(find.byKey(child1Key)); + final StackParentData child1RenderObjectParentData = child1.renderObject.parentData; + expect(child1RenderObjectParentData.offset, equals(const Offset(5.0, 5.0))); + }); - tester.pumpWidget( - new Stack( - children: [ - new Positioned( - right: 10.0, - width: 11.0, - height: 12.0, - child: new DecoratedBox(key: key, decoration: kBoxDecoration) - ) - ] - ) - ); + testWidgets('Can construct an empty IndexedStack', (WidgetTester tester) { + tester.pumpWidget(new IndexedStack()); + }); - box = tester.findElementByKey(key); - renderBox = box.renderObject; - parentData = renderBox.parentData; - expect(parentData.top, isNull); - expect(parentData.right, equals(10.0)); - expect(parentData.bottom, isNull); - expect(parentData.left, isNull); - expect(parentData.width, equals(11.0)); - expect(parentData.height, equals(12.0)); - expect(parentData.offset.dx, equals(779.0)); - expect(parentData.offset.dy, equals(0.0)); - expect(renderBox.size.width, equals(11.0)); - expect(renderBox.size.height, equals(12.0)); - }); + testWidgets('Can construct an empty Centered IndexedStack', (WidgetTester tester) { + tester.pumpWidget(new Center(child: new IndexedStack())); + }); + + testWidgets('Can construct an IndexedStack', (WidgetTester tester) { + int itemCount = 3; + List itemsPainted; + + Widget buildFrame(int index) { + itemsPainted = []; + List items = new List.generate(itemCount, (int i) { + return new CustomPaint( + child: new Text('$i'), + painter: new TestCallbackPainter( + onPaint: () { itemsPainted.add(i); } + ) + ); + }); + return new Center(child: new IndexedStack(children: items, index: index)); + } + + tester.pumpWidget(buildFrame(0)); + expect(find.text('0'), findsOneWidget); + expect(find.text('1'), findsOneWidget); + expect(find.text('2'), findsOneWidget); + expect(itemsPainted, equals([0])); + + tester.pumpWidget(buildFrame(1)); + expect(itemsPainted, equals([1])); + + tester.pumpWidget(buildFrame(2)); + expect(itemsPainted, equals([2])); + }); + + testWidgets('Can hit test an IndexedStack', (WidgetTester tester) { + Key key = new Key('indexedStack'); + int itemCount = 3; + List itemsTapped; + + Widget buildFrame(int index) { + itemsTapped = []; + List items = new List.generate(itemCount, (int i) { + return new GestureDetector(child: new Text('$i'), onTap: () { itemsTapped.add(i); }); + }); + return new Center(child: new IndexedStack(children: items, key: key, index: index)); + } + + tester.pumpWidget(buildFrame(0)); + expect(itemsTapped, isEmpty); + tester.tap(find.byKey(key)); + expect(itemsTapped, [0]); + + tester.pumpWidget(buildFrame(2)); + expect(itemsTapped, isEmpty); + tester.tap(find.byKey(key)); + expect(itemsTapped, [2]); + }); + + testWidgets('Can set width and height', (WidgetTester tester) { + Key key = new Key('container'); + + BoxDecoration kBoxDecoration = new BoxDecoration( + backgroundColor: new Color(0xFF00FF00) + ); + + tester.pumpWidget( + new Stack( + children: [ + new Positioned( + left: 10.0, + width: 11.0, + height: 12.0, + child: new DecoratedBox(key: key, decoration: kBoxDecoration) + ) + ] + ) + ); + + Element box; + RenderBox renderBox; + StackParentData parentData; + + box = tester.element(find.byKey(key)); + renderBox = box.renderObject; + parentData = renderBox.parentData; + expect(parentData.top, isNull); + expect(parentData.right, isNull); + expect(parentData.bottom, isNull); + expect(parentData.left, equals(10.0)); + expect(parentData.width, equals(11.0)); + expect(parentData.height, equals(12.0)); + expect(parentData.offset.dx, equals(10.0)); + expect(parentData.offset.dy, equals(0.0)); + expect(renderBox.size.width, equals(11.0)); + expect(renderBox.size.height, equals(12.0)); + + tester.pumpWidget( + new Stack( + children: [ + new Positioned( + right: 10.0, + width: 11.0, + height: 12.0, + child: new DecoratedBox(key: key, decoration: kBoxDecoration) + ) + ] + ) + ); + + box = tester.element(find.byKey(key)); + renderBox = box.renderObject; + parentData = renderBox.parentData; + expect(parentData.top, isNull); + expect(parentData.right, equals(10.0)); + expect(parentData.bottom, isNull); + expect(parentData.left, isNull); + expect(parentData.width, equals(11.0)); + expect(parentData.height, equals(12.0)); + expect(parentData.offset.dx, equals(779.0)); + expect(parentData.offset.dy, equals(0.0)); + expect(renderBox.size.width, equals(11.0)); + expect(renderBox.size.height, equals(12.0)); }); } diff --git a/packages/flutter/test/widget/stateful_component_test.dart b/packages/flutter/test/widget/stateful_component_test.dart index 778219c58f..9d534f92aa 100644 --- a/packages/flutter/test/widget/stateful_component_test.dart +++ b/packages/flutter/test/widget/stateful_component_test.dart @@ -10,71 +10,67 @@ import 'package:test/test.dart'; import 'test_widgets.dart'; void main() { - test('Stateful widget smoke test', () { - testWidgets((WidgetTester tester) { + testWidgets('Stateful widget smoke test', (WidgetTester tester) { - void checkTree(BoxDecoration expectedDecoration) { - SingleChildRenderObjectElement element = tester.elementOf( - find.byElementPredicate((Element element) => element is SingleChildRenderObjectElement) - ); - expect(element, isNotNull); - expect(element.renderObject is RenderDecoratedBox, isTrue); - RenderDecoratedBox renderObject = element.renderObject; - expect(renderObject.decoration, equals(expectedDecoration)); - } - - tester.pumpWidget( - new FlipWidget( - left: new DecoratedBox(decoration: kBoxDecorationA), - right: new DecoratedBox(decoration: kBoxDecorationB) - ) + void checkTree(BoxDecoration expectedDecoration) { + SingleChildRenderObjectElement element = tester.element( + find.byElementPredicate((Element element) => element is SingleChildRenderObjectElement) ); + expect(element, isNotNull); + expect(element.renderObject is RenderDecoratedBox, isTrue); + RenderDecoratedBox renderObject = element.renderObject; + expect(renderObject.decoration, equals(expectedDecoration)); + } - checkTree(kBoxDecorationA); + tester.pumpWidget( + new FlipWidget( + left: new DecoratedBox(decoration: kBoxDecorationA), + right: new DecoratedBox(decoration: kBoxDecorationB) + ) + ); - tester.pumpWidget( - new FlipWidget( - left: new DecoratedBox(decoration: kBoxDecorationB), - right: new DecoratedBox(decoration: kBoxDecorationA) - ) - ); + checkTree(kBoxDecorationA); - checkTree(kBoxDecorationB); + tester.pumpWidget( + new FlipWidget( + left: new DecoratedBox(decoration: kBoxDecorationB), + right: new DecoratedBox(decoration: kBoxDecorationA) + ) + ); - flipStatefulWidget(tester); + checkTree(kBoxDecorationB); - tester.pump(); + flipStatefulWidget(tester); - checkTree(kBoxDecorationA); + tester.pump(); - tester.pumpWidget( - new FlipWidget( - left: new DecoratedBox(decoration: kBoxDecorationA), - right: new DecoratedBox(decoration: kBoxDecorationB) - ) - ); + checkTree(kBoxDecorationA); - checkTree(kBoxDecorationB); - }); + tester.pumpWidget( + new FlipWidget( + left: new DecoratedBox(decoration: kBoxDecorationA), + right: new DecoratedBox(decoration: kBoxDecorationB) + ) + ); + + checkTree(kBoxDecorationB); }); - test('Don\'t rebuild subwidgets', () { - testWidgets((WidgetTester tester) { - tester.pumpWidget( - new FlipWidget( - key: new Key('rebuild test'), - left: new TestBuildCounter(), - right: new DecoratedBox(decoration: kBoxDecorationB) - ) - ); + testWidgets('Don\'t rebuild subwidgets', (WidgetTester tester) { + tester.pumpWidget( + new FlipWidget( + key: new Key('rebuild test'), + left: new TestBuildCounter(), + right: new DecoratedBox(decoration: kBoxDecorationB) + ) + ); - expect(TestBuildCounter.buildCount, equals(1)); + expect(TestBuildCounter.buildCount, equals(1)); - flipStatefulWidget(tester); + flipStatefulWidget(tester); - tester.pump(); + tester.pump(); - expect(TestBuildCounter.buildCount, equals(1)); - }); + expect(TestBuildCounter.buildCount, equals(1)); }); } diff --git a/packages/flutter/test/widget/stateful_components_test.dart b/packages/flutter/test/widget/stateful_components_test.dart index 8a40c3f2fd..cb05646800 100644 --- a/packages/flutter/test/widget/stateful_components_test.dart +++ b/packages/flutter/test/widget/stateful_components_test.dart @@ -45,45 +45,43 @@ class OuterContainerState extends State { } void main() { - test('resync stateful widget', () { - testElementTree((ElementTreeTester tester) { - Key innerKey = new Key('inner'); - Key outerKey = new Key('outer'); + testWidgets('resync stateful widget', (WidgetTester tester) { + Key innerKey = new Key('inner'); + Key outerKey = new Key('outer'); - InnerWidget inner1 = new InnerWidget(key: innerKey); - InnerWidget inner2; - OuterContainer outer1 = new OuterContainer(key: outerKey, child: inner1); - OuterContainer outer2; + InnerWidget inner1 = new InnerWidget(key: innerKey); + InnerWidget inner2; + OuterContainer outer1 = new OuterContainer(key: outerKey, child: inner1); + OuterContainer outer2; - tester.pumpWidget(outer1); + tester.pumpWidget(outer1); - StatefulElement innerElement = tester.findElementByKey(innerKey); - InnerWidgetState innerElementState = innerElement.state; - expect(innerElementState.config, equals(inner1)); - expect(innerElementState._didInitState, isTrue); - expect(innerElement.renderObject.attached, isTrue); + StatefulElement innerElement = tester.element(find.byKey(innerKey)); + InnerWidgetState innerElementState = innerElement.state; + expect(innerElementState.config, equals(inner1)); + expect(innerElementState._didInitState, isTrue); + expect(innerElement.renderObject.attached, isTrue); - inner2 = new InnerWidget(key: innerKey); - outer2 = new OuterContainer(key: outerKey, child: inner2); + inner2 = new InnerWidget(key: innerKey); + outer2 = new OuterContainer(key: outerKey, child: inner2); - tester.pumpWidget(outer2); + tester.pumpWidget(outer2); - expect(tester.findElementByKey(innerKey), equals(innerElement)); - expect(innerElement.state, equals(innerElementState)); + expect(tester.element(find.byKey(innerKey)), equals(innerElement)); + expect(innerElement.state, equals(innerElementState)); - expect(innerElementState.config, equals(inner2)); - expect(innerElementState._didInitState, isTrue); - expect(innerElement.renderObject.attached, isTrue); + expect(innerElementState.config, equals(inner2)); + expect(innerElementState._didInitState, isTrue); + expect(innerElement.renderObject.attached, isTrue); - StatefulElement outerElement = tester.findElementByKey(outerKey); - expect(outerElement.state.config, equals(outer2)); - outerElement.state.setState(() {}); - tester.pump(); + StatefulElement outerElement = tester.element(find.byKey(outerKey)); + expect(outerElement.state.config, equals(outer2)); + outerElement.state.setState(() {}); + tester.pump(); - expect(tester.findElementByKey(innerKey), equals(innerElement)); - expect(innerElement.state, equals(innerElementState)); - expect(innerElementState.config, equals(inner2)); - expect(innerElement.renderObject.attached, isTrue); - }); + expect(tester.element(find.byKey(innerKey)), equals(innerElement)); + expect(innerElement.state, equals(innerElementState)); + expect(innerElementState.config, equals(inner2)); + expect(innerElement.renderObject.attached, isTrue); }); } diff --git a/packages/flutter/test/widget/syncing_test.dart b/packages/flutter/test/widget/syncing_test.dart index 15a5ad31df..2b025862e7 100644 --- a/packages/flutter/test/widget/syncing_test.dart +++ b/packages/flutter/test/widget/syncing_test.dart @@ -43,167 +43,161 @@ class TestWidgetState extends State { void main() { - test('no change', () { - testWidgets((WidgetTester tester) { - tester.pumpWidget( - new Container( - child: new Container( - child: new TestWidget( - persistentState: 1, - child: new Container() - ) - ) - ) - ); - - TestWidgetState state = tester.stateOf(find.byType(TestWidget)); - - expect(state.persistentState, equals(1)); - expect(state.updates, equals(0)); - - tester.pumpWidget( - new Container( - child: new Container( - child: new TestWidget( - persistentState: 2, - child: new Container() - ) - ) - ) - ); - - expect(state.persistentState, equals(1)); - expect(state.updates, equals(1)); - - tester.pumpWidget(new Container()); - }); - }); - - test('remove one', () { - testWidgets((WidgetTester tester) { - tester.pumpWidget( - new Container( - child: new Container( - child: new TestWidget( - persistentState: 10, - child: new Container() - ) - ) - ) - ); - - TestWidgetState state = tester.stateOf(find.byType(TestWidget)); - - expect(state.persistentState, equals(10)); - expect(state.updates, equals(0)); - - tester.pumpWidget( - new Container( + testWidgets('no change', (WidgetTester tester) { + tester.pumpWidget( + new Container( + child: new Container( child: new TestWidget( - persistentState: 11, + persistentState: 1, child: new Container() ) ) - ); + ) + ); - state = tester.stateOf(find.byType(TestWidget)); + TestWidgetState state = tester.state(find.byType(TestWidget)); - expect(state.persistentState, equals(11)); - expect(state.updates, equals(0)); + expect(state.persistentState, equals(1)); + expect(state.updates, equals(0)); - tester.pumpWidget(new Container()); - }); + tester.pumpWidget( + new Container( + child: new Container( + child: new TestWidget( + persistentState: 2, + child: new Container() + ) + ) + ) + ); + + expect(state.persistentState, equals(1)); + expect(state.updates, equals(1)); + + tester.pumpWidget(new Container()); }); - test('swap instances around', () { - testElementTree((ElementTreeTester tester) { - Widget a = new TestWidget(persistentState: 0x61, syncedState: 0x41, child: new Text('apple')); - Widget b = new TestWidget(persistentState: 0x62, syncedState: 0x42, child: new Text('banana')); - tester.pumpWidget(new Column()); - - GlobalKey keyA = new GlobalKey(); - GlobalKey keyB = new GlobalKey(); - - tester.pumpWidget( - new Column( - children: [ - new Container( - key: keyA, - child: a - ), - new Container( - key: keyB, - child: b - ) - ] + testWidgets('remove one', (WidgetTester tester) { + tester.pumpWidget( + new Container( + child: new Container( + child: new TestWidget( + persistentState: 10, + child: new Container() + ) ) - ); + ) + ); - TestWidgetState first, second; + TestWidgetState state = tester.state(find.byType(TestWidget)); - first = tester.findStateByConfig(a); - second = tester.findStateByConfig(b); + expect(state.persistentState, equals(10)); + expect(state.updates, equals(0)); - expect(first.config, equals(a)); - expect(first.persistentState, equals(0x61)); - expect(first.syncedState, equals(0x41)); - expect(second.config, equals(b)); - expect(second.persistentState, equals(0x62)); - expect(second.syncedState, equals(0x42)); - - tester.pumpWidget( - new Column( - children: [ - new Container( - key: keyA, - child: a - ), - new Container( - key: keyB, - child: b - ) - ] + tester.pumpWidget( + new Container( + child: new TestWidget( + persistentState: 11, + child: new Container() ) - ); + ) + ); - first = tester.findStateByConfig(a); - second = tester.findStateByConfig(b); + state = tester.state(find.byType(TestWidget)); - // same as before - expect(first.config, equals(a)); - expect(first.persistentState, equals(0x61)); - expect(first.syncedState, equals(0x41)); - expect(second.config, equals(b)); - expect(second.persistentState, equals(0x62)); - expect(second.syncedState, equals(0x42)); + expect(state.persistentState, equals(11)); + expect(state.updates, equals(0)); - // now we swap the nodes over - // since they are both "old" nodes, they shouldn't sync with each other even though they look alike + tester.pumpWidget(new Container()); + }); - tester.pumpWidget( - new Column( - children: [ - new Container( - key: keyA, - child: b - ), - new Container( - key: keyB, - child: a - ) - ] - ) - ); + testWidgets('swap instances around', (WidgetTester tester) { + Widget a = new TestWidget(persistentState: 0x61, syncedState: 0x41, child: new Text('apple')); + Widget b = new TestWidget(persistentState: 0x62, syncedState: 0x42, child: new Text('banana')); + tester.pumpWidget(new Column()); - first = tester.findStateByConfig(b); - second = tester.findStateByConfig(a); + GlobalKey keyA = new GlobalKey(); + GlobalKey keyB = new GlobalKey(); - expect(first.config, equals(b)); - expect(first.persistentState, equals(0x61)); - expect(first.syncedState, equals(0x42)); - expect(second.config, equals(a)); - expect(second.persistentState, equals(0x62)); - expect(second.syncedState, equals(0x41)); - }); + tester.pumpWidget( + new Column( + children: [ + new Container( + key: keyA, + child: a + ), + new Container( + key: keyB, + child: b + ) + ] + ) + ); + + TestWidgetState first, second; + + first = tester.state(find.byConfig(a)); + second = tester.state(find.byConfig(b)); + + expect(first.config, equals(a)); + expect(first.persistentState, equals(0x61)); + expect(first.syncedState, equals(0x41)); + expect(second.config, equals(b)); + expect(second.persistentState, equals(0x62)); + expect(second.syncedState, equals(0x42)); + + tester.pumpWidget( + new Column( + children: [ + new Container( + key: keyA, + child: a + ), + new Container( + key: keyB, + child: b + ) + ] + ) + ); + + first = tester.state(find.byConfig(a)); + second = tester.state(find.byConfig(b)); + + // same as before + expect(first.config, equals(a)); + expect(first.persistentState, equals(0x61)); + expect(first.syncedState, equals(0x41)); + expect(second.config, equals(b)); + expect(second.persistentState, equals(0x62)); + expect(second.syncedState, equals(0x42)); + + // now we swap the nodes over + // since they are both "old" nodes, they shouldn't sync with each other even though they look alike + + tester.pumpWidget( + new Column( + children: [ + new Container( + key: keyA, + child: b + ), + new Container( + key: keyB, + child: a + ) + ] + ) + ); + + first = tester.state(find.byConfig(b)); + second = tester.state(find.byConfig(a)); + + expect(first.config, equals(b)); + expect(first.persistentState, equals(0x61)); + expect(first.syncedState, equals(0x42)); + expect(second.config, equals(a)); + expect(second.persistentState, equals(0x62)); + expect(second.syncedState, equals(0x41)); }); } diff --git a/packages/flutter/test/widget/table_test.dart b/packages/flutter/test/widget/table_test.dart index e396cb9262..fc8d058299 100644 --- a/packages/flutter/test/widget/table_test.dart +++ b/packages/flutter/test/widget/table_test.dart @@ -8,337 +8,329 @@ import 'package:flutter/widgets.dart'; import 'package:test/test.dart'; void main() { - test('Table widget - control test', () { - testElementTree((ElementTreeTester tester) { - tester.pumpWidget( - new Table( - children: [ - new TableRow( - children: [ - new Text('AAAAAA'), new Text('B'), new Text('C') - ] - ), - new TableRow( - children: [ - new Text('D'), new Text('EEE'), new Text('F') - ] - ), - new TableRow( - children: [ - new Text('G'), new Text('H'), new Text('III') - ] - ), - ] - ) - ); - RenderBox boxA = tester.findText('AAAAAA').findRenderObject(); - RenderBox boxD = tester.findText('D').findRenderObject(); - RenderBox boxG = tester.findText('G').findRenderObject(); - RenderBox boxB = tester.findText('B').findRenderObject(); - expect(boxA.size, equals(boxD.size)); - expect(boxA.size, equals(boxG.size)); - expect(boxA.size, equals(boxB.size)); - }); + testWidgets('Table widget - control test', (WidgetTester tester) { + tester.pumpWidget( + new Table( + children: [ + new TableRow( + children: [ + new Text('AAAAAA'), new Text('B'), new Text('C') + ] + ), + new TableRow( + children: [ + new Text('D'), new Text('EEE'), new Text('F') + ] + ), + new TableRow( + children: [ + new Text('G'), new Text('H'), new Text('III') + ] + ), + ] + ) + ); + RenderBox boxA = tester.renderObject(find.text('AAAAAA')); + RenderBox boxD = tester.renderObject(find.text('D')); + RenderBox boxG = tester.renderObject(find.text('G')); + RenderBox boxB = tester.renderObject(find.text('B')); + expect(boxA.size, equals(boxD.size)); + expect(boxA.size, equals(boxG.size)); + expect(boxA.size, equals(boxB.size)); }); - test('Table widget - changing table dimensions', () { - testElementTree((ElementTreeTester tester) { - tester.pumpWidget( - new Table( - children: [ - new TableRow( - children: [ - new Text('A'), new Text('B'), new Text('C') - ] - ), - new TableRow( - children: [ - new Text('D'), new Text('E'), new Text('F') - ] - ), - new TableRow( - children: [ - new Text('G'), new Text('H'), new Text('I') - ] - ), - ] - ) - ); - RenderBox boxA1 = tester.findText('A').findRenderObject(); - RenderBox boxG1 = tester.findText('G').findRenderObject(); - expect(boxA1, isNotNull); - expect(boxG1, isNotNull); - tester.pumpWidget( - new Table( - children: [ - new TableRow( - children: [ - new Text('a'), new Text('b'), new Text('c'), new Text('d') - ] - ), - new TableRow( - children: [ - new Text('e'), new Text('f'), new Text('g'), new Text('h') - ] - ), - ] - ) - ); - RenderBox boxA2 = tester.findText('a').findRenderObject(); - RenderBox boxG2 = tester.findText('g').findRenderObject(); - expect(boxA2, isNotNull); - expect(boxG2, isNotNull); - expect(boxA1, equals(boxA2)); - expect(boxG1, isNot(equals(boxG2))); - }); + + testWidgets('Table widget - changing table dimensions', (WidgetTester tester) { + tester.pumpWidget( + new Table( + children: [ + new TableRow( + children: [ + new Text('A'), new Text('B'), new Text('C') + ] + ), + new TableRow( + children: [ + new Text('D'), new Text('E'), new Text('F') + ] + ), + new TableRow( + children: [ + new Text('G'), new Text('H'), new Text('I') + ] + ), + ] + ) + ); + RenderBox boxA1 = tester.renderObject(find.text('A')); + RenderBox boxG1 = tester.renderObject(find.text('G')); + expect(boxA1, isNotNull); + expect(boxG1, isNotNull); + tester.pumpWidget( + new Table( + children: [ + new TableRow( + children: [ + new Text('a'), new Text('b'), new Text('c'), new Text('d') + ] + ), + new TableRow( + children: [ + new Text('e'), new Text('f'), new Text('g'), new Text('h') + ] + ), + ] + ) + ); + RenderBox boxA2 = tester.renderObject(find.text('a')); + RenderBox boxG2 = tester.renderObject(find.text('g')); + expect(boxA2, isNotNull); + expect(boxG2, isNotNull); + expect(boxA1, equals(boxA2)); + expect(boxG1, isNot(equals(boxG2))); }); - test('Table widget - repump test', () { - testElementTree((ElementTreeTester tester) { - tester.pumpWidget( - new Table( - children: [ - new TableRow( - children: [ - new Text('AAAAAA'), new Text('B'), new Text('C') - ] - ), - new TableRow( - children: [ - new Text('D'), new Text('EEE'), new Text('F') - ] - ), - new TableRow( - children: [ - new Text('G'), new Text('H'), new Text('III') - ] - ), - ] - ) - ); - tester.pumpWidget( - new Table( - children: [ - new TableRow( - children: [ - new Text('AAA'), new Text('B'), new Text('C') - ] - ), - new TableRow( - children: [ - new Text('D'), new Text('E'), new Text('FFFFFF') - ] - ), - new TableRow( - children: [ - new Text('G'), new Text('H'), new Text('III') - ] - ), - ] - ) - ); - RenderBox boxA = tester.findText('AAA').findRenderObject(); - RenderBox boxD = tester.findText('D').findRenderObject(); - RenderBox boxG = tester.findText('G').findRenderObject(); - RenderBox boxB = tester.findText('B').findRenderObject(); - expect(boxA.size, equals(boxD.size)); - expect(boxA.size, equals(boxG.size)); - expect(boxA.size, equals(boxB.size)); - }); + + testWidgets('Table widget - repump test', (WidgetTester tester) { + tester.pumpWidget( + new Table( + children: [ + new TableRow( + children: [ + new Text('AAAAAA'), new Text('B'), new Text('C') + ] + ), + new TableRow( + children: [ + new Text('D'), new Text('EEE'), new Text('F') + ] + ), + new TableRow( + children: [ + new Text('G'), new Text('H'), new Text('III') + ] + ), + ] + ) + ); + tester.pumpWidget( + new Table( + children: [ + new TableRow( + children: [ + new Text('AAA'), new Text('B'), new Text('C') + ] + ), + new TableRow( + children: [ + new Text('D'), new Text('E'), new Text('FFFFFF') + ] + ), + new TableRow( + children: [ + new Text('G'), new Text('H'), new Text('III') + ] + ), + ] + ) + ); + RenderBox boxA = tester.renderObject(find.text('AAA')); + RenderBox boxD = tester.renderObject(find.text('D')); + RenderBox boxG = tester.renderObject(find.text('G')); + RenderBox boxB = tester.renderObject(find.text('B')); + expect(boxA.size, equals(boxD.size)); + expect(boxA.size, equals(boxG.size)); + expect(boxA.size, equals(boxB.size)); }); - test('Table widget - intrinsic sizing test', () { - testElementTree((ElementTreeTester tester) { - tester.pumpWidget( - new Table( - defaultColumnWidth: const IntrinsicColumnWidth(), - children: [ - new TableRow( - children: [ - new Text('AAA'), new Text('B'), new Text('C') - ] - ), - new TableRow( - children: [ - new Text('D'), new Text('E'), new Text('FFFFFF') - ] - ), - new TableRow( - children: [ - new Text('G'), new Text('H'), new Text('III') - ] - ), - ] - ) - ); - RenderBox boxA = tester.findText('AAA').findRenderObject(); - RenderBox boxD = tester.findText('D').findRenderObject(); - RenderBox boxG = tester.findText('G').findRenderObject(); - RenderBox boxB = tester.findText('B').findRenderObject(); - expect(boxA.size, equals(boxD.size)); - expect(boxA.size, equals(boxG.size)); - expect(boxA.size.width, greaterThan(boxB.size.width)); - expect(boxA.size.height, equals(boxB.size.height)); - }); + + testWidgets('Table widget - intrinsic sizing test', (WidgetTester tester) { + tester.pumpWidget( + new Table( + defaultColumnWidth: const IntrinsicColumnWidth(), + children: [ + new TableRow( + children: [ + new Text('AAA'), new Text('B'), new Text('C') + ] + ), + new TableRow( + children: [ + new Text('D'), new Text('E'), new Text('FFFFFF') + ] + ), + new TableRow( + children: [ + new Text('G'), new Text('H'), new Text('III') + ] + ), + ] + ) + ); + RenderBox boxA = tester.renderObject(find.text('AAA')); + RenderBox boxD = tester.renderObject(find.text('D')); + RenderBox boxG = tester.renderObject(find.text('G')); + RenderBox boxB = tester.renderObject(find.text('B')); + expect(boxA.size, equals(boxD.size)); + expect(boxA.size, equals(boxG.size)); + expect(boxA.size.width, greaterThan(boxB.size.width)); + expect(boxA.size.height, equals(boxB.size.height)); }); - test('Table widget - intrinsic sizing test, resizing', () { - testElementTree((ElementTreeTester tester) { - tester.pumpWidget( - new Table( - defaultColumnWidth: const IntrinsicColumnWidth(), - children: [ - new TableRow( - children: [ - new Text('AAAAAA'), new Text('B'), new Text('C') - ] - ), - new TableRow( - children: [ - new Text('D'), new Text('EEE'), new Text('F') - ] - ), - new TableRow( - children: [ - new Text('G'), new Text('H'), new Text('III') - ] - ), - ] - ) - ); - tester.pumpWidget( - new Table( - defaultColumnWidth: const IntrinsicColumnWidth(), - children: [ - new TableRow( - children: [ - new Text('A'), new Text('B'), new Text('C') - ] - ), - new TableRow( - children: [ - new Text('D'), new Text('EEE'), new Text('F') - ] - ), - new TableRow( - children: [ - new Text('G'), new Text('H'), new Text('III') - ] - ), - ] - ) - ); - RenderBox boxA = tester.findText('A').findRenderObject(); - RenderBox boxD = tester.findText('D').findRenderObject(); - RenderBox boxG = tester.findText('G').findRenderObject(); - RenderBox boxB = tester.findText('B').findRenderObject(); - expect(boxA.size, equals(boxD.size)); - expect(boxA.size, equals(boxG.size)); - expect(boxA.size.width, lessThan(boxB.size.width)); - expect(boxA.size.height, equals(boxB.size.height)); - }); + + testWidgets('Table widget - intrinsic sizing test, resizing', (WidgetTester tester) { + tester.pumpWidget( + new Table( + defaultColumnWidth: const IntrinsicColumnWidth(), + children: [ + new TableRow( + children: [ + new Text('AAAAAA'), new Text('B'), new Text('C') + ] + ), + new TableRow( + children: [ + new Text('D'), new Text('EEE'), new Text('F') + ] + ), + new TableRow( + children: [ + new Text('G'), new Text('H'), new Text('III') + ] + ), + ] + ) + ); + tester.pumpWidget( + new Table( + defaultColumnWidth: const IntrinsicColumnWidth(), + children: [ + new TableRow( + children: [ + new Text('A'), new Text('B'), new Text('C') + ] + ), + new TableRow( + children: [ + new Text('D'), new Text('EEE'), new Text('F') + ] + ), + new TableRow( + children: [ + new Text('G'), new Text('H'), new Text('III') + ] + ), + ] + ) + ); + RenderBox boxA = tester.renderObject(find.text('A')); + RenderBox boxD = tester.renderObject(find.text('D')); + RenderBox boxG = tester.renderObject(find.text('G')); + RenderBox boxB = tester.renderObject(find.text('B')); + expect(boxA.size, equals(boxD.size)); + expect(boxA.size, equals(boxG.size)); + expect(boxA.size.width, lessThan(boxB.size.width)); + expect(boxA.size.height, equals(boxB.size.height)); }); - test('Table widget - intrinsic sizing test, changing column widths', () { - testElementTree((ElementTreeTester tester) { - tester.pumpWidget( - new Table( - children: [ - new TableRow( - children: [ - new Text('AAA'), new Text('B'), new Text('C') - ] - ), - new TableRow( - children: [ - new Text('D'), new Text('E'), new Text('FFFFFF') - ] - ), - new TableRow( - children: [ - new Text('G'), new Text('H'), new Text('III') - ] - ), - ] - ) - ); - tester.pumpWidget( - new Table( - defaultColumnWidth: const IntrinsicColumnWidth(), - children: [ - new TableRow( - children: [ - new Text('AAA'), new Text('B'), new Text('C') - ] - ), - new TableRow( - children: [ - new Text('D'), new Text('E'), new Text('FFFFFF') - ] - ), - new TableRow( - children: [ - new Text('G'), new Text('H'), new Text('III') - ] - ), - ] - ) - ); - RenderBox boxA = tester.findText('AAA').findRenderObject(); - RenderBox boxD = tester.findText('D').findRenderObject(); - RenderBox boxG = tester.findText('G').findRenderObject(); - RenderBox boxB = tester.findText('B').findRenderObject(); - expect(boxA.size, equals(boxD.size)); - expect(boxA.size, equals(boxG.size)); - expect(boxA.size.width, greaterThan(boxB.size.width)); - expect(boxA.size.height, equals(boxB.size.height)); - }); + + testWidgets('Table widget - intrinsic sizing test, changing column widths', (WidgetTester tester) { + tester.pumpWidget( + new Table( + children: [ + new TableRow( + children: [ + new Text('AAA'), new Text('B'), new Text('C') + ] + ), + new TableRow( + children: [ + new Text('D'), new Text('E'), new Text('FFFFFF') + ] + ), + new TableRow( + children: [ + new Text('G'), new Text('H'), new Text('III') + ] + ), + ] + ) + ); + tester.pumpWidget( + new Table( + defaultColumnWidth: const IntrinsicColumnWidth(), + children: [ + new TableRow( + children: [ + new Text('AAA'), new Text('B'), new Text('C') + ] + ), + new TableRow( + children: [ + new Text('D'), new Text('E'), new Text('FFFFFF') + ] + ), + new TableRow( + children: [ + new Text('G'), new Text('H'), new Text('III') + ] + ), + ] + ) + ); + RenderBox boxA = tester.renderObject(find.text('AAA')); + RenderBox boxD = tester.renderObject(find.text('D')); + RenderBox boxG = tester.renderObject(find.text('G')); + RenderBox boxB = tester.renderObject(find.text('B')); + expect(boxA.size, equals(boxD.size)); + expect(boxA.size, equals(boxG.size)); + expect(boxA.size.width, greaterThan(boxB.size.width)); + expect(boxA.size.height, equals(boxB.size.height)); }); - test('Table widget - moving test', () { - testElementTree((ElementTreeTester tester) { - List contexts = []; - tester.pumpWidget( - new Table( - children: [ - new TableRow( - key: new ValueKey(1), - children: [ - new StatefulBuilder( - builder: (BuildContext context, StateSetter setState) { - contexts.add(context); - return new Text('A'); - } - ) - ] - ), - new TableRow( - children: [ - new Text('b') - ] - ), - ] - ) - ); - tester.pumpWidget( - new Table( - children: [ - new TableRow( - children: [ - new Text('b') - ] - ), - new TableRow( - key: new ValueKey(1), - children: [ - new StatefulBuilder( - builder: (BuildContext context, StateSetter setState) { - contexts.add(context); - return new Text('A'); - } - ) - ] - ), - ] - ) - ); - expect(contexts.length, equals(2)); - expect(contexts[0], equals(contexts[1])); - }); + + testWidgets('Table widget - moving test', (WidgetTester tester) { + List contexts = []; + tester.pumpWidget( + new Table( + children: [ + new TableRow( + key: new ValueKey(1), + children: [ + new StatefulBuilder( + builder: (BuildContext context, StateSetter setState) { + contexts.add(context); + return new Text('A'); + } + ) + ] + ), + new TableRow( + children: [ + new Text('b') + ] + ), + ] + ) + ); + tester.pumpWidget( + new Table( + children: [ + new TableRow( + children: [ + new Text('b') + ] + ), + new TableRow( + key: new ValueKey(1), + children: [ + new StatefulBuilder( + builder: (BuildContext context, StateSetter setState) { + contexts.add(context); + return new Text('A'); + } + ) + ] + ), + ] + ) + ); + expect(contexts.length, equals(2)); + expect(contexts[0], equals(contexts[1])); }); // TODO(ianh): Test handling of TableCell object } diff --git a/packages/flutter/test/widget/test_matchers.dart b/packages/flutter/test/widget/test_matchers.dart deleted file mode 100644 index 8b23098afb..0000000000 --- a/packages/flutter/test/widget/test_matchers.dart +++ /dev/null @@ -1,73 +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/material.dart'; -import 'package:flutter_test/flutter_test.dart'; -import 'package:test/test.dart'; - -bool _hasAncestorOfType(WidgetTester tester, Finder finder, Type targetType) { - expect(tester, hasWidget(finder)); - bool result = false; - finder.findFirst(tester).visitAncestorElements((Element ancestor) { - if (ancestor.widget.runtimeType == targetType) { - result = true; - return false; - } - return true; - }); - return result; -} - -class _IsOnStage extends Matcher { - const _IsOnStage(this.tester); - - final WidgetTester tester; - - @override - bool matches(Finder finder, Map matchState) => !_hasAncestorOfType(tester, finder, OffStage); - - @override - Description describe(Description description) => description.add('onstage'); -} - -class _IsOffStage extends Matcher { - const _IsOffStage(this.tester); - - final WidgetTester tester; - - @override - bool matches(Finder finder, Map matchState) => _hasAncestorOfType(tester, finder, OffStage); - - @override - Description describe(Description description) => description.add('offstage'); -} - -class _IsInCard extends Matcher { - const _IsInCard(this.tester); - - final WidgetTester tester; - - @override - bool matches(Finder finder, Map matchState) => _hasAncestorOfType(tester, finder, Card); - - @override - Description describe(Description description) => description.add('in card'); -} - -class _IsNotInCard extends Matcher { - const _IsNotInCard(this.tester); - - final WidgetTester tester; - - @override - bool matches(Finder finder, Map matchState) => !_hasAncestorOfType(tester, finder, Card); - - @override - Description describe(Description description) => description.add('not in card'); -} - -Matcher isOnStage(WidgetTester tester) => new _IsOnStage(tester); -Matcher isOffStage(WidgetTester tester) => new _IsOffStage(tester); -Matcher isInCard(WidgetTester tester) => new _IsInCard(tester); -Matcher isNotInCard(WidgetTester tester) => new _IsNotInCard(tester); diff --git a/packages/flutter/test/widget/test_widgets.dart b/packages/flutter/test/widget/test_widgets.dart index 56794ac852..cbcc5bb37a 100644 --- a/packages/flutter/test/widget/test_widgets.dart +++ b/packages/flutter/test/widget/test_widgets.dart @@ -22,7 +22,7 @@ class TestBuildCounter extends StatelessWidget { @override Widget build(BuildContext context) { - ++buildCount; + buildCount += 1; return new DecoratedBox(decoration: kBoxDecorationA); } } @@ -54,6 +54,6 @@ class FlipWidgetState extends State { } void flipStatefulWidget(WidgetTester tester) { - FlipWidgetState state = tester.stateOf(find.byType(FlipWidget)); + FlipWidgetState state = tester.state(find.byType(FlipWidget)); state.flip(); } diff --git a/packages/flutter/test/widget/transform_test.dart b/packages/flutter/test/widget/transform_test.dart index 8a2b8c49d0..80a51de99e 100644 --- a/packages/flutter/test/widget/transform_test.dart +++ b/packages/flutter/test/widget/transform_test.dart @@ -7,157 +7,151 @@ import 'package:flutter/widgets.dart'; import 'package:test/test.dart'; void main() { - test('Transform origin', () { - testWidgets((WidgetTester tester) { - bool didReceiveTap = false; - tester.pumpWidget( - new Stack( - children: [ - new Positioned( - top: 100.0, - left: 100.0, - child: new Container( - width: 100.0, - height: 100.0, - decoration: new BoxDecoration( - backgroundColor: new Color(0xFF0000FF) - ) + testWidgets('Transform origin', (WidgetTester tester) { + bool didReceiveTap = false; + tester.pumpWidget( + new Stack( + children: [ + new Positioned( + top: 100.0, + left: 100.0, + child: new Container( + width: 100.0, + height: 100.0, + decoration: new BoxDecoration( + backgroundColor: new Color(0xFF0000FF) ) - ), - new Positioned( - top: 100.0, - left: 100.0, - child: new Container( - width: 100.0, - height: 100.0, - child: new Transform( - transform: new Matrix4.identity().scale(0.5, 0.5), - origin: new Offset(100.0, 50.0), - child: new GestureDetector( - onTap: () { - didReceiveTap = true; - }, - child: new Container( - decoration: new BoxDecoration( - backgroundColor: new Color(0xFF00FFFF) - ) + ) + ), + new Positioned( + top: 100.0, + left: 100.0, + child: new Container( + width: 100.0, + height: 100.0, + child: new Transform( + transform: new Matrix4.identity().scale(0.5, 0.5), + origin: new Offset(100.0, 50.0), + child: new GestureDetector( + onTap: () { + didReceiveTap = true; + }, + child: new Container( + decoration: new BoxDecoration( + backgroundColor: new Color(0xFF00FFFF) ) ) ) ) ) - ] - ) - ); + ) + ] + ) + ); - expect(didReceiveTap, isFalse); - tester.tapAt(new Point(110.0, 110.0)); - expect(didReceiveTap, isFalse); - tester.tapAt(new Point(190.0, 150.0)); - expect(didReceiveTap, isTrue); - }); + expect(didReceiveTap, isFalse); + tester.tapAt(new Point(110.0, 110.0)); + expect(didReceiveTap, isFalse); + tester.tapAt(new Point(190.0, 150.0)); + expect(didReceiveTap, isTrue); }); - test('Transform alignment', () { - testWidgets((WidgetTester tester) { - bool didReceiveTap = false; - tester.pumpWidget( - new Stack( - children: [ - new Positioned( - top: 100.0, - left: 100.0, - child: new Container( - width: 100.0, - height: 100.0, - decoration: new BoxDecoration( - backgroundColor: new Color(0xFF0000FF) - ) + testWidgets('Transform alignment', (WidgetTester tester) { + bool didReceiveTap = false; + tester.pumpWidget( + new Stack( + children: [ + new Positioned( + top: 100.0, + left: 100.0, + child: new Container( + width: 100.0, + height: 100.0, + decoration: new BoxDecoration( + backgroundColor: new Color(0xFF0000FF) ) - ), - new Positioned( - top: 100.0, - left: 100.0, - child: new Container( - width: 100.0, - height: 100.0, - child: new Transform( - transform: new Matrix4.identity().scale(0.5, 0.5), - alignment: new FractionalOffset(1.0, 0.5), - child: new GestureDetector( - onTap: () { - didReceiveTap = true; - }, - child: new Container( - decoration: new BoxDecoration( - backgroundColor: new Color(0xFF00FFFF) - ) + ) + ), + new Positioned( + top: 100.0, + left: 100.0, + child: new Container( + width: 100.0, + height: 100.0, + child: new Transform( + transform: new Matrix4.identity().scale(0.5, 0.5), + alignment: new FractionalOffset(1.0, 0.5), + child: new GestureDetector( + onTap: () { + didReceiveTap = true; + }, + child: new Container( + decoration: new BoxDecoration( + backgroundColor: new Color(0xFF00FFFF) ) ) ) ) ) - ] - ) - ); + ) + ] + ) + ); - expect(didReceiveTap, isFalse); - tester.tapAt(new Point(110.0, 110.0)); - expect(didReceiveTap, isFalse); - tester.tapAt(new Point(190.0, 150.0)); - expect(didReceiveTap, isTrue); - }); + expect(didReceiveTap, isFalse); + tester.tapAt(new Point(110.0, 110.0)); + expect(didReceiveTap, isFalse); + tester.tapAt(new Point(190.0, 150.0)); + expect(didReceiveTap, isTrue); }); - test('Transform offset + alignment', () { - testWidgets((WidgetTester tester) { - bool didReceiveTap = false; - tester.pumpWidget( - new Stack( - children: [ - new Positioned( - top: 100.0, - left: 100.0, - child: new Container( - width: 100.0, - height: 100.0, - decoration: new BoxDecoration( - backgroundColor: new Color(0xFF0000FF) - ) + testWidgets('Transform offset + alignment', (WidgetTester tester) { + bool didReceiveTap = false; + tester.pumpWidget( + new Stack( + children: [ + new Positioned( + top: 100.0, + left: 100.0, + child: new Container( + width: 100.0, + height: 100.0, + decoration: new BoxDecoration( + backgroundColor: new Color(0xFF0000FF) ) - ), - new Positioned( - top: 100.0, - left: 100.0, - child: new Container( - width: 100.0, - height: 100.0, - child: new Transform( - transform: new Matrix4.identity().scale(0.5, 0.5), - origin: new Offset(100.0, 0.0), - alignment: new FractionalOffset(0.0, 0.5), - child: new GestureDetector( - onTap: () { - didReceiveTap = true; - }, - child: new Container( - decoration: new BoxDecoration( - backgroundColor: new Color(0xFF00FFFF) - ) + ) + ), + new Positioned( + top: 100.0, + left: 100.0, + child: new Container( + width: 100.0, + height: 100.0, + child: new Transform( + transform: new Matrix4.identity().scale(0.5, 0.5), + origin: new Offset(100.0, 0.0), + alignment: new FractionalOffset(0.0, 0.5), + child: new GestureDetector( + onTap: () { + didReceiveTap = true; + }, + child: new Container( + decoration: new BoxDecoration( + backgroundColor: new Color(0xFF00FFFF) ) ) ) ) ) - ] - ) - ); + ) + ] + ) + ); - expect(didReceiveTap, isFalse); - tester.tapAt(new Point(110.0, 110.0)); - expect(didReceiveTap, isFalse); - tester.tapAt(new Point(190.0, 150.0)); - expect(didReceiveTap, isTrue); - }); + expect(didReceiveTap, isFalse); + tester.tapAt(new Point(110.0, 110.0)); + expect(didReceiveTap, isFalse); + tester.tapAt(new Point(190.0, 150.0)); + expect(didReceiveTap, isTrue); }); } diff --git a/packages/flutter/test/widget/two_level_list_test.dart b/packages/flutter/test/widget/two_level_list_test.dart index 7167418df0..644ef0a0da 100644 --- a/packages/flutter/test/widget/two_level_list_test.dart +++ b/packages/flutter/test/widget/two_level_list_test.dart @@ -8,7 +8,7 @@ import 'package:flutter/material.dart'; import 'package:test/test.dart'; void main() { - test('TwoLeveList basics', () { + testWidgets('TwoLeveList basics', (WidgetTester tester) { final Key topKey = new UniqueKey(); final Key sublistKey = new UniqueKey(); final Key bottomKey = new UniqueKey(); @@ -36,37 +36,35 @@ void main() { } }; - testWidgets((WidgetTester tester) { - tester.pumpWidget(new MaterialApp(routes: routes)); + tester.pumpWidget(new MaterialApp(routes: routes)); - expect(tester, hasWidget(find.text('Top'))); - expect(tester, hasWidget(find.text('Sublist'))); - expect(tester, hasWidget(find.text('Bottom'))); + expect(find.text('Top'), findsOneWidget); + expect(find.text('Sublist'), findsOneWidget); + expect(find.text('Bottom'), findsOneWidget); - double getY(Key key) => tester.getTopLeft(find.byKey(key)).y; - double getHeight(Key key) => tester.getSize(find.byKey(key)).height; + double getY(Key key) => tester.getTopLeft(find.byKey(key)).y; + double getHeight(Key key) => tester.getSize(find.byKey(key)).height; - expect(getY(topKey), lessThan(getY(sublistKey))); - expect(getY(sublistKey), lessThan(getY(bottomKey))); + expect(getY(topKey), lessThan(getY(sublistKey))); + expect(getY(sublistKey), lessThan(getY(bottomKey))); - // The sublist has a one pixel border above and below. - expect(getHeight(topKey), equals(getHeight(sublistKey) - 2.0)); - expect(getHeight(bottomKey), equals(getHeight(sublistKey) - 2.0)); + // The sublist has a one pixel border above and below. + expect(getHeight(topKey), equals(getHeight(sublistKey) - 2.0)); + expect(getHeight(bottomKey), equals(getHeight(sublistKey) - 2.0)); - tester.tap(find.text('Sublist')); - tester.pump(const Duration(seconds: 1)); - tester.pump(const Duration(seconds: 1)); + tester.tap(find.text('Sublist')); + tester.pump(const Duration(seconds: 1)); + tester.pump(const Duration(seconds: 1)); - expect(tester, hasWidget(find.text('Top'))); - expect(tester, hasWidget(find.text('Sublist'))); - expect(tester, hasWidget(find.text('0'))); - expect(tester, hasWidget(find.text('1'))); - expect(tester, hasWidget(find.text('Bottom'))); + expect(find.text('Top'), findsOneWidget); + expect(find.text('Sublist'), findsOneWidget); + expect(find.text('0'), findsOneWidget); + expect(find.text('1'), findsOneWidget); + expect(find.text('Bottom'), findsOneWidget); - expect(getY(topKey), lessThan(getY(sublistKey))); - expect(getY(sublistKey), lessThan(getY(bottomKey))); - expect(getY(bottomKey) - getY(sublistKey), greaterThan(getHeight(topKey))); - expect(getY(bottomKey) - getY(sublistKey), greaterThan(getHeight(bottomKey))); - }); + expect(getY(topKey), lessThan(getY(sublistKey))); + expect(getY(sublistKey), lessThan(getY(bottomKey))); + expect(getY(bottomKey) - getY(sublistKey), greaterThan(getHeight(topKey))); + expect(getY(bottomKey) - getY(sublistKey), greaterThan(getHeight(bottomKey))); }); } diff --git a/packages/flutter_driver/lib/src/extension.dart b/packages/flutter_driver/lib/src/extension.dart index fbea093231..42260b495a 100644 --- a/packages/flutter_driver/lib/src/extension.dart +++ b/packages/flutter_driver/lib/src/extension.dart @@ -8,8 +8,7 @@ import 'package:flutter/gestures.dart'; import 'package:flutter/material.dart'; import 'package:flutter/scheduler.dart'; import 'package:flutter/widgets.dart'; -import 'package:flutter_test/src/instrumentation.dart'; -import 'package:flutter_test/src/test_pointer.dart'; +import 'package:flutter_test/flutter_test.dart'; import 'error.dart'; import 'find.dart'; @@ -53,7 +52,7 @@ typedef Future CommandHandlerCallback(Command c); typedef Command CommandDeserializerCallback(Map params); /// Runs the finder and returns the [Element] found, or `null`. -typedef Future FinderCallback(SerializableFinder finder); +typedef Finder FinderConstructor(SerializableFinder finder); class FlutterDriverExtension { static final Logger _log = new Logger('FlutterDriverExtension'); @@ -75,17 +74,17 @@ class FlutterDriverExtension { 'waitFor': WaitFor.deserialize, }); - _finders.addAll({ - 'ByValueKey': _findByValueKey, - 'ByTooltipMessage': _findByTooltipMessage, - 'ByText': _findByText, + _finders.addAll({ + 'ByText': _createByTextFinder, + 'ByTooltipMessage': _createByTooltipMessageFinder, + 'ByValueKey': _createByValueKeyFinder, }); } - final Instrumentation prober = new Instrumentation(); + final WidgetController prober = new WidgetController(WidgetsBinding.instance); final Map _commandHandlers = {}; final Map _commandDeserializers = {}; - final Map _finders = {}; + final Map _finders = {}; Future> call(Map params) async { try { @@ -119,92 +118,74 @@ class FlutterDriverExtension { Future getHealth(GetHealth command) async => new Health(HealthStatus.ok); - /// Runs [locator] repeatedly until it finds an [Element] or times out. - Future _waitForElement(String descriptionGetter(), Element locator()) async { + /// Runs `finder` repeatedly until it finds one or more [Element]s, or times out. + /// + /// The timeout is five seconds. + Future _waitForElement(Finder finder) { // Short-circuit if the element is already on the UI - Element element = locator(); - if (element != null) { - return element; - } + if (finder.precache()) + return new Future.value(finder); // No element yet, so we retry on frames rendered in the future. - Completer completer = new Completer(); + Completer completer = new Completer(); StreamSubscription subscription; Timer timeout = new Timer(_kDefaultTimeout, () { subscription.cancel(); - completer.completeError('Timed out waiting for ${descriptionGetter()}'); + completer.completeError('Timed out waiting for ${finder.description}'); }); subscription = _onFrameReady.listen((Duration duration) { - Element element = locator(); - if (element != null) { + if (finder.precache()) { subscription.cancel(); timeout.cancel(); - completer.complete(element); + completer.complete(finder); } }); return completer.future; } - Future _findByValueKey(ByValueKey byKey) async { - return _waitForElement( - () => 'element with key "${byKey.keyValue}" of type ${byKey.keyValueType}', - () { - return prober.findElementByKey(new ValueKey(byKey.keyValue)); - } - ); + Finder _createByTextFinder(ByText arguments) { + return find.text(arguments.text); } - Future _findByTooltipMessage(ByTooltipMessage byTooltipMessage) async { - return _waitForElement( - () => 'tooltip with message "${byTooltipMessage.text}" on it', - () { - return prober.findElement((Element element) { - Widget widget = element.widget; - - if (widget is Tooltip) - return widget.message == byTooltipMessage.text; - - return false; - }); - } - ); + Finder _createByTooltipMessageFinder(ByTooltipMessage arguments) { + return find.byElementPredicate((Element element) { + Widget widget = element.widget; + if (widget is Tooltip) + return widget.message == arguments.text; + return false; + }); } - Future _findByText(ByText byText) async { - return await _waitForElement( - () => 'text "${byText.text}"', - () { - return prober.findText(byText.text); - }); + Finder _createByValueKeyFinder(ByValueKey arguments) { + return find.byKey(new ValueKey(arguments.keyValue)); } - Future _runFinder(SerializableFinder finder) { - FinderCallback cb = _finders[finder.finderType]; + Finder _createFinder(SerializableFinder finder) { + FinderConstructor constructor = _finders[finder.finderType]; - if (cb == null) + if (constructor == null) throw 'Unsupported finder type: ${finder.finderType}'; - return cb(finder); + return constructor(finder); } Future tap(Tap command) async { - Element target = await _runFinder(command.finder); - prober.tap(target); + prober.tap(await _waitForElement(_createFinder(command.finder))); return new TapResult(); } Future waitFor(WaitFor command) async { - if (await _runFinder(command.finder) != null) + if ((await _waitForElement(_createFinder(command.finder))).evaluate().isNotEmpty) return new WaitForResult(); else return null; } Future scroll(Scroll command) async { - Element target = await _runFinder(command.finder); + Finder target = await _waitForElement(_createFinder(command.finder)); final int totalMoves = command.duration.inMicroseconds * command.frequency ~/ Duration.MICROSECONDS_PER_SECOND; Offset delta = new Offset(command.dx, command.dy) / totalMoves.toDouble(); Duration pause = command.duration ~/ totalMoves; @@ -227,9 +208,9 @@ class FlutterDriverExtension { } Future getText(GetText command) async { - Element target = await _runFinder(command.finder); + Finder target = await _waitForElement(_createFinder(command.finder)); // TODO(yjbanov): support more ways to read text - Text text = target.widget; + Text text = target.evaluate().single.widget; return new GetTextResult(text.data); } } diff --git a/packages/flutter_markdown/test/flutter_markdown_test.dart b/packages/flutter_markdown/test/flutter_markdown_test.dart index 6e362a829c..5ad8dbd8ab 100644 --- a/packages/flutter_markdown/test/flutter_markdown_test.dart +++ b/packages/flutter_markdown/test/flutter_markdown_test.dart @@ -6,72 +6,61 @@ import 'package:test/test.dart'; import 'package:flutter/material.dart'; void main() { - test("Simple string", () { - testWidgets((WidgetTester tester) { - tester.pumpWidget(new MarkdownBody(data: "Hello")); + testWidgets('Simple string', (WidgetTester tester) { + tester.pumpWidget(new MarkdownBody(data: 'Hello')); - Iterable widgets = tester.widgets; + Iterable widgets = tester.allWidgets; _expectWidgetTypes(widgets, [MarkdownBody, Column, Container, Padding, RichText]); - _expectTextStrings(widgets, ["Hello"]); - }); + _expectTextStrings(widgets, ['Hello']); }); - test("Header", () { - testWidgets((WidgetTester tester) { - tester.pumpWidget(new MarkdownBody(data: "# Header")); + testWidgets('Header', (WidgetTester tester) { + tester.pumpWidget(new MarkdownBody(data: '# Header')); - Iterable widgets = tester.widgets; + Iterable widgets = tester.allWidgets; _expectWidgetTypes(widgets, [MarkdownBody, Column, Container, Padding, RichText]); - _expectTextStrings(widgets, ["Header"]); - }); + _expectTextStrings(widgets, ['Header']); }); - test("Empty string", () { - testWidgets((WidgetTester tester) { - tester.pumpWidget(new MarkdownBody(data: "")); + testWidgets('Empty string', (WidgetTester tester) { + tester.pumpWidget(new MarkdownBody(data: '')); - Iterable widgets = tester.widgets; + Iterable widgets = tester.allWidgets; _expectWidgetTypes(widgets, [MarkdownBody, Column]); - }); }); - test("Ordered list", () { - testWidgets((WidgetTester tester) { - tester.pumpWidget(new MarkdownBody(data: "1. Item 1\n1. Item 2\n2. Item 3")); + testWidgets('Ordered list', (WidgetTester tester) { + tester.pumpWidget(new MarkdownBody(data: '1. Item 1\n1. Item 2\n2. Item 3')); - Iterable widgets = tester.widgets; + Iterable widgets = tester.allWidgets; _expectTextStrings(widgets, [ - "1.", - "Item 1", - "2.", - "Item 2", - "3.", - "Item 3"] + '1.', + 'Item 1', + '2.', + 'Item 2', + '3.', + 'Item 3'] ); - }); }); - test("Unordered list", () { - testWidgets((WidgetTester tester) { - tester.pumpWidget(new MarkdownBody(data: "- Item 1\n- Item 2\n- Item 3")); + testWidgets('Unordered list', (WidgetTester tester) { + tester.pumpWidget(new MarkdownBody(data: '- Item 1\n- Item 2\n- Item 3')); - Iterable widgets = tester.widgets; + Iterable widgets = tester.allWidgets; _expectTextStrings(widgets, [ - "•", - "Item 1", - "•", - "Item 2", - "•", - "Item 3"] + '•', + 'Item 1', + '•', + 'Item 2', + '•', + 'Item 3'] ); - }); }); - test("Scrollable wrapping", () { - testWidgets((WidgetTester tester) { - tester.pumpWidget(new Markdown(data: "")); + testWidgets('Scrollable wrapping', (WidgetTester tester) { + tester.pumpWidget(new Markdown(data: '')); - List widgets = tester.widgets.toList(); + List widgets = tester.allWidgets.toList(); _expectWidgetTypes(widgets.take(2), [ Markdown, ScrollableViewport, @@ -81,49 +70,42 @@ void main() { MarkdownBody, Column ]); - }); }); - test("Links", () { - testWidgets((WidgetTester tester) { - tester.pumpWidget(new Markdown(data: "[Link Text](href)")); + testWidgets('Links', (WidgetTester tester) { + tester.pumpWidget(new Markdown(data: '[Link Text](href)')); - RichText textWidget = tester.widgets.firstWhere((Widget widget) => widget is RichText); + RichText textWidget = tester.allWidgets.firstWhere((Widget widget) => widget is RichText); TextSpan span = textWidget.text; expect(span.children[0].recognizer.runtimeType, equals(TapGestureRecognizer)); - }); }); - test("Changing config - data", () { - testWidgets((WidgetTester tester) { - tester.pumpWidget(new Markdown(data: "Data1")); - _expectTextStrings(tester.widgets, ["Data1"]); + testWidgets('Changing config - data', (WidgetTester tester) { + tester.pumpWidget(new Markdown(data: 'Data1')); + _expectTextStrings(tester.allWidgets, ['Data1']); String stateBefore = WidgetsBinding.instance.renderViewElement.toStringDeep(); - tester.pumpWidget(new Markdown(data: "Data1")); + tester.pumpWidget(new Markdown(data: 'Data1')); String stateAfter = WidgetsBinding.instance.renderViewElement.toStringDeep(); expect(stateBefore, equals(stateAfter)); - tester.pumpWidget(new Markdown(data: "Data2")); - _expectTextStrings(tester.widgets, ["Data2"]); - }); + tester.pumpWidget(new Markdown(data: 'Data2')); + _expectTextStrings(tester.allWidgets, ['Data2']); }); - test("Changing config - style", () { - testWidgets((WidgetTester tester) { + testWidgets('Changing config - style', (WidgetTester tester) { ThemeData theme = new ThemeData.light(); MarkdownStyle style1 = new MarkdownStyle.defaultFromTheme(theme); MarkdownStyle style2 = new MarkdownStyle.largeFromTheme(theme); - tester.pumpWidget(new Markdown(data: "Test", markdownStyle: style1)); + tester.pumpWidget(new Markdown(data: 'Test', markdownStyle: style1)); String stateBefore = WidgetsBinding.instance.renderViewElement.toStringDeep(); - tester.pumpWidget(new Markdown(data: "Test", markdownStyle: style2)); + tester.pumpWidget(new Markdown(data: 'Test', markdownStyle: style2)); String stateAfter = WidgetsBinding.instance.renderViewElement.toStringDeep(); expect(stateBefore, isNot(stateAfter)); - }); }); } @@ -145,7 +127,7 @@ void _expectTextStrings(Iterable widgets, List strings) { } String _extractTextFromTextSpan(TextSpan span) { - String text = span.text ?? ""; + String text = span.text ?? ''; if (span.children != null) { for (TextSpan child in span.children) { text += _extractTextFromTextSpan(child); diff --git a/packages/flutter_test/lib/flutter_test.dart b/packages/flutter_test/lib/flutter_test.dart index 5883d9b86f..b374436ba9 100644 --- a/packages/flutter_test/lib/flutter_test.dart +++ b/packages/flutter_test/lib/flutter_test.dart @@ -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'; diff --git a/packages/flutter_test/lib/src/all_elements.dart b/packages/flutter_test/lib/src/all_elements.dart new file mode 100644 index 0000000000..077983b0a7 --- /dev/null +++ b/packages/flutter_test/lib/src/all_elements.dart @@ -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 collectAllElementsFrom(Element rootElement) { + return new CachingIterable(new _DepthFirstChildIterator(rootElement)); +} + +class _DepthFirstChildIterator implements Iterator { + _DepthFirstChildIterator(Element rootElement) + : _stack = _reverseChildrenOf(rootElement).toList(); + + Element _current; + + final List _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 _reverseChildrenOf(Element element) { + final List children = []; + element.visitChildren(children.add); + return children.reversed; + } +} diff --git a/packages/flutter_test/lib/src/binding.dart b/packages/flutter_test/lib/src/binding.dart index 95d606898b..ef09dbc490 100644 --- a/packages/flutter_test/lib/src/binding.dart +++ b/packages/flutter_test/lib/src/binding.dart @@ -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 runTest(Future callback()) { + assert(inTest); + Future 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.value(callbackResult); + } + + Future _runTest(Future 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; + } + } diff --git a/packages/flutter_test/lib/src/controller.dart b/packages/flutter_test/lib/src/controller.dart new file mode 100644 index 0000000000..6ac2528d3d --- /dev/null +++ b/packages/flutter_test/lib/src/controller.dart @@ -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 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/**/(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/**/(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 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/**/(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/**/(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 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/**/(Finder finder) { + return _stateOf/**/(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/**/(Finder finder) { + return _stateOf/**/(finder.evaluate().first, finder); + } + + State/*=T*/ _stateOf/**/(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 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/**/(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/**/(Finder finder) { + return finder.evaluate().first.renderObject; + } + + + /// Returns a list of all the [Layer] objects in the rendering. + List get layers => _walkLayers(binding.renderView.layer).toList(); + Iterable _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; + } +} diff --git a/packages/flutter_test/lib/src/finders.dart b/packages/flutter_test/lib/src/finders.dart new file mode 100644 index 0000000000..610b638d04 --- /dev/null +++ b/packages/flutter_test/lib/src/finders.dart @@ -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 apply(Iterable 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 get _allElements => collectAllElementsFrom(WidgetsBinding.instance.renderViewElement); + + Iterable _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 evaluate() { + final Iterable 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 result = apply(_allElements); + if (result.isNotEmpty) { + _cachedResult = result; + return true; + } + _cachedResult = null; + return false; + } + + @override + String toString() { + final List 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 apply(Iterable 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 apply(Iterable 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); + } +} diff --git a/packages/flutter_test/lib/src/instrumentation.dart b/packages/flutter_test/lib/src/instrumentation.dart deleted file mode 100644 index aed7dad55f..0000000000 --- a/packages/flutter_test/lib/src/instrumentation.dart +++ /dev/null @@ -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 get layers => _layers(binding.renderView.layer); - // TODO(ianh): This should not be O(N) hidden behind a getter! - List _layers(Layer layer) { - List result = [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; - } -} diff --git a/packages/flutter_test/lib/src/matchers.dart b/packages/flutter_test/lib/src/matchers.dart new file mode 100644 index 0000000000..4577eacd24 --- /dev/null +++ b/packages/flutter_test/lib/src/matchers.dart @@ -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 matchState) { + assert(min != null || max != null); + matchState[Finder] = finder; + if (min != null) { + int count = 0; + Iterator iterator = finder.evaluate().iterator; + while (count < min && iterator.moveNext()) + count += 1; + if (count < min) + return false; + } + if (max != null) { + int count = 0; + Iterator 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 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 matchState) => _hasAncestorOfType(finder, OffStage); + + @override + Description describe(Description description) => description.add('offstage'); +} + +class _IsOnStage extends Matcher { + const _IsOnStage(); + + @override + bool matches(Finder finder, Map matchState) => !_hasAncestorOfType(finder, OffStage); + + @override + Description describe(Description description) => description.add('onstage'); +} + +class _IsInCard extends Matcher { + const _IsInCard(); + + @override + bool matches(Finder finder, Map 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 matchState) => !_hasAncestorOfType(finder, Card); + + @override + Description describe(Description description) => description.add('not in card'); +} diff --git a/packages/flutter_test/lib/src/service_mocker.dart b/packages/flutter_test/lib/src/service_mocker.dart index 7ffc24756e..1f92119506 100644 --- a/packages/flutter_test/lib/src/service_mocker.dart +++ b/packages/flutter_test/lib/src/service_mocker.dart @@ -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._(); diff --git a/packages/flutter_test/lib/src/test_pointer.dart b/packages/flutter_test/lib/src/test_pointer.dart index 7ae5263f00..3ad1adfd7b 100644 --- a/packages/flutter_test/lib/src/test_pointer.dart +++ b/packages/flutter_test/lib/src/test_pointer.dart @@ -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(); } } diff --git a/packages/flutter_test/lib/src/widget_tester.dart b/packages/flutter_test/lib/src/widget_tester.dart index 057bec2fb7..64fadead74 100644 --- a/packages/flutter_test/lib/src/widget_tester.dart +++ b/packages/flutter_test/lib/src/widget_tester.dart @@ -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 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 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.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 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/**/(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 get allElements { - return new _DepthFirstChildIterable(binding.renderViewElement); - } -} - -class _DepthFirstChildIterable extends IterableBase { - _DepthFirstChildIterable(this.rootElement); - - Element rootElement; - - @override - Iterator get iterator => new _DepthFirstChildIterator(rootElement); -} - -class _DepthFirstChildIterator implements Iterator { - _DepthFirstChildIterator(Element rootElement) - : _stack = _reverseChildrenOf(rootElement).toList(); - - Element _current; - - final List _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 _reverseChildrenOf(Element element) { - final List children = []; - 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 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 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 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 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 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 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 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 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 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 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 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 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 matchState, bool verbose) { - return mismatchDescription.add('Contains $finder'); + binding.fakeAsync.flushMicrotasks(); } } diff --git a/packages/flutter_test/test/widget_tester_test.dart b/packages/flutter_test/test/widget_tester_test.dart index f9d310ace8..501f59eecf 100644 --- a/packages/flutter_test/test/widget_tester_test.dart +++ b/packages/flutter_test/test/widget_tester_test.dart @@ -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: ")); - 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: ?:\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: ")); - 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: ?:\n')); + expect(message, contains('Which: means one was found but none were expected\n')); }); }); + }