From 3dec6a693059dc65ccd66e751f53ef21525a7d74 Mon Sep 17 00:00:00 2001 From: Ian Hickson Date: Fri, 17 Aug 2018 13:17:23 -0700 Subject: [PATCH] Clean up usage of temporary directories (#20682) All temporary directory start with `flutter_` and have their random component separated from the name by a period, as in `flutter_test_bundle.YFYQMY`. I've tried to find some of the places where we didn't cleanly delete temporary directories, too. This greatly reduces, though it does not entirely eliminate, the directories we leave behind when running tests, especially `flutter_tools` tests. While I was at it I standardized on `tempDir` as the variable name for temporary directories, since it was the most common, removing occurrences of `temp` and `tmp`, among others. Also I factored out some common code that used to catch exceptions that happen on Windows, and made more places use that pattern. --- dev/bots/analyze-sample-code.dart | 15 +++---- dev/bots/prepare_package.dart | 2 +- dev/bots/test.dart | 12 ++---- dev/bots/test/common.dart | 13 ++++++ dev/bots/test/prepare_package_test.dart | 43 +++++++------------ .../bin/tasks/gradle_plugin_test.dart | 12 +++--- dev/devicelab/bin/tasks/module_test.dart | 33 +++++++------- dev/devicelab/lib/framework/utils.dart | 20 ++++++--- dev/devicelab/lib/tasks/perf_tests.dart | 3 +- dev/devicelab/lib/tasks/plugin_tests.dart | 29 +++++++------ dev/tools/dartdoc.dart | 2 +- packages/flutter_driver/test/common.dart | 15 ++++++- .../test/src/timeline_summary_test.dart | 4 +- .../flutter_tools/bin/fuchsia_tester.dart | 16 +++---- .../lib/src/application_package.dart | 3 +- .../lib/src/commands/update_packages.dart | 10 ++--- packages/flutter_tools/lib/src/ios/mac.dart | 10 ++--- .../src/runner/flutter_command_runner.dart | 19 ++++---- .../lib/src/test/coverage_collector.dart | 2 +- .../lib/src/test/flutter_platform.dart | 14 +++--- .../flutter_tools/test/analytics_test.dart | 27 +++++++----- .../test/android/android_sdk_test.dart | 6 ++- .../test/android/android_workflow_test.dart | 9 ---- .../flutter_tools/test/artifacts_test.dart | 8 ++-- .../test/asset_bundle_package_fonts_test.dart | 10 +---- .../test/asset_bundle_package_test.dart | 10 +---- .../flutter_tools/test/asset_bundle_test.dart | 10 +---- .../test/asset_bundle_variant_test.dart | 10 +---- .../test/base/os_utils_test.dart | 8 ++-- .../commands/analyze_continuously_test.dart | 4 +- .../test/commands/analyze_once_test.dart | 17 +++----- .../test/commands/analyze_test.dart | 6 ++- .../test/commands/create_test.dart | 13 ++---- .../test/commands/drive_test.dart | 29 +++++++------ .../test/commands/format_test.dart | 12 +++--- .../test/commands/ide_config_test.dart | 42 +++++++++--------- .../test/commands/packages_test.dart | 16 +++---- .../test/commands/upgrade_test.dart | 10 ++--- packages/flutter_tools/test/config_test.dart | 9 +++- .../test/dependency_checker_test.dart | 8 ++-- packages/flutter_tools/test/devfs_test.dart | 7 ++- .../expression_evaluation_test.dart | 17 +++----- .../test/integration/flutter_attach_test.dart | 18 +++----- .../test/integration/flutter_tester_test.dart | 9 +--- .../test/integration/hot_reload_test.dart | 17 +++----- .../test/integration/lifetime_test.dart | 11 ++--- .../integration/test_data/test_project.dart | 4 -- .../test/integration/test_driver.dart | 14 +++--- packages/flutter_tools/test/src/common.dart | 11 +++++ packages/flutter_tools/test/src/context.dart | 11 +++-- packages/flutter_tools/test/src/mocks.dart | 25 ++++++----- 51 files changed, 339 insertions(+), 346 deletions(-) diff --git a/dev/bots/analyze-sample-code.dart b/dev/bots/analyze-sample-code.dart index 5974d4b019e..ecc1491c4ad 100644 --- a/dev/bots/analyze-sample-code.dart +++ b/dev/bots/analyze-sample-code.dart @@ -100,13 +100,13 @@ const String kDartDocPrefix = '///'; const String kDartDocPrefixWithSpace = '$kDartDocPrefix '; Future main() async { - final Directory temp = Directory.systemTemp.createTempSync('analyze_sample_code_'); + final Directory tempDir = Directory.systemTemp.createTempSync('flutter_analyze_sample_code.'); int exitCode = 1; bool keepMain = false; final List buffer = []; try { - final File mainDart = new File(path.join(temp.path, 'main.dart')); - final File pubSpec = new File(path.join(temp.path, 'pubspec.yaml')); + final File mainDart = new File(path.join(tempDir.path, 'main.dart')); + final File pubSpec = new File(path.join(tempDir.path, 'pubspec.yaml')); final Directory flutterPackage = new Directory(path.join(_flutterRoot, 'packages', 'flutter', 'lib')); final List
sections =
[]; int sampleCodeSections = 0; @@ -210,7 +210,7 @@ dependencies: final Process process = await Process.start( _flutter, ['analyze', '--no-preamble', '--no-congratulate', mainDart.parent.path], - workingDirectory: temp.path, + workingDirectory: tempDir.path, ); stderr.addStream(process.stderr); final List errors = await process.stdout.transform(utf8.decoder).transform(const LineSplitter()).toList(); @@ -285,7 +285,7 @@ dependencies: print('No errors!'); } finally { if (keepMain) { - print('Kept ${temp.path} because it had errors (see above).'); + print('Kept ${tempDir.path} because it had errors (see above).'); print('-------8<-------'); int number = 1; for (String line in buffer) { @@ -295,10 +295,9 @@ dependencies: print('-------8<-------'); } else { try { - temp.deleteSync(recursive: true); + tempDir.deleteSync(recursive: true); } on FileSystemException catch (e) { - // ignore errors deleting the temporary directory - print('Ignored exception during tearDown: $e'); + print('Failed to delete ${tempDir.path}: $e'); } } } diff --git a/dev/bots/prepare_package.dart b/dev/bots/prepare_package.dart index d323f877f2e..cbaf1e2584a 100644 --- a/dev/bots/prepare_package.dart +++ b/dev/bots/prepare_package.dart @@ -640,7 +640,7 @@ Future main(List argList) async { Directory tempDir; bool removeTempDir = false; if (args['temp_dir'] == null || args['temp_dir'].isEmpty) { - tempDir = Directory.systemTemp.createTempSync('flutter_'); + tempDir = Directory.systemTemp.createTempSync('flutter_package.'); removeTempDir = true; } else { tempDir = new Directory(args['temp_dir']); diff --git a/dev/bots/test.dart b/dev/bots/test.dart index 09e66f5f79e..61e3c049c34 100644 --- a/dev/bots/test.dart +++ b/dev/bots/test.dart @@ -191,7 +191,7 @@ Future _analyzeRepo() async { await _checkForTrailingSpaces(); // Try analysis against a big version of the gallery; generate into a temporary directory. - final String outDir = Directory.systemTemp.createTempSync('mega_gallery').path; + final Directory outDir = Directory.systemTemp.createTempSync('flutter_mega_gallery.'); try { await _runCommand(dart, @@ -199,17 +199,13 @@ Future _analyzeRepo() async { '--preview-dart-2', path.join(flutterRoot, 'dev', 'tools', 'mega_gallery.dart'), '--out', - outDir, + outDir.path, ], workingDirectory: flutterRoot, ); - await _runFlutterAnalyze(outDir, options: ['--watch', '--benchmark']); + await _runFlutterAnalyze(outDir.path, options: ['--watch', '--benchmark']); } finally { - try { - new Directory(outDir).deleteSync(recursive: true); - } catch (e) { - // ignore - } + outDir.deleteSync(recursive: true); } print('${bold}DONE: Analysis successful.$reset'); diff --git a/dev/bots/test/common.dart b/dev/bots/test/common.dart index b36d043b0ad..7638adba378 100644 --- a/dev/bots/test/common.dart +++ b/dev/bots/test/common.dart @@ -2,6 +2,8 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. +import 'dart:io'; + import 'package:test/test.dart' hide TypeMatcher, isInstanceOf; import 'package:test/test.dart' as test_package show TypeMatcher; @@ -12,3 +14,14 @@ export 'package:test/test.dart' hide TypeMatcher, isInstanceOf; /// A matcher that compares the type of the actual value to the type argument T. Matcher isInstanceOf() => new test_package.TypeMatcher(); // ignore: prefer_const_constructors, https://github.com/dart-lang/sdk/issues/32544 + +void tryToDelete(Directory directory) { + // This should not be necessary, but it turns out that + // on Windows it's common for deletions to fail due to + // bogus (we think) "access denied" errors. + try { + directory.deleteSync(recursive: true); + } on FileSystemException catch (error) { + print('Failed to delete ${directory.path}: $error'); + } +} diff --git a/dev/bots/test/prepare_package_test.dart b/dev/bots/test/prepare_package_test.dart index bfeb9e4e9cd..1da66ea592a 100644 --- a/dev/bots/test/prepare_package_test.dart +++ b/dev/bots/test/prepare_package_test.dart @@ -67,7 +67,7 @@ void main() { }); group('ArchiveCreator for $platformName', () { ArchiveCreator creator; - Directory tmpDir; + Directory tempDir; Directory flutterDir; FakeProcessManager processManager; final List> args = >[]; @@ -82,12 +82,12 @@ void main() { processManager = new FakeProcessManager(); args.clear(); namedArgs.clear(); - tmpDir = await Directory.systemTemp.createTemp('flutter_'); - flutterDir = new Directory(path.join(tmpDir.path, 'flutter')); + tempDir = Directory.systemTemp.createTempSync('flutter_prepage_package_test.'); + flutterDir = new Directory(path.join(tempDir.path, 'flutter')); flutterDir.createSync(recursive: true); creator = new ArchiveCreator( - tmpDir, - tmpDir, + tempDir, + tempDir, testRef, Branch.dev, processManager: processManager, @@ -99,16 +99,11 @@ void main() { }); tearDown(() async { - // On Windows, the directory is locked and not able to be deleted yet. So - // we just leave some (very small, because we're not actually building - // archives here) trash around to be deleted at the next reboot. - if (!platform.isWindows) { - await tmpDir.delete(recursive: true); - } + tryToDelete(tempDir); }); test('sets PUB_CACHE properly', () async { - final String createBase = path.join(tmpDir.absolute.path, 'create_'); + final String createBase = path.join(tempDir.absolute.path, 'create_'); final Map> calls = >{ 'git clone -b dev https://chromium.googlesource.com/external/github.com/flutter/flutter': null, 'git reset --hard $testRef': null, @@ -116,7 +111,7 @@ void main() { 'git describe --tags --abbrev=0': [new ProcessResult(0, 0, 'v1.2.3', '')], }; if (platform.isWindows) { - calls['7za x ${path.join(tmpDir.path, 'mingit.zip')}'] = null; + calls['7za x ${path.join(tempDir.path, 'mingit.zip')}'] = null; } calls.addAll(>{ '$flutter doctor': null, @@ -128,7 +123,7 @@ void main() { '$flutter create --template=plugin ${createBase}plugin': null, 'git clean -f -X **/.packages': null, }); - final String archiveName = path.join(tmpDir.absolute.path, + final String archiveName = path.join(tempDir.absolute.path, 'flutter_${platformName}_v1.2.3-dev${platform.isLinux ? '.tar.xz' : '.zip'}'); if (platform.isWindows) { calls['7za a -tzip -mx=9 $archiveName flutter'] = null; @@ -151,7 +146,7 @@ void main() { }); test('calls the right commands for archive output', () async { - final String createBase = path.join(tmpDir.absolute.path, 'create_'); + final String createBase = path.join(tempDir.absolute.path, 'create_'); final Map> calls = >{ 'git clone -b dev https://chromium.googlesource.com/external/github.com/flutter/flutter': null, 'git reset --hard $testRef': null, @@ -159,7 +154,7 @@ void main() { 'git describe --tags --abbrev=0': [new ProcessResult(0, 0, 'v1.2.3', '')], }; if (platform.isWindows) { - calls['7za x ${path.join(tmpDir.path, 'mingit.zip')}'] = null; + calls['7za x ${path.join(tempDir.path, 'mingit.zip')}'] = null; } calls.addAll(>{ '$flutter doctor': null, @@ -171,7 +166,7 @@ void main() { '$flutter create --template=plugin ${createBase}plugin': null, 'git clean -f -X **/.packages': null, }); - final String archiveName = path.join(tmpDir.absolute.path, + final String archiveName = path.join(tempDir.absolute.path, 'flutter_${platformName}_v1.2.3-dev${platform.isLinux ? '.tar.xz' : '.zip'}'); if (platform.isWindows) { calls['7za a -tzip -mx=9 $archiveName flutter'] = null; @@ -182,8 +177,8 @@ void main() { } processManager.fakeResults = calls; creator = new ArchiveCreator( - tmpDir, - tmpDir, + tempDir, + tempDir, testRef, Branch.dev, processManager: processManager, @@ -214,17 +209,11 @@ void main() { setUp(() async { processManager = new FakeProcessManager(); - tempDir = await Directory.systemTemp.createTemp('flutter_'); - tempDir.createSync(); + tempDir = Directory.systemTemp.createTempSync('flutter_prepage_package_test.'); }); tearDown(() async { - // On Windows, the directory is locked and not able to be deleted yet. So - // we just leave some (very small, because we're not actually building - // archives here) trash around to be deleted at the next reboot. - if (!platform.isWindows) { - await tempDir.delete(recursive: true); - } + tryToDelete(tempDir); }); test('calls the right processes', () async { diff --git a/dev/devicelab/bin/tasks/gradle_plugin_test.dart b/dev/devicelab/bin/tasks/gradle_plugin_test.dart index 70eacefdb67..7e218189f8f 100644 --- a/dev/devicelab/bin/tasks/gradle_plugin_test.dart +++ b/dev/devicelab/bin/tasks/gradle_plugin_test.dart @@ -14,25 +14,25 @@ String errorMessage; /// Runs the given [testFunction] on a freshly generated Flutter project. Future runProjectTest(Future testFunction(FlutterProject project)) async { - final Directory tmp = await Directory.systemTemp.createTemp('gradle'); - final FlutterProject project = await FlutterProject.create(tmp, 'hello'); + final Directory tempDir = Directory.systemTemp.createTempSync('flutter_devicelab_gradle_plugin_test.'); + final FlutterProject project = await FlutterProject.create(tempDir, 'hello'); try { await testFunction(project); } finally { - project.parent.deleteSync(recursive: true); + rmTree(tempDir); } } /// Runs the given [testFunction] on a freshly generated Flutter plugin project. Future runPluginProjectTest(Future testFunction(FlutterPluginProject pluginProject)) async { - final Directory tmp = await Directory.systemTemp.createTemp('gradle'); - final FlutterPluginProject pluginProject = await FlutterPluginProject.create(tmp, 'aaa'); + final Directory tempDir = Directory.systemTemp.createTempSync('flutter_devicelab_gradle_plugin_test.'); + final FlutterPluginProject pluginProject = await FlutterPluginProject.create(tempDir, 'aaa'); try { await testFunction(pluginProject); } finally { - pluginProject.parent.deleteSync(recursive: true); + rmTree(tempDir); } } diff --git a/dev/devicelab/bin/tasks/module_test.dart b/dev/devicelab/bin/tasks/module_test.dart index 75ee57a2935..88a35fe8cde 100644 --- a/dev/devicelab/bin/tasks/module_test.dart +++ b/dev/devicelab/bin/tasks/module_test.dart @@ -4,6 +4,7 @@ import 'dart:async'; import 'dart:io'; + import 'package:flutter_devicelab/framework/framework.dart'; import 'package:flutter_devicelab/framework/utils.dart'; import 'package:path/path.dart' as path; @@ -22,9 +23,9 @@ Future main() async { section('Create Flutter module project'); - final Directory directory = await Directory.systemTemp.createTemp('module'); + final Directory tempDir = Directory.systemTemp.createTempSync('flutter_module_test.'); try { - await inDirectory(directory, () async { + await inDirectory(tempDir, () async { await flutter( 'create', options: ['--org', 'io.flutter.devicelab', '-t', 'module', 'hello'], @@ -33,14 +34,14 @@ Future main() async { section('Add plugins'); - final File pubspec = new File(path.join(directory.path, 'hello', 'pubspec.yaml')); + final File pubspec = new File(path.join(tempDir.path, 'hello', 'pubspec.yaml')); String content = await pubspec.readAsString(); content = content.replaceFirst( '\ndependencies:\n', '\ndependencies:\n battery:\n package_info:\n', ); await pubspec.writeAsString(content, flush: true); - await inDirectory(new Directory(path.join(directory.path, 'hello')), () async { + await inDirectory(new Directory(path.join(tempDir.path, 'hello')), () async { await flutter( 'packages', options: ['get'], @@ -49,7 +50,7 @@ Future main() async { section('Build Flutter module library archive'); - await inDirectory(new Directory(path.join(directory.path, 'hello', '.android')), () async { + await inDirectory(new Directory(path.join(tempDir.path, 'hello', '.android')), () async { await exec( './gradlew', ['flutter:assembleDebug'], @@ -58,7 +59,7 @@ Future main() async { }); final bool aarBuilt = exists(new File(path.join( - directory.path, + tempDir.path, 'hello', '.android', 'Flutter', @@ -74,7 +75,7 @@ Future main() async { section('Build ephemeral host app'); - await inDirectory(new Directory(path.join(directory.path, 'hello')), () async { + await inDirectory(new Directory(path.join(tempDir.path, 'hello')), () async { await flutter( 'build', options: ['apk'], @@ -82,7 +83,7 @@ Future main() async { }); final bool ephemeralHostApkBuilt = exists(new File(path.join( - directory.path, + tempDir.path, 'hello', 'build', 'host', @@ -98,13 +99,13 @@ Future main() async { section('Clean build'); - await inDirectory(new Directory(path.join(directory.path, 'hello')), () async { + await inDirectory(new Directory(path.join(tempDir.path, 'hello')), () async { await flutter('clean'); }); section('Materialize host app'); - await inDirectory(new Directory(path.join(directory.path, 'hello')), () async { + await inDirectory(new Directory(path.join(tempDir.path, 'hello')), () async { await flutter( 'materialize', options: ['android'], @@ -113,7 +114,7 @@ Future main() async { section('Build materialized host app'); - await inDirectory(new Directory(path.join(directory.path, 'hello')), () async { + await inDirectory(new Directory(path.join(tempDir.path, 'hello')), () async { await flutter( 'build', options: ['apk'], @@ -121,7 +122,7 @@ Future main() async { }); final bool materializedHostApkBuilt = exists(new File(path.join( - directory.path, + tempDir.path, 'hello', 'build', 'host', @@ -137,18 +138,18 @@ Future main() async { section('Add to Android app'); - final Directory hostApp = new Directory(path.join(directory.path, 'hello_host_app')); + final Directory hostApp = new Directory(path.join(tempDir.path, 'hello_host_app')); mkdir(hostApp); recursiveCopy( new Directory(path.join(flutterDirectory.path, 'dev', 'integration_tests', 'android_host_app')), hostApp, ); copy( - new File(path.join(directory.path, 'hello', '.android', 'gradlew')), + new File(path.join(tempDir.path, 'hello', '.android', 'gradlew')), hostApp, ); copy( - new File(path.join(directory.path, 'hello', '.android', 'gradle', 'wrapper', 'gradle-wrapper.jar')), + new File(path.join(tempDir.path, 'hello', '.android', 'gradle', 'wrapper', 'gradle-wrapper.jar')), new Directory(path.join(hostApp.path, 'gradle', 'wrapper')), ); @@ -177,7 +178,7 @@ Future main() async { } catch (e) { return new TaskResult.failure(e.toString()); } finally { - rmTree(directory); + rmTree(tempDir); } }); } diff --git a/dev/devicelab/lib/framework/utils.dart b/dev/devicelab/lib/framework/utils.dart index 3263000b70d..65b09235047 100644 --- a/dev/devicelab/lib/framework/utils.dart +++ b/dev/devicelab/lib/framework/utils.dart @@ -77,15 +77,23 @@ void fail(String message) { throw new BuildFailedError(message); } -void rm(FileSystemEntity entity) { - if (entity.existsSync()) - entity.deleteSync(); +// Remove the given file or directory. +void rm(FileSystemEntity entity, { bool recursive = false}) { + if (entity.existsSync()) { + // This should not be necessary, but it turns out that + // on Windows it's common for deletions to fail due to + // bogus (we think) "access denied" errors. + try { + entity.deleteSync(recursive: recursive); + } on FileSystemException catch (error) { + print('Failed to delete ${entity.path}: $error'); + } + } } /// Remove recursively. void rmTree(FileSystemEntity entity) { - if (entity.existsSync()) - entity.deleteSync(recursive: true); + rm(entity, recursive: true); } List ls(Directory directory) => directory.listSync(); @@ -414,7 +422,7 @@ Future getFlutter(String revision) async { section('Get Flutter!'); if (exists(flutterDirectory)) { - rmTree(flutterDirectory); + flutterDirectory.deleteSync(recursive: true); } await inDirectory(flutterDirectory.parent, () async { diff --git a/dev/devicelab/lib/tasks/perf_tests.dart b/dev/devicelab/lib/tasks/perf_tests.dart index 0d31ef63ff3..cea0ca330fb 100644 --- a/dev/devicelab/lib/tasks/perf_tests.dart +++ b/dev/devicelab/lib/tasks/perf_tests.dart @@ -73,8 +73,7 @@ TaskFunction createBasicMaterialCompileTest() { const String sampleAppName = 'sample_flutter_app'; final Directory sampleDir = dir('${Directory.systemTemp.path}/$sampleAppName'); - if (await sampleDir.exists()) - rmTree(sampleDir); + rmTree(sampleDir); await inDirectory(Directory.systemTemp, () async { await flutter('create', options: [sampleAppName]); diff --git a/dev/devicelab/lib/tasks/plugin_tests.dart b/dev/devicelab/lib/tasks/plugin_tests.dart index 3f032fa31e3..556d99c7567 100644 --- a/dev/devicelab/lib/tasks/plugin_tests.dart +++ b/dev/devicelab/lib/tasks/plugin_tests.dart @@ -33,23 +33,24 @@ class PluginTest { Future call() async { section('Create Flutter project'); - final Directory tmp = await Directory.systemTemp.createTemp('plugin'); - final FlutterProject project = await FlutterProject.create(tmp, options); - if (buildTarget == 'ios') { - await prepareProvisioningCertificates(project.rootPath); - } + final Directory tempDir = Directory.systemTemp.createTempSync('flutter_devicelab_plugin_test.'); try { - section('Add plugin'); - await project.addPlugin('path_provider'); - - section('Build'); - await project.build(buildTarget); - + final FlutterProject project = await FlutterProject.create(tempDir, options); + try { + if (buildTarget == 'ios') + await prepareProvisioningCertificates(project.rootPath); + section('Add plugin'); + await project.addPlugin('path_provider'); + section('Build'); + await project.build(buildTarget); + } finally { + await project.delete(); + } return new TaskResult.success(null); } catch (e) { return new TaskResult.failure(e.toString()); } finally { - await project.delete(); + rmTree(tempDir); } } } @@ -97,9 +98,9 @@ class FlutterProject { ['--stop'], canFail: true, ); - // TODO(mravn): Investigating if flakiness is timing dependent. + // TODO(ianh): Investigating if flakiness is timing dependent. await new Future.delayed(const Duration(seconds: 10)); } - await parent.delete(recursive: true); + rmTree(parent); } } diff --git a/dev/tools/dartdoc.dart b/dev/tools/dartdoc.dart index f672ef44aa1..4ee08177aa2 100644 --- a/dev/tools/dartdoc.dart +++ b/dev/tools/dartdoc.dart @@ -244,7 +244,7 @@ void createIndexAndCleanup() { void removeOldFlutterDocsDir() { try { new Directory('$kDocRoot/flutter').deleteSync(recursive: true); - } catch (e) { + } on FileSystemException { // If the directory does not exist, that's OK. } } diff --git a/packages/flutter_driver/test/common.dart b/packages/flutter_driver/test/common.dart index b36d043b0ad..dbc658f9499 100644 --- a/packages/flutter_driver/test/common.dart +++ b/packages/flutter_driver/test/common.dart @@ -2,13 +2,26 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. +import 'dart:io'; + import 'package:test/test.dart' hide TypeMatcher, isInstanceOf; import 'package:test/test.dart' as test_package show TypeMatcher; export 'package:test/test.dart' hide TypeMatcher, isInstanceOf; // Defines a 'package:test' shim. -// TODO(ianh): Remove this file once https://github.com/dart-lang/matcher/issues/98 is fixed +// TODO(ianh): Clean this up once https://github.com/dart-lang/matcher/issues/98 is fixed /// A matcher that compares the type of the actual value to the type argument T. Matcher isInstanceOf() => new test_package.TypeMatcher(); // ignore: prefer_const_constructors, https://github.com/dart-lang/sdk/issues/32544 + +void tryToDelete(Directory directory) { + // This should not be necessary, but it turns out that + // on Windows it's common for deletions to fail due to + // bogus (we think) "access denied" errors. + try { + directory.deleteSync(recursive: true); + } on FileSystemException catch (error) { + print('Failed to delete ${directory.path}: $error'); + } +} \ No newline at end of file diff --git a/packages/flutter_driver/test/src/timeline_summary_test.dart b/packages/flutter_driver/test/src/timeline_summary_test.dart index 166fdbd425a..96b38b184a0 100644 --- a/packages/flutter_driver/test/src/timeline_summary_test.dart +++ b/packages/flutter_driver/test/src/timeline_summary_test.dart @@ -287,11 +287,11 @@ void main() { setUp(() { useMemoryFileSystemForTesting(); - tempDir = fs.systemTempDirectory.createTempSync('flutter_driver_test'); + tempDir = fs.systemTempDirectory.createTempSync('flutter_driver_test.'); }); tearDown(() { - tempDir.deleteSync(recursive: true); + tryToDelete(tempDir); restoreFileSystem(); }); diff --git a/packages/flutter_tools/bin/fuchsia_tester.dart b/packages/flutter_tools/bin/fuchsia_tester.dart index b77017d5e5a..2182f6be3c4 100644 --- a/packages/flutter_tools/bin/fuchsia_tester.dart +++ b/packages/flutter_tools/bin/fuchsia_tester.dart @@ -21,7 +21,7 @@ import 'package:flutter_tools/src/test/coverage_collector.dart'; import 'package:flutter_tools/src/test/runner.dart'; import 'package:flutter_tools/src/usage.dart'; -// Note: this was largely inspired by lib/src/commands/test.dart. +// This was largely inspired by lib/src/commands/test.dart. const String _kOptionPackages = 'packages'; const String _kOptionShell = 'shell'; @@ -71,10 +71,10 @@ Future run(List args) async { .any((String option) => !argResults.options.contains(option))) { throwToolExit('Missing option! All options must be specified.'); } - final Directory tempDirectory = - fs.systemTempDirectory.createTempSync('fuchsia_tester'); + final Directory tempDir = + fs.systemTempDirectory.createTempSync('flutter_fuchsia_tester.'); try { - Cache.flutterRoot = tempDirectory.path; + Cache.flutterRoot = tempDir.path; final Directory testDirectory = fs.directory(argResults[_kOptionTestDirectory]); final File testFile = fs.file(argResults[_kOptionTestFile]); @@ -130,13 +130,13 @@ Future run(List args) async { // collector expects currentDirectory to be the root of the dart // package (i.e. contains lib/ and test/ sub-dirs). fs.currentDirectory = testDirectory.parent; - if (!await - collector.collectCoverageData(argResults[_kOptionCoveragePath])) + if (!await collector.collectCoverageData(argResults[_kOptionCoveragePath])) throwToolExit('Failed to collect coverage data'); } } finally { - tempDirectory.deleteSync(recursive: true); + tempDir.deleteSync(recursive: true); } - // Not sure why this is needed, but main() doesn't seem to exit on its own. + // TODO(ianh): There's apparently some sort of lost async task keeping the + // process open. Remove the next line once that's been resolved. exit(exitCode); } diff --git a/packages/flutter_tools/lib/src/application_package.dart b/packages/flutter_tools/lib/src/application_package.dart index ac7faf5d604..cbe569bb9bb 100644 --- a/packages/flutter_tools/lib/src/application_package.dart +++ b/packages/flutter_tools/lib/src/application_package.dart @@ -175,8 +175,7 @@ abstract class IOSApp extends ApplicationPackage { bundleDir = fs.directory(applicationBinary); } else { // Try to unpack as an ipa. - final Directory tempDir = fs.systemTempDirectory.createTempSync( - 'flutter_app_'); + final Directory tempDir = fs.systemTempDirectory.createTempSync('flutter_app.'); addShutdownHook(() async { await tempDir.delete(recursive: true); }, ShutdownStage.STILL_RECORDING); diff --git a/packages/flutter_tools/lib/src/commands/update_packages.dart b/packages/flutter_tools/lib/src/commands/update_packages.dart index 49f202e6a9f..78e6a8c6b93 100644 --- a/packages/flutter_tools/lib/src/commands/update_packages.dart +++ b/packages/flutter_tools/lib/src/commands/update_packages.dart @@ -215,13 +215,13 @@ class UpdatePackagesCommand extends FlutterCommand { // pub tool will attempt to bring these dependencies up to the most recent // possible versions while honoring all their constraints. final PubDependencyTree tree = new PubDependencyTree(); // object to collect results - final Directory temporaryDirectory = fs.systemTempDirectory.createTempSync('flutter_update_packages_'); + final Directory tempDir = fs.systemTempDirectory.createTempSync('flutter_update_packages.'); try { - final File fakePackage = _pubspecFor(temporaryDirectory); + final File fakePackage = _pubspecFor(tempDir); fakePackage.createSync(); fakePackage.writeAsStringSync(_generateFakePubspec(dependencies.values)); // First we run "pub upgrade" on this generated package: - await pubGet(context: PubContext.updatePackages, directory: temporaryDirectory.path, upgrade: true, checkLastModified: false); + await pubGet(context: PubContext.updatePackages, directory: tempDir.path, upgrade: true, checkLastModified: false); // Then we run "pub deps --style=compact" on the result. We pipe all the // output to tree.fill(), which parses it so that it can create a graph // of all the dependencies so that we can figure out the transitive @@ -230,12 +230,12 @@ class UpdatePackagesCommand extends FlutterCommand { await pub( ['deps', '--style=compact'], context: PubContext.updatePackages, - directory: temporaryDirectory.path, + directory: tempDir.path, filter: tree.fill, retry: false, // errors here are usually fatal since we're not hitting the network ); } finally { - temporaryDirectory.deleteSync(recursive: true); + tempDir.deleteSync(recursive: true); } // The transitive dependency tree for the fake package does not contain diff --git a/packages/flutter_tools/lib/src/ios/mac.dart b/packages/flutter_tools/lib/src/ios/mac.dart index e8890f14956..f9a1e7aba29 100644 --- a/packages/flutter_tools/lib/src/ios/mac.dart +++ b/packages/flutter_tools/lib/src/ios/mac.dart @@ -318,13 +318,11 @@ Future buildXcodeProject({ Status buildSubStatus; Status initialBuildStatus; - Directory scriptOutputPipeTempDirectory; + Directory tempDir; if (logger.supportsColor) { - scriptOutputPipeTempDirectory = fs.systemTempDirectory - .createTempSync('flutter_build_log_pipe'); - final File scriptOutputPipeFile = - scriptOutputPipeTempDirectory.childFile('pipe_to_stdout'); + tempDir = fs.systemTempDirectory.createTempSync('flutter_build_log_pipe.'); + final File scriptOutputPipeFile = tempDir.childFile('pipe_to_stdout'); os.makePipe(scriptOutputPipeFile.path); Future listenToScriptOutputLine() async { @@ -362,7 +360,7 @@ Future buildXcodeProject({ initialBuildStatus?.cancel(); buildStopwatch.stop(); // Free pipe file. - scriptOutputPipeTempDirectory?.deleteSync(recursive: true); + tempDir?.deleteSync(recursive: true); printStatus( 'Xcode build done.', ansiAlternative: 'Xcode build done.'.padRight(kDefaultStatusPadding + 1) diff --git a/packages/flutter_tools/lib/src/runner/flutter_command_runner.dart b/packages/flutter_tools/lib/src/runner/flutter_command_runner.dart index 5c665dfffdb..454fac98439 100644 --- a/packages/flutter_tools/lib/src/runner/flutter_command_runner.dart +++ b/packages/flutter_tools/lib/src/runner/flutter_command_runner.dart @@ -233,13 +233,13 @@ class FlutterCommandRunner extends CommandRunner { if (topLevelResults['bug-report']) { // --bug-report implies --record-to= - final Directory tmp = await const LocalFileSystem() + final Directory tempDir = const LocalFileSystem() .systemTempDirectory - .createTemp('flutter_tools_'); - recordTo = tmp.path; + .createTempSync('flutter_tools_bug_report.'); + recordTo = tempDir.path; // Record the arguments that were used to invoke this runner. - final File manifest = tmp.childFile('MANIFEST.txt'); + final File manifest = tempDir.childFile('MANIFEST.txt'); final StringBuffer buffer = new StringBuffer() ..writeln('# arguments') ..writeln(topLevelResults.arguments) @@ -251,13 +251,14 @@ class FlutterCommandRunner extends CommandRunner { // ZIP the recording up once the recording has been serialized. addShutdownHook(() async { final File zipFile = getUniqueFile(fs.currentDirectory, 'bugreport', 'zip'); - os.zip(tmp, zipFile); + os.zip(tempDir, zipFile); printStatus( - 'Bug report written to ${zipFile.basename}.\n' - 'Note that this bug report contains local paths, device ' - 'identifiers, and log snippets.'); + 'Bug report written to ${zipFile.basename}.\n' + 'Note that this bug report contains local paths, device ' + 'identifiers, and log snippets.' + ); }, ShutdownStage.POST_PROCESS_RECORDING); - addShutdownHook(() => tmp.delete(recursive: true), ShutdownStage.CLEANUP); + addShutdownHook(() => tempDir.delete(recursive: true), ShutdownStage.CLEANUP); } assert(recordTo == null || replayFrom == null); diff --git a/packages/flutter_tools/lib/src/test/coverage_collector.dart b/packages/flutter_tools/lib/src/test/coverage_collector.dart index 461038ca493..3ed1c9dcdd7 100644 --- a/packages/flutter_tools/lib/src/test/coverage_collector.dart +++ b/packages/flutter_tools/lib/src/test/coverage_collector.dart @@ -136,7 +136,7 @@ class CoverageCollector extends TestWatcher { return false; } - final Directory tempDir = fs.systemTempDirectory.createTempSync('flutter_tools'); + final Directory tempDir = fs.systemTempDirectory.createTempSync('flutter_tools_test_coverage.'); try { final File sourceFile = coverageFile.copySync(fs.path.join(tempDir.path, 'lcov.source.info')); final ProcessResult result = processManager.runSync([ diff --git a/packages/flutter_tools/lib/src/test/flutter_platform.dart b/packages/flutter_tools/lib/src/test/flutter_platform.dart index f219c08ea3f..f5b56bb75f5 100644 --- a/packages/flutter_tools/lib/src/test/flutter_platform.dart +++ b/packages/flutter_tools/lib/src/test/flutter_platform.dart @@ -203,7 +203,7 @@ class _Compiler { // Incremental compilation requests done for each test copy that file away // for independent execution. final Directory outputDillDirectory = fs.systemTempDirectory - .createTempSync('output_dill'); + .createTempSync('flutter_test_compiler.'); final File outputDill = outputDillDirectory.childFile('output.dill'); bool suppressOutput = false; @@ -656,15 +656,15 @@ class _FlutterPlatform extends PlatformPlugin { String _createListenerDart(List<_Finalizer> finalizers, int ourTestCount, String testPath, HttpServer server) { // Prepare a temporary directory to store the Dart file that will talk to us. - final Directory temporaryDirectory = fs.systemTempDirectory - .createTempSync('dart_test_listener'); + final Directory tempDir = fs.systemTempDirectory + .createTempSync('flutter_test_listener.'); finalizers.add(() async { printTrace('test $ourTestCount: deleting temporary directory'); - temporaryDirectory.deleteSync(recursive: true); + tempDir.deleteSync(recursive: true); }); // Prepare the Dart file that will talk to us and start the test. - final File listenerFile = fs.file('${temporaryDirectory.path}/listener.dart'); + final File listenerFile = fs.file('${tempDir.path}/listener.dart'); listenerFile.createSync(); listenerFile.writeAsStringSync(_generateTestMain( testUrl: fs.path.toUri(fs.path.absolute(testPath)), @@ -683,7 +683,7 @@ class _FlutterPlatform extends PlatformPlugin { // bundlePath needs to point to a folder with `platform.dill` file. final Directory tempBundleDirectory = fs.systemTempDirectory - .createTempSync('flutter_bundle_directory'); + .createTempSync('flutter_test_bundle.'); finalizers.add(() async { printTrace( 'test $ourTestCount: deleting temporary bundle directory'); @@ -757,7 +757,7 @@ class _FlutterPlatform extends PlatformPlugin { sb.writeln(' /var/cache/fontconfig'); sb.writeln(''); - final Directory fontsDir = fs.systemTempDirectory.createTempSync('flutter_fonts'); + final Directory fontsDir = fs.systemTempDirectory.createTempSync('flutter_test_fonts.'); _cachedFontConfig = fs.file('${fontsDir.path}/fonts.conf'); _cachedFontConfig.createSync(); _cachedFontConfig.writeAsStringSync(sb.toString()); diff --git a/packages/flutter_tools/test/analytics_test.dart b/packages/flutter_tools/test/analytics_test.dart index b61cd35b024..f6f2b759455 100644 --- a/packages/flutter_tools/test/analytics_test.dart +++ b/packages/flutter_tools/test/analytics_test.dart @@ -21,7 +21,7 @@ import 'src/context.dart'; void main() { group('analytics', () { - Directory temp; + Directory tempDir; setUpAll(() { Cache.disableLocking(); @@ -29,11 +29,11 @@ void main() { setUp(() { Cache.flutterRoot = '../..'; - temp = fs.systemTempDirectory.createTempSync('flutter_tools'); + tempDir = fs.systemTempDirectory.createTempSync('flutter_tools_analytics_test.'); }); tearDown(() { - temp.deleteSync(recursive: true); + tryToDelete(tempDir); }); // Ensure we don't send anything when analytics is disabled. @@ -42,11 +42,11 @@ void main() { flutterUsage.onSend.listen((Map data) => count++); flutterUsage.enabled = false; - await createProject(temp); + await createProject(tempDir); expect(count, 0); flutterUsage.enabled = true; - await createProject(temp); + await createProject(tempDir); expect(count, flutterUsage.isFirstRun ? 0 : 2); count = 0; @@ -57,7 +57,7 @@ void main() { expect(count, 0); }, overrides: { FlutterVersion: () => new FlutterVersion(const Clock()), - Usage: () => new Usage(configDirOverride: temp.path), + Usage: () => new Usage(configDirOverride: tempDir.path), }); // Ensure we don't send for the 'flutter config' command. @@ -76,7 +76,7 @@ void main() { expect(count, 0); }, overrides: { FlutterVersion: () => new FlutterVersion(const Clock()), - Usage: () => new Usage(configDirOverride: temp.path), + Usage: () => new Usage(configDirOverride: tempDir.path), }); }); @@ -151,9 +151,14 @@ void main() { }); group('analytics bots', () { - Directory temp; + Directory tempDir; + setUp(() { - temp = fs.systemTempDirectory.createTempSync('flutter_tools'); + tempDir = fs.systemTempDirectory.createTempSync('flutter_tools_analytics_bots_test.'); + }); + + tearDown(() { + tryToDelete(tempDir); }); testUsingContext('don\'t send on bots', () async { @@ -166,7 +171,7 @@ void main() { Usage: () => new Usage( settingsName: 'flutter_bot_test', versionOverride: 'dev/unknown', - configDirOverride: temp.path, + configDirOverride: tempDir.path, ), }); @@ -181,7 +186,7 @@ void main() { Usage: () => new Usage( settingsName: 'flutter_bot_test', versionOverride: 'dev/unknown', - configDirOverride: temp.path, + configDirOverride: tempDir.path, ), }); }); diff --git a/packages/flutter_tools/test/android/android_sdk_test.dart b/packages/flutter_tools/test/android/android_sdk_test.dart index 179db332772..870a0bf81b5 100644 --- a/packages/flutter_tools/test/android/android_sdk_test.dart +++ b/packages/flutter_tools/test/android/android_sdk_test.dart @@ -30,8 +30,10 @@ void main() { Directory sdkDir; tearDown(() { - sdkDir?.deleteSync(recursive: true); - sdkDir = null; + if (sdkDir != null) { + tryToDelete(sdkDir); + sdkDir = null; + } }); testUsingContext('parse sdk', () { diff --git a/packages/flutter_tools/test/android/android_workflow_test.dart b/packages/flutter_tools/test/android/android_workflow_test.dart index 48831650f3a..70bc842e157 100644 --- a/packages/flutter_tools/test/android/android_workflow_test.dart +++ b/packages/flutter_tools/test/android/android_workflow_test.dart @@ -39,7 +39,6 @@ void main() { testUsingContext('licensesAccepted throws if cannot run sdkmanager', () async { processManager.succeed = false; - MockAndroidSdk.createSdkDirectory(); when(sdk.sdkManagerPath).thenReturn('/foo/bar/sdkmanager'); final AndroidWorkflow androidWorkflow = new AndroidWorkflow(); expect(androidWorkflow.licensesAccepted, throwsToolExit()); @@ -52,7 +51,6 @@ void main() { }); testUsingContext('licensesAccepted handles garbage/no output', () async { - MockAndroidSdk.createSdkDirectory(); when(sdk.sdkManagerPath).thenReturn('/foo/bar/sdkmanager'); final AndroidWorkflow androidWorkflow = new AndroidWorkflow(); final LicensesAccepted result = await androidWorkflow.licensesAccepted; @@ -68,7 +66,6 @@ void main() { }); testUsingContext('licensesAccepted works for all licenses accepted', () async { - MockAndroidSdk.createSdkDirectory(); when(sdk.sdkManagerPath).thenReturn('/foo/bar/sdkmanager'); processManager.processFactory = processMetaFactory([ '[=======================================] 100% Computing updates... ', @@ -87,7 +84,6 @@ void main() { }); testUsingContext('licensesAccepted works for some licenses accepted', () async { - MockAndroidSdk.createSdkDirectory(); when(sdk.sdkManagerPath).thenReturn('/foo/bar/sdkmanager'); processManager.processFactory = processMetaFactory([ '[=======================================] 100% Computing updates... ', @@ -107,7 +103,6 @@ void main() { }); testUsingContext('licensesAccepted works for no licenses accepted', () async { - MockAndroidSdk.createSdkDirectory(); when(sdk.sdkManagerPath).thenReturn('/foo/bar/sdkmanager'); processManager.processFactory = processMetaFactory([ '[=======================================] 100% Computing updates... ', @@ -127,7 +122,6 @@ void main() { }); testUsingContext('runLicenseManager succeeds for version >= 26', () async { - MockAndroidSdk.createSdkDirectory(); when(sdk.sdkManagerPath).thenReturn('/foo/bar/sdkmanager'); when(sdk.sdkManagerVersion).thenReturn('26.0.0'); @@ -141,7 +135,6 @@ void main() { }); testUsingContext('runLicenseManager errors for version < 26', () async { - MockAndroidSdk.createSdkDirectory(); when(sdk.sdkManagerPath).thenReturn('/foo/bar/sdkmanager'); when(sdk.sdkManagerVersion).thenReturn('25.0.0'); @@ -155,7 +148,6 @@ void main() { }); testUsingContext('runLicenseManager errors correctly for null version', () async { - MockAndroidSdk.createSdkDirectory(); when(sdk.sdkManagerPath).thenReturn('/foo/bar/sdkmanager'); when(sdk.sdkManagerVersion).thenReturn(null); @@ -169,7 +161,6 @@ void main() { }); testUsingContext('runLicenseManager errors when sdkmanager is not found', () async { - MockAndroidSdk.createSdkDirectory(); when(sdk.sdkManagerPath).thenReturn('/foo/bar/sdkmanager'); processManager.succeed = false; diff --git a/packages/flutter_tools/test/artifacts_test.dart b/packages/flutter_tools/test/artifacts_test.dart index 77677361322..ac1c8fe776a 100644 --- a/packages/flutter_tools/test/artifacts_test.dart +++ b/packages/flutter_tools/test/artifacts_test.dart @@ -18,12 +18,12 @@ void main() { CachedArtifacts artifacts; setUp(() { - tempDir = fs.systemTempDirectory.createTempSync('flutter_temp'); + tempDir = fs.systemTempDirectory.createTempSync('flutter_tools_artifacts_test_cached.'); artifacts = new CachedArtifacts(); }); tearDown(() { - tempDir.deleteSync(recursive: true); + tryToDelete(tempDir); }); testUsingContext('getArtifactPath', () { @@ -69,7 +69,7 @@ void main() { LocalEngineArtifacts artifacts; setUp(() { - tempDir = fs.systemTempDirectory.createTempSync('flutter_temp'); + tempDir = fs.systemTempDirectory.createTempSync('flutter_tools_artifacts_test_local.'); artifacts = new LocalEngineArtifacts(tempDir.path, fs.path.join(tempDir.path, 'out', 'android_debug_unopt'), fs.path.join(tempDir.path, 'out', 'host_debug_unopt'), @@ -77,7 +77,7 @@ void main() { }); tearDown(() { - tempDir.deleteSync(recursive: true); + tryToDelete(tempDir); }); testUsingContext('getArtifactPath', () { 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 dc7c135eb19..4804dba56eb 100644 --- a/packages/flutter_tools/test/asset_bundle_package_fonts_test.dart +++ b/packages/flutter_tools/test/asset_bundle_package_fonts_test.dart @@ -95,20 +95,14 @@ $fontsSection Directory oldCurrentDir; setUp(() async { - tempDir = await fs.systemTempDirectory.createTemp('asset_bundle_tests'); + tempDir = fs.systemTempDirectory.createTempSync('flutter_asset_bundle_test.'); oldCurrentDir = fs.currentDirectory; fs.currentDirectory = tempDir; }); tearDown(() { fs.currentDirectory = oldCurrentDir; - try { - tempDir?.deleteSync(recursive: true); - tempDir = null; - } on FileSystemException catch (e) { - // Do nothing, windows sometimes has trouble deleting. - print('Ignored exception during tearDown: $e'); - } + tryToDelete(tempDir); }); group('AssetBundle fonts from packages', () { diff --git a/packages/flutter_tools/test/asset_bundle_package_test.dart b/packages/flutter_tools/test/asset_bundle_package_test.dart index 624607698a5..4361bba3ba6 100644 --- a/packages/flutter_tools/test/asset_bundle_package_test.dart +++ b/packages/flutter_tools/test/asset_bundle_package_test.dart @@ -106,20 +106,14 @@ $assetsSection Directory oldCurrentDir; setUp(() async { - tempDir = await fs.systemTempDirectory.createTemp('asset_bundle_tests'); + tempDir = fs.systemTempDirectory.createTempSync('flutter_asset_bundle_test.'); oldCurrentDir = fs.currentDirectory; fs.currentDirectory = tempDir; }); tearDown(() { fs.currentDirectory = oldCurrentDir; - try { - tempDir?.deleteSync(recursive: true); - tempDir = null; - } on FileSystemException catch (e) { - // Do nothing, windows sometimes has trouble deleting. - print('Ignored exception during tearDown: $e'); - } + tryToDelete(tempDir); }); group('AssetBundle assets from packages', () { diff --git a/packages/flutter_tools/test/asset_bundle_test.dart b/packages/flutter_tools/test/asset_bundle_test.dart index e4fdf8ee188..afafc7171c0 100644 --- a/packages/flutter_tools/test/asset_bundle_test.dart +++ b/packages/flutter_tools/test/asset_bundle_test.dart @@ -25,20 +25,14 @@ void main() { Directory oldCurrentDir; setUp(() async { - tempDir = await fs.systemTempDirectory.createTemp('asset_bundle_tests'); + tempDir = fs.systemTempDirectory.createTempSync('flutter_asset_bundle_test.'); oldCurrentDir = fs.currentDirectory; fs.currentDirectory = tempDir; }); tearDown(() { fs.currentDirectory = oldCurrentDir; - try { - tempDir?.deleteSync(recursive: true); - tempDir = null; - } on FileSystemException catch (e) { - // Do nothing, windows sometimes has trouble deleting. - print('Ignored exception during tearDown: $e'); - } + tryToDelete(tempDir); }); testUsingContext('nonempty', () async { diff --git a/packages/flutter_tools/test/asset_bundle_variant_test.dart b/packages/flutter_tools/test/asset_bundle_variant_test.dart index e58f0e7f0d6..afdbcc6a90b 100644 --- a/packages/flutter_tools/test/asset_bundle_variant_test.dart +++ b/packages/flutter_tools/test/asset_bundle_variant_test.dart @@ -20,20 +20,14 @@ void main() { Directory oldCurrentDir; setUp(() async { - tempDir = await fs.systemTempDirectory.createTemp('asset_bundle_tests'); + tempDir = fs.systemTempDirectory.createTempSync('flutter_asset_bundle_variant_test.'); oldCurrentDir = fs.currentDirectory; fs.currentDirectory = tempDir; }); tearDown(() { fs.currentDirectory = oldCurrentDir; - try { - tempDir?.deleteSync(recursive: true); - tempDir = null; - } on FileSystemException catch (e) { - // Do nothing, windows sometimes has trouble deleting. - print('Ignored exception during tearDown: $e'); - } + tryToDelete(tempDir); }); group('AssetBundle asset variants', () { diff --git a/packages/flutter_tools/test/base/os_utils_test.dart b/packages/flutter_tools/test/base/os_utils_test.dart index 5f6987c26b6..27c98497073 100644 --- a/packages/flutter_tools/test/base/os_utils_test.dart +++ b/packages/flutter_tools/test/base/os_utils_test.dart @@ -11,18 +11,18 @@ import '../src/context.dart'; void main() { group('OperatingSystemUtils', () { - Directory temp; + Directory tempDir; setUp(() { - temp = fs.systemTempDirectory.createTempSync('flutter_tools'); + tempDir = fs.systemTempDirectory.createTempSync('flutter_tools_os_utils_test.'); }); tearDown(() { - temp.deleteSync(recursive: true); + tryToDelete(tempDir); }); testUsingContext('makeExecutable', () async { - final File file = fs.file(fs.path.join(temp.path, 'foo.script')); + final File file = fs.file(fs.path.join(tempDir.path, 'foo.script')); file.writeAsStringSync('hello world'); os.makeExecutable(file); diff --git a/packages/flutter_tools/test/commands/analyze_continuously_test.dart b/packages/flutter_tools/test/commands/analyze_continuously_test.dart index dfb1972edf5..018dc85595e 100644 --- a/packages/flutter_tools/test/commands/analyze_continuously_test.dart +++ b/packages/flutter_tools/test/commands/analyze_continuously_test.dart @@ -20,11 +20,11 @@ void main() { setUp(() { FlutterCommandRunner.initFlutterRoot(); - tempDir = fs.systemTempDirectory.createTempSync('analysis_test'); + tempDir = fs.systemTempDirectory.createTempSync('flutter_analysis_test.'); }); tearDown(() { - tempDir?.deleteSync(recursive: true); + tryToDelete(tempDir); return server?.dispose(); }); diff --git a/packages/flutter_tools/test/commands/analyze_once_test.dart b/packages/flutter_tools/test/commands/analyze_once_test.dart index 37360820ba1..3b0ee80b4a6 100644 --- a/packages/flutter_tools/test/commands/analyze_once_test.dart +++ b/packages/flutter_tools/test/commands/analyze_once_test.dart @@ -28,18 +28,13 @@ void main() { setUpAll(() { Cache.disableLocking(); - tempDir = fs.systemTempDirectory.createTempSync('analyze_once_test_').absolute; + tempDir = fs.systemTempDirectory.createTempSync('flutter_analyze_once_test_1.').absolute; projectPath = fs.path.join(tempDir.path, 'flutter_project'); libMain = fs.file(fs.path.join(projectPath, 'lib', 'main.dart')); }); tearDownAll(() { - try { - tempDir?.deleteSync(recursive: true); - } on FileSystemException catch (e) { - // ignore errors deleting the temporary directory - print('Ignored exception during tearDown: $e'); - } + tryToDelete(tempDir); }); // Create a project to be analyzed @@ -134,7 +129,7 @@ void main() { }, timeout: allowForSlowAnalyzeTests); testUsingContext('no duplicate issues', () async { - final Directory tempDir = fs.systemTempDirectory.createTempSync('analyze_once_test_').absolute; + final Directory tempDir = fs.systemTempDirectory.createTempSync('flutter_analyze_once_test_2.').absolute; try { final File foo = fs.file(fs.path.join(tempDir.path, 'foo.dart')); @@ -163,7 +158,7 @@ void bar() { toolExit: true, ); } finally { - tempDir.deleteSync(recursive: true); + tryToDelete(tempDir); } }); @@ -171,7 +166,7 @@ void bar() { const String contents = ''' StringBuffer bar = StringBuffer('baz'); '''; - final Directory tempDir = fs.systemTempDirectory.createTempSync(); + final Directory tempDir = fs.systemTempDirectory.createTempSync('flutter_analyze_once_test_3.'); tempDir.childFile('main.dart').writeAsStringSync(contents); try { await runCommand( @@ -180,7 +175,7 @@ StringBuffer bar = StringBuffer('baz'); statusTextContains: ['No issues found!'], ); } finally { - tempDir.deleteSync(recursive: true); + tryToDelete(tempDir); } }); }); diff --git a/packages/flutter_tools/test/commands/analyze_test.dart b/packages/flutter_tools/test/commands/analyze_test.dart index bae562c6eae..d86b5745c6e 100644 --- a/packages/flutter_tools/test/commands/analyze_test.dart +++ b/packages/flutter_tools/test/commands/analyze_test.dart @@ -20,7 +20,11 @@ void main() { fs = new MemoryFileSystem(); fs.directory(_kFlutterRoot).createSync(recursive: true); Cache.flutterRoot = _kFlutterRoot; - tempDir = fs.systemTempDirectory.createTempSync('analysis_test'); + tempDir = fs.systemTempDirectory.createTempSync('flutter_analysis_test.'); + }); + + tearDown(() { + tryToDelete(tempDir); }); group('analyze', () { diff --git a/packages/flutter_tools/test/commands/create_test.dart b/packages/flutter_tools/test/commands/create_test.dart index d71d4fbd758..18edccef06e 100644 --- a/packages/flutter_tools/test/commands/create_test.dart +++ b/packages/flutter_tools/test/commands/create_test.dart @@ -24,7 +24,7 @@ const String frameworkChannel = 'omega'; void main() { group('create', () { - Directory temp; + Directory tempDir; Directory projectDir; FlutterVersion mockFlutterVersion; LoggingProcessManager loggingProcessManager; @@ -35,18 +35,13 @@ void main() { setUp(() { loggingProcessManager = new LoggingProcessManager(); - temp = fs.systemTempDirectory.createTempSync('flutter_tools'); - projectDir = temp.childDirectory('flutter_project'); + tempDir = fs.systemTempDirectory.createTempSync('flutter_tools_create_test.'); + projectDir = tempDir.childDirectory('flutter_project'); mockFlutterVersion = new MockFlutterVersion(); }); tearDown(() { - try { - temp.deleteSync(recursive: true); - } on FileSystemException catch (e) { - // ignore errors deleting the temporary directory - print('Ignored exception during tearDown: $e'); - } + tryToDelete(tempDir); }); // Verify that we create a project that is well-formed. diff --git a/packages/flutter_tools/test/commands/drive_test.dart b/packages/flutter_tools/test/commands/drive_test.dart index 9507805d2a0..c15bbc9591b 100644 --- a/packages/flutter_tools/test/commands/drive_test.dart +++ b/packages/flutter_tools/test/commands/drive_test.dart @@ -24,7 +24,7 @@ void main() { DriveCommand command; Device mockDevice; MemoryFileSystem fs; - Directory cwd; + Directory tempDir; void withMockDevice([Device mock]) { mockDevice = mock ?? new MockDevice(); @@ -40,8 +40,8 @@ void main() { command = new DriveCommand(); applyMocksToCommand(command); fs = new MemoryFileSystem(); - cwd = fs.systemTempDirectory.createTempSync('some_app_'); - fs.currentDirectory = cwd; + tempDir = fs.systemTempDirectory.createTempSync('flutter_drive_test.'); + fs.currentDirectory = tempDir; fs.directory('test').createSync(); fs.directory('test_driver').createSync(); fs.file('pubspec.yaml')..createSync(); @@ -68,13 +68,14 @@ void main() { restoreAppStopper(); restoreTestRunner(); restoreTargetDeviceFinder(); + tryToDelete(tempDir); }); testUsingContext('returns 1 when test file is not found', () async { withMockDevice(); - final String testApp = fs.path.join(cwd.path, 'test', 'e2e.dart'); - final String testFile = fs.path.join(cwd.path, 'test_driver', 'e2e_test.dart'); + final String testApp = fs.path.join(tempDir.path, 'test', 'e2e.dart'); + final String testFile = fs.path.join(tempDir.path, 'test_driver', 'e2e_test.dart'); fs.file(testApp).createSync(recursive: true); final List args = [ @@ -96,8 +97,8 @@ void main() { withMockDevice(); appStarter = expectAsync1((DriveCommand command) async => null); - final String testApp = fs.path.join(cwd.path, 'test_driver', 'e2e.dart'); - final String testFile = fs.path.join(cwd.path, 'test_driver', 'e2e_test.dart'); + final String testApp = fs.path.join(tempDir.path, 'test_driver', 'e2e.dart'); + final String testFile = fs.path.join(tempDir.path, 'test_driver', 'e2e_test.dart'); final MemoryFileSystem memFs = fs; await memFs.file(testApp).writeAsString('main() { }'); @@ -119,7 +120,7 @@ void main() { }); testUsingContext('returns 1 when app file is outside package', () async { - final String appFile = fs.path.join(cwd.dirname, 'other_app', 'app.dart'); + final String appFile = fs.path.join(tempDir.dirname, 'other_app', 'app.dart'); fs.file(appFile).createSync(recursive: true); final List args = [ 'drive', @@ -131,7 +132,7 @@ void main() { } on ToolExit catch (e) { expect(e.exitCode ?? 1, 1); expect(testLogger.errorText, contains( - 'Application file $appFile is outside the package directory ${cwd.path}', + 'Application file $appFile is outside the package directory ${tempDir.path}', )); } }, overrides: { @@ -139,7 +140,7 @@ void main() { }); testUsingContext('returns 1 when app file is in the root dir', () async { - final String appFile = fs.path.join(cwd.path, 'main.dart'); + final String appFile = fs.path.join(tempDir.path, 'main.dart'); fs.file(appFile).createSync(recursive: true); final List args = [ 'drive', @@ -162,8 +163,8 @@ void main() { testUsingContext('returns 0 when test ends successfully', () async { withMockDevice(); - final String testApp = fs.path.join(cwd.path, 'test', 'e2e.dart'); - final String testFile = fs.path.join(cwd.path, 'test_driver', 'e2e_test.dart'); + final String testApp = fs.path.join(tempDir.path, 'test', 'e2e.dart'); + final String testFile = fs.path.join(tempDir.path, 'test_driver', 'e2e_test.dart'); appStarter = expectAsync1((DriveCommand command) async { return new LaunchResult.succeeded(); @@ -193,8 +194,8 @@ void main() { testUsingContext('returns exitCode set by test runner', () async { withMockDevice(); - final String testApp = fs.path.join(cwd.path, 'test', 'e2e.dart'); - final String testFile = fs.path.join(cwd.path, 'test_driver', 'e2e_test.dart'); + final String testApp = fs.path.join(tempDir.path, 'test', 'e2e.dart'); + final String testFile = fs.path.join(tempDir.path, 'test_driver', 'e2e_test.dart'); appStarter = expectAsync1((DriveCommand command) async { return new LaunchResult.succeeded(); diff --git a/packages/flutter_tools/test/commands/format_test.dart b/packages/flutter_tools/test/commands/format_test.dart index 43e7b5cecb8..752e720da1e 100644 --- a/packages/flutter_tools/test/commands/format_test.dart +++ b/packages/flutter_tools/test/commands/format_test.dart @@ -12,19 +12,19 @@ import '../src/context.dart'; void main() { group('format', () { - Directory temp; + Directory tempDir; setUp(() { Cache.disableLocking(); - temp = fs.systemTempDirectory.createTempSync('flutter_tools'); + tempDir = fs.systemTempDirectory.createTempSync('flutter_tools_format_test.'); }); tearDown(() { - temp.deleteSync(recursive: true); + tryToDelete(tempDir); }); testUsingContext('a file', () async { - final String projectPath = await createProject(temp); + final String projectPath = await createProject(tempDir); final File srcFile = fs.file(fs.path.join(projectPath, 'lib', 'main.dart')); final String original = srcFile.readAsStringSync(); @@ -39,7 +39,7 @@ void main() { }); testUsingContext('dry-run', () async { - final String projectPath = await createProject(temp); + final String projectPath = await createProject(tempDir); final File srcFile = fs.file( fs.path.join(projectPath, 'lib', 'main.dart')); @@ -56,7 +56,7 @@ void main() { }); testUsingContext('dry-run with set-exit-if-changed', () async { - final String projectPath = await createProject(temp); + final String projectPath = await createProject(tempDir); final File srcFile = fs.file( fs.path.join(projectPath, 'lib', 'main.dart')); diff --git a/packages/flutter_tools/test/commands/ide_config_test.dart b/packages/flutter_tools/test/commands/ide_config_test.dart index aa97518fa1c..79e799f9522 100644 --- a/packages/flutter_tools/test/commands/ide_config_test.dart +++ b/packages/flutter_tools/test/commands/ide_config_test.dart @@ -15,15 +15,15 @@ import '../src/context.dart'; void main() { group('ide_config', () { - Directory temp; + Directory tempDir; Directory templateDir; Directory intellijDir; Directory toolsDir; Map _getFilesystemContents([Directory root]) { - final String tempPath = temp.absolute.path; + final String tempPath = tempDir.absolute.path; final List paths = - (root ?? temp).listSync(recursive: true).map((FileSystemEntity entity) { + (root ?? tempDir).listSync(recursive: true).map((FileSystemEntity entity) { final String relativePath = fs.path.relative(entity.path, from: tempPath); return relativePath; }).toList(); @@ -40,7 +40,7 @@ void main() { } Map _getManifest(Directory base, String marker, {bool isTemplate = false}) { - final String basePath = fs.path.relative(base.path, from: temp.absolute.path); + final String basePath = fs.path.relative(base.path, from: tempDir.absolute.path); final String suffix = isTemplate ? Template.copyTemplateExtension : ''; return { fs.path.join(basePath, '.idea'): 'dir', @@ -59,12 +59,12 @@ void main() { void _populateDir(Map manifest) { for (String key in manifest.keys) { if (manifest[key] == 'dir') { - temp.childDirectory(key)..createSync(recursive: true); + tempDir.childDirectory(key)..createSync(recursive: true); } } for (String key in manifest.keys) { if (manifest[key] != 'dir') { - temp.childFile(key) + tempDir.childFile(key) ..createSync(recursive: true) ..writeAsStringSync(manifest[key]); } @@ -72,7 +72,7 @@ void main() { } bool _fileOrDirectoryExists(String path) { - final String absPath = fs.path.join(temp.absolute.path, path); + final String absPath = fs.path.join(tempDir.absolute.path, path); return fs.file(absPath).existsSync() || fs.directory(absPath).existsSync(); } @@ -82,15 +82,15 @@ void main() { Map expectedContents = const {}, List unexpectedPaths = const [], }) async { - dir ??= temp; + dir ??= tempDir; final IdeConfigCommand command = new IdeConfigCommand(); final CommandRunner runner = createTestCommandRunner(command); - final List finalArgs = ['--flutter-root=${temp.absolute.path}', 'ide-config']; + final List finalArgs = ['--flutter-root=${tempDir.absolute.path}', 'ide-config']; finalArgs.addAll(args); await runner.run(finalArgs); for (String path in expectedContents.keys) { - final String absPath = fs.path.join(temp.absolute.path, path); + final String absPath = fs.path.join(tempDir.absolute.path, path); expect(_fileOrDirectoryExists(fs.path.join(dir.path, path)), true, reason: "$path doesn't exist"); if (fs.file(absPath).existsSync()) { @@ -108,15 +108,15 @@ void main() { }); setUp(() { - temp = fs.systemTempDirectory.createTempSync('flutter_tools_'); - final Directory packagesDir = temp.childDirectory('packages')..createSync(recursive: true); + tempDir = fs.systemTempDirectory.createTempSync('flutter_tools_ide_config_test.'); + final Directory packagesDir = tempDir.childDirectory('packages')..createSync(recursive: true); toolsDir = packagesDir.childDirectory('flutter_tools')..createSync(); templateDir = toolsDir.childDirectory('ide_templates')..createSync(); intellijDir = templateDir.childDirectory('intellij')..createSync(); }); tearDown(() { - temp.deleteSync(recursive: true); + tryToDelete(tempDir); }); testUsingContext("doesn't touch existing files without --overwrite", () async { @@ -126,7 +126,7 @@ void main() { isTemplate: true, ); final Map flutterManifest = _getManifest( - temp, + tempDir, 'existing', ); _populateDir(templateManifest); @@ -144,7 +144,7 @@ void main() { isTemplate: true, ); final Map flutterManifest = _getManifest( - temp, + tempDir, 'template', ); _populateDir(templateManifest); @@ -162,13 +162,13 @@ void main() { isTemplate: true, ); final Map flutterManifest = _getManifest( - temp, + tempDir, 'existing', ); _populateDir(templateManifest); _populateDir(flutterManifest); final Map overwrittenManifest = _getManifest( - temp, + tempDir, 'template', ); final Map expectedContents = templateManifest; @@ -196,7 +196,7 @@ void main() { _populateDir(templateManifest); templateManifest[flutterIml] = 'flutter existing'; final Map flutterManifest = _getManifest( - temp, + tempDir, 'existing', ); _populateDir(flutterManifest); @@ -216,7 +216,7 @@ void main() { ); _populateDir(templateManifest); final Map flutterManifest = _getManifest( - temp, + tempDir, 'existing', ); _populateDir(flutterManifest); @@ -241,7 +241,7 @@ void main() { ); _populateDir(templateManifest); final Map flutterManifest = _getManifest( - temp, + tempDir, 'existing', ); flutterManifest.remove('flutter.iml'); @@ -275,7 +275,7 @@ void main() { ); _populateDir(templateManifest); final Map flutterManifest = _getManifest( - temp, + tempDir, 'existing', ); flutterManifest.remove(fs.path.join('packages', 'new', 'deep.iml')); diff --git a/packages/flutter_tools/test/commands/packages_test.dart b/packages/flutter_tools/test/commands/packages_test.dart index 7d5d67025ba..efa71ddabf3 100644 --- a/packages/flutter_tools/test/commands/packages_test.dart +++ b/packages/flutter_tools/test/commands/packages_test.dart @@ -35,18 +35,18 @@ class AlwaysFalseBotDetector implements BotDetector { void main() { Cache.disableLocking(); group('packages get/upgrade', () { - Directory temp; + Directory tempDir; setUp(() { - temp = fs.systemTempDirectory.createTempSync('flutter_tools'); + tempDir = fs.systemTempDirectory.createTempSync('flutter_tools_packages_test.'); }); tearDown(() { - temp.deleteSync(recursive: true); + tryToDelete(tempDir); }); Future createProjectWithPlugin(String plugin) async { - final String projectPath = await createProject(temp); + final String projectPath = await createProject(tempDir); final File pubspec = fs.file(fs.path.join(projectPath, 'pubspec.yaml')); String content = await pubspec.readAsString(); content = content.replaceFirst( @@ -168,7 +168,7 @@ void main() { } testUsingContext('get fetches packages', () async { - final String projectPath = await createProject(temp); + final String projectPath = await createProject(tempDir); removeGeneratedFiles(projectPath); await runCommandIn(projectPath, 'get'); @@ -178,7 +178,7 @@ void main() { }, timeout: allowForRemotePubInvocation); testUsingContext('get --offline fetches packages', () async { - final String projectPath = await createProject(temp); + final String projectPath = await createProject(tempDir); removeGeneratedFiles(projectPath); await runCommandIn(projectPath, 'get', args: ['--offline']); @@ -188,7 +188,7 @@ void main() { }, timeout: allowForCreateFlutterProject); testUsingContext('upgrade fetches packages', () async { - final String projectPath = await createProject(temp); + final String projectPath = await createProject(tempDir); removeGeneratedFiles(projectPath); await runCommandIn(projectPath, 'upgrade'); @@ -210,7 +210,7 @@ void main() { }, timeout: allowForRemotePubInvocation, skip: true); testUsingContext('get fetches packages and injects plugin in plugin project', () async { final String projectPath = await createProject( - temp, + tempDir, arguments: ['-t', 'plugin', '--no-pub'], ); final String exampleProjectPath = fs.path.join(projectPath, 'example'); diff --git a/packages/flutter_tools/test/commands/upgrade_test.dart b/packages/flutter_tools/test/commands/upgrade_test.dart index 16469bebed4..f4a0f0da805 100644 --- a/packages/flutter_tools/test/commands/upgrade_test.dart +++ b/packages/flutter_tools/test/commands/upgrade_test.dart @@ -35,18 +35,18 @@ void main() { }); group('findProjectRoot', () { - Directory temp; + Directory tempDir; setUp(() async { - temp = fs.systemTempDirectory.createTempSync('flutter_tools'); + tempDir = fs.systemTempDirectory.createTempSync('flutter_tools_upgrade_test.'); }); tearDown(() { - temp.deleteSync(recursive: true); + tryToDelete(tempDir); }); testUsingContext('in project', () async { - final String projectPath = await createProject(temp); + final String projectPath = await createProject(tempDir); expect(findProjectRoot(projectPath), projectPath); expect(findProjectRoot(fs.path.join(projectPath, 'lib')), projectPath); @@ -56,7 +56,7 @@ void main() { }); testUsingContext('outside project', () async { - final String projectPath = await createProject(temp); + final String projectPath = await createProject(tempDir); expect(findProjectRoot(fs.directory(projectPath).parent.path), null); expect(findProjectRoot(Cache.flutterRoot), null); }); diff --git a/packages/flutter_tools/test/config_test.dart b/packages/flutter_tools/test/config_test.dart index e476cb8f417..30edb71d5d3 100644 --- a/packages/flutter_tools/test/config_test.dart +++ b/packages/flutter_tools/test/config_test.dart @@ -9,13 +9,18 @@ import 'src/common.dart'; void main() { Config config; + Directory tempDir; setUp(() { - final Directory tempDirectory = fs.systemTempDirectory.createTempSync('flutter_test'); - final File file = fs.file(fs.path.join(tempDirectory.path, '.settings')); + tempDir = fs.systemTempDirectory.createTempSync('flutter_config_test.'); + final File file = fs.file(fs.path.join(tempDir.path, '.settings')); config = new Config(file); }); + tearDown(() { + tryToDelete(tempDir); + }); + group('config', () { test('get set value', () async { expect(config.getValue('foo'), null); diff --git a/packages/flutter_tools/test/dependency_checker_test.dart b/packages/flutter_tools/test/dependency_checker_test.dart index 0c557822566..1fdbc7c9922 100644 --- a/packages/flutter_tools/test/dependency_checker_test.dart +++ b/packages/flutter_tools/test/dependency_checker_test.dart @@ -93,16 +93,18 @@ void main() { /// Tests that the flutter tool doesn't crash and displays a warning when its own location /// changed since it was last referenced to in a package's .packages file. testUsingContext('moved flutter sdk', () async { - final Directory destinationPath = fs.systemTempDirectory.createTempSync('dependency_checker_test_'); + final Directory tempDir = fs.systemTempDirectory.createTempSync('flutter_dependency_checker_test.'); + // Copy the golden input and let the test run in an isolated temporary in-memory file system. const LocalFileSystem localFileSystem = LocalFileSystem(); final Directory sourcePath = localFileSystem.directory(localFileSystem.path.join(dataPath, 'changed_sdk_location')); - copyDirectorySync(sourcePath, destinationPath); - fs.currentDirectory = destinationPath; + copyDirectorySync(sourcePath, tempDir); + fs.currentDirectory = tempDir; // Doesn't matter what commands we run. Arbitrarily list devices here. await createTestCommandRunner(new DevicesCommand()).run(['devices']); expect(testLogger.errorText, contains('.packages')); + tryToDelete(tempDir); }, overrides: { FileSystem: () => testFileSystem, }); diff --git a/packages/flutter_tools/test/devfs_test.dart b/packages/flutter_tools/test/devfs_test.dart index b2fb44532db..6a9d309b92e 100644 --- a/packages/flutter_tools/test/devfs_test.dart +++ b/packages/flutter_tools/test/devfs_test.dart @@ -459,15 +459,14 @@ final List _tempDirs = []; final Map _packages = {}; Directory _newTempDir(FileSystem fs) { - final Directory tempDir = fs.systemTempDirectory.createTempSync('devfs${_tempDirs.length}'); + final Directory tempDir = fs.systemTempDirectory.createTempSync('flutter_devfs${_tempDirs.length}_test.'); _tempDirs.add(tempDir); return tempDir; } void _cleanupTempDirs() { - while (_tempDirs.isNotEmpty) { - _tempDirs.removeLast().deleteSync(recursive: true); - } + while (_tempDirs.isNotEmpty) + tryToDelete(_tempDirs.removeLast()); } Future _createPackage(FileSystem fs, String pkgName, String pkgFileName, { bool doubleSlash = false }) async { diff --git a/packages/flutter_tools/test/integration/expression_evaluation_test.dart b/packages/flutter_tools/test/integration/expression_evaluation_test.dart index 677bd29d809..e68b7c24862 100644 --- a/packages/flutter_tools/test/integration/expression_evaluation_test.dart +++ b/packages/flutter_tools/test/integration/expression_evaluation_test.dart @@ -13,24 +13,21 @@ import '../src/common.dart'; import 'test_data/basic_project.dart'; import 'test_driver.dart'; -BasicProject _project = new BasicProject(); -FlutterTestDriver _flutter; - void main() { group('expression evaluation', () { + Directory tempDir; + final BasicProject _project = new BasicProject(); + FlutterTestDriver _flutter; + setUp(() async { - final Directory tempDir = await fs.systemTempDirectory.createTemp('test_app'); + tempDir = fs.systemTempDirectory.createTempSync('flutter_expression_test.'); await _project.setUpIn(tempDir); _flutter = new FlutterTestDriver(tempDir); }); tearDown(() async { - try { - await _flutter.stop(); - _project.cleanup(); - } catch (e) { - // Don't fail tests if we failed to clean up temp folder. - } + await _flutter.stop(); + tryToDelete(tempDir); }); Future breakInBuildMethod(FlutterTestDriver flutter) async { diff --git a/packages/flutter_tools/test/integration/flutter_attach_test.dart b/packages/flutter_tools/test/integration/flutter_attach_test.dart index 6a2bace8450..68fb836b677 100644 --- a/packages/flutter_tools/test/integration/flutter_attach_test.dart +++ b/packages/flutter_tools/test/integration/flutter_attach_test.dart @@ -11,26 +11,22 @@ import '../src/context.dart'; import 'test_data/basic_project.dart'; import 'test_driver.dart'; -FlutterTestDriver _flutterRun, _flutterAttach; -BasicProject _project = new BasicProject(); - void main() { + FlutterTestDriver _flutterRun, _flutterAttach; + final BasicProject _project = new BasicProject(); + Directory tempDir; setUp(() async { - final Directory tempDir = await fs.systemTempDirectory.createTemp('test_app'); + tempDir = fs.systemTempDirectory.createTempSync('flutter_attach_test.'); await _project.setUpIn(tempDir); _flutterRun = new FlutterTestDriver(tempDir); _flutterAttach = new FlutterTestDriver(tempDir); }); tearDown(() async { - try { - await _flutterRun.stop(); - await _flutterAttach.stop(); - _project.cleanup(); - } catch (e) { - // Don't fail tests if we failed to clean up temp folder. - } + await _flutterRun.stop(); + await _flutterAttach.stop(); + tryToDelete(tempDir); }); group('attached process', () { diff --git a/packages/flutter_tools/test/integration/flutter_tester_test.dart b/packages/flutter_tools/test/integration/flutter_tester_test.dart index e3d2575cb67..6b98e192cc6 100644 --- a/packages/flutter_tools/test/integration/flutter_tester_test.dart +++ b/packages/flutter_tools/test/integration/flutter_tester_test.dart @@ -19,19 +19,14 @@ void main() { Directory oldCurrentDir; setUp(() async { - tempDir = await fs.systemTempDirectory.createTemp('flutter_tester_device'); + tempDir = fs.systemTempDirectory.createTempSync('flutter_tester_device_test.'); oldCurrentDir = fs.currentDirectory; fs.currentDirectory = tempDir; }); tearDown(() { fs.currentDirectory = oldCurrentDir; - try { - tempDir?.deleteSync(recursive: true); - tempDir = null; - } catch (e) { - // Ignored. - } + tryToDelete(tempDir); }); group('FlutterTesterDevice', () { diff --git a/packages/flutter_tools/test/integration/hot_reload_test.dart b/packages/flutter_tools/test/integration/hot_reload_test.dart index 58e6ddff583..7d721ca01db 100644 --- a/packages/flutter_tools/test/integration/hot_reload_test.dart +++ b/packages/flutter_tools/test/integration/hot_reload_test.dart @@ -12,24 +12,21 @@ import '../src/common.dart'; import 'test_data/basic_project.dart'; import 'test_driver.dart'; -BasicProject _project = new BasicProject(); -FlutterTestDriver _flutter; - void main() { group('hot reload', () { + Directory tempDir; + final BasicProject _project = new BasicProject(); + FlutterTestDriver _flutter; + setUp(() async { - final Directory tempDir = await fs.systemTempDirectory.createTemp('test_app'); + tempDir = fs.systemTempDirectory.createTempSync('flutter_hot_reload_test_app.'); await _project.setUpIn(tempDir); _flutter = new FlutterTestDriver(tempDir); }); tearDown(() async { - try { - await _flutter.stop(); - _project.cleanup(); - } catch (e) { - // Don't fail tests if we failed to clean up temp folder. - } + await _flutter.stop(); + tryToDelete(tempDir); }); test('works without error', () async { diff --git a/packages/flutter_tools/test/integration/lifetime_test.dart b/packages/flutter_tools/test/integration/lifetime_test.dart index 10336a609af..79576da0881 100644 --- a/packages/flutter_tools/test/integration/lifetime_test.dart +++ b/packages/flutter_tools/test/integration/lifetime_test.dart @@ -12,9 +12,6 @@ import '../src/common.dart'; import 'test_data/basic_project.dart'; import 'test_driver.dart'; -BasicProject _project = new BasicProject(); -FlutterTestDriver _flutter; - /// This duration is arbitrary but is ideally: /// a) long enough to ensure that if the app is crashing at startup, we notice /// b) as short as possible, to avoid inflating build times @@ -22,15 +19,19 @@ const Duration requiredLifespan = Duration(seconds: 5); void main() { group('flutter run', () { + final BasicProject _project = new BasicProject(); + FlutterTestDriver _flutter; + Directory tempDir; + setUp(() async { - final Directory tempDir = await fs.systemTempDirectory.createTemp('test_app'); + tempDir = fs.systemTempDirectory.createTempSync('flutter_lifetime_test.'); await _project.setUpIn(tempDir); _flutter = new FlutterTestDriver(tempDir); }); tearDown(() async { await _flutter.stop(); - _project.cleanup(); + tryToDelete(tempDir); }); test('does not terminate when a debugger is attached', () async { diff --git a/packages/flutter_tools/test/integration/test_data/test_project.dart b/packages/flutter_tools/test/integration/test_data/test_project.dart index af825d261b6..1b73c45c1b4 100644 --- a/packages/flutter_tools/test/integration/test_data/test_project.dart +++ b/packages/flutter_tools/test/integration/test_data/test_project.dart @@ -26,10 +26,6 @@ abstract class TestProject { await getPackages(dir.path); } - void cleanup() { - dir?.deleteSync(recursive: true); - } - int lineContaining(String contents, String search) { final int index = contents.split('\n').indexWhere((String l) => l.contains(search)); if (index == -1) diff --git a/packages/flutter_tools/test/integration/test_driver.dart b/packages/flutter_tools/test/integration/test_driver.dart index 0df87924ccf..ee9a76d62cf 100644 --- a/packages/flutter_tools/test/integration/test_driver.dart +++ b/packages/flutter_tools/test/integration/test_driver.dart @@ -23,6 +23,8 @@ const Duration appStartTimeout = Duration(seconds: 60); const Duration quitTimeout = Duration(seconds: 5); class FlutterTestDriver { + FlutterTestDriver(this._projectFolder); + final Directory _projectFolder; Process _proc; int _procPid; @@ -36,8 +38,6 @@ class FlutterTestDriver { int _vmServicePort; bool _hasExited = false; - FlutterTestDriver(this._projectFolder); - VMServiceClient vmService; String get lastErrorInfo => _errorBuffer.toString(); int get vmServicePort => _vmServicePort; @@ -318,24 +318,24 @@ class FlutterTestDriver { int id = 1; Future _sendRequest(String method, dynamic params) async { final int requestId = id++; - final Map req = { + final Map request = { 'id': requestId, 'method': method, 'params': params }; - final String jsonEncoded = json.encode(>[req]); + final String jsonEncoded = json.encode(>[request]); _debugPrint(jsonEncoded); // Set up the response future before we send the request to avoid any // races. final Future> responseFuture = _waitFor(id: requestId); _proc.stdin.writeln(jsonEncoded); - final Map resp = await responseFuture; + final Map response = await responseFuture; - if (resp['error'] != null || resp['result'] == null) + if (response['error'] != null || response['result'] == null) _throwErrorResponse('Unexpected error response'); - return resp['result']; + return response['result']; } void _throwErrorResponse(String msg) { diff --git a/packages/flutter_tools/test/src/common.dart b/packages/flutter_tools/test/src/common.dart index 3aa0331de22..b932cf85172 100644 --- a/packages/flutter_tools/test/src/common.dart +++ b/packages/flutter_tools/test/src/common.dart @@ -22,6 +22,17 @@ export 'package:test/test.dart' hide TypeMatcher, isInstanceOf; // Defines a 'pa // TODO(ianh): Remove this once https://github.com/dart-lang/matcher/issues/98 is fixed Matcher isInstanceOf() => new test_package.TypeMatcher(); // ignore: prefer_const_constructors, https://github.com/dart-lang/sdk/issues/32544 +void tryToDelete(Directory directory) { + // This should not be necessary, but it turns out that + // on Windows it's common for deletions to fail due to + // bogus (we think) "access denied" errors. + try { + directory.deleteSync(recursive: true); + } on FileSystemException catch (error) { + print('Failed to delete ${directory.path}: $error'); + } +} + /// Gets the path to the root of the Flutter repository. /// /// This will first look for a `FLUTTER_ROOT` environment variable. If the diff --git a/packages/flutter_tools/test/src/context.dart b/packages/flutter_tools/test/src/context.dart index 0136da14277..c3666335571 100644 --- a/packages/flutter_tools/test/src/context.dart +++ b/packages/flutter_tools/test/src/context.dart @@ -48,13 +48,16 @@ void testUsingContext(String description, dynamic testMethod(), { // leak a sticky $HOME/.flutter_settings behind! Directory configDir; tearDown(() { - configDir?.deleteSync(recursive: true); - configDir = null; + if (configDir != null) { + tryToDelete(configDir); + configDir = null; + } }); Config buildConfig(FileSystem fs) { - configDir = fs.systemTempDirectory.createTempSync('config-dir'); + configDir = fs.systemTempDirectory.createTempSync('flutter_config_dir_test.'); final File settingsFile = fs.file( - fs.path.join(configDir.path, '.flutter_settings')); + fs.path.join(configDir.path, '.flutter_settings') + ); return new Config(settingsFile); } diff --git a/packages/flutter_tools/test/src/mocks.dart b/packages/flutter_tools/test/src/mocks.dart index 19e6e455745..a4326e0db6b 100644 --- a/packages/flutter_tools/test/src/mocks.dart +++ b/packages/flutter_tools/test/src/mocks.dart @@ -44,7 +44,7 @@ class MockAndroidSdk extends Mock implements AndroidSdk { bool withNdkSysroot = false, bool withSdkManager = true, }) { - final Directory dir = fs.systemTempDirectory.createTempSync('android-sdk'); + final Directory dir = fs.systemTempDirectory.createTempSync('flutter_mock_android_sdk.'); _createSdkFile(dir, 'platform-tools/adb'); @@ -66,18 +66,23 @@ class MockAndroidSdk extends Mock implements AndroidSdk { if (withNdkDir != null) { final String ndkCompiler = fs.path.join( - 'ndk-bundle', - 'toolchains', - 'arm-linux-androideabi-4.9', - 'prebuilt', - withNdkDir, - 'bin', - 'arm-linux-androideabi-gcc'); + 'ndk-bundle', + 'toolchains', + 'arm-linux-androideabi-4.9', + 'prebuilt', + withNdkDir, + 'bin', + 'arm-linux-androideabi-gcc', + ); _createSdkFile(dir, ndkCompiler); } if (withNdkSysroot) { - final String armPlatform = - fs.path.join('ndk-bundle', 'platforms', 'android-9', 'arch-arm'); + final String armPlatform = fs.path.join( + 'ndk-bundle', + 'platforms', + 'android-9', + 'arch-arm', + ); _createDir(dir, armPlatform); }