From 445505d6f2d4a0b658385f0ef735d3a826ca49ab Mon Sep 17 00:00:00 2001 From: Jonah Williams Date: Thu, 30 May 2019 16:13:46 -0700 Subject: [PATCH] Devfs cleanup and testing (#33374) --- .../bin/fuchsia_asset_builder.dart | 9 +- packages/flutter_tools/lib/src/bundle.dart | 23 +- .../flutter_tools/lib/src/commands/test.dart | 2 +- packages/flutter_tools/lib/src/devfs.dart | 133 ++++------- .../lib/src/fuchsia/fuchsia_build.dart | 2 +- .../lib/src/resident_web_runner.dart | 3 +- .../flutter_tools/lib/src/web/web_device.dart | 2 +- .../test/asset_bundle_package_fonts_test.dart | 6 +- .../test/asset_bundle_package_test.dart | 12 +- .../flutter_tools/test/asset_bundle_test.dart | 2 +- .../test/asset_bundle_variant_test.dart | 4 +- packages/flutter_tools/test/asset_test.dart | 3 +- packages/flutter_tools/test/devfs_test.dart | 223 +++++++----------- packages/flutter_tools/test/src/mocks.dart | 25 -- 14 files changed, 167 insertions(+), 282 deletions(-) diff --git a/packages/flutter_tools/bin/fuchsia_asset_builder.dart b/packages/flutter_tools/bin/fuchsia_asset_builder.dart index 2de562425f..0163a1bdb6 100644 --- a/packages/flutter_tools/bin/fuchsia_asset_builder.dart +++ b/packages/flutter_tools/bin/fuchsia_asset_builder.dart @@ -36,10 +36,9 @@ Future main(List args) { }); } -Future writeFile(libfs.File outputFile, DevFSContent content) async { +void writeFile(libfs.File outputFile, DevFSContent content) { outputFile.createSync(recursive: true); - final List data = await content.contentsAsBytes(); - outputFile.writeAsBytesSync(data); + content.copyToFile(outputFile); } Future run(List args) async { @@ -71,12 +70,10 @@ Future run(List args) async { exit(1); } - final List> calls = >[]; assets.entries.forEach((String fileName, DevFSContent content) { final libfs.File outputFile = libfs.fs.file(libfs.fs.path.join(assetDir, fileName)); - calls.add(writeFile(outputFile, content)); + writeFile(outputFile, content); }); - await Future.wait(calls); final String outputMan = argResults[_kOptionAssetManifestOut]; await writeFuchsiaManifest(assets, argResults[_kOptionAsset], outputMan, argResults[_kOptionComponentName]); diff --git a/packages/flutter_tools/lib/src/bundle.dart b/packages/flutter_tools/lib/src/bundle.dart index 70a42653ec..3355f72019 100644 --- a/packages/flutter_tools/lib/src/bundle.dart +++ b/packages/flutter_tools/lib/src/bundle.dart @@ -147,7 +147,7 @@ Future build({ if (assets == null) throwToolExit('Error building assets', exitCode: 1); - await assemble( + assemble( buildMode: buildMode, assetBundle: assets, kernelContent: kernelContent, @@ -182,14 +182,14 @@ Future buildAssets({ return assetBundle; } -Future assemble({ +void assemble({ BuildMode buildMode, AssetBundle assetBundle, DevFSContent kernelContent, String privateKeyPath = defaultPrivateKeyPath, String assetDirPath, String compilationTraceFilePath, -}) async { +}) { assetDirPath ??= getAssetBuildDirectory(); printTrace('Building bundle'); @@ -214,22 +214,21 @@ Future assemble({ printTrace('Writing asset files to $assetDirPath'); ensureDirectoryExists(assetDirPath); - await writeBundle(fs.directory(assetDirPath), assetEntries); + writeBundle(fs.directory(assetDirPath), assetEntries); printTrace('Wrote $assetDirPath'); } -Future writeBundle( +void writeBundle( Directory bundleDir, Map assetEntries, -) async { +) { if (bundleDir.existsSync()) bundleDir.deleteSync(recursive: true); bundleDir.createSync(recursive: true); - await Future.wait( - assetEntries.entries.map>((MapEntry entry) async { - final File file = fs.file(fs.path.join(bundleDir.path, entry.key)); - file.parent.createSync(recursive: true); - await file.writeAsBytes(await entry.value.contentsAsBytes()); - })); + for (MapEntry entry in assetEntries.entries) { + final File file = fs.file(fs.path.join(bundleDir.path, entry.key)); + file.parent.createSync(recursive: true); + entry.value.copyToFile(file); + } } diff --git a/packages/flutter_tools/lib/src/commands/test.dart b/packages/flutter_tools/lib/src/commands/test.dart index 6f1caa480f..6a2307fb2a 100644 --- a/packages/flutter_tools/lib/src/commands/test.dart +++ b/packages/flutter_tools/lib/src/commands/test.dart @@ -242,7 +242,7 @@ class TestCommand extends FastFlutterCommand { throwToolExit('Error: Failed to build asset bundle'); } if (_needRebuild(assetBundle.entries)) { - await writeBundle(fs.directory(fs.path.join('build', 'unit_test_assets')), + writeBundle(fs.directory(fs.path.join('build', 'unit_test_assets')), assetBundle.entries); } } diff --git a/packages/flutter_tools/lib/src/devfs.dart b/packages/flutter_tools/lib/src/devfs.dart index e15fb5c7dd..ec97f957db 100644 --- a/packages/flutter_tools/lib/src/devfs.dart +++ b/packages/flutter_tools/lib/src/devfs.dart @@ -38,21 +38,25 @@ abstract class DevFSContent { /// or if the given time is null. bool isModifiedAfter(DateTime time); + /// The number of bytes in this file. int get size; - Future> contentsAsBytes(); + /// Returns the raw bytes of this file. + List contentsAsBytes(); - Stream> contentsAsStream(); - - Stream> contentsAsCompressedStream() { - return contentsAsStream().cast>().transform>(gzip.encoder); + /// Returns a gzipped representation of the contents of this file. + List contentsAsCompressedBytes() { + return gzip.encode(contentsAsBytes()); } - /// Return the list of files this content depends on. - List get fileDependencies => []; + /// Copies the content into the provided file. + /// + /// Requires that the `destination` directory already exists, but the target + /// file need not. + void copyToFile(File destination); } -// File content to be copied to the device. +/// File content to be copied to the device. class DevFSFileContent extends DevFSContent { DevFSFileContent(this.file); @@ -102,9 +106,6 @@ class DevFSFileContent extends DevFSContent { } } - @override - List get fileDependencies => [_getFile().path]; - @override bool get isModified { final FileStat _oldFileStat = _fileStat; @@ -135,10 +136,12 @@ class DevFSFileContent extends DevFSContent { } @override - Future> contentsAsBytes() => _getFile().readAsBytes(); + List contentsAsBytes() => _getFile().readAsBytesSync().cast(); @override - Stream> contentsAsStream() => _getFile().openRead(); + void copyToFile(File destination) { + _getFile().copySync(destination.path); + } } /// Byte content to be copied to the device. @@ -175,14 +178,15 @@ class DevFSByteContent extends DevFSContent { int get size => _bytes.length; @override - Future> contentsAsBytes() async => _bytes; + List contentsAsBytes() => _bytes; @override - Stream> contentsAsStream() => - Stream>.fromIterable(>[_bytes]); + void copyToFile(File destination) { + destination.writeAsBytesSync(contentsAsBytes()); + } } -/// String content to be copied to the device. +/// String content to be copied to the device encoded as utf8. class DevFSStringContent extends DevFSByteContent { DevFSStringContent(String string) : _string = string, @@ -203,75 +207,29 @@ class DevFSStringContent extends DevFSByteContent { } } -/// Abstract DevFS operations interface. -abstract class DevFSOperations { - Future create(String fsName); - Future destroy(String fsName); - Future writeFile(String fsName, Uri deviceUri, DevFSContent content); -} - -/// An implementation of [DevFSOperations] that speaks to the -/// vm service. -class ServiceProtocolDevFSOperations implements DevFSOperations { - ServiceProtocolDevFSOperations(this.vmService); +class DevFSOperations { + DevFSOperations(this.vmService, this.fsName) + : httpAddress = vmService.httpAddress; final VMService vmService; - - @override - Future create(String fsName) async { - final Map response = await vmService.vm.createDevFS(fsName); - return Uri.parse(response['uri']); - } - - @override - Future destroy(String fsName) async { - await vmService.vm.deleteDevFS(fsName); - } - - @override - Future writeFile(String fsName, Uri deviceUri, DevFSContent content) async { - List bytes; - try { - bytes = await content.contentsAsBytes(); - } catch (e) { - return e; - } - final String fileContents = base64.encode(bytes); - try { - return await vmService.vm.invokeRpcRaw( - '_writeDevFSFile', - params: { - 'fsName': fsName, - 'uri': deviceUri.toString(), - 'fileContents': fileContents, - }, - ); - } catch (error) { - printTrace('DevFS: Failed to write $deviceUri: $error'); - } - } -} - -class DevFSException implements Exception { - DevFSException(this.message, [this.error, this.stackTrace]); - final String message; - final dynamic error; - final StackTrace stackTrace; -} - -class _DevFSHttpWriter { - _DevFSHttpWriter(this.fsName, VMService serviceProtocol) - : httpAddress = serviceProtocol.httpAddress; - final String fsName; final Uri httpAddress; + final HttpClient _client = HttpClient(); static const int kMaxInFlight = 6; int _inFlight = 0; Map _outstanding; Completer _completer; - final HttpClient _client = HttpClient(); + + Future create(String fsName) async { + final Map response = await vmService.vm.createDevFS(fsName); + return Uri.parse(response['uri']); + } + + Future destroy(String fsName) async { + await vmService.vm.deleteDevFS(fsName); + } Future write(Map entries) async { _client.maxConnectionsPerHost = kMaxInFlight; @@ -301,9 +259,9 @@ class _DevFSHttpWriter { final HttpClientRequest request = await _client.putUrl(httpAddress); request.headers.removeAll(HttpHeaders.acceptEncodingHeader); request.headers.add('dev_fs_name', fsName); - request.headers.add('dev_fs_uri_b64', base64.encode(utf8.encode('$deviceUri'))); - final Stream> contents = content.contentsAsCompressedStream(); - await request.addStream(contents); + request.headers.add('dev_fs_uri_b64', + base64.encode(utf8.encode(deviceUri.toString()))); + request.add(content.contentsAsCompressedBytes()); final HttpClientResponse response = await request.close(); await response.drain(); } catch (error, trace) { @@ -317,6 +275,14 @@ class _DevFSHttpWriter { } } +class DevFSException implements Exception { + DevFSException(this.message, [this.error, this.stackTrace]); + + final String message; + final dynamic error; + final StackTrace stackTrace; +} + // Basic statistics for DevFS update operation. class UpdateFSReport { UpdateFSReport({ @@ -353,8 +319,7 @@ class DevFS { this.fsName, this.rootDirectory, { String packagesFilePath, - }) : _operations = ServiceProtocolDevFSOperations(serviceProtocol), - _httpWriter = _DevFSHttpWriter(fsName, serviceProtocol), + }) : _operations = DevFSOperations(serviceProtocol, fsName), _packagesFilePath = packagesFilePath ?? fs.path.join(rootDirectory.path, kPackagesFileName); DevFS.operations( @@ -362,11 +327,9 @@ class DevFS { this.fsName, this.rootDirectory, { String packagesFilePath, - }) : _httpWriter = null, - _packagesFilePath = packagesFilePath ?? fs.path.join(rootDirectory.path, kPackagesFileName); + }) : _packagesFilePath = packagesFilePath ?? fs.path.join(rootDirectory.path, kPackagesFileName); final DevFSOperations _operations; - final _DevFSHttpWriter _httpWriter; final String fsName; final Directory rootDirectory; String _packagesFilePath; @@ -489,7 +452,7 @@ class DevFS { printTrace('Updating files'); if (dirtyEntries.isNotEmpty) { try { - await _httpWriter.write(dirtyEntries); + await _operations.write(dirtyEntries); } on SocketException catch (socketException, stackTrace) { printTrace('DevFS sync failed. Lost connection to device: $socketException'); throw DevFSException('Lost connection to device.', socketException, stackTrace); diff --git a/packages/flutter_tools/lib/src/fuchsia/fuchsia_build.dart b/packages/flutter_tools/lib/src/fuchsia/fuchsia_build.dart index 00d95fa784..3dac651cbe 100644 --- a/packages/flutter_tools/lib/src/fuchsia/fuchsia_build.dart +++ b/packages/flutter_tools/lib/src/fuchsia/fuchsia_build.dart @@ -52,7 +52,7 @@ Future _buildAssets( final Map assetEntries = Map.from(assets.entries); - await writeBundle(fs.directory(assetDir), assetEntries); + writeBundle(fs.directory(assetDir), assetEntries); final String appName = fuchsiaProject.project.manifest.appName; final String outDir = getFuchsiaBuildDirectory(); diff --git a/packages/flutter_tools/lib/src/resident_web_runner.dart b/packages/flutter_tools/lib/src/resident_web_runner.dart index 1652628c72..aa1b61da71 100644 --- a/packages/flutter_tools/lib/src/resident_web_runner.dart +++ b/packages/flutter_tools/lib/src/resident_web_runner.dart @@ -120,8 +120,7 @@ class ResidentWebRunner extends ResidentRunner { if (build != 0) { throwToolExit('Error: Failed to build asset bundle'); } - await writeBundle( - fs.directory(getAssetBuildDirectory()), assetBundle.entries); + writeBundle(fs.directory(getAssetBuildDirectory()), assetBundle.entries); // Step 2: Start an HTTP server _server = WebAssetServer(flutterProject, target, ipv6); diff --git a/packages/flutter_tools/lib/src/web/web_device.dart b/packages/flutter_tools/lib/src/web/web_device.dart index d8ce9ce3e5..3288e41fa7 100644 --- a/packages/flutter_tools/lib/src/web/web_device.dart +++ b/packages/flutter_tools/lib/src/web/web_device.dart @@ -119,7 +119,7 @@ class WebDevice extends Device { if (build != 0) { throwToolExit('Error: Failed to build asset bundle'); } - await writeBundle(fs.directory(getAssetBuildDirectory()), assetBundle.entries); + writeBundle(fs.directory(getAssetBuildDirectory()), assetBundle.entries); _package = package; _server = await HttpServer.bind(InternetAddress.loopbackIPv4, 0); diff --git a/packages/flutter_tools/test/asset_bundle_package_fonts_test.dart b/packages/flutter_tools/test/asset_bundle_package_fonts_test.dart index 648a092549..0d2a3a2d1a 100644 --- a/packages/flutter_tools/test/asset_bundle_package_fonts_test.dart +++ b/packages/flutter_tools/test/asset_bundle_package_fonts_test.dart @@ -74,7 +74,7 @@ $fontsSection final String entryKey = 'packages/$packageName/$packageFont'; expect(bundle.entries.containsKey(entryKey), true); expect( - utf8.decode(await bundle.entries[entryKey].contentsAsBytes()), + utf8.decode(bundle.entries[entryKey].contentsAsBytes()), packageFont, ); } @@ -82,14 +82,14 @@ $fontsSection for (String localFont in localFonts) { expect(bundle.entries.containsKey(localFont), true); expect( - utf8.decode(await bundle.entries[localFont].contentsAsBytes()), + utf8.decode(bundle.entries[localFont].contentsAsBytes()), localFont, ); } } expect( - json.decode(utf8.decode(await bundle.entries['FontManifest.json'].contentsAsBytes())), + json.decode(utf8.decode(bundle.entries['FontManifest.json'].contentsAsBytes())), json.decode(expectedAssetManifest), ); } diff --git a/packages/flutter_tools/test/asset_bundle_package_test.dart b/packages/flutter_tools/test/asset_bundle_package_test.dart index 2ea79460ec..1e67c1107e 100644 --- a/packages/flutter_tools/test/asset_bundle_package_test.dart +++ b/packages/flutter_tools/test/asset_bundle_package_test.dart @@ -79,14 +79,14 @@ $assetsSection final String entryKey = Uri.encodeFull('packages/$packageName/$asset'); expect(bundle.entries.containsKey(entryKey), true, reason: 'Cannot find key on bundle: $entryKey'); expect( - utf8.decode(await bundle.entries[entryKey].contentsAsBytes()), + utf8.decode(bundle.entries[entryKey].contentsAsBytes()), asset, ); } } expect( - utf8.decode(await bundle.entries['AssetManifest.json'].contentsAsBytes()), + utf8.decode(bundle.entries['AssetManifest.json'].contentsAsBytes()), expectedAssetManifest, ); } @@ -126,11 +126,11 @@ $assetsSection expect(bundle.entries.length, 3); // LICENSE, AssetManifest, FontManifest const String expectedAssetManifest = '{}'; expect( - utf8.decode(await bundle.entries['AssetManifest.json'].contentsAsBytes()), + utf8.decode(bundle.entries['AssetManifest.json'].contentsAsBytes()), expectedAssetManifest, ); expect( - utf8.decode(await bundle.entries['FontManifest.json'].contentsAsBytes()), + utf8.decode(bundle.entries['FontManifest.json'].contentsAsBytes()), '[]', ); }, overrides: { @@ -153,11 +153,11 @@ $assetsSection expect(bundle.entries.length, 3); // LICENSE, AssetManifest, FontManifest const String expectedAssetManifest = '{}'; expect( - utf8.decode(await bundle.entries['AssetManifest.json'].contentsAsBytes()), + utf8.decode(bundle.entries['AssetManifest.json'].contentsAsBytes()), expectedAssetManifest, ); expect( - utf8.decode(await bundle.entries['FontManifest.json'].contentsAsBytes()), + utf8.decode(bundle.entries['FontManifest.json'].contentsAsBytes()), '[]', ); }, overrides: { diff --git a/packages/flutter_tools/test/asset_bundle_test.dart b/packages/flutter_tools/test/asset_bundle_test.dart index 6d99cde99a..6bd084e18b 100644 --- a/packages/flutter_tools/test/asset_bundle_test.dart +++ b/packages/flutter_tools/test/asset_bundle_test.dart @@ -50,7 +50,7 @@ void main() { expect(bundle.entries.length, 1); const String expectedAssetManifest = '{}'; expect( - utf8.decode(await bundle.entries['AssetManifest.json'].contentsAsBytes()), + utf8.decode(bundle.entries['AssetManifest.json'].contentsAsBytes()), expectedAssetManifest, ); }, overrides: { diff --git a/packages/flutter_tools/test/asset_bundle_variant_test.dart b/packages/flutter_tools/test/asset_bundle_variant_test.dart index 9a7b9f5335..77bdbfdc87 100644 --- a/packages/flutter_tools/test/asset_bundle_variant_test.dart +++ b/packages/flutter_tools/test/asset_bundle_variant_test.dart @@ -76,7 +76,7 @@ flutter: // The main asset file, /a/b/c/foo, and its variants exist. for (String asset in assets) { expect(bundle.entries.containsKey(asset), true); - expect(utf8.decode(await bundle.entries[asset].contentsAsBytes()), asset); + expect(utf8.decode(bundle.entries[asset].contentsAsBytes()), asset); } fs.file(fixPath('a/b/c/foo')).deleteSync(); @@ -88,7 +88,7 @@ flutter: expect(bundle.entries.containsKey('a/b/c/foo'), false); for (String asset in assets.skip(1)) { expect(bundle.entries.containsKey(asset), true); - expect(utf8.decode(await bundle.entries[asset].contentsAsBytes()), asset); + expect(utf8.decode(bundle.entries[asset].contentsAsBytes()), asset); } }, overrides: { FileSystem: () => testFileSystem, diff --git a/packages/flutter_tools/test/asset_test.dart b/packages/flutter_tools/test/asset_test.dart index bb8f2598e3..af961eb73c 100644 --- a/packages/flutter_tools/test/asset_test.dart +++ b/packages/flutter_tools/test/asset_test.dart @@ -7,6 +7,7 @@ import 'dart:async'; import 'package:flutter_tools/src/asset.dart'; import 'package:flutter_tools/src/base/file_system.dart'; import 'package:flutter_tools/src/cache.dart'; +import 'package:flutter_tools/src/convert.dart'; import 'src/common.dart'; import 'src/context.dart'; @@ -65,5 +66,5 @@ void main() { } Future getValueAsString(String key, AssetBundle asset) async { - return String.fromCharCodes(await asset.entries[key].contentsAsBytes()); + return utf8.decode(asset.entries[key].contentsAsBytes()); } diff --git a/packages/flutter_tools/test/devfs_test.dart b/packages/flutter_tools/test/devfs_test.dart index b8d93d4e10..1887e74913 100644 --- a/packages/flutter_tools/test/devfs_test.dart +++ b/packages/flutter_tools/test/devfs_test.dart @@ -4,15 +4,17 @@ import 'dart:async'; import 'dart:convert'; -import 'dart:io'; // ignore: dart_io_import import 'package:file/file.dart'; import 'package:file/memory.dart'; +import 'package:flutter_tools/src/base/context.dart'; import 'package:flutter_tools/src/base/file_system.dart'; import 'package:flutter_tools/src/base/io.dart'; +import 'package:flutter_tools/src/base/platform.dart'; import 'package:flutter_tools/src/devfs.dart'; import 'package:flutter_tools/src/vmservice.dart'; import 'package:json_rpc_2/json_rpc_2.dart' as rpc; +import 'package:mockito/mockito.dart'; import 'src/common.dart'; import 'src/context.dart'; @@ -20,17 +22,39 @@ import 'src/mocks.dart'; void main() { FileSystem fs; - String filePath; - Directory tempDir; - String basePath; - DevFS devFS; + MockPlatform mockPlatform; - setUpAll(() { - fs = MemoryFileSystem(); - filePath = fs.path.join('lib', 'foo.txt'); + setUp(() { + fs = MemoryFileSystem(style: FileSystemStyle.posix); + mockPlatform = MockPlatform(); + when(mockPlatform.pathSeparator).thenReturn('/'); + when(mockPlatform.isWindows).thenReturn(false); }); group('DevFSContent', () { + test('copyToFile', () { + final String filePath = fs.path.join('lib', 'foo.txt'); + final File file = fs.file(filePath) + ..createSync(recursive: true) + ..writeAsStringSync('hello, world'); + final DevFSByteContent byteContent = DevFSByteContent([4, 5, 6]); + final DevFSStringContent stringContent = DevFSStringContent('some string'); + final DevFSFileContent fileContent = DevFSFileContent(file); + + final File byteDestination = fs.file('byte_dest'); + final File stringDestination = fs.file('string_dest'); + final File fileDestination = fs.file('file_dest'); + + byteContent.copyToFile(byteDestination); + expect(byteDestination.readAsBytesSync(), [4, 5, 6]); + + stringContent.copyToFile(stringDestination); + expect(stringDestination.readAsStringSync(), 'some string'); + + fileContent.copyToFile(fileDestination); + expect(fileDestination.readAsStringSync(), 'hello, world'); + }); + test('bytes', () { final DevFSByteContent content = DevFSByteContent([4, 5, 6]); expect(content.bytes, orderedEquals([4, 5, 6])); @@ -41,6 +65,7 @@ void main() { expect(content.isModified, isTrue); expect(content.isModified, isFalse); }); + test('string', () { final DevFSStringContent content = DevFSStringContent('some string'); expect(content.string, 'some string'); @@ -58,7 +83,9 @@ void main() { expect(content.isModified, isTrue); expect(content.isModified, isFalse); }); + testUsingContext('file', () async { + final String filePath = fs.path.join('lib', 'foo.txt'); final File file = fs.file(filePath); final DevFSFileContent content = DevFSFileContent(file); expect(content.isModified, isFalse); @@ -73,10 +100,9 @@ void main() { expect(content.isModifiedAfter(null), isTrue); file.writeAsBytesSync([2, 3, 4], flush: true); - expect(content.fileDependencies, [filePath]); expect(content.isModified, isTrue); expect(content.isModified, isFalse); - expect(await content.contentsAsBytes(), [2, 3, 4]); + expect(content.contentsAsBytes(), [2, 3, 4]); updateFileModificationTime(file.path, fiveSecondsAgo, 0); expect(content.isModified, isFalse); expect(content.isModified, isFalse); @@ -87,36 +113,56 @@ void main() { expect(content.isModified, isFalse); }, overrides: { FileSystem: () => fs, - }, skip: Platform.isWindows); // TODO(jonahwilliams): fix or disable this functionality. + }, skip: platform.isWindows); // Still flaky, but only on CI :( }); group('devfs remote', () { - MockVMService vmService; - final MockResidentCompiler residentCompiler = MockResidentCompiler(); + DevFS devFS; + MockResidentCompiler residentCompiler; + MockDevFSOperations mockDevFSOperations; + int created; + int destroyed; + List writtenFiles; + bool exists; - setUpAll(() async { - tempDir = _newTempDir(fs); - basePath = tempDir.path; - vmService = MockVMService(); - await vmService.setUp(); - }); - tearDownAll(() async { - await vmService.tearDown(); - _cleanupTempDirs(); + setUp(() async { + mockDevFSOperations = MockDevFSOperations(); + devFS = DevFS.operations(mockDevFSOperations, 'test', fs.currentDirectory); + residentCompiler = MockResidentCompiler(); + created = 0; + destroyed = 0; + exists = false; + writtenFiles = []; + when(mockDevFSOperations.create('test')).thenAnswer((Invocation invocation) async { + if (exists) { + throw rpc.RpcException(1001, 'already exists'); + } + exists = true; + created += 1; + return Uri.parse(InternetAddress.loopbackIPv4.toString()); + }); + when(mockDevFSOperations.destroy('test')).thenAnswer((Invocation invocation) async { + exists = false; + destroyed += 1; + }); + when(mockDevFSOperations.write(any)).thenAnswer((Invocation invocation) async { + final Map entries = invocation.positionalArguments.first; + writtenFiles.addAll(entries.keys.map((Uri uri) => uri.toFilePath())); + }); }); testUsingContext('create dev file system', () async { // simulate workspace - final File file = fs.file(fs.path.join(basePath, filePath)); + final String filePath = fs.path.join('lib', 'foo.txt'); + final File file = fs.file(filePath); await file.parent.create(recursive: true); file.writeAsBytesSync([1, 2, 3]); // simulate package await _createPackage(fs, 'somepkg', 'somefile.txt'); - - devFS = DevFS(vmService, 'test', tempDir); await devFS.create(); - vmService.expectMessages(['create test']); + + expect(created, 1); expect(devFS.assetPathsToEvict, isEmpty); final UpdateFSReport report = await devFS.update( @@ -126,9 +172,8 @@ void main() { trackWidgetCreation: false, invalidatedFiles: [], ); - vmService.expectMessages([ - 'writeFile test lib/foo.txt.dill', - ]); + + expect(writtenFiles.single, contains('foo.txt.dill')); expect(devFS.assetPathsToEvict, isEmpty); expect(report.syncedBytes, 22); expect(report.success, true); @@ -137,9 +182,8 @@ void main() { }); testUsingContext('delete dev file system', () async { - expect(vmService.messages, isEmpty, reason: 'prior test timeout'); await devFS.destroy(); - vmService.expectMessages(['destroy test']); + expect(destroyed, 1); expect(devFS.assetPathsToEvict, isEmpty); }, overrides: { FileSystem: () => fs, @@ -147,26 +191,27 @@ void main() { testUsingContext('cleanup preexisting file system', () async { // simulate workspace - final File file = fs.file(fs.path.join(basePath, filePath)); + final String filePath = fs.path.join('lib', 'foo.txt'); + final File file = fs.file(filePath); await file.parent.create(recursive: true); file.writeAsBytesSync([1, 2, 3]); // simulate package await _createPackage(fs, 'somepkg', 'somefile.txt'); - devFS = DevFS(vmService, 'test', tempDir); await devFS.create(); - vmService.expectMessages(['create test']); + expect(created, 1); expect(devFS.assetPathsToEvict, isEmpty); // Try to create again. await devFS.create(); - vmService.expectMessages(['create test', 'destroy test', 'create test']); + expect(created, 2); + expect(destroyed, 1); expect(devFS.assetPathsToEvict, isEmpty); // Really destroy. await devFS.destroy(); - vmService.expectMessages(['destroy test']); + expect(destroyed, 2); expect(devFS.assetPathsToEvict, isEmpty); }, overrides: { FileSystem: () => fs, @@ -174,113 +219,20 @@ void main() { }); } -class MockVMService extends BasicMock implements VMService { - MockVMService() { - _vm = MockVM(this); - } +class MockVMService extends Mock implements VMService {} - Uri _httpAddress; - HttpServer _server; - MockVM _vm; +class MockDevFSOperations extends Mock implements DevFSOperations {} - @override - Uri get httpAddress => _httpAddress; +class MockPlatform extends Mock implements Platform {} - @override - VM get vm => _vm; - - Future setUp() async { - try { - _server = await HttpServer.bind(InternetAddress.loopbackIPv6, 0); - _httpAddress = Uri.parse('http://[::1]:${_server.port}'); - } on SocketException { - // Fall back to IPv4 if the host doesn't support binding to IPv6 localhost - _server = await HttpServer.bind(InternetAddress.loopbackIPv4, 0); - _httpAddress = Uri.parse('http://127.0.0.1:${_server.port}'); - } - _server.listen((HttpRequest request) { - final String fsName = request.headers.value('dev_fs_name'); - final String devicePath = utf8.decode(base64.decode(request.headers.value('dev_fs_uri_b64'))); - messages.add('writeFile $fsName $devicePath'); - request.drain>().then((List value) { - request.response - ..write('Got it') - ..close(); - }); - }); - } - - Future tearDown() async { - await _server?.close(); - } - - @override - dynamic noSuchMethod(Invocation invocation) => super.noSuchMethod(invocation); -} - -class MockVM implements VM { - MockVM(this._service); - - final MockVMService _service; - final Uri _baseUri = Uri.parse('file:///tmp/devfs/test'); - bool _devFSExists = false; - - static const int kFileSystemAlreadyExists = 1001; - - @override - Future> createDevFS(String fsName) async { - _service.messages.add('create $fsName'); - if (_devFSExists) { - throw rpc.RpcException(kFileSystemAlreadyExists, 'File system already exists'); - } - _devFSExists = true; - return {'uri': '$_baseUri'}; - } - - @override - Future> deleteDevFS(String fsName) async { - _service.messages.add('destroy $fsName'); - _devFSExists = false; - return {'type': 'Success'}; - } - - @override - Future> invokeRpcRaw( - String method, { - Map params = const {}, - Duration timeout, - bool timeoutFatal = true, - }) async { - _service.messages.add('$method $params'); - return {'success': true}; - } - - @override - dynamic noSuchMethod(Invocation invocation) => super.noSuchMethod(invocation); -} - - -final List _tempDirs = []; final Map _packages = {}; -Directory _newTempDir(FileSystem fs) { - final Directory tempDir = fs.systemTempDirectory.createTempSync('flutter_devfs${_tempDirs.length}_test.'); - _tempDirs.add(tempDir); - return tempDir; -} - -void _cleanupTempDirs() { - while (_tempDirs.isNotEmpty) - tryToDelete(_tempDirs.removeLast()); -} Future _createPackage(FileSystem fs, String pkgName, String pkgFileName, { bool doubleSlash = false }) async { - final Directory pkgTempDir = _newTempDir(fs); - String pkgFilePath = fs.path.join(pkgTempDir.path, pkgName, 'lib', pkgFileName); + String pkgFilePath = fs.path.join(pkgName, 'lib', pkgFileName); if (doubleSlash) { // Force two separators into the path. - final String doubleSlash = fs.path.separator + fs.path.separator; - pkgFilePath = pkgTempDir.path + doubleSlash + fs.path.join(pkgName, 'lib', pkgFileName); + pkgFilePath = fs.path.join(pkgName, 'lib', pkgFileName); } final File pkgFile = fs.file(pkgFilePath); await pkgFile.parent.create(recursive: true); @@ -290,6 +242,5 @@ Future _createPackage(FileSystem fs, String pkgName, String pkgFileName, { _packages.forEach((String pkgName, Uri pkgUri) { sb.writeln('$pkgName:$pkgUri'); }); - fs.file(fs.path.join(_tempDirs[0].path, '.packages')).writeAsStringSync(sb.toString()); + fs.file('.packages').writeAsStringSync(sb.toString()); } - diff --git a/packages/flutter_tools/test/src/mocks.dart b/packages/flutter_tools/test/src/mocks.dart index 8c318bc8c6..1d1da52061 100644 --- a/packages/flutter_tools/test/src/mocks.dart +++ b/packages/flutter_tools/test/src/mocks.dart @@ -14,7 +14,6 @@ import 'package:flutter_tools/src/base/io.dart'; import 'package:flutter_tools/src/base/platform.dart'; import 'package:flutter_tools/src/build_info.dart'; import 'package:flutter_tools/src/compile.dart'; -import 'package:flutter_tools/src/devfs.dart'; import 'package:flutter_tools/src/device.dart'; import 'package:flutter_tools/src/ios/devices.dart'; import 'package:flutter_tools/src/ios/simulators.dart'; @@ -478,30 +477,6 @@ class BasicMock { } } -class MockDevFSOperations extends BasicMock implements DevFSOperations { - Map devicePathToContent = {}; - - @override - Future create(String fsName) async { - messages.add('create $fsName'); - return Uri.parse('file:///$fsName'); - } - - @override - Future destroy(String fsName) async { - messages.add('destroy $fsName'); - } - - @override - Future writeFile(String fsName, Uri deviceUri, DevFSContent content) async { - String message = 'writeFile $fsName $deviceUri'; - if (content is DevFSFileContent) { - message += ' ${content.file.path}'; - } - messages.add(message); - devicePathToContent[deviceUri] = content; - } -} class MockResidentCompiler extends BasicMock implements ResidentCompiler { @override