Unverified Commit 3dec6a69 authored by Ian Hickson's avatar Ian Hickson Committed by GitHub

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.
parent d5812085
...@@ -100,13 +100,13 @@ const String kDartDocPrefix = '///'; ...@@ -100,13 +100,13 @@ const String kDartDocPrefix = '///';
const String kDartDocPrefixWithSpace = '$kDartDocPrefix '; const String kDartDocPrefixWithSpace = '$kDartDocPrefix ';
Future<Null> main() async { Future<Null> main() async {
final Directory temp = Directory.systemTemp.createTempSync('analyze_sample_code_'); final Directory tempDir = Directory.systemTemp.createTempSync('flutter_analyze_sample_code.');
int exitCode = 1; int exitCode = 1;
bool keepMain = false; bool keepMain = false;
final List<String> buffer = <String>[]; final List<String> buffer = <String>[];
try { try {
final File mainDart = new File(path.join(temp.path, 'main.dart')); final File mainDart = new File(path.join(tempDir.path, 'main.dart'));
final File pubSpec = new File(path.join(temp.path, 'pubspec.yaml')); final File pubSpec = new File(path.join(tempDir.path, 'pubspec.yaml'));
final Directory flutterPackage = new Directory(path.join(_flutterRoot, 'packages', 'flutter', 'lib')); final Directory flutterPackage = new Directory(path.join(_flutterRoot, 'packages', 'flutter', 'lib'));
final List<Section> sections = <Section>[]; final List<Section> sections = <Section>[];
int sampleCodeSections = 0; int sampleCodeSections = 0;
...@@ -210,7 +210,7 @@ dependencies: ...@@ -210,7 +210,7 @@ dependencies:
final Process process = await Process.start( final Process process = await Process.start(
_flutter, _flutter,
<String>['analyze', '--no-preamble', '--no-congratulate', mainDart.parent.path], <String>['analyze', '--no-preamble', '--no-congratulate', mainDart.parent.path],
workingDirectory: temp.path, workingDirectory: tempDir.path,
); );
stderr.addStream(process.stderr); stderr.addStream(process.stderr);
final List<String> errors = await process.stdout.transform<String>(utf8.decoder).transform<String>(const LineSplitter()).toList(); final List<String> errors = await process.stdout.transform<String>(utf8.decoder).transform<String>(const LineSplitter()).toList();
...@@ -285,7 +285,7 @@ dependencies: ...@@ -285,7 +285,7 @@ dependencies:
print('No errors!'); print('No errors!');
} finally { } finally {
if (keepMain) { if (keepMain) {
print('Kept ${temp.path} because it had errors (see above).'); print('Kept ${tempDir.path} because it had errors (see above).');
print('-------8<-------'); print('-------8<-------');
int number = 1; int number = 1;
for (String line in buffer) { for (String line in buffer) {
...@@ -295,10 +295,9 @@ dependencies: ...@@ -295,10 +295,9 @@ dependencies:
print('-------8<-------'); print('-------8<-------');
} else { } else {
try { try {
temp.deleteSync(recursive: true); tempDir.deleteSync(recursive: true);
} on FileSystemException catch (e) { } on FileSystemException catch (e) {
// ignore errors deleting the temporary directory print('Failed to delete ${tempDir.path}: $e');
print('Ignored exception during tearDown: $e');
} }
} }
} }
......
...@@ -640,7 +640,7 @@ Future<Null> main(List<String> argList) async { ...@@ -640,7 +640,7 @@ Future<Null> main(List<String> argList) async {
Directory tempDir; Directory tempDir;
bool removeTempDir = false; bool removeTempDir = false;
if (args['temp_dir'] == null || args['temp_dir'].isEmpty) { if (args['temp_dir'] == null || args['temp_dir'].isEmpty) {
tempDir = Directory.systemTemp.createTempSync('flutter_'); tempDir = Directory.systemTemp.createTempSync('flutter_package.');
removeTempDir = true; removeTempDir = true;
} else { } else {
tempDir = new Directory(args['temp_dir']); tempDir = new Directory(args['temp_dir']);
......
...@@ -191,7 +191,7 @@ Future<Null> _analyzeRepo() async { ...@@ -191,7 +191,7 @@ Future<Null> _analyzeRepo() async {
await _checkForTrailingSpaces(); await _checkForTrailingSpaces();
// Try analysis against a big version of the gallery; generate into a temporary directory. // 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 { try {
await _runCommand(dart, await _runCommand(dart,
...@@ -199,17 +199,13 @@ Future<Null> _analyzeRepo() async { ...@@ -199,17 +199,13 @@ Future<Null> _analyzeRepo() async {
'--preview-dart-2', '--preview-dart-2',
path.join(flutterRoot, 'dev', 'tools', 'mega_gallery.dart'), path.join(flutterRoot, 'dev', 'tools', 'mega_gallery.dart'),
'--out', '--out',
outDir, outDir.path,
], ],
workingDirectory: flutterRoot, workingDirectory: flutterRoot,
); );
await _runFlutterAnalyze(outDir, options: <String>['--watch', '--benchmark']); await _runFlutterAnalyze(outDir.path, options: <String>['--watch', '--benchmark']);
} finally { } finally {
try { outDir.deleteSync(recursive: true);
new Directory(outDir).deleteSync(recursive: true);
} catch (e) {
// ignore
}
} }
print('${bold}DONE: Analysis successful.$reset'); print('${bold}DONE: Analysis successful.$reset');
......
...@@ -2,6 +2,8 @@ ...@@ -2,6 +2,8 @@
// Use of this source code is governed by a BSD-style license that can be // Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file. // found in the LICENSE file.
import 'dart:io';
import 'package:test/test.dart' hide TypeMatcher, isInstanceOf; import 'package:test/test.dart' hide TypeMatcher, isInstanceOf;
import 'package:test/test.dart' as test_package show TypeMatcher; import 'package:test/test.dart' as test_package show TypeMatcher;
...@@ -12,3 +14,14 @@ export 'package:test/test.dart' hide TypeMatcher, isInstanceOf; ...@@ -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. /// A matcher that compares the type of the actual value to the type argument T.
Matcher isInstanceOf<T>() => new test_package.TypeMatcher<T>(); // ignore: prefer_const_constructors, https://github.com/dart-lang/sdk/issues/32544 Matcher isInstanceOf<T>() => new test_package.TypeMatcher<T>(); // 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');
}
}
...@@ -67,7 +67,7 @@ void main() { ...@@ -67,7 +67,7 @@ void main() {
}); });
group('ArchiveCreator for $platformName', () { group('ArchiveCreator for $platformName', () {
ArchiveCreator creator; ArchiveCreator creator;
Directory tmpDir; Directory tempDir;
Directory flutterDir; Directory flutterDir;
FakeProcessManager processManager; FakeProcessManager processManager;
final List<List<String>> args = <List<String>>[]; final List<List<String>> args = <List<String>>[];
...@@ -82,12 +82,12 @@ void main() { ...@@ -82,12 +82,12 @@ void main() {
processManager = new FakeProcessManager(); processManager = new FakeProcessManager();
args.clear(); args.clear();
namedArgs.clear(); namedArgs.clear();
tmpDir = await Directory.systemTemp.createTemp('flutter_'); tempDir = Directory.systemTemp.createTempSync('flutter_prepage_package_test.');
flutterDir = new Directory(path.join(tmpDir.path, 'flutter')); flutterDir = new Directory(path.join(tempDir.path, 'flutter'));
flutterDir.createSync(recursive: true); flutterDir.createSync(recursive: true);
creator = new ArchiveCreator( creator = new ArchiveCreator(
tmpDir, tempDir,
tmpDir, tempDir,
testRef, testRef,
Branch.dev, Branch.dev,
processManager: processManager, processManager: processManager,
...@@ -99,16 +99,11 @@ void main() { ...@@ -99,16 +99,11 @@ void main() {
}); });
tearDown(() async { tearDown(() async {
// On Windows, the directory is locked and not able to be deleted yet. So tryToDelete(tempDir);
// 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);
}
}); });
test('sets PUB_CACHE properly', () async { 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<String, List<ProcessResult>> calls = <String, List<ProcessResult>>{ final Map<String, List<ProcessResult>> calls = <String, List<ProcessResult>>{
'git clone -b dev https://chromium.googlesource.com/external/github.com/flutter/flutter': null, 'git clone -b dev https://chromium.googlesource.com/external/github.com/flutter/flutter': null,
'git reset --hard $testRef': null, 'git reset --hard $testRef': null,
...@@ -116,7 +111,7 @@ void main() { ...@@ -116,7 +111,7 @@ void main() {
'git describe --tags --abbrev=0': <ProcessResult>[new ProcessResult(0, 0, 'v1.2.3', '')], 'git describe --tags --abbrev=0': <ProcessResult>[new ProcessResult(0, 0, 'v1.2.3', '')],
}; };
if (platform.isWindows) { 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(<String, List<ProcessResult>>{ calls.addAll(<String, List<ProcessResult>>{
'$flutter doctor': null, '$flutter doctor': null,
...@@ -128,7 +123,7 @@ void main() { ...@@ -128,7 +123,7 @@ void main() {
'$flutter create --template=plugin ${createBase}plugin': null, '$flutter create --template=plugin ${createBase}plugin': null,
'git clean -f -X **/.packages': 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'}'); 'flutter_${platformName}_v1.2.3-dev${platform.isLinux ? '.tar.xz' : '.zip'}');
if (platform.isWindows) { if (platform.isWindows) {
calls['7za a -tzip -mx=9 $archiveName flutter'] = null; calls['7za a -tzip -mx=9 $archiveName flutter'] = null;
...@@ -151,7 +146,7 @@ void main() { ...@@ -151,7 +146,7 @@ void main() {
}); });
test('calls the right commands for archive output', () async { 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<String, List<ProcessResult>> calls = <String, List<ProcessResult>>{ final Map<String, List<ProcessResult>> calls = <String, List<ProcessResult>>{
'git clone -b dev https://chromium.googlesource.com/external/github.com/flutter/flutter': null, 'git clone -b dev https://chromium.googlesource.com/external/github.com/flutter/flutter': null,
'git reset --hard $testRef': null, 'git reset --hard $testRef': null,
...@@ -159,7 +154,7 @@ void main() { ...@@ -159,7 +154,7 @@ void main() {
'git describe --tags --abbrev=0': <ProcessResult>[new ProcessResult(0, 0, 'v1.2.3', '')], 'git describe --tags --abbrev=0': <ProcessResult>[new ProcessResult(0, 0, 'v1.2.3', '')],
}; };
if (platform.isWindows) { 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(<String, List<ProcessResult>>{ calls.addAll(<String, List<ProcessResult>>{
'$flutter doctor': null, '$flutter doctor': null,
...@@ -171,7 +166,7 @@ void main() { ...@@ -171,7 +166,7 @@ void main() {
'$flutter create --template=plugin ${createBase}plugin': null, '$flutter create --template=plugin ${createBase}plugin': null,
'git clean -f -X **/.packages': 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'}'); 'flutter_${platformName}_v1.2.3-dev${platform.isLinux ? '.tar.xz' : '.zip'}');
if (platform.isWindows) { if (platform.isWindows) {
calls['7za a -tzip -mx=9 $archiveName flutter'] = null; calls['7za a -tzip -mx=9 $archiveName flutter'] = null;
...@@ -182,8 +177,8 @@ void main() { ...@@ -182,8 +177,8 @@ void main() {
} }
processManager.fakeResults = calls; processManager.fakeResults = calls;
creator = new ArchiveCreator( creator = new ArchiveCreator(
tmpDir, tempDir,
tmpDir, tempDir,
testRef, testRef,
Branch.dev, Branch.dev,
processManager: processManager, processManager: processManager,
...@@ -214,17 +209,11 @@ void main() { ...@@ -214,17 +209,11 @@ void main() {
setUp(() async { setUp(() async {
processManager = new FakeProcessManager(); processManager = new FakeProcessManager();
tempDir = await Directory.systemTemp.createTemp('flutter_'); tempDir = Directory.systemTemp.createTempSync('flutter_prepage_package_test.');
tempDir.createSync();
}); });
tearDown(() async { tearDown(() async {
// On Windows, the directory is locked and not able to be deleted yet. So tryToDelete(tempDir);
// 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);
}
}); });
test('calls the right processes', () async { test('calls the right processes', () async {
......
...@@ -14,25 +14,25 @@ String errorMessage; ...@@ -14,25 +14,25 @@ String errorMessage;
/// Runs the given [testFunction] on a freshly generated Flutter project. /// Runs the given [testFunction] on a freshly generated Flutter project.
Future<void> runProjectTest(Future<void> testFunction(FlutterProject project)) async { Future<void> runProjectTest(Future<void> testFunction(FlutterProject project)) async {
final Directory tmp = await Directory.systemTemp.createTemp('gradle'); final Directory tempDir = Directory.systemTemp.createTempSync('flutter_devicelab_gradle_plugin_test.');
final FlutterProject project = await FlutterProject.create(tmp, 'hello'); final FlutterProject project = await FlutterProject.create(tempDir, 'hello');
try { try {
await testFunction(project); await testFunction(project);
} finally { } finally {
project.parent.deleteSync(recursive: true); rmTree(tempDir);
} }
} }
/// Runs the given [testFunction] on a freshly generated Flutter plugin project. /// Runs the given [testFunction] on a freshly generated Flutter plugin project.
Future<void> runPluginProjectTest(Future<void> testFunction(FlutterPluginProject pluginProject)) async { Future<void> runPluginProjectTest(Future<void> testFunction(FlutterPluginProject pluginProject)) async {
final Directory tmp = await Directory.systemTemp.createTemp('gradle'); final Directory tempDir = Directory.systemTemp.createTempSync('flutter_devicelab_gradle_plugin_test.');
final FlutterPluginProject pluginProject = await FlutterPluginProject.create(tmp, 'aaa'); final FlutterPluginProject pluginProject = await FlutterPluginProject.create(tempDir, 'aaa');
try { try {
await testFunction(pluginProject); await testFunction(pluginProject);
} finally { } finally {
pluginProject.parent.deleteSync(recursive: true); rmTree(tempDir);
} }
} }
......
...@@ -4,6 +4,7 @@ ...@@ -4,6 +4,7 @@
import 'dart:async'; import 'dart:async';
import 'dart:io'; import 'dart:io';
import 'package:flutter_devicelab/framework/framework.dart'; import 'package:flutter_devicelab/framework/framework.dart';
import 'package:flutter_devicelab/framework/utils.dart'; import 'package:flutter_devicelab/framework/utils.dart';
import 'package:path/path.dart' as path; import 'package:path/path.dart' as path;
...@@ -22,9 +23,9 @@ Future<Null> main() async { ...@@ -22,9 +23,9 @@ Future<Null> main() async {
section('Create Flutter module project'); section('Create Flutter module project');
final Directory directory = await Directory.systemTemp.createTemp('module'); final Directory tempDir = Directory.systemTemp.createTempSync('flutter_module_test.');
try { try {
await inDirectory(directory, () async { await inDirectory(tempDir, () async {
await flutter( await flutter(
'create', 'create',
options: <String>['--org', 'io.flutter.devicelab', '-t', 'module', 'hello'], options: <String>['--org', 'io.flutter.devicelab', '-t', 'module', 'hello'],
...@@ -33,14 +34,14 @@ Future<Null> main() async { ...@@ -33,14 +34,14 @@ Future<Null> main() async {
section('Add plugins'); 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(); String content = await pubspec.readAsString();
content = content.replaceFirst( content = content.replaceFirst(
'\ndependencies:\n', '\ndependencies:\n',
'\ndependencies:\n battery:\n package_info:\n', '\ndependencies:\n battery:\n package_info:\n',
); );
await pubspec.writeAsString(content, flush: true); 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( await flutter(
'packages', 'packages',
options: <String>['get'], options: <String>['get'],
...@@ -49,7 +50,7 @@ Future<Null> main() async { ...@@ -49,7 +50,7 @@ Future<Null> main() async {
section('Build Flutter module library archive'); 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( await exec(
'./gradlew', './gradlew',
<String>['flutter:assembleDebug'], <String>['flutter:assembleDebug'],
...@@ -58,7 +59,7 @@ Future<Null> main() async { ...@@ -58,7 +59,7 @@ Future<Null> main() async {
}); });
final bool aarBuilt = exists(new File(path.join( final bool aarBuilt = exists(new File(path.join(
directory.path, tempDir.path,
'hello', 'hello',
'.android', '.android',
'Flutter', 'Flutter',
...@@ -74,7 +75,7 @@ Future<Null> main() async { ...@@ -74,7 +75,7 @@ Future<Null> main() async {
section('Build ephemeral host app'); 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( await flutter(
'build', 'build',
options: <String>['apk'], options: <String>['apk'],
...@@ -82,7 +83,7 @@ Future<Null> main() async { ...@@ -82,7 +83,7 @@ Future<Null> main() async {
}); });
final bool ephemeralHostApkBuilt = exists(new File(path.join( final bool ephemeralHostApkBuilt = exists(new File(path.join(
directory.path, tempDir.path,
'hello', 'hello',
'build', 'build',
'host', 'host',
...@@ -98,13 +99,13 @@ Future<Null> main() async { ...@@ -98,13 +99,13 @@ Future<Null> main() async {
section('Clean build'); 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'); await flutter('clean');
}); });
section('Materialize host app'); 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( await flutter(
'materialize', 'materialize',
options: <String>['android'], options: <String>['android'],
...@@ -113,7 +114,7 @@ Future<Null> main() async { ...@@ -113,7 +114,7 @@ Future<Null> main() async {
section('Build materialized host app'); 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( await flutter(
'build', 'build',
options: <String>['apk'], options: <String>['apk'],
...@@ -121,7 +122,7 @@ Future<Null> main() async { ...@@ -121,7 +122,7 @@ Future<Null> main() async {
}); });
final bool materializedHostApkBuilt = exists(new File(path.join( final bool materializedHostApkBuilt = exists(new File(path.join(
directory.path, tempDir.path,
'hello', 'hello',
'build', 'build',
'host', 'host',
...@@ -137,18 +138,18 @@ Future<Null> main() async { ...@@ -137,18 +138,18 @@ Future<Null> main() async {
section('Add to Android app'); 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); mkdir(hostApp);
recursiveCopy( recursiveCopy(
new Directory(path.join(flutterDirectory.path, 'dev', 'integration_tests', 'android_host_app')), new Directory(path.join(flutterDirectory.path, 'dev', 'integration_tests', 'android_host_app')),
hostApp, hostApp,
); );
copy( copy(
new File(path.join(directory.path, 'hello', '.android', 'gradlew')), new File(path.join(tempDir.path, 'hello', '.android', 'gradlew')),
hostApp, hostApp,
); );
copy( 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')), new Directory(path.join(hostApp.path, 'gradle', 'wrapper')),
); );
...@@ -177,7 +178,7 @@ Future<Null> main() async { ...@@ -177,7 +178,7 @@ Future<Null> main() async {
} catch (e) { } catch (e) {
return new TaskResult.failure(e.toString()); return new TaskResult.failure(e.toString());
} finally { } finally {
rmTree(directory); rmTree(tempDir);
} }
}); });
} }
...@@ -77,15 +77,23 @@ void fail(String message) { ...@@ -77,15 +77,23 @@ void fail(String message) {
throw new BuildFailedError(message); throw new BuildFailedError(message);
} }
void rm(FileSystemEntity entity) { // Remove the given file or directory.
if (entity.existsSync()) void rm(FileSystemEntity entity, { bool recursive = false}) {
entity.deleteSync(); 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. /// Remove recursively.
void rmTree(FileSystemEntity entity) { void rmTree(FileSystemEntity entity) {
if (entity.existsSync()) rm(entity, recursive: true);
entity.deleteSync(recursive: true);
} }
List<FileSystemEntity> ls(Directory directory) => directory.listSync(); List<FileSystemEntity> ls(Directory directory) => directory.listSync();
...@@ -414,7 +422,7 @@ Future<Null> getFlutter(String revision) async { ...@@ -414,7 +422,7 @@ Future<Null> getFlutter(String revision) async {
section('Get Flutter!'); section('Get Flutter!');
if (exists(flutterDirectory)) { if (exists(flutterDirectory)) {
rmTree(flutterDirectory); flutterDirectory.deleteSync(recursive: true);
} }
await inDirectory(flutterDirectory.parent, () async { await inDirectory(flutterDirectory.parent, () async {
......
...@@ -73,8 +73,7 @@ TaskFunction createBasicMaterialCompileTest() { ...@@ -73,8 +73,7 @@ TaskFunction createBasicMaterialCompileTest() {
const String sampleAppName = 'sample_flutter_app'; const String sampleAppName = 'sample_flutter_app';
final Directory sampleDir = dir('${Directory.systemTemp.path}/$sampleAppName'); final Directory sampleDir = dir('${Directory.systemTemp.path}/$sampleAppName');
if (await sampleDir.exists()) rmTree(sampleDir);
rmTree(sampleDir);
await inDirectory(Directory.systemTemp, () async { await inDirectory(Directory.systemTemp, () async {
await flutter('create', options: <String>[sampleAppName]); await flutter('create', options: <String>[sampleAppName]);
......
...@@ -33,23 +33,24 @@ class PluginTest { ...@@ -33,23 +33,24 @@ class PluginTest {
Future<TaskResult> call() async { Future<TaskResult> call() async {
section('Create Flutter project'); section('Create Flutter project');
final Directory tmp = await Directory.systemTemp.createTemp('plugin'); final Directory tempDir = Directory.systemTemp.createTempSync('flutter_devicelab_plugin_test.');
final FlutterProject project = await FlutterProject.create(tmp, options);
if (buildTarget == 'ios') {
await prepareProvisioningCertificates(project.rootPath);
}
try { try {
section('Add plugin'); final FlutterProject project = await FlutterProject.create(tempDir, options);
await project.addPlugin('path_provider'); try {
if (buildTarget == 'ios')
section('Build'); await prepareProvisioningCertificates(project.rootPath);
await project.build(buildTarget); section('Add plugin');
await project.addPlugin('path_provider');
section('Build');
await project.build(buildTarget);
} finally {
await project.delete();
}
return new TaskResult.success(null); return new TaskResult.success(null);
} catch (e) { } catch (e) {
return new TaskResult.failure(e.toString()); return new TaskResult.failure(e.toString());
} finally { } finally {
await project.delete(); rmTree(tempDir);
} }
} }
} }
...@@ -97,9 +98,9 @@ class FlutterProject { ...@@ -97,9 +98,9 @@ class FlutterProject {
<String>['--stop'], <String>['--stop'],
canFail: true, canFail: true,
); );
// TODO(mravn): Investigating if flakiness is timing dependent. // TODO(ianh): Investigating if flakiness is timing dependent.
await new Future<Null>.delayed(const Duration(seconds: 10)); await new Future<Null>.delayed(const Duration(seconds: 10));
} }
await parent.delete(recursive: true); rmTree(parent);
} }
} }
...@@ -244,7 +244,7 @@ void createIndexAndCleanup() { ...@@ -244,7 +244,7 @@ void createIndexAndCleanup() {
void removeOldFlutterDocsDir() { void removeOldFlutterDocsDir() {
try { try {
new Directory('$kDocRoot/flutter').deleteSync(recursive: true); new Directory('$kDocRoot/flutter').deleteSync(recursive: true);
} catch (e) { } on FileSystemException {
// If the directory does not exist, that's OK. // If the directory does not exist, that's OK.
} }
} }
......
...@@ -2,13 +2,26 @@ ...@@ -2,13 +2,26 @@
// Use of this source code is governed by a BSD-style license that can be // Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file. // found in the LICENSE file.
import 'dart:io';
import 'package:test/test.dart' hide TypeMatcher, isInstanceOf; import 'package:test/test.dart' hide TypeMatcher, isInstanceOf;
import 'package:test/test.dart' as test_package show TypeMatcher; import 'package:test/test.dart' as test_package show TypeMatcher;
export 'package:test/test.dart' hide TypeMatcher, isInstanceOf; export 'package:test/test.dart' hide TypeMatcher, isInstanceOf;
// Defines a 'package:test' shim. // 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. /// A matcher that compares the type of the actual value to the type argument T.
Matcher isInstanceOf<T>() => new test_package.TypeMatcher<T>(); // ignore: prefer_const_constructors, https://github.com/dart-lang/sdk/issues/32544 Matcher isInstanceOf<T>() => new test_package.TypeMatcher<T>(); // 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
...@@ -287,11 +287,11 @@ void main() { ...@@ -287,11 +287,11 @@ void main() {
setUp(() { setUp(() {
useMemoryFileSystemForTesting(); useMemoryFileSystemForTesting();
tempDir = fs.systemTempDirectory.createTempSync('flutter_driver_test'); tempDir = fs.systemTempDirectory.createTempSync('flutter_driver_test.');
}); });
tearDown(() { tearDown(() {
tempDir.deleteSync(recursive: true); tryToDelete(tempDir);
restoreFileSystem(); restoreFileSystem();
}); });
......
...@@ -21,7 +21,7 @@ import 'package:flutter_tools/src/test/coverage_collector.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/test/runner.dart';
import 'package:flutter_tools/src/usage.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 _kOptionPackages = 'packages';
const String _kOptionShell = 'shell'; const String _kOptionShell = 'shell';
...@@ -71,10 +71,10 @@ Future<Null> run(List<String> args) async { ...@@ -71,10 +71,10 @@ Future<Null> run(List<String> args) async {
.any((String option) => !argResults.options.contains(option))) { .any((String option) => !argResults.options.contains(option))) {
throwToolExit('Missing option! All options must be specified.'); throwToolExit('Missing option! All options must be specified.');
} }
final Directory tempDirectory = final Directory tempDir =
fs.systemTempDirectory.createTempSync('fuchsia_tester'); fs.systemTempDirectory.createTempSync('flutter_fuchsia_tester.');
try { try {
Cache.flutterRoot = tempDirectory.path; Cache.flutterRoot = tempDir.path;
final Directory testDirectory = final Directory testDirectory =
fs.directory(argResults[_kOptionTestDirectory]); fs.directory(argResults[_kOptionTestDirectory]);
final File testFile = fs.file(argResults[_kOptionTestFile]); final File testFile = fs.file(argResults[_kOptionTestFile]);
...@@ -130,13 +130,13 @@ Future<Null> run(List<String> args) async { ...@@ -130,13 +130,13 @@ Future<Null> run(List<String> args) async {
// collector expects currentDirectory to be the root of the dart // collector expects currentDirectory to be the root of the dart
// package (i.e. contains lib/ and test/ sub-dirs). // package (i.e. contains lib/ and test/ sub-dirs).
fs.currentDirectory = testDirectory.parent; fs.currentDirectory = testDirectory.parent;
if (!await if (!await collector.collectCoverageData(argResults[_kOptionCoveragePath]))
collector.collectCoverageData(argResults[_kOptionCoveragePath]))
throwToolExit('Failed to collect coverage data'); throwToolExit('Failed to collect coverage data');
} }
} finally { } 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); exit(exitCode);
} }
...@@ -175,8 +175,7 @@ abstract class IOSApp extends ApplicationPackage { ...@@ -175,8 +175,7 @@ abstract class IOSApp extends ApplicationPackage {
bundleDir = fs.directory(applicationBinary); bundleDir = fs.directory(applicationBinary);
} else { } else {
// Try to unpack as an ipa. // Try to unpack as an ipa.
final Directory tempDir = fs.systemTempDirectory.createTempSync( final Directory tempDir = fs.systemTempDirectory.createTempSync('flutter_app.');
'flutter_app_');
addShutdownHook(() async { addShutdownHook(() async {
await tempDir.delete(recursive: true); await tempDir.delete(recursive: true);
}, ShutdownStage.STILL_RECORDING); }, ShutdownStage.STILL_RECORDING);
......
...@@ -215,13 +215,13 @@ class UpdatePackagesCommand extends FlutterCommand { ...@@ -215,13 +215,13 @@ class UpdatePackagesCommand extends FlutterCommand {
// pub tool will attempt to bring these dependencies up to the most recent // pub tool will attempt to bring these dependencies up to the most recent
// possible versions while honoring all their constraints. // possible versions while honoring all their constraints.
final PubDependencyTree tree = new PubDependencyTree(); // object to collect results 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 { try {
final File fakePackage = _pubspecFor(temporaryDirectory); final File fakePackage = _pubspecFor(tempDir);
fakePackage.createSync(); fakePackage.createSync();
fakePackage.writeAsStringSync(_generateFakePubspec(dependencies.values)); fakePackage.writeAsStringSync(_generateFakePubspec(dependencies.values));
// First we run "pub upgrade" on this generated package: // 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 // 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 // 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 // of all the dependencies so that we can figure out the transitive
...@@ -230,12 +230,12 @@ class UpdatePackagesCommand extends FlutterCommand { ...@@ -230,12 +230,12 @@ class UpdatePackagesCommand extends FlutterCommand {
await pub( await pub(
<String>['deps', '--style=compact'], <String>['deps', '--style=compact'],
context: PubContext.updatePackages, context: PubContext.updatePackages,
directory: temporaryDirectory.path, directory: tempDir.path,
filter: tree.fill, filter: tree.fill,
retry: false, // errors here are usually fatal since we're not hitting the network retry: false, // errors here are usually fatal since we're not hitting the network
); );
} finally { } finally {
temporaryDirectory.deleteSync(recursive: true); tempDir.deleteSync(recursive: true);
} }
// The transitive dependency tree for the fake package does not contain // The transitive dependency tree for the fake package does not contain
......
...@@ -318,13 +318,11 @@ Future<XcodeBuildResult> buildXcodeProject({ ...@@ -318,13 +318,11 @@ Future<XcodeBuildResult> buildXcodeProject({
Status buildSubStatus; Status buildSubStatus;
Status initialBuildStatus; Status initialBuildStatus;
Directory scriptOutputPipeTempDirectory; Directory tempDir;
if (logger.supportsColor) { if (logger.supportsColor) {
scriptOutputPipeTempDirectory = fs.systemTempDirectory tempDir = fs.systemTempDirectory.createTempSync('flutter_build_log_pipe.');
.createTempSync('flutter_build_log_pipe'); final File scriptOutputPipeFile = tempDir.childFile('pipe_to_stdout');
final File scriptOutputPipeFile =
scriptOutputPipeTempDirectory.childFile('pipe_to_stdout');
os.makePipe(scriptOutputPipeFile.path); os.makePipe(scriptOutputPipeFile.path);
Future<void> listenToScriptOutputLine() async { Future<void> listenToScriptOutputLine() async {
...@@ -362,7 +360,7 @@ Future<XcodeBuildResult> buildXcodeProject({ ...@@ -362,7 +360,7 @@ Future<XcodeBuildResult> buildXcodeProject({
initialBuildStatus?.cancel(); initialBuildStatus?.cancel();
buildStopwatch.stop(); buildStopwatch.stop();
// Free pipe file. // Free pipe file.
scriptOutputPipeTempDirectory?.deleteSync(recursive: true); tempDir?.deleteSync(recursive: true);
printStatus( printStatus(
'Xcode build done.', 'Xcode build done.',
ansiAlternative: 'Xcode build done.'.padRight(kDefaultStatusPadding + 1) ansiAlternative: 'Xcode build done.'.padRight(kDefaultStatusPadding + 1)
......
...@@ -233,13 +233,13 @@ class FlutterCommandRunner extends CommandRunner<Null> { ...@@ -233,13 +233,13 @@ class FlutterCommandRunner extends CommandRunner<Null> {
if (topLevelResults['bug-report']) { if (topLevelResults['bug-report']) {
// --bug-report implies --record-to=<tmp_path> // --bug-report implies --record-to=<tmp_path>
final Directory tmp = await const LocalFileSystem() final Directory tempDir = const LocalFileSystem()
.systemTempDirectory .systemTempDirectory
.createTemp('flutter_tools_'); .createTempSync('flutter_tools_bug_report.');
recordTo = tmp.path; recordTo = tempDir.path;
// Record the arguments that were used to invoke this runner. // 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() final StringBuffer buffer = new StringBuffer()
..writeln('# arguments') ..writeln('# arguments')
..writeln(topLevelResults.arguments) ..writeln(topLevelResults.arguments)
...@@ -251,13 +251,14 @@ class FlutterCommandRunner extends CommandRunner<Null> { ...@@ -251,13 +251,14 @@ class FlutterCommandRunner extends CommandRunner<Null> {
// ZIP the recording up once the recording has been serialized. // ZIP the recording up once the recording has been serialized.
addShutdownHook(() async { addShutdownHook(() async {
final File zipFile = getUniqueFile(fs.currentDirectory, 'bugreport', 'zip'); final File zipFile = getUniqueFile(fs.currentDirectory, 'bugreport', 'zip');
os.zip(tmp, zipFile); os.zip(tempDir, zipFile);
printStatus( printStatus(
'Bug report written to ${zipFile.basename}.\n' 'Bug report written to ${zipFile.basename}.\n'
'Note that this bug report contains local paths, device ' 'Note that this bug report contains local paths, device '
'identifiers, and log snippets.'); 'identifiers, and log snippets.'
);
}, ShutdownStage.POST_PROCESS_RECORDING); }, ShutdownStage.POST_PROCESS_RECORDING);
addShutdownHook(() => tmp.delete(recursive: true), ShutdownStage.CLEANUP); addShutdownHook(() => tempDir.delete(recursive: true), ShutdownStage.CLEANUP);
} }
assert(recordTo == null || replayFrom == null); assert(recordTo == null || replayFrom == null);
......
...@@ -136,7 +136,7 @@ class CoverageCollector extends TestWatcher { ...@@ -136,7 +136,7 @@ class CoverageCollector extends TestWatcher {
return false; return false;
} }
final Directory tempDir = fs.systemTempDirectory.createTempSync('flutter_tools'); final Directory tempDir = fs.systemTempDirectory.createTempSync('flutter_tools_test_coverage.');
try { try {
final File sourceFile = coverageFile.copySync(fs.path.join(tempDir.path, 'lcov.source.info')); final File sourceFile = coverageFile.copySync(fs.path.join(tempDir.path, 'lcov.source.info'));
final ProcessResult result = processManager.runSync(<String>[ final ProcessResult result = processManager.runSync(<String>[
......
...@@ -203,7 +203,7 @@ class _Compiler { ...@@ -203,7 +203,7 @@ class _Compiler {
// Incremental compilation requests done for each test copy that file away // Incremental compilation requests done for each test copy that file away
// for independent execution. // for independent execution.
final Directory outputDillDirectory = fs.systemTempDirectory final Directory outputDillDirectory = fs.systemTempDirectory
.createTempSync('output_dill'); .createTempSync('flutter_test_compiler.');
final File outputDill = outputDillDirectory.childFile('output.dill'); final File outputDill = outputDillDirectory.childFile('output.dill');
bool suppressOutput = false; bool suppressOutput = false;
...@@ -656,15 +656,15 @@ class _FlutterPlatform extends PlatformPlugin { ...@@ -656,15 +656,15 @@ class _FlutterPlatform extends PlatformPlugin {
String _createListenerDart(List<_Finalizer> finalizers, int ourTestCount, String _createListenerDart(List<_Finalizer> finalizers, int ourTestCount,
String testPath, HttpServer server) { String testPath, HttpServer server) {
// Prepare a temporary directory to store the Dart file that will talk to us. // Prepare a temporary directory to store the Dart file that will talk to us.
final Directory temporaryDirectory = fs.systemTempDirectory final Directory tempDir = fs.systemTempDirectory
.createTempSync('dart_test_listener'); .createTempSync('flutter_test_listener.');
finalizers.add(() async { finalizers.add(() async {
printTrace('test $ourTestCount: deleting temporary directory'); 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. // 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.createSync();
listenerFile.writeAsStringSync(_generateTestMain( listenerFile.writeAsStringSync(_generateTestMain(
testUrl: fs.path.toUri(fs.path.absolute(testPath)), testUrl: fs.path.toUri(fs.path.absolute(testPath)),
...@@ -683,7 +683,7 @@ class _FlutterPlatform extends PlatformPlugin { ...@@ -683,7 +683,7 @@ class _FlutterPlatform extends PlatformPlugin {
// bundlePath needs to point to a folder with `platform.dill` file. // bundlePath needs to point to a folder with `platform.dill` file.
final Directory tempBundleDirectory = fs.systemTempDirectory final Directory tempBundleDirectory = fs.systemTempDirectory
.createTempSync('flutter_bundle_directory'); .createTempSync('flutter_test_bundle.');
finalizers.add(() async { finalizers.add(() async {
printTrace( printTrace(
'test $ourTestCount: deleting temporary bundle directory'); 'test $ourTestCount: deleting temporary bundle directory');
...@@ -757,7 +757,7 @@ class _FlutterPlatform extends PlatformPlugin { ...@@ -757,7 +757,7 @@ class _FlutterPlatform extends PlatformPlugin {
sb.writeln(' <cachedir>/var/cache/fontconfig</cachedir>'); sb.writeln(' <cachedir>/var/cache/fontconfig</cachedir>');
sb.writeln('</fontconfig>'); sb.writeln('</fontconfig>');
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 = fs.file('${fontsDir.path}/fonts.conf');
_cachedFontConfig.createSync(); _cachedFontConfig.createSync();
_cachedFontConfig.writeAsStringSync(sb.toString()); _cachedFontConfig.writeAsStringSync(sb.toString());
......
...@@ -21,7 +21,7 @@ import 'src/context.dart'; ...@@ -21,7 +21,7 @@ import 'src/context.dart';
void main() { void main() {
group('analytics', () { group('analytics', () {
Directory temp; Directory tempDir;
setUpAll(() { setUpAll(() {
Cache.disableLocking(); Cache.disableLocking();
...@@ -29,11 +29,11 @@ void main() { ...@@ -29,11 +29,11 @@ void main() {
setUp(() { setUp(() {
Cache.flutterRoot = '../..'; Cache.flutterRoot = '../..';
temp = fs.systemTempDirectory.createTempSync('flutter_tools'); tempDir = fs.systemTempDirectory.createTempSync('flutter_tools_analytics_test.');
}); });
tearDown(() { tearDown(() {
temp.deleteSync(recursive: true); tryToDelete(tempDir);
}); });
// Ensure we don't send anything when analytics is disabled. // Ensure we don't send anything when analytics is disabled.
...@@ -42,11 +42,11 @@ void main() { ...@@ -42,11 +42,11 @@ void main() {
flutterUsage.onSend.listen((Map<String, dynamic> data) => count++); flutterUsage.onSend.listen((Map<String, dynamic> data) => count++);
flutterUsage.enabled = false; flutterUsage.enabled = false;
await createProject(temp); await createProject(tempDir);
expect(count, 0); expect(count, 0);
flutterUsage.enabled = true; flutterUsage.enabled = true;
await createProject(temp); await createProject(tempDir);
expect(count, flutterUsage.isFirstRun ? 0 : 2); expect(count, flutterUsage.isFirstRun ? 0 : 2);
count = 0; count = 0;
...@@ -57,7 +57,7 @@ void main() { ...@@ -57,7 +57,7 @@ void main() {
expect(count, 0); expect(count, 0);
}, overrides: <Type, Generator>{ }, overrides: <Type, Generator>{
FlutterVersion: () => new FlutterVersion(const Clock()), 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. // Ensure we don't send for the 'flutter config' command.
...@@ -76,7 +76,7 @@ void main() { ...@@ -76,7 +76,7 @@ void main() {
expect(count, 0); expect(count, 0);
}, overrides: <Type, Generator>{ }, overrides: <Type, Generator>{
FlutterVersion: () => new FlutterVersion(const Clock()), FlutterVersion: () => new FlutterVersion(const Clock()),
Usage: () => new Usage(configDirOverride: temp.path), Usage: () => new Usage(configDirOverride: tempDir.path),
}); });
}); });
...@@ -151,9 +151,14 @@ void main() { ...@@ -151,9 +151,14 @@ void main() {
}); });
group('analytics bots', () { group('analytics bots', () {
Directory temp; Directory tempDir;
setUp(() { 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 { testUsingContext('don\'t send on bots', () async {
...@@ -166,7 +171,7 @@ void main() { ...@@ -166,7 +171,7 @@ void main() {
Usage: () => new Usage( Usage: () => new Usage(
settingsName: 'flutter_bot_test', settingsName: 'flutter_bot_test',
versionOverride: 'dev/unknown', versionOverride: 'dev/unknown',
configDirOverride: temp.path, configDirOverride: tempDir.path,
), ),
}); });
...@@ -181,7 +186,7 @@ void main() { ...@@ -181,7 +186,7 @@ void main() {
Usage: () => new Usage( Usage: () => new Usage(
settingsName: 'flutter_bot_test', settingsName: 'flutter_bot_test',
versionOverride: 'dev/unknown', versionOverride: 'dev/unknown',
configDirOverride: temp.path, configDirOverride: tempDir.path,
), ),
}); });
}); });
......
...@@ -30,8 +30,10 @@ void main() { ...@@ -30,8 +30,10 @@ void main() {
Directory sdkDir; Directory sdkDir;
tearDown(() { tearDown(() {
sdkDir?.deleteSync(recursive: true); if (sdkDir != null) {
sdkDir = null; tryToDelete(sdkDir);
sdkDir = null;
}
}); });
testUsingContext('parse sdk', () { testUsingContext('parse sdk', () {
......
...@@ -39,7 +39,6 @@ void main() { ...@@ -39,7 +39,6 @@ void main() {
testUsingContext('licensesAccepted throws if cannot run sdkmanager', () async { testUsingContext('licensesAccepted throws if cannot run sdkmanager', () async {
processManager.succeed = false; processManager.succeed = false;
MockAndroidSdk.createSdkDirectory();
when(sdk.sdkManagerPath).thenReturn('/foo/bar/sdkmanager'); when(sdk.sdkManagerPath).thenReturn('/foo/bar/sdkmanager');
final AndroidWorkflow androidWorkflow = new AndroidWorkflow(); final AndroidWorkflow androidWorkflow = new AndroidWorkflow();
expect(androidWorkflow.licensesAccepted, throwsToolExit()); expect(androidWorkflow.licensesAccepted, throwsToolExit());
...@@ -52,7 +51,6 @@ void main() { ...@@ -52,7 +51,6 @@ void main() {
}); });
testUsingContext('licensesAccepted handles garbage/no output', () async { testUsingContext('licensesAccepted handles garbage/no output', () async {
MockAndroidSdk.createSdkDirectory();
when(sdk.sdkManagerPath).thenReturn('/foo/bar/sdkmanager'); when(sdk.sdkManagerPath).thenReturn('/foo/bar/sdkmanager');
final AndroidWorkflow androidWorkflow = new AndroidWorkflow(); final AndroidWorkflow androidWorkflow = new AndroidWorkflow();
final LicensesAccepted result = await androidWorkflow.licensesAccepted; final LicensesAccepted result = await androidWorkflow.licensesAccepted;
...@@ -68,7 +66,6 @@ void main() { ...@@ -68,7 +66,6 @@ void main() {
}); });
testUsingContext('licensesAccepted works for all licenses accepted', () async { testUsingContext('licensesAccepted works for all licenses accepted', () async {
MockAndroidSdk.createSdkDirectory();
when(sdk.sdkManagerPath).thenReturn('/foo/bar/sdkmanager'); when(sdk.sdkManagerPath).thenReturn('/foo/bar/sdkmanager');
processManager.processFactory = processMetaFactory(<String>[ processManager.processFactory = processMetaFactory(<String>[
'[=======================================] 100% Computing updates... ', '[=======================================] 100% Computing updates... ',
...@@ -87,7 +84,6 @@ void main() { ...@@ -87,7 +84,6 @@ void main() {
}); });
testUsingContext('licensesAccepted works for some licenses accepted', () async { testUsingContext('licensesAccepted works for some licenses accepted', () async {
MockAndroidSdk.createSdkDirectory();
when(sdk.sdkManagerPath).thenReturn('/foo/bar/sdkmanager'); when(sdk.sdkManagerPath).thenReturn('/foo/bar/sdkmanager');
processManager.processFactory = processMetaFactory(<String>[ processManager.processFactory = processMetaFactory(<String>[
'[=======================================] 100% Computing updates... ', '[=======================================] 100% Computing updates... ',
...@@ -107,7 +103,6 @@ void main() { ...@@ -107,7 +103,6 @@ void main() {
}); });
testUsingContext('licensesAccepted works for no licenses accepted', () async { testUsingContext('licensesAccepted works for no licenses accepted', () async {
MockAndroidSdk.createSdkDirectory();
when(sdk.sdkManagerPath).thenReturn('/foo/bar/sdkmanager'); when(sdk.sdkManagerPath).thenReturn('/foo/bar/sdkmanager');
processManager.processFactory = processMetaFactory(<String>[ processManager.processFactory = processMetaFactory(<String>[
'[=======================================] 100% Computing updates... ', '[=======================================] 100% Computing updates... ',
...@@ -127,7 +122,6 @@ void main() { ...@@ -127,7 +122,6 @@ void main() {
}); });
testUsingContext('runLicenseManager succeeds for version >= 26', () async { testUsingContext('runLicenseManager succeeds for version >= 26', () async {
MockAndroidSdk.createSdkDirectory();
when(sdk.sdkManagerPath).thenReturn('/foo/bar/sdkmanager'); when(sdk.sdkManagerPath).thenReturn('/foo/bar/sdkmanager');
when(sdk.sdkManagerVersion).thenReturn('26.0.0'); when(sdk.sdkManagerVersion).thenReturn('26.0.0');
...@@ -141,7 +135,6 @@ void main() { ...@@ -141,7 +135,6 @@ void main() {
}); });
testUsingContext('runLicenseManager errors for version < 26', () async { testUsingContext('runLicenseManager errors for version < 26', () async {
MockAndroidSdk.createSdkDirectory();
when(sdk.sdkManagerPath).thenReturn('/foo/bar/sdkmanager'); when(sdk.sdkManagerPath).thenReturn('/foo/bar/sdkmanager');
when(sdk.sdkManagerVersion).thenReturn('25.0.0'); when(sdk.sdkManagerVersion).thenReturn('25.0.0');
...@@ -155,7 +148,6 @@ void main() { ...@@ -155,7 +148,6 @@ void main() {
}); });
testUsingContext('runLicenseManager errors correctly for null version', () async { testUsingContext('runLicenseManager errors correctly for null version', () async {
MockAndroidSdk.createSdkDirectory();
when(sdk.sdkManagerPath).thenReturn('/foo/bar/sdkmanager'); when(sdk.sdkManagerPath).thenReturn('/foo/bar/sdkmanager');
when(sdk.sdkManagerVersion).thenReturn(null); when(sdk.sdkManagerVersion).thenReturn(null);
...@@ -169,7 +161,6 @@ void main() { ...@@ -169,7 +161,6 @@ void main() {
}); });
testUsingContext('runLicenseManager errors when sdkmanager is not found', () async { testUsingContext('runLicenseManager errors when sdkmanager is not found', () async {
MockAndroidSdk.createSdkDirectory();
when(sdk.sdkManagerPath).thenReturn('/foo/bar/sdkmanager'); when(sdk.sdkManagerPath).thenReturn('/foo/bar/sdkmanager');
processManager.succeed = false; processManager.succeed = false;
......
...@@ -18,12 +18,12 @@ void main() { ...@@ -18,12 +18,12 @@ void main() {
CachedArtifacts artifacts; CachedArtifacts artifacts;
setUp(() { setUp(() {
tempDir = fs.systemTempDirectory.createTempSync('flutter_temp'); tempDir = fs.systemTempDirectory.createTempSync('flutter_tools_artifacts_test_cached.');
artifacts = new CachedArtifacts(); artifacts = new CachedArtifacts();
}); });
tearDown(() { tearDown(() {
tempDir.deleteSync(recursive: true); tryToDelete(tempDir);
}); });
testUsingContext('getArtifactPath', () { testUsingContext('getArtifactPath', () {
...@@ -69,7 +69,7 @@ void main() { ...@@ -69,7 +69,7 @@ void main() {
LocalEngineArtifacts artifacts; LocalEngineArtifacts artifacts;
setUp(() { setUp(() {
tempDir = fs.systemTempDirectory.createTempSync('flutter_temp'); tempDir = fs.systemTempDirectory.createTempSync('flutter_tools_artifacts_test_local.');
artifacts = new LocalEngineArtifacts(tempDir.path, artifacts = new LocalEngineArtifacts(tempDir.path,
fs.path.join(tempDir.path, 'out', 'android_debug_unopt'), fs.path.join(tempDir.path, 'out', 'android_debug_unopt'),
fs.path.join(tempDir.path, 'out', 'host_debug_unopt'), fs.path.join(tempDir.path, 'out', 'host_debug_unopt'),
...@@ -77,7 +77,7 @@ void main() { ...@@ -77,7 +77,7 @@ void main() {
}); });
tearDown(() { tearDown(() {
tempDir.deleteSync(recursive: true); tryToDelete(tempDir);
}); });
testUsingContext('getArtifactPath', () { testUsingContext('getArtifactPath', () {
......
...@@ -95,20 +95,14 @@ $fontsSection ...@@ -95,20 +95,14 @@ $fontsSection
Directory oldCurrentDir; Directory oldCurrentDir;
setUp(() async { setUp(() async {
tempDir = await fs.systemTempDirectory.createTemp('asset_bundle_tests'); tempDir = fs.systemTempDirectory.createTempSync('flutter_asset_bundle_test.');
oldCurrentDir = fs.currentDirectory; oldCurrentDir = fs.currentDirectory;
fs.currentDirectory = tempDir; fs.currentDirectory = tempDir;
}); });
tearDown(() { tearDown(() {
fs.currentDirectory = oldCurrentDir; fs.currentDirectory = oldCurrentDir;
try { tryToDelete(tempDir);
tempDir?.deleteSync(recursive: true);
tempDir = null;
} on FileSystemException catch (e) {
// Do nothing, windows sometimes has trouble deleting.
print('Ignored exception during tearDown: $e');
}
}); });
group('AssetBundle fonts from packages', () { group('AssetBundle fonts from packages', () {
......
...@@ -106,20 +106,14 @@ $assetsSection ...@@ -106,20 +106,14 @@ $assetsSection
Directory oldCurrentDir; Directory oldCurrentDir;
setUp(() async { setUp(() async {
tempDir = await fs.systemTempDirectory.createTemp('asset_bundle_tests'); tempDir = fs.systemTempDirectory.createTempSync('flutter_asset_bundle_test.');
oldCurrentDir = fs.currentDirectory; oldCurrentDir = fs.currentDirectory;
fs.currentDirectory = tempDir; fs.currentDirectory = tempDir;
}); });
tearDown(() { tearDown(() {
fs.currentDirectory = oldCurrentDir; fs.currentDirectory = oldCurrentDir;
try { tryToDelete(tempDir);
tempDir?.deleteSync(recursive: true);
tempDir = null;
} on FileSystemException catch (e) {
// Do nothing, windows sometimes has trouble deleting.
print('Ignored exception during tearDown: $e');
}
}); });
group('AssetBundle assets from packages', () { group('AssetBundle assets from packages', () {
......
...@@ -25,20 +25,14 @@ void main() { ...@@ -25,20 +25,14 @@ void main() {
Directory oldCurrentDir; Directory oldCurrentDir;
setUp(() async { setUp(() async {
tempDir = await fs.systemTempDirectory.createTemp('asset_bundle_tests'); tempDir = fs.systemTempDirectory.createTempSync('flutter_asset_bundle_test.');
oldCurrentDir = fs.currentDirectory; oldCurrentDir = fs.currentDirectory;
fs.currentDirectory = tempDir; fs.currentDirectory = tempDir;
}); });
tearDown(() { tearDown(() {
fs.currentDirectory = oldCurrentDir; fs.currentDirectory = oldCurrentDir;
try { tryToDelete(tempDir);
tempDir?.deleteSync(recursive: true);
tempDir = null;
} on FileSystemException catch (e) {
// Do nothing, windows sometimes has trouble deleting.
print('Ignored exception during tearDown: $e');
}
}); });
testUsingContext('nonempty', () async { testUsingContext('nonempty', () async {
......
...@@ -20,20 +20,14 @@ void main() { ...@@ -20,20 +20,14 @@ void main() {
Directory oldCurrentDir; Directory oldCurrentDir;
setUp(() async { setUp(() async {
tempDir = await fs.systemTempDirectory.createTemp('asset_bundle_tests'); tempDir = fs.systemTempDirectory.createTempSync('flutter_asset_bundle_variant_test.');
oldCurrentDir = fs.currentDirectory; oldCurrentDir = fs.currentDirectory;
fs.currentDirectory = tempDir; fs.currentDirectory = tempDir;
}); });
tearDown(() { tearDown(() {
fs.currentDirectory = oldCurrentDir; fs.currentDirectory = oldCurrentDir;
try { tryToDelete(tempDir);
tempDir?.deleteSync(recursive: true);
tempDir = null;
} on FileSystemException catch (e) {
// Do nothing, windows sometimes has trouble deleting.
print('Ignored exception during tearDown: $e');
}
}); });
group('AssetBundle asset variants', () { group('AssetBundle asset variants', () {
......
...@@ -11,18 +11,18 @@ import '../src/context.dart'; ...@@ -11,18 +11,18 @@ import '../src/context.dart';
void main() { void main() {
group('OperatingSystemUtils', () { group('OperatingSystemUtils', () {
Directory temp; Directory tempDir;
setUp(() { setUp(() {
temp = fs.systemTempDirectory.createTempSync('flutter_tools'); tempDir = fs.systemTempDirectory.createTempSync('flutter_tools_os_utils_test.');
}); });
tearDown(() { tearDown(() {
temp.deleteSync(recursive: true); tryToDelete(tempDir);
}); });
testUsingContext('makeExecutable', () async { 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'); file.writeAsStringSync('hello world');
os.makeExecutable(file); os.makeExecutable(file);
......
...@@ -20,11 +20,11 @@ void main() { ...@@ -20,11 +20,11 @@ void main() {
setUp(() { setUp(() {
FlutterCommandRunner.initFlutterRoot(); FlutterCommandRunner.initFlutterRoot();
tempDir = fs.systemTempDirectory.createTempSync('analysis_test'); tempDir = fs.systemTempDirectory.createTempSync('flutter_analysis_test.');
}); });
tearDown(() { tearDown(() {
tempDir?.deleteSync(recursive: true); tryToDelete(tempDir);
return server?.dispose(); return server?.dispose();
}); });
......
...@@ -28,18 +28,13 @@ void main() { ...@@ -28,18 +28,13 @@ void main() {
setUpAll(() { setUpAll(() {
Cache.disableLocking(); 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'); projectPath = fs.path.join(tempDir.path, 'flutter_project');
libMain = fs.file(fs.path.join(projectPath, 'lib', 'main.dart')); libMain = fs.file(fs.path.join(projectPath, 'lib', 'main.dart'));
}); });
tearDownAll(() { tearDownAll(() {
try { tryToDelete(tempDir);
tempDir?.deleteSync(recursive: true);
} on FileSystemException catch (e) {
// ignore errors deleting the temporary directory
print('Ignored exception during tearDown: $e');
}
}); });
// Create a project to be analyzed // Create a project to be analyzed
...@@ -134,7 +129,7 @@ void main() { ...@@ -134,7 +129,7 @@ void main() {
}, timeout: allowForSlowAnalyzeTests); }, timeout: allowForSlowAnalyzeTests);
testUsingContext('no duplicate issues', () async { 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 { try {
final File foo = fs.file(fs.path.join(tempDir.path, 'foo.dart')); final File foo = fs.file(fs.path.join(tempDir.path, 'foo.dart'));
...@@ -163,7 +158,7 @@ void bar() { ...@@ -163,7 +158,7 @@ void bar() {
toolExit: true, toolExit: true,
); );
} finally { } finally {
tempDir.deleteSync(recursive: true); tryToDelete(tempDir);
} }
}); });
...@@ -171,7 +166,7 @@ void bar() { ...@@ -171,7 +166,7 @@ void bar() {
const String contents = ''' const String contents = '''
StringBuffer bar = StringBuffer('baz'); 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); tempDir.childFile('main.dart').writeAsStringSync(contents);
try { try {
await runCommand( await runCommand(
...@@ -180,7 +175,7 @@ StringBuffer bar = StringBuffer('baz'); ...@@ -180,7 +175,7 @@ StringBuffer bar = StringBuffer('baz');
statusTextContains: <String>['No issues found!'], statusTextContains: <String>['No issues found!'],
); );
} finally { } finally {
tempDir.deleteSync(recursive: true); tryToDelete(tempDir);
} }
}); });
}); });
......
...@@ -20,7 +20,11 @@ void main() { ...@@ -20,7 +20,11 @@ void main() {
fs = new MemoryFileSystem(); fs = new MemoryFileSystem();
fs.directory(_kFlutterRoot).createSync(recursive: true); fs.directory(_kFlutterRoot).createSync(recursive: true);
Cache.flutterRoot = _kFlutterRoot; Cache.flutterRoot = _kFlutterRoot;
tempDir = fs.systemTempDirectory.createTempSync('analysis_test'); tempDir = fs.systemTempDirectory.createTempSync('flutter_analysis_test.');
});
tearDown(() {
tryToDelete(tempDir);
}); });
group('analyze', () { group('analyze', () {
......
...@@ -24,7 +24,7 @@ const String frameworkChannel = 'omega'; ...@@ -24,7 +24,7 @@ const String frameworkChannel = 'omega';
void main() { void main() {
group('create', () { group('create', () {
Directory temp; Directory tempDir;
Directory projectDir; Directory projectDir;
FlutterVersion mockFlutterVersion; FlutterVersion mockFlutterVersion;
LoggingProcessManager loggingProcessManager; LoggingProcessManager loggingProcessManager;
...@@ -35,18 +35,13 @@ void main() { ...@@ -35,18 +35,13 @@ void main() {
setUp(() { setUp(() {
loggingProcessManager = new LoggingProcessManager(); loggingProcessManager = new LoggingProcessManager();
temp = fs.systemTempDirectory.createTempSync('flutter_tools'); tempDir = fs.systemTempDirectory.createTempSync('flutter_tools_create_test.');
projectDir = temp.childDirectory('flutter_project'); projectDir = tempDir.childDirectory('flutter_project');
mockFlutterVersion = new MockFlutterVersion(); mockFlutterVersion = new MockFlutterVersion();
}); });
tearDown(() { tearDown(() {
try { tryToDelete(tempDir);
temp.deleteSync(recursive: true);
} on FileSystemException catch (e) {
// ignore errors deleting the temporary directory
print('Ignored exception during tearDown: $e');
}
}); });
// Verify that we create a project that is well-formed. // Verify that we create a project that is well-formed.
......
...@@ -24,7 +24,7 @@ void main() { ...@@ -24,7 +24,7 @@ void main() {
DriveCommand command; DriveCommand command;
Device mockDevice; Device mockDevice;
MemoryFileSystem fs; MemoryFileSystem fs;
Directory cwd; Directory tempDir;
void withMockDevice([Device mock]) { void withMockDevice([Device mock]) {
mockDevice = mock ?? new MockDevice(); mockDevice = mock ?? new MockDevice();
...@@ -40,8 +40,8 @@ void main() { ...@@ -40,8 +40,8 @@ void main() {
command = new DriveCommand(); command = new DriveCommand();
applyMocksToCommand(command); applyMocksToCommand(command);
fs = new MemoryFileSystem(); fs = new MemoryFileSystem();
cwd = fs.systemTempDirectory.createTempSync('some_app_'); tempDir = fs.systemTempDirectory.createTempSync('flutter_drive_test.');
fs.currentDirectory = cwd; fs.currentDirectory = tempDir;
fs.directory('test').createSync(); fs.directory('test').createSync();
fs.directory('test_driver').createSync(); fs.directory('test_driver').createSync();
fs.file('pubspec.yaml')..createSync(); fs.file('pubspec.yaml')..createSync();
...@@ -68,13 +68,14 @@ void main() { ...@@ -68,13 +68,14 @@ void main() {
restoreAppStopper(); restoreAppStopper();
restoreTestRunner(); restoreTestRunner();
restoreTargetDeviceFinder(); restoreTargetDeviceFinder();
tryToDelete(tempDir);
}); });
testUsingContext('returns 1 when test file is not found', () async { testUsingContext('returns 1 when test file is not found', () async {
withMockDevice(); withMockDevice();
final String testApp = fs.path.join(cwd.path, 'test', 'e2e.dart'); final String testApp = fs.path.join(tempDir.path, 'test', 'e2e.dart');
final String testFile = fs.path.join(cwd.path, 'test_driver', 'e2e_test.dart'); final String testFile = fs.path.join(tempDir.path, 'test_driver', 'e2e_test.dart');
fs.file(testApp).createSync(recursive: true); fs.file(testApp).createSync(recursive: true);
final List<String> args = <String>[ final List<String> args = <String>[
...@@ -96,8 +97,8 @@ void main() { ...@@ -96,8 +97,8 @@ void main() {
withMockDevice(); withMockDevice();
appStarter = expectAsync1((DriveCommand command) async => null); appStarter = expectAsync1((DriveCommand command) async => null);
final String testApp = fs.path.join(cwd.path, 'test_driver', 'e2e.dart'); final String testApp = fs.path.join(tempDir.path, 'test_driver', 'e2e.dart');
final String testFile = fs.path.join(cwd.path, 'test_driver', 'e2e_test.dart'); final String testFile = fs.path.join(tempDir.path, 'test_driver', 'e2e_test.dart');
final MemoryFileSystem memFs = fs; final MemoryFileSystem memFs = fs;
await memFs.file(testApp).writeAsString('main() { }'); await memFs.file(testApp).writeAsString('main() { }');
...@@ -119,7 +120,7 @@ void main() { ...@@ -119,7 +120,7 @@ void main() {
}); });
testUsingContext('returns 1 when app file is outside package', () async { 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); fs.file(appFile).createSync(recursive: true);
final List<String> args = <String>[ final List<String> args = <String>[
'drive', 'drive',
...@@ -131,7 +132,7 @@ void main() { ...@@ -131,7 +132,7 @@ void main() {
} on ToolExit catch (e) { } on ToolExit catch (e) {
expect(e.exitCode ?? 1, 1); expect(e.exitCode ?? 1, 1);
expect(testLogger.errorText, contains( 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: <Type, Generator>{ }, overrides: <Type, Generator>{
...@@ -139,7 +140,7 @@ void main() { ...@@ -139,7 +140,7 @@ void main() {
}); });
testUsingContext('returns 1 when app file is in the root dir', () async { 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); fs.file(appFile).createSync(recursive: true);
final List<String> args = <String>[ final List<String> args = <String>[
'drive', 'drive',
...@@ -162,8 +163,8 @@ void main() { ...@@ -162,8 +163,8 @@ void main() {
testUsingContext('returns 0 when test ends successfully', () async { testUsingContext('returns 0 when test ends successfully', () async {
withMockDevice(); withMockDevice();
final String testApp = fs.path.join(cwd.path, 'test', 'e2e.dart'); final String testApp = fs.path.join(tempDir.path, 'test', 'e2e.dart');
final String testFile = fs.path.join(cwd.path, 'test_driver', 'e2e_test.dart'); final String testFile = fs.path.join(tempDir.path, 'test_driver', 'e2e_test.dart');
appStarter = expectAsync1((DriveCommand command) async { appStarter = expectAsync1((DriveCommand command) async {
return new LaunchResult.succeeded(); return new LaunchResult.succeeded();
...@@ -193,8 +194,8 @@ void main() { ...@@ -193,8 +194,8 @@ void main() {
testUsingContext('returns exitCode set by test runner', () async { testUsingContext('returns exitCode set by test runner', () async {
withMockDevice(); withMockDevice();
final String testApp = fs.path.join(cwd.path, 'test', 'e2e.dart'); final String testApp = fs.path.join(tempDir.path, 'test', 'e2e.dart');
final String testFile = fs.path.join(cwd.path, 'test_driver', 'e2e_test.dart'); final String testFile = fs.path.join(tempDir.path, 'test_driver', 'e2e_test.dart');
appStarter = expectAsync1((DriveCommand command) async { appStarter = expectAsync1((DriveCommand command) async {
return new LaunchResult.succeeded(); return new LaunchResult.succeeded();
......
...@@ -12,19 +12,19 @@ import '../src/context.dart'; ...@@ -12,19 +12,19 @@ import '../src/context.dart';
void main() { void main() {
group('format', () { group('format', () {
Directory temp; Directory tempDir;
setUp(() { setUp(() {
Cache.disableLocking(); Cache.disableLocking();
temp = fs.systemTempDirectory.createTempSync('flutter_tools'); tempDir = fs.systemTempDirectory.createTempSync('flutter_tools_format_test.');
}); });
tearDown(() { tearDown(() {
temp.deleteSync(recursive: true); tryToDelete(tempDir);
}); });
testUsingContext('a file', () async { 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 File srcFile = fs.file(fs.path.join(projectPath, 'lib', 'main.dart'));
final String original = srcFile.readAsStringSync(); final String original = srcFile.readAsStringSync();
...@@ -39,7 +39,7 @@ void main() { ...@@ -39,7 +39,7 @@ void main() {
}); });
testUsingContext('dry-run', () async { testUsingContext('dry-run', () async {
final String projectPath = await createProject(temp); final String projectPath = await createProject(tempDir);
final File srcFile = fs.file( final File srcFile = fs.file(
fs.path.join(projectPath, 'lib', 'main.dart')); fs.path.join(projectPath, 'lib', 'main.dart'));
...@@ -56,7 +56,7 @@ void main() { ...@@ -56,7 +56,7 @@ void main() {
}); });
testUsingContext('dry-run with set-exit-if-changed', () async { 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( final File srcFile = fs.file(
fs.path.join(projectPath, 'lib', 'main.dart')); fs.path.join(projectPath, 'lib', 'main.dart'));
......
...@@ -15,15 +15,15 @@ import '../src/context.dart'; ...@@ -15,15 +15,15 @@ import '../src/context.dart';
void main() { void main() {
group('ide_config', () { group('ide_config', () {
Directory temp; Directory tempDir;
Directory templateDir; Directory templateDir;
Directory intellijDir; Directory intellijDir;
Directory toolsDir; Directory toolsDir;
Map<String, String> _getFilesystemContents([Directory root]) { Map<String, String> _getFilesystemContents([Directory root]) {
final String tempPath = temp.absolute.path; final String tempPath = tempDir.absolute.path;
final List<String> paths = final List<String> 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); final String relativePath = fs.path.relative(entity.path, from: tempPath);
return relativePath; return relativePath;
}).toList(); }).toList();
...@@ -40,7 +40,7 @@ void main() { ...@@ -40,7 +40,7 @@ void main() {
} }
Map<String, String> _getManifest(Directory base, String marker, {bool isTemplate = false}) { Map<String, String> _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 : ''; final String suffix = isTemplate ? Template.copyTemplateExtension : '';
return <String, String>{ return <String, String>{
fs.path.join(basePath, '.idea'): 'dir', fs.path.join(basePath, '.idea'): 'dir',
...@@ -59,12 +59,12 @@ void main() { ...@@ -59,12 +59,12 @@ void main() {
void _populateDir(Map<String, String> manifest) { void _populateDir(Map<String, String> manifest) {
for (String key in manifest.keys) { for (String key in manifest.keys) {
if (manifest[key] == 'dir') { if (manifest[key] == 'dir') {
temp.childDirectory(key)..createSync(recursive: true); tempDir.childDirectory(key)..createSync(recursive: true);
} }
} }
for (String key in manifest.keys) { for (String key in manifest.keys) {
if (manifest[key] != 'dir') { if (manifest[key] != 'dir') {
temp.childFile(key) tempDir.childFile(key)
..createSync(recursive: true) ..createSync(recursive: true)
..writeAsStringSync(manifest[key]); ..writeAsStringSync(manifest[key]);
} }
...@@ -72,7 +72,7 @@ void main() { ...@@ -72,7 +72,7 @@ void main() {
} }
bool _fileOrDirectoryExists(String path) { 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(); return fs.file(absPath).existsSync() || fs.directory(absPath).existsSync();
} }
...@@ -82,15 +82,15 @@ void main() { ...@@ -82,15 +82,15 @@ void main() {
Map<String, String> expectedContents = const <String, String>{}, Map<String, String> expectedContents = const <String, String>{},
List<String> unexpectedPaths = const <String>[], List<String> unexpectedPaths = const <String>[],
}) async { }) async {
dir ??= temp; dir ??= tempDir;
final IdeConfigCommand command = new IdeConfigCommand(); final IdeConfigCommand command = new IdeConfigCommand();
final CommandRunner<Null> runner = createTestCommandRunner(command); final CommandRunner<Null> runner = createTestCommandRunner(command);
final List<String> finalArgs = <String>['--flutter-root=${temp.absolute.path}', 'ide-config']; final List<String> finalArgs = <String>['--flutter-root=${tempDir.absolute.path}', 'ide-config'];
finalArgs.addAll(args); finalArgs.addAll(args);
await runner.run(finalArgs); await runner.run(finalArgs);
for (String path in expectedContents.keys) { 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, expect(_fileOrDirectoryExists(fs.path.join(dir.path, path)), true,
reason: "$path doesn't exist"); reason: "$path doesn't exist");
if (fs.file(absPath).existsSync()) { if (fs.file(absPath).existsSync()) {
...@@ -108,15 +108,15 @@ void main() { ...@@ -108,15 +108,15 @@ void main() {
}); });
setUp(() { setUp(() {
temp = fs.systemTempDirectory.createTempSync('flutter_tools_'); tempDir = fs.systemTempDirectory.createTempSync('flutter_tools_ide_config_test.');
final Directory packagesDir = temp.childDirectory('packages')..createSync(recursive: true); final Directory packagesDir = tempDir.childDirectory('packages')..createSync(recursive: true);
toolsDir = packagesDir.childDirectory('flutter_tools')..createSync(); toolsDir = packagesDir.childDirectory('flutter_tools')..createSync();
templateDir = toolsDir.childDirectory('ide_templates')..createSync(); templateDir = toolsDir.childDirectory('ide_templates')..createSync();
intellijDir = templateDir.childDirectory('intellij')..createSync(); intellijDir = templateDir.childDirectory('intellij')..createSync();
}); });
tearDown(() { tearDown(() {
temp.deleteSync(recursive: true); tryToDelete(tempDir);
}); });
testUsingContext("doesn't touch existing files without --overwrite", () async { testUsingContext("doesn't touch existing files without --overwrite", () async {
...@@ -126,7 +126,7 @@ void main() { ...@@ -126,7 +126,7 @@ void main() {
isTemplate: true, isTemplate: true,
); );
final Map<String, String> flutterManifest = _getManifest( final Map<String, String> flutterManifest = _getManifest(
temp, tempDir,
'existing', 'existing',
); );
_populateDir(templateManifest); _populateDir(templateManifest);
...@@ -144,7 +144,7 @@ void main() { ...@@ -144,7 +144,7 @@ void main() {
isTemplate: true, isTemplate: true,
); );
final Map<String, String> flutterManifest = _getManifest( final Map<String, String> flutterManifest = _getManifest(
temp, tempDir,
'template', 'template',
); );
_populateDir(templateManifest); _populateDir(templateManifest);
...@@ -162,13 +162,13 @@ void main() { ...@@ -162,13 +162,13 @@ void main() {
isTemplate: true, isTemplate: true,
); );
final Map<String, String> flutterManifest = _getManifest( final Map<String, String> flutterManifest = _getManifest(
temp, tempDir,
'existing', 'existing',
); );
_populateDir(templateManifest); _populateDir(templateManifest);
_populateDir(flutterManifest); _populateDir(flutterManifest);
final Map<String, String> overwrittenManifest = _getManifest( final Map<String, String> overwrittenManifest = _getManifest(
temp, tempDir,
'template', 'template',
); );
final Map<String, String> expectedContents = templateManifest; final Map<String, String> expectedContents = templateManifest;
...@@ -196,7 +196,7 @@ void main() { ...@@ -196,7 +196,7 @@ void main() {
_populateDir(templateManifest); _populateDir(templateManifest);
templateManifest[flutterIml] = 'flutter existing'; templateManifest[flutterIml] = 'flutter existing';
final Map<String, String> flutterManifest = _getManifest( final Map<String, String> flutterManifest = _getManifest(
temp, tempDir,
'existing', 'existing',
); );
_populateDir(flutterManifest); _populateDir(flutterManifest);
...@@ -216,7 +216,7 @@ void main() { ...@@ -216,7 +216,7 @@ void main() {
); );
_populateDir(templateManifest); _populateDir(templateManifest);
final Map<String, String> flutterManifest = _getManifest( final Map<String, String> flutterManifest = _getManifest(
temp, tempDir,
'existing', 'existing',
); );
_populateDir(flutterManifest); _populateDir(flutterManifest);
...@@ -241,7 +241,7 @@ void main() { ...@@ -241,7 +241,7 @@ void main() {
); );
_populateDir(templateManifest); _populateDir(templateManifest);
final Map<String, String> flutterManifest = _getManifest( final Map<String, String> flutterManifest = _getManifest(
temp, tempDir,
'existing', 'existing',
); );
flutterManifest.remove('flutter.iml'); flutterManifest.remove('flutter.iml');
...@@ -275,7 +275,7 @@ void main() { ...@@ -275,7 +275,7 @@ void main() {
); );
_populateDir(templateManifest); _populateDir(templateManifest);
final Map<String, String> flutterManifest = _getManifest( final Map<String, String> flutterManifest = _getManifest(
temp, tempDir,
'existing', 'existing',
); );
flutterManifest.remove(fs.path.join('packages', 'new', 'deep.iml')); flutterManifest.remove(fs.path.join('packages', 'new', 'deep.iml'));
......
...@@ -35,18 +35,18 @@ class AlwaysFalseBotDetector implements BotDetector { ...@@ -35,18 +35,18 @@ class AlwaysFalseBotDetector implements BotDetector {
void main() { void main() {
Cache.disableLocking(); Cache.disableLocking();
group('packages get/upgrade', () { group('packages get/upgrade', () {
Directory temp; Directory tempDir;
setUp(() { setUp(() {
temp = fs.systemTempDirectory.createTempSync('flutter_tools'); tempDir = fs.systemTempDirectory.createTempSync('flutter_tools_packages_test.');
}); });
tearDown(() { tearDown(() {
temp.deleteSync(recursive: true); tryToDelete(tempDir);
}); });
Future<String> createProjectWithPlugin(String plugin) async { Future<String> 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')); final File pubspec = fs.file(fs.path.join(projectPath, 'pubspec.yaml'));
String content = await pubspec.readAsString(); String content = await pubspec.readAsString();
content = content.replaceFirst( content = content.replaceFirst(
...@@ -168,7 +168,7 @@ void main() { ...@@ -168,7 +168,7 @@ void main() {
} }
testUsingContext('get fetches packages', () async { testUsingContext('get fetches packages', () async {
final String projectPath = await createProject(temp); final String projectPath = await createProject(tempDir);
removeGeneratedFiles(projectPath); removeGeneratedFiles(projectPath);
await runCommandIn(projectPath, 'get'); await runCommandIn(projectPath, 'get');
...@@ -178,7 +178,7 @@ void main() { ...@@ -178,7 +178,7 @@ void main() {
}, timeout: allowForRemotePubInvocation); }, timeout: allowForRemotePubInvocation);
testUsingContext('get --offline fetches packages', () async { testUsingContext('get --offline fetches packages', () async {
final String projectPath = await createProject(temp); final String projectPath = await createProject(tempDir);
removeGeneratedFiles(projectPath); removeGeneratedFiles(projectPath);
await runCommandIn(projectPath, 'get', args: <String>['--offline']); await runCommandIn(projectPath, 'get', args: <String>['--offline']);
...@@ -188,7 +188,7 @@ void main() { ...@@ -188,7 +188,7 @@ void main() {
}, timeout: allowForCreateFlutterProject); }, timeout: allowForCreateFlutterProject);
testUsingContext('upgrade fetches packages', () async { testUsingContext('upgrade fetches packages', () async {
final String projectPath = await createProject(temp); final String projectPath = await createProject(tempDir);
removeGeneratedFiles(projectPath); removeGeneratedFiles(projectPath);
await runCommandIn(projectPath, 'upgrade'); await runCommandIn(projectPath, 'upgrade');
...@@ -210,7 +210,7 @@ void main() { ...@@ -210,7 +210,7 @@ void main() {
}, timeout: allowForRemotePubInvocation, skip: true); }, timeout: allowForRemotePubInvocation, skip: true);
testUsingContext('get fetches packages and injects plugin in plugin project', () async { testUsingContext('get fetches packages and injects plugin in plugin project', () async {
final String projectPath = await createProject( final String projectPath = await createProject(
temp, tempDir,
arguments: <String>['-t', 'plugin', '--no-pub'], arguments: <String>['-t', 'plugin', '--no-pub'],
); );
final String exampleProjectPath = fs.path.join(projectPath, 'example'); final String exampleProjectPath = fs.path.join(projectPath, 'example');
......
...@@ -35,18 +35,18 @@ void main() { ...@@ -35,18 +35,18 @@ void main() {
}); });
group('findProjectRoot', () { group('findProjectRoot', () {
Directory temp; Directory tempDir;
setUp(() async { setUp(() async {
temp = fs.systemTempDirectory.createTempSync('flutter_tools'); tempDir = fs.systemTempDirectory.createTempSync('flutter_tools_upgrade_test.');
}); });
tearDown(() { tearDown(() {
temp.deleteSync(recursive: true); tryToDelete(tempDir);
}); });
testUsingContext('in project', () async { testUsingContext('in project', () async {
final String projectPath = await createProject(temp); final String projectPath = await createProject(tempDir);
expect(findProjectRoot(projectPath), projectPath); expect(findProjectRoot(projectPath), projectPath);
expect(findProjectRoot(fs.path.join(projectPath, 'lib')), projectPath); expect(findProjectRoot(fs.path.join(projectPath, 'lib')), projectPath);
...@@ -56,7 +56,7 @@ void main() { ...@@ -56,7 +56,7 @@ void main() {
}); });
testUsingContext('outside project', () async { 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(fs.directory(projectPath).parent.path), null);
expect(findProjectRoot(Cache.flutterRoot), null); expect(findProjectRoot(Cache.flutterRoot), null);
}); });
......
...@@ -9,13 +9,18 @@ import 'src/common.dart'; ...@@ -9,13 +9,18 @@ import 'src/common.dart';
void main() { void main() {
Config config; Config config;
Directory tempDir;
setUp(() { setUp(() {
final Directory tempDirectory = fs.systemTempDirectory.createTempSync('flutter_test'); tempDir = fs.systemTempDirectory.createTempSync('flutter_config_test.');
final File file = fs.file(fs.path.join(tempDirectory.path, '.settings')); final File file = fs.file(fs.path.join(tempDir.path, '.settings'));
config = new Config(file); config = new Config(file);
}); });
tearDown(() {
tryToDelete(tempDir);
});
group('config', () { group('config', () {
test('get set value', () async { test('get set value', () async {
expect(config.getValue('foo'), null); expect(config.getValue('foo'), null);
......
...@@ -93,16 +93,18 @@ void main() { ...@@ -93,16 +93,18 @@ void main() {
/// Tests that the flutter tool doesn't crash and displays a warning when its own location /// 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. /// changed since it was last referenced to in a package's .packages file.
testUsingContext('moved flutter sdk', () async { 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. // Copy the golden input and let the test run in an isolated temporary in-memory file system.
const LocalFileSystem localFileSystem = LocalFileSystem(); const LocalFileSystem localFileSystem = LocalFileSystem();
final Directory sourcePath = localFileSystem.directory(localFileSystem.path.join(dataPath, 'changed_sdk_location')); final Directory sourcePath = localFileSystem.directory(localFileSystem.path.join(dataPath, 'changed_sdk_location'));
copyDirectorySync(sourcePath, destinationPath); copyDirectorySync(sourcePath, tempDir);
fs.currentDirectory = destinationPath; fs.currentDirectory = tempDir;
// Doesn't matter what commands we run. Arbitrarily list devices here. // Doesn't matter what commands we run. Arbitrarily list devices here.
await createTestCommandRunner(new DevicesCommand()).run(<String>['devices']); await createTestCommandRunner(new DevicesCommand()).run(<String>['devices']);
expect(testLogger.errorText, contains('.packages')); expect(testLogger.errorText, contains('.packages'));
tryToDelete(tempDir);
}, overrides: <Type, Generator>{ }, overrides: <Type, Generator>{
FileSystem: () => testFileSystem, FileSystem: () => testFileSystem,
}); });
......
...@@ -459,15 +459,14 @@ final List<Directory> _tempDirs = <Directory>[]; ...@@ -459,15 +459,14 @@ final List<Directory> _tempDirs = <Directory>[];
final Map <String, Uri> _packages = <String, Uri>{}; final Map <String, Uri> _packages = <String, Uri>{};
Directory _newTempDir(FileSystem fs) { 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); _tempDirs.add(tempDir);
return tempDir; return tempDir;
} }
void _cleanupTempDirs() { void _cleanupTempDirs() {
while (_tempDirs.isNotEmpty) { while (_tempDirs.isNotEmpty)
_tempDirs.removeLast().deleteSync(recursive: true); tryToDelete(_tempDirs.removeLast());
}
} }
Future<Null> _createPackage(FileSystem fs, String pkgName, String pkgFileName, { bool doubleSlash = false }) async { Future<Null> _createPackage(FileSystem fs, String pkgName, String pkgFileName, { bool doubleSlash = false }) async {
......
...@@ -13,24 +13,21 @@ import '../src/common.dart'; ...@@ -13,24 +13,21 @@ import '../src/common.dart';
import 'test_data/basic_project.dart'; import 'test_data/basic_project.dart';
import 'test_driver.dart'; import 'test_driver.dart';
BasicProject _project = new BasicProject();
FlutterTestDriver _flutter;
void main() { void main() {
group('expression evaluation', () { group('expression evaluation', () {
Directory tempDir;
final BasicProject _project = new BasicProject();
FlutterTestDriver _flutter;
setUp(() async { setUp(() async {
final Directory tempDir = await fs.systemTempDirectory.createTemp('test_app'); tempDir = fs.systemTempDirectory.createTempSync('flutter_expression_test.');
await _project.setUpIn(tempDir); await _project.setUpIn(tempDir);
_flutter = new FlutterTestDriver(tempDir); _flutter = new FlutterTestDriver(tempDir);
}); });
tearDown(() async { tearDown(() async {
try { await _flutter.stop();
await _flutter.stop(); tryToDelete(tempDir);
_project.cleanup();
} catch (e) {
// Don't fail tests if we failed to clean up temp folder.
}
}); });
Future<VMIsolate> breakInBuildMethod(FlutterTestDriver flutter) async { Future<VMIsolate> breakInBuildMethod(FlutterTestDriver flutter) async {
......
...@@ -11,26 +11,22 @@ import '../src/context.dart'; ...@@ -11,26 +11,22 @@ import '../src/context.dart';
import 'test_data/basic_project.dart'; import 'test_data/basic_project.dart';
import 'test_driver.dart'; import 'test_driver.dart';
FlutterTestDriver _flutterRun, _flutterAttach;
BasicProject _project = new BasicProject();
void main() { void main() {
FlutterTestDriver _flutterRun, _flutterAttach;
final BasicProject _project = new BasicProject();
Directory tempDir;
setUp(() async { setUp(() async {
final Directory tempDir = await fs.systemTempDirectory.createTemp('test_app'); tempDir = fs.systemTempDirectory.createTempSync('flutter_attach_test.');
await _project.setUpIn(tempDir); await _project.setUpIn(tempDir);
_flutterRun = new FlutterTestDriver(tempDir); _flutterRun = new FlutterTestDriver(tempDir);
_flutterAttach = new FlutterTestDriver(tempDir); _flutterAttach = new FlutterTestDriver(tempDir);
}); });
tearDown(() async { tearDown(() async {
try { await _flutterRun.stop();
await _flutterRun.stop(); await _flutterAttach.stop();
await _flutterAttach.stop(); tryToDelete(tempDir);
_project.cleanup();
} catch (e) {
// Don't fail tests if we failed to clean up temp folder.
}
}); });
group('attached process', () { group('attached process', () {
......
...@@ -19,19 +19,14 @@ void main() { ...@@ -19,19 +19,14 @@ void main() {
Directory oldCurrentDir; Directory oldCurrentDir;
setUp(() async { setUp(() async {
tempDir = await fs.systemTempDirectory.createTemp('flutter_tester_device'); tempDir = fs.systemTempDirectory.createTempSync('flutter_tester_device_test.');
oldCurrentDir = fs.currentDirectory; oldCurrentDir = fs.currentDirectory;
fs.currentDirectory = tempDir; fs.currentDirectory = tempDir;
}); });
tearDown(() { tearDown(() {
fs.currentDirectory = oldCurrentDir; fs.currentDirectory = oldCurrentDir;
try { tryToDelete(tempDir);
tempDir?.deleteSync(recursive: true);
tempDir = null;
} catch (e) {
// Ignored.
}
}); });
group('FlutterTesterDevice', () { group('FlutterTesterDevice', () {
......
...@@ -12,24 +12,21 @@ import '../src/common.dart'; ...@@ -12,24 +12,21 @@ import '../src/common.dart';
import 'test_data/basic_project.dart'; import 'test_data/basic_project.dart';
import 'test_driver.dart'; import 'test_driver.dart';
BasicProject _project = new BasicProject();
FlutterTestDriver _flutter;
void main() { void main() {
group('hot reload', () { group('hot reload', () {
Directory tempDir;
final BasicProject _project = new BasicProject();
FlutterTestDriver _flutter;
setUp(() async { setUp(() async {
final Directory tempDir = await fs.systemTempDirectory.createTemp('test_app'); tempDir = fs.systemTempDirectory.createTempSync('flutter_hot_reload_test_app.');
await _project.setUpIn(tempDir); await _project.setUpIn(tempDir);
_flutter = new FlutterTestDriver(tempDir); _flutter = new FlutterTestDriver(tempDir);
}); });
tearDown(() async { tearDown(() async {
try { await _flutter.stop();
await _flutter.stop(); tryToDelete(tempDir);
_project.cleanup();
} catch (e) {
// Don't fail tests if we failed to clean up temp folder.
}
}); });
test('works without error', () async { test('works without error', () async {
......
...@@ -12,9 +12,6 @@ import '../src/common.dart'; ...@@ -12,9 +12,6 @@ import '../src/common.dart';
import 'test_data/basic_project.dart'; import 'test_data/basic_project.dart';
import 'test_driver.dart'; import 'test_driver.dart';
BasicProject _project = new BasicProject();
FlutterTestDriver _flutter;
/// This duration is arbitrary but is ideally: /// This duration is arbitrary but is ideally:
/// a) long enough to ensure that if the app is crashing at startup, we notice /// 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 /// b) as short as possible, to avoid inflating build times
...@@ -22,15 +19,19 @@ const Duration requiredLifespan = Duration(seconds: 5); ...@@ -22,15 +19,19 @@ const Duration requiredLifespan = Duration(seconds: 5);
void main() { void main() {
group('flutter run', () { group('flutter run', () {
final BasicProject _project = new BasicProject();
FlutterTestDriver _flutter;
Directory tempDir;
setUp(() async { setUp(() async {
final Directory tempDir = await fs.systemTempDirectory.createTemp('test_app'); tempDir = fs.systemTempDirectory.createTempSync('flutter_lifetime_test.');
await _project.setUpIn(tempDir); await _project.setUpIn(tempDir);
_flutter = new FlutterTestDriver(tempDir); _flutter = new FlutterTestDriver(tempDir);
}); });
tearDown(() async { tearDown(() async {
await _flutter.stop(); await _flutter.stop();
_project.cleanup(); tryToDelete(tempDir);
}); });
test('does not terminate when a debugger is attached', () async { test('does not terminate when a debugger is attached', () async {
......
...@@ -26,10 +26,6 @@ abstract class TestProject { ...@@ -26,10 +26,6 @@ abstract class TestProject {
await getPackages(dir.path); await getPackages(dir.path);
} }
void cleanup() {
dir?.deleteSync(recursive: true);
}
int lineContaining(String contents, String search) { int lineContaining(String contents, String search) {
final int index = contents.split('\n').indexWhere((String l) => l.contains(search)); final int index = contents.split('\n').indexWhere((String l) => l.contains(search));
if (index == -1) if (index == -1)
......
...@@ -23,6 +23,8 @@ const Duration appStartTimeout = Duration(seconds: 60); ...@@ -23,6 +23,8 @@ const Duration appStartTimeout = Duration(seconds: 60);
const Duration quitTimeout = Duration(seconds: 5); const Duration quitTimeout = Duration(seconds: 5);
class FlutterTestDriver { class FlutterTestDriver {
FlutterTestDriver(this._projectFolder);
final Directory _projectFolder; final Directory _projectFolder;
Process _proc; Process _proc;
int _procPid; int _procPid;
...@@ -36,8 +38,6 @@ class FlutterTestDriver { ...@@ -36,8 +38,6 @@ class FlutterTestDriver {
int _vmServicePort; int _vmServicePort;
bool _hasExited = false; bool _hasExited = false;
FlutterTestDriver(this._projectFolder);
VMServiceClient vmService; VMServiceClient vmService;
String get lastErrorInfo => _errorBuffer.toString(); String get lastErrorInfo => _errorBuffer.toString();
int get vmServicePort => _vmServicePort; int get vmServicePort => _vmServicePort;
...@@ -318,24 +318,24 @@ class FlutterTestDriver { ...@@ -318,24 +318,24 @@ class FlutterTestDriver {
int id = 1; int id = 1;
Future<dynamic> _sendRequest(String method, dynamic params) async { Future<dynamic> _sendRequest(String method, dynamic params) async {
final int requestId = id++; final int requestId = id++;
final Map<String, dynamic> req = <String, dynamic>{ final Map<String, dynamic> request = <String, dynamic>{
'id': requestId, 'id': requestId,
'method': method, 'method': method,
'params': params 'params': params
}; };
final String jsonEncoded = json.encode(<Map<String, dynamic>>[req]); final String jsonEncoded = json.encode(<Map<String, dynamic>>[request]);
_debugPrint(jsonEncoded); _debugPrint(jsonEncoded);
// Set up the response future before we send the request to avoid any // Set up the response future before we send the request to avoid any
// races. // races.
final Future<Map<String, dynamic>> responseFuture = _waitFor(id: requestId); final Future<Map<String, dynamic>> responseFuture = _waitFor(id: requestId);
_proc.stdin.writeln(jsonEncoded); _proc.stdin.writeln(jsonEncoded);
final Map<String, dynamic> resp = await responseFuture; final Map<String, dynamic> response = await responseFuture;
if (resp['error'] != null || resp['result'] == null) if (response['error'] != null || response['result'] == null)
_throwErrorResponse('Unexpected error response'); _throwErrorResponse('Unexpected error response');
return resp['result']; return response['result'];
} }
void _throwErrorResponse(String msg) { void _throwErrorResponse(String msg) {
......
...@@ -22,6 +22,17 @@ export 'package:test/test.dart' hide TypeMatcher, isInstanceOf; // Defines a 'pa ...@@ -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 // TODO(ianh): Remove this once https://github.com/dart-lang/matcher/issues/98 is fixed
Matcher isInstanceOf<T>() => new test_package.TypeMatcher<T>(); // ignore: prefer_const_constructors, https://github.com/dart-lang/sdk/issues/32544 Matcher isInstanceOf<T>() => new test_package.TypeMatcher<T>(); // 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. /// Gets the path to the root of the Flutter repository.
/// ///
/// This will first look for a `FLUTTER_ROOT` environment variable. If the /// This will first look for a `FLUTTER_ROOT` environment variable. If the
......
...@@ -48,13 +48,16 @@ void testUsingContext(String description, dynamic testMethod(), { ...@@ -48,13 +48,16 @@ void testUsingContext(String description, dynamic testMethod(), {
// leak a sticky $HOME/.flutter_settings behind! // leak a sticky $HOME/.flutter_settings behind!
Directory configDir; Directory configDir;
tearDown(() { tearDown(() {
configDir?.deleteSync(recursive: true); if (configDir != null) {
configDir = null; tryToDelete(configDir);
configDir = null;
}
}); });
Config buildConfig(FileSystem fs) { Config buildConfig(FileSystem fs) {
configDir = fs.systemTempDirectory.createTempSync('config-dir'); configDir = fs.systemTempDirectory.createTempSync('flutter_config_dir_test.');
final File settingsFile = fs.file( final File settingsFile = fs.file(
fs.path.join(configDir.path, '.flutter_settings')); fs.path.join(configDir.path, '.flutter_settings')
);
return new Config(settingsFile); return new Config(settingsFile);
} }
......
...@@ -44,7 +44,7 @@ class MockAndroidSdk extends Mock implements AndroidSdk { ...@@ -44,7 +44,7 @@ class MockAndroidSdk extends Mock implements AndroidSdk {
bool withNdkSysroot = false, bool withNdkSysroot = false,
bool withSdkManager = true, 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'); _createSdkFile(dir, 'platform-tools/adb');
...@@ -66,18 +66,23 @@ class MockAndroidSdk extends Mock implements AndroidSdk { ...@@ -66,18 +66,23 @@ class MockAndroidSdk extends Mock implements AndroidSdk {
if (withNdkDir != null) { if (withNdkDir != null) {
final String ndkCompiler = fs.path.join( final String ndkCompiler = fs.path.join(
'ndk-bundle', 'ndk-bundle',
'toolchains', 'toolchains',
'arm-linux-androideabi-4.9', 'arm-linux-androideabi-4.9',
'prebuilt', 'prebuilt',
withNdkDir, withNdkDir,
'bin', 'bin',
'arm-linux-androideabi-gcc'); 'arm-linux-androideabi-gcc',
);
_createSdkFile(dir, ndkCompiler); _createSdkFile(dir, ndkCompiler);
} }
if (withNdkSysroot) { if (withNdkSysroot) {
final String armPlatform = final String armPlatform = fs.path.join(
fs.path.join('ndk-bundle', 'platforms', 'android-9', 'arch-arm'); 'ndk-bundle',
'platforms',
'android-9',
'arch-arm',
);
_createDir(dir, armPlatform); _createDir(dir, armPlatform);
} }
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment