diff --git a/packages/flutter_tools/lib/src/base/context.dart b/packages/flutter_tools/lib/src/base/context.dart index 9204f78db0..362532ef95 100644 --- a/packages/flutter_tools/lib/src/base/context.dart +++ b/packages/flutter_tools/lib/src/base/context.dart @@ -26,6 +26,10 @@ class ContextDependencyCycleException implements Exception { String toString() => 'Dependency cycle detected: ${cycle.join(' -> ')}'; } +/// The Zone key used to look up the [AppContext]. +@visibleForTesting +const Object contextKey = _Key.key; + /// The current [AppContext], as determined by the [Zone] hierarchy. /// /// This will be the first context found as we scan up the zone hierarchy, or @@ -33,7 +37,7 @@ class ContextDependencyCycleException implements Exception { /// context will not have any values associated with it. /// /// This is guaranteed to never return `null`. -AppContext get context => Zone.current[_Key.key] as AppContext ?? AppContext._root; +AppContext get context => Zone.current[contextKey] as AppContext ?? AppContext._root; /// A lookup table (mapping types to values) and an implied scope, in which /// code is run. diff --git a/packages/flutter_tools/lib/src/run_hot.dart b/packages/flutter_tools/lib/src/run_hot.dart index a3fbe18bff..26a1e36475 100644 --- a/packages/flutter_tools/lib/src/run_hot.dart +++ b/packages/flutter_tools/lib/src/run_hot.dart @@ -26,7 +26,12 @@ import 'reporting/reporting.dart'; import 'resident_runner.dart'; import 'vmservice.dart'; -ProjectFileInvalidator get projectFileInvalidator => context.get() ?? const ProjectFileInvalidator(); +ProjectFileInvalidator get projectFileInvalidator => context.get() ?? _defaultInvalidator; +final ProjectFileInvalidator _defaultInvalidator = ProjectFileInvalidator( + fileSystem: fs, + platform: platform, + logger: logger, +); HotRunnerConfig get hotRunnerConfig => context.get(); @@ -1112,8 +1117,20 @@ class HotRunner extends ResidentRunner { } } +/// The [ProjectFileInvalidator] track the dependencies for a running +/// application to determine when they are dirty. class ProjectFileInvalidator { - const ProjectFileInvalidator(); + ProjectFileInvalidator({ + @required FileSystem fileSystem, + @required Platform platform, + @required Logger logger, + }): _fileSystem = fileSystem, + _platform = platform, + _logger = logger; + + final FileSystem _fileSystem; + final Platform _platform; + final Logger _logger; static const String _pubCachePathLinuxAndMac = '.pub-cache'; static const String _pubCachePathWindows = 'Pub/Cache'; @@ -1142,13 +1159,13 @@ class ProjectFileInvalidator { } final Stopwatch stopwatch = Stopwatch()..start(); - final List urisToScan = [ // Don't watch pub cache directories to speed things up a little. - ...urisToMonitor.where(_isNotInPubCache), + for (Uri uri in urisToMonitor) + if (_isNotInPubCache(uri)) uri, // We need to check the .packages file too since it is not used in compilation. - fs.file(packagesPath).uri, + _fileSystem.file(packagesPath).uri, ]; final List invalidatedFiles = []; @@ -1157,8 +1174,8 @@ class ProjectFileInvalidator { final List> waitList = >[]; for (final Uri uri in urisToScan) { waitList.add(pool.withResource( - () => fs - .stat(uri.toFilePath(windows: platform.isWindows)) + () => _fileSystem + .stat(uri.toFilePath(windows: _platform.isWindows)) .then((FileStat stat) { final DateTime updatedAt = stat.modified; if (updatedAt != null && updatedAt.isAfter(lastCompiled)) { @@ -1170,14 +1187,14 @@ class ProjectFileInvalidator { await Future.wait(waitList); } else { for (final Uri uri in urisToScan) { - final DateTime updatedAt = fs.statSync( - uri.toFilePath(windows: platform.isWindows)).modified; + final DateTime updatedAt = _fileSystem.statSync( + uri.toFilePath(windows: _platform.isWindows)).modified; if (updatedAt != null && updatedAt.isAfter(lastCompiled)) { invalidatedFiles.add(uri); } } } - printTrace( + _logger.printTrace( 'Scanned through ${urisToScan.length} files in ' '${stopwatch.elapsedMilliseconds}ms' '${asyncScanning ? " (async)" : ""}', @@ -1185,8 +1202,8 @@ class ProjectFileInvalidator { return invalidatedFiles; } - static bool _isNotInPubCache(Uri uri) { - return !(platform.isWindows && uri.path.contains(_pubCachePathWindows)) + bool _isNotInPubCache(Uri uri) { + return !(_platform.isWindows && uri.path.contains(_pubCachePathWindows)) && !uri.path.contains(_pubCachePathLinuxAndMac); } } diff --git a/packages/flutter_tools/test/general.shard/base/common_test.dart b/packages/flutter_tools/test/general.shard/base/common_test.dart index 31d718c21d..958e0ad71d 100644 --- a/packages/flutter_tools/test/general.shard/base/common_test.dart +++ b/packages/flutter_tools/test/general.shard/base/common_test.dart @@ -3,6 +3,7 @@ // found in the LICENSE file. import 'package:flutter_tools/src/base/common.dart'; +import 'package:flutter_tools/src/base/context.dart'; import '../../src/common.dart'; @@ -23,5 +24,9 @@ void main() { test('throws ToolExit with message and exit code', () { expect(() => throwToolExit('message', exitCode: 42), throwsToolExit(exitCode: 42, message: 'message')); }); + + testWithoutContext('Throws if accessing the Zone', () { + expect(() => context.get(), throwsA(isInstanceOf())); + }); }); } diff --git a/packages/flutter_tools/test/general.shard/project_file_invalidator_test.dart b/packages/flutter_tools/test/general.shard/project_file_invalidator_test.dart index 55836c49d5..9d6dd394ec 100644 --- a/packages/flutter_tools/test/general.shard/project_file_invalidator_test.dart +++ b/packages/flutter_tools/test/general.shard/project_file_invalidator_test.dart @@ -3,67 +3,69 @@ // found in the LICENSE file. import 'package:file/memory.dart'; -import 'package:flutter_tools/src/base/file_system.dart'; +import 'package:flutter_tools/src/base/logger.dart'; +import 'package:flutter_tools/src/base/platform.dart'; import 'package:flutter_tools/src/run_hot.dart'; -import 'package:meta/meta.dart'; import '../src/common.dart'; -import '../src/context.dart'; // assumption: tests have a timeout less than 100 days final DateTime inFuture = DateTime.now().add(const Duration(days: 100)); void main() { - group('ProjectFileInvalidator', () { - _testProjectFileInvalidator(asyncScanning: false); - }); - group('ProjectFileInvalidator (async scanning)', () { - _testProjectFileInvalidator(asyncScanning: true); - }); -} - -void _testProjectFileInvalidator({@required bool asyncScanning}) { - const ProjectFileInvalidator projectFileInvalidator = ProjectFileInvalidator(); - - testUsingContext('No last compile', () async { - expect( - await projectFileInvalidator.findInvalidated( - lastCompiled: null, - urisToMonitor: [], - packagesPath: '', - asyncScanning: asyncScanning, - ), - isEmpty, - ); - }); - - testUsingContext('Empty project', () async { - expect( - await projectFileInvalidator.findInvalidated( - lastCompiled: inFuture, - urisToMonitor: [], - packagesPath: '', - asyncScanning: asyncScanning, - ), - isEmpty, - ); - }, overrides: { - FileSystem: () => MemoryFileSystem(), - ProcessManager: () => FakeProcessManager.any(), - }); - - testUsingContext('Non-existent files are ignored', () async { - expect( - await projectFileInvalidator.findInvalidated( - lastCompiled: inFuture, - urisToMonitor: [Uri.parse('/not-there-anymore'),], - packagesPath: '', - asyncScanning: asyncScanning, - ), - isEmpty, - ); - }, overrides: { - FileSystem: () => MemoryFileSystem(), - ProcessManager: () => FakeProcessManager.any(), - }); + for (bool asyncScanning in [true, false]) { + testWithoutContext('No last compile, asyncScanning: $asyncScanning', () async { + final ProjectFileInvalidator projectFileInvalidator = ProjectFileInvalidator( + fileSystem: MemoryFileSystem(), + platform: FakePlatform(), + logger: BufferLogger(), + ); + + expect( + await projectFileInvalidator.findInvalidated( + lastCompiled: null, + urisToMonitor: [], + packagesPath: '', + asyncScanning: asyncScanning, + ), + isEmpty, + ); + }); + + testWithoutContext('Empty project, asyncScanning: $asyncScanning', () async { + final ProjectFileInvalidator projectFileInvalidator = ProjectFileInvalidator( + fileSystem: MemoryFileSystem(), + platform: FakePlatform(), + logger: BufferLogger(), + ); + + expect( + await projectFileInvalidator.findInvalidated( + lastCompiled: inFuture, + urisToMonitor: [], + packagesPath: '', + asyncScanning: asyncScanning, + ), + isEmpty, + ); + }); + + testWithoutContext('Non-existent files are ignored, asyncScanning: $asyncScanning', () async { + final ProjectFileInvalidator projectFileInvalidator = ProjectFileInvalidator( + fileSystem: MemoryFileSystem(), + platform: FakePlatform(), + logger: BufferLogger(), + ); + + expect( + await projectFileInvalidator.findInvalidated( + lastCompiled: inFuture, + urisToMonitor: [Uri.parse('/not-there-anymore'),], + packagesPath: '', + asyncScanning: asyncScanning, + ), + isEmpty, + ); + }); + } } diff --git a/packages/flutter_tools/test/src/common.dart b/packages/flutter_tools/test/src/common.dart index 0383603194..c693e52fd2 100644 --- a/packages/flutter_tools/test/src/common.dart +++ b/packages/flutter_tools/test/src/common.dart @@ -6,13 +6,15 @@ import 'dart:async'; import 'package:args/command_runner.dart'; import 'package:flutter_tools/src/base/common.dart'; +import 'package:flutter_tools/src/base/context.dart'; import 'package:flutter_tools/src/base/file_system.dart'; import 'package:flutter_tools/src/base/platform.dart'; import 'package:flutter_tools/src/base/process.dart'; import 'package:flutter_tools/src/commands/create.dart'; import 'package:flutter_tools/src/runner/flutter_command.dart'; import 'package:flutter_tools/src/runner/flutter_command_runner.dart'; -import 'package:test_api/test_api.dart' as test_package show TypeMatcher; // ignore: deprecated_member_use +import 'package:meta/meta.dart'; +import 'package:test_api/test_api.dart' as test_package show TypeMatcher, test; // ignore: deprecated_member_use import 'package:test_api/test_api.dart' hide TypeMatcher, isInstanceOf; // ignore: deprecated_member_use // ignore: deprecated_member_use export 'package:test_core/test_core.dart' hide TypeMatcher, isInstanceOf; // Defines a 'package:test' shim. @@ -137,3 +139,67 @@ Future expectToolExitLater(Future future, Matcher messageMatcher) fail('ToolExit expected, got $e\n$trace'); } } + +/// Executes a test body in zone that does not allow context-based injection. +/// +/// For classes which have been refactored to excluded context-based injection +/// or globals like [fs] or [platform], prefer using this test method as it +/// will prevent accidentally including these context getters in future code +/// changes. +/// +/// For more information, see https://github.com/flutter/flutter/issues/47161 +@isTest +void testWithoutContext(String description, FutureOr body(), { + String testOn, + Timeout timeout, + bool skip, + List tags, + Map onPlatform, + int retry, + }) { + return test_package.test( + description, () async { + return runZoned(body, zoneValues: { + contextKey: const NoContext(), + }); + }, + timeout: timeout, + skip: skip, + tags: tags, + onPlatform: onPlatform, + retry: retry, + testOn: testOn, + ); +} + +/// An implementation of [AppContext] that throws if context.get is called in the test. +/// +/// The intention of the class is to ensure we do not accidentally regress when +/// moving towards more explicit dependency injection by accidentally using +/// a Zone value in place of a constructor parameter. +class NoContext implements AppContext { + const NoContext(); + + @override + T get() { + throw UnsupportedError( + 'context.get<$T> is not supported in test methods. ' + 'Use Testbed or testUsingContext if accessing Zone injected ' + 'values.' + ); + } + + @override + String get name => 'No Context'; + + @override + Future run({ + FutureOr Function() body, + String name, + Map overrides, + Map fallbacks, + ZoneSpecification zoneSpecification, + }) async { + return body(); + } +}