Restoration Framework (#60375)

* state restoration

* added example

* typos and analyzer

* whitespace

* more typos

* remove unnecessary import

* whitespace

* fix sample code

* tests for restorationmanager and restorationid

* ++

* typo

* tests for bucket, part1

* rename tests

* more tests

* finished tests for service layer

* remove wrong todo

* ++

* review comments

* tests for Unmanaged and regular scope

* RootRestorationScope tests

* typo

* whitespace

* testing framework

* tests for properties

* last set of tests

* analyzer

* typo

* dan review

* whitespace

* ++

* refactor finalizers

* ++

* ++

* dispose guard

* ++

* ++

* dan review

* add manager assert

* ++

* analyzer

* greg review

* fix typo

* Ian & John review

* ian review

* RestorationID -> String

* revert comment

* Make primitives non-nullable in prep for NNBD
This commit is contained in:
Michael Goderbauer
2020-07-28 10:16:36 -07:00
committed by GitHub
parent 1fff10500f
commit 175e5c9aca
20 changed files with 5599 additions and 0 deletions

View File

@@ -58,6 +58,7 @@ export 'src/goldens.dart';
export 'src/matchers.dart';
export 'src/nonconst.dart';
export 'src/platform.dart';
export 'src/restoration.dart';
export 'src/stack_manipulation.dart';
export 'src/test_async_utils.dart';
export 'src/test_compat.dart';

View File

@@ -23,6 +23,7 @@ import 'package:vector_math/vector_math_64.dart';
import '_binding_io.dart' if (dart.library.html) '_binding_web.dart' as binding;
import 'goldens.dart';
import 'platform.dart';
import 'restoration.dart';
import 'stack_manipulation.dart';
import 'test_async_utils.dart';
import 'test_exception_reporter.dart';
@@ -187,6 +188,21 @@ abstract class TestWidgetsFlutterBinding extends BindingBase
TestWindow get window => _window;
final TestWindow _window;
@override
TestRestorationManager get restorationManager => _restorationManager;
TestRestorationManager _restorationManager;
/// Called by the test framework at the beginning of a widget test to
/// prepare the binding for the next test.
void reset() {
_restorationManager = createRestorationManager();
}
@override
TestRestorationManager createRestorationManager() {
return TestRestorationManager();
}
/// The value to set [debugPrint] to while tests are running.
///
/// This can be used to redirect console output from the framework, or to

View File

@@ -0,0 +1,85 @@
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'dart:typed_data';
import 'package:flutter/foundation.dart';
import 'package:flutter/services.dart';
/// The [RestorationManager] used for tests.
///
/// Unlike the real [RestorationManager], this one just keeps the restoration
/// data in memory and does not make it available to the engine.
class TestRestorationManager extends RestorationManager {
/// Creates a [TestRestorationManager].
TestRestorationManager() {
// Ensures that [rootBucket] always returns a synchronous future to avoid
// extra pumps in tests.
restoreFrom(TestRestorationData.empty);
}
@override
Future<RestorationBucket> get rootBucket {
_debugRootBucketAccessed = true;
return super.rootBucket;
}
/// The current restoration data from which the current state can be restored.
///
/// To restore the state to the one described by this data, pass the
/// [TestRestorationData] obtained from this getter back to [restoreFrom].
///
/// See also:
///
/// * [WidgetTester.getRestorationData], which makes this data available
/// in a widget test.
TestRestorationData get restorationData => _restorationData;
TestRestorationData _restorationData;
/// Whether the [rootBucket] has been obtained.
bool get debugRootBucketAccessed => _debugRootBucketAccessed;
bool _debugRootBucketAccessed = false;
/// Restores the state from the provided [TestRestorationData].
///
/// The restoration data obtained form [restorationData] can be passed into
/// this method to restore the state to what it was when the restoration data
/// was originally retrieved.
///
/// See also:
///
/// * [WidgetTester.restoreFrom], which exposes this method to a widget test.
void restoreFrom(TestRestorationData data) {
_restorationData = data;
handleRestorationUpdateFromEngine(enabled: true, data: data.binary);
}
@override
Future<void> sendToEngine(Uint8List encodedData) async {
_restorationData = TestRestorationData._(encodedData);
}
}
/// Restoration data that can be used to restore the state to the one described
/// by this data.
///
/// See also:
///
/// * [WidgetTester.getRestorationData], which retrieves the restoration data
/// from the widget under test.
/// * [WidgetTester.restoreFrom], which takes a [TestRestorationData] to
/// restore the state of the widget under test from the provided data.
class TestRestorationData {
const TestRestorationData._(this.binary);
/// Empty restoration data indicating that no data is available to restore
/// state from.
static const TestRestorationData empty = TestRestorationData._(null);
/// The serialized representation of the restoration data.
///
/// Should only be accessed by the test framework.
@protected
final Uint8List binary;
}

View File

@@ -23,6 +23,7 @@ import 'controller.dart';
import 'event_simulation.dart';
import 'finders.dart';
import 'matchers.dart';
import 'restoration.dart';
import 'test_async_utils.dart';
import 'test_compat.dart';
import 'test_pointer.dart';
@@ -137,6 +138,7 @@ void testWidgets(
test_package.addTearDown(binding.postTest);
return binding.runTest(
() async {
binding.reset();
debugResetSemanticsIdCounter();
tester.resetTestTextInput();
Object memento;
@@ -678,6 +680,53 @@ class WidgetTester extends WidgetController implements HitTestDispatcher, Ticker
});
}
/// Simulates restoring the state of the widget tree after the application
/// is restarted.
///
/// The method grabs the current serialized restoration data from the
/// [RestorationManager], takes down the widget tree to destroy all in-memory
/// state, and then restores the widget tree from the serialized restoration
/// data.
Future<void> restartAndRestore() async {
assert(
binding.restorationManager.debugRootBucketAccessed,
'The current widget tree did not inject the root bucket of the RestorationManager and '
'therefore no restoration data has been collected to restore from. Did you forget to wrap '
'your widget tree in a RootRestorationScope?',
);
final Widget widget = (binding.renderViewElement as RenderObjectToWidgetElement<RenderObject>).widget.child;
final TestRestorationData restorationData = binding.restorationManager.restorationData;
runApp(Container(key: UniqueKey()));
await pump();
binding.restorationManager.restoreFrom(restorationData);
return pumpWidget(widget);
}
/// Retrieves the current restoration data from the [RestorationManager].
///
/// The returned [TestRestorationData] describes the current state of the
/// widget tree under test and can be provided to [restoreFrom] to restore
/// the widget tree to the state described by this data.
Future<TestRestorationData> getRestorationData() async {
assert(
binding.restorationManager.debugRootBucketAccessed,
'The current widget tree did not inject the root bucket of the RestorationManager and '
'therefore no restoration data has been collected. Did you forget to wrap your widget tree '
'in a RootRestorationScope?',
);
return binding.restorationManager.restorationData;
}
/// Restores the widget tree under test to the state described by the
/// provided [TestRestorationData].
///
/// The data provided to this method is usually obtained from
/// [getRestorationData].
Future<void> restoreFrom(TestRestorationData data) {
binding.restorationManager.restoreFrom(data);
return pump();
}
/// Runs a [callback] that performs real asynchronous work.
///
/// This is intended for callers who need to call asynchronous methods where

View File

@@ -0,0 +1,111 @@
// Copyright 2014 The Flutter 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/services.dart';
import 'package:flutter/widgets.dart';
import 'package:flutter_test/flutter_test.dart';
void main() {
testWidgets('restartAndRestore', (WidgetTester tester) async {
await tester.pumpWidget(
const RootRestorationScope(
restorationId: 'root-child',
child: _RestorableWidget(
restorationId: 'restorable-widget',
),
),
);
final _RestorableWidgetState state = tester.state(find.byType(_RestorableWidget));
expect(find.text('Hello World 100'), findsOneWidget);
expect(state.doubleValue, 1.0);
state.setValues('Guten Morgen', 200, 33.4);
await tester.pump();
expect(find.text('Guten Morgen 200'), findsOneWidget);
expect(state.doubleValue, 33.4);
await tester.restartAndRestore();
expect(find.text('Guten Morgen 200'), findsOneWidget);
expect(find.text('Hello World 100'), findsNothing);
final _RestorableWidgetState restoredState = tester.state(find.byType(_RestorableWidget));
expect(restoredState, isNot(same(state)));
expect(restoredState.doubleValue, 1.0);
});
testWidgets('restore from previous restoration data', (WidgetTester tester) async {
await tester.pumpWidget(
const RootRestorationScope(
restorationId: 'root-child',
child: _RestorableWidget(
restorationId: 'restorable-widget',
),
),
);
final _RestorableWidgetState state = tester.state(find.byType(_RestorableWidget));
expect(find.text('Hello World 100'), findsOneWidget);
expect(state.doubleValue, 1.0);
state.setValues('Guten Morgen', 200, 33.4);
await tester.pump();
expect(find.text('Guten Morgen 200'), findsOneWidget);
expect(state.doubleValue, 33.4);
final TestRestorationData data = await tester.getRestorationData();
state.setValues('See you later!', 400, 123.5);
await tester.pump();
expect(find.text('See you later! 400'), findsOneWidget);
expect(state.doubleValue, 123.5);
await tester.restoreFrom(data);
expect(tester.state(find.byType(_RestorableWidget)), same(state));
expect(find.text('Guten Morgen 200'), findsOneWidget);
expect(state.doubleValue, 123.5);
});
}
class _RestorableWidget extends StatefulWidget {
const _RestorableWidget({Key key, this.restorationId}) : super(key: key);
final String restorationId;
@override
State<_RestorableWidget> createState() => _RestorableWidgetState();
}
class _RestorableWidgetState extends State<_RestorableWidget> with RestorationMixin {
final RestorableString stringValue = RestorableString('Hello World');
final RestorableInt intValue = RestorableInt(100);
double doubleValue = 1.0; // Not restorable.
@override
void restoreState(RestorationBucket oldBucket) {
registerForRestoration(stringValue, 'string');
registerForRestoration(intValue, 'int');
}
void setValues(String s, int i, double d) {
setState(() {
stringValue.value = s;
intValue.value = i;
doubleValue = d;
});
}
@override
Widget build(BuildContext context) {
return Text('${stringValue.value} ${intValue.value}', textDirection: TextDirection.ltr);
}
@override
String get restorationId => widget.restorationId;
}