From 2ba0deb77a6dcacfb996eb2a3122a9d654230956 Mon Sep 17 00:00:00 2001 From: Todd Volkert Date: Mon, 7 May 2018 18:33:44 -0700 Subject: [PATCH] Make runAsync() run in child zone, not root zone (#17359) Some APIs (such as the ones in package:test) assume you're running in a child zone of the test zone by attempting to extract information from the zone values. When we run runAsync() in the root zone, those zone values are lost, and such API methods don't work. The solution is to run in a child zone, but with a specification that says to use the Root zone for task scheduling (both timers and microtakss). --- packages/flutter_test/lib/src/binding.dart | 16 +++++++++++++++- .../flutter_test/test/widget_tester_test.dart | 12 ++++++++++++ 2 files changed, 27 insertions(+), 1 deletion(-) diff --git a/packages/flutter_test/lib/src/binding.dart b/packages/flutter_test/lib/src/binding.dart index 7150377105..6e784783f2 100644 --- a/packages/flutter_test/lib/src/binding.dart +++ b/packages/flutter_test/lib/src/binding.dart @@ -634,7 +634,21 @@ class AutomatedTestWidgetsFlutterBinding extends TestWidgetsFlutterBinding { ); }()); - return Zone.root.run(() { + final Zone realAsyncZone = Zone.current.fork( + specification: new ZoneSpecification( + scheduleMicrotask: (Zone self, ZoneDelegate parent, Zone zone, void f()) { + Zone.root.scheduleMicrotask(f); + }, + createTimer: (Zone self, ZoneDelegate parent, Zone zone, Duration duration, void f()) { + return Zone.root.createTimer(duration, f); + }, + createPeriodicTimer: (Zone self, ZoneDelegate parent, Zone zone, Duration period, void f(Timer timer)) { + return Zone.root.createPeriodicTimer(period, f); + }, + ), + ); + + return realAsyncZone.run(() { _pendingAsyncTasks = new Completer(); return callback().catchError((dynamic exception, StackTrace stack) { FlutterError.reportError(new FlutterErrorDetails( diff --git a/packages/flutter_test/test/widget_tester_test.dart b/packages/flutter_test/test/widget_tester_test.dart index 56eb6ae55c..f55a17ef62 100644 --- a/packages/flutter_test/test/widget_tester_test.dart +++ b/packages/flutter_test/test/widget_tester_test.dart @@ -481,6 +481,18 @@ void main() { expect(() => tester.runAsync(() async {}), throwsA(const isInstanceOf())); completer.complete(); }); + + testWidgets('maintains existing zone values', (WidgetTester tester) async { + final Object key = new Object(); + await runZoned(() { + expect(Zone.current[key], 'abczed'); + return tester.runAsync(() async { + expect(Zone.current[key], 'abczed'); + }); + }, zoneValues: { + key: 'abczed', + }); + }); }); }