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