Turn off AnimationControllers when not in use (#5902)

This requires all AnimationController objects to be given a
TickerProvider, a class that can create the Ticker.

It also provides some nice mixins for people who want to have their
State provide a TickerProvider. And a schedulerTickerProvider for those
cases where you just want to see your battery burn.

Also, we now enforce destruction order for elements.
This commit is contained in:
Ian Hickson
2016-09-26 10:57:10 -07:00
committed by GitHub
parent c825237a38
commit 9e673853e5
63 changed files with 1358 additions and 492 deletions

View File

@@ -226,14 +226,17 @@ abstract class TestWidgetsFlutterBinding extends BindingBase
/// test failures.
bool showAppDumpInErrors = false;
/// Call the callback inside a [FakeAsync] scope on which [pump] can
/// Call the testBody inside a [FakeAsync] scope on which [pump] can
/// advance time.
///
/// Returns a future which completes when the test has run.
///
/// Called by the [testWidgets] and [benchmarkWidgets] functions to
/// run a test.
Future<Null> runTest(Future<Null> callback());
///
/// The `invariantTester` argument is called after the `testBody`'s [Future]
/// completes. If it throws, then the test is marked as failed.
Future<Null> runTest(Future<Null> testBody(), VoidCallback invariantTester);
/// This is called during test execution before and after the body has been
/// executed.
@@ -266,7 +269,7 @@ abstract class TestWidgetsFlutterBinding extends BindingBase
_currentTestCompleter.complete(null);
}
Future<Null> _runTest(Future<Null> callback()) {
Future<Null> _runTest(Future<Null> testBody(), VoidCallback invariantTester) {
assert(inTest);
_oldExceptionHandler = FlutterError.onError;
int _exceptionCount = 0; // number of un-taken exceptions
@@ -357,20 +360,20 @@ abstract class TestWidgetsFlutterBinding extends BindingBase
);
_parentZone = Zone.current;
Zone testZone = _parentZone.fork(specification: errorHandlingZoneSpecification);
testZone.runUnaryGuarded(_runTestBody, callback)
testZone.runBinaryGuarded(_runTestBody, testBody, invariantTester)
.whenComplete(_testCompletionHandler);
asyncBarrier(); // When using AutomatedTestWidgetsFlutterBinding, this flushes the microtasks.
return _currentTestCompleter.future;
}
Future<Null> _runTestBody(Future<Null> callback()) async {
Future<Null> _runTestBody(Future<Null> testBody(), VoidCallback invariantTester) async {
assert(inTest);
runApp(new Container(key: new UniqueKey(), child: _kPreTestMessage)); // Reset the tree to a known state.
await pump();
// run the test
await callback();
await testBody();
asyncBarrier(); // drains the microtasks in `flutter test` mode (when using AutomatedTestWidgetsFlutterBinding)
if (_pendingExceptionDetails == null) {
@@ -379,6 +382,7 @@ abstract class TestWidgetsFlutterBinding extends BindingBase
// alone so that we don't cause more spurious errors.
runApp(new Container(key: new UniqueKey(), child: _kPostTestMessage)); // Unmount any remaining widgets.
await pump();
invariantTester();
_verifyInvariants();
}
@@ -489,24 +493,24 @@ class AutomatedTestWidgetsFlutterBinding extends TestWidgetsFlutterBinding {
}
@override
Future<Null> runTest(Future<Null> callback()) {
Future<Null> runTest(Future<Null> testBody(), VoidCallback invariantTester) {
assert(!inTest);
assert(_fakeAsync == null);
assert(_clock == null);
_fakeAsync = new FakeAsync();
_clock = _fakeAsync.getClock(new DateTime.utc(2015, 1, 1));
Future<Null> callbackResult;
Future<Null> testBodyResult;
_fakeAsync.run((FakeAsync fakeAsync) {
assert(fakeAsync == _fakeAsync);
callbackResult = _runTest(callback);
testBodyResult = _runTest(testBody, invariantTester);
assert(inTest);
});
// callbackResult is a Future that was created in the Zone of the fakeAsync.
// testBodyResult is a Future that was created in the Zone of the fakeAsync.
// This means that if we call .then() on it (as the test framework is about to),
// it will register a microtask to handle the future _in the fake async zone_.
// To avoid this, we wrap it in a Future that we've created _outside_ the fake
// async zone.
return new Future<Null>.value(callbackResult);
return new Future<Null>.value(testBodyResult);
}
@override
@@ -686,10 +690,10 @@ class LiveTestWidgetsFlutterBinding extends TestWidgetsFlutterBinding {
}
@override
Future<Null> runTest(Future<Null> callback()) async {
Future<Null> runTest(Future<Null> testBody(), VoidCallback invariantTester) async {
assert(!inTest);
_inTest = true;
return _runTest(callback);
return _runTest(testBody, invariantTester);
}
@override

View File

@@ -6,6 +6,7 @@ import 'dart:async';
import 'package:flutter/gestures.dart';
import 'package:flutter/rendering.dart';
import 'package:flutter/scheduler.dart';
import 'package:flutter/widgets.dart';
import 'package:meta/meta.dart';
import 'package:test/test.dart' as test_package;
@@ -50,7 +51,7 @@ void testWidgets(String description, WidgetTesterCallback callback, {
WidgetTester tester = new WidgetTester._(binding);
timeout ??= binding.defaultTestTimeout;
test_package.group('-', () {
test_package.test(description, () => binding.runTest(() => callback(tester)), skip: skip);
test_package.test(description, () => binding.runTest(() => callback(tester), tester._endOfTestVerifications), skip: skip);
test_package.tearDown(binding.postTest);
}, timeout: timeout);
}
@@ -108,7 +109,7 @@ Future<Null> benchmarkWidgets(WidgetTesterCallback callback) {
TestWidgetsFlutterBinding binding = TestWidgetsFlutterBinding.ensureInitialized();
assert(binding is! AutomatedTestWidgetsFlutterBinding);
WidgetTester tester = new WidgetTester._(binding);
return binding.runTest(() => callback(tester)) ?? new Future<Null>.value();
return binding.runTest(() => callback(tester), tester._endOfTestVerifications) ?? new Future<Null>.value();
}
/// Assert that `actual` matches `matcher`.
@@ -143,7 +144,10 @@ void expectSync(dynamic actual, dynamic matcher, {
}
/// Class that programmatically interacts with widgets and the test environment.
class WidgetTester extends WidgetController implements HitTestDispatcher {
///
/// For convenience, instances of this class (such as the one provided by
/// `testWidget`) can be used as the `vsync` for `AnimationController` objects.
class WidgetTester extends WidgetController implements HitTestDispatcher, TickerProvider {
WidgetTester._(TestWidgetsFlutterBinding binding) : super(binding) {
if (binding is LiveTestWidgetsFlutterBinding)
binding.deviceEventDispatcher = this;
@@ -328,6 +332,7 @@ class WidgetTester extends WidgetController implements HitTestDispatcher {
}
bool _isPrivate(Type type) {
// used above so that we don't suggest matchers for private types
return '_'.matchAsPrefix(type.toString()) != null;
}
@@ -348,4 +353,62 @@ class WidgetTester extends WidgetController implements HitTestDispatcher {
Future<Null> idle() {
return TestAsyncUtils.guard(() => binding.idle());
}
Set<Ticker> _tickers;
@override
Ticker createTicker(TickerCallback onTick) {
_tickers ??= new Set<_TestTicker>();
final _TestTicker result = new _TestTicker(onTick, _removeTicker);
_tickers.add(result);
return result;
}
void _removeTicker(_TestTicker ticker) {
assert(_tickers != null);
assert(_tickers.contains(ticker));
_tickers.remove(ticker);
}
/// Throws an exception if any tickers created by the [WidgetTester] are still
/// active when the method is called.
///
/// An argument can be specified to provide a string that will be used in the
/// error message. It should be an adverbial phrase describing the current
/// situation, such as "at the end of the test".
void verifyTickersWereDisposed([ String when = 'when none should have been' ]) {
assert(when != null);
if (_tickers != null) {
for (Ticker ticker in _tickers) {
if (ticker.isActive) {
throw new FlutterError(
'A Ticker was active $when.\n'
'All Tickers must be disposed. Tickers used by AnimationControllers '
'should be disposed by calling dispose() on the AnimationController itself. '
'Otherwise, the ticker will leak.\n'
'The offending ticker was: ${ticker.toString(debugIncludeStack: true)}'
);
}
}
}
}
void _endOfTestVerifications() {
verifyTickersWereDisposed('at the end of the test');
}
}
typedef void _TickerDisposeCallback(_TestTicker ticker);
class _TestTicker extends Ticker {
_TestTicker(TickerCallback onTick, this._onDispose) : super(onTick);
_TickerDisposeCallback _onDispose;
@override
void dispose() {
if (_onDispose != null)
_onDispose(this);
super.dispose();
}
}

View File

@@ -73,7 +73,10 @@ void main() {
await tester.pumpWidget(new Text('foo'));
int count;
AnimationController test = new AnimationController(duration: const Duration(milliseconds: 5100));
AnimationController test = new AnimationController(
duration: const Duration(milliseconds: 5100),
vsync: tester,
);
count = await tester.pumpUntilNoTransientCallbacks(const Duration(seconds: 1));
expect(count, 0);