Unnecessary new (#20138)

* enable lint unnecessary_new

* fix tests

* fix tests

* fix tests
This commit is contained in:
Alexandre Ardhuin
2018-09-12 08:29:29 +02:00
committed by GitHub
parent d7a0dcaa4a
commit d927c93310
1285 changed files with 26519 additions and 26519 deletions

View File

@@ -58,7 +58,7 @@ class Line {
Line operator +(int count) {
if (count == 0)
return this;
return new Line(filename, line + count, indent);
return Line(filename, line + count, indent);
}
@override
String toString([int column]) {
@@ -87,7 +87,7 @@ class Section {
}
}
List<Line> get lines {
final List<Line> result = new List<Line>.generate(code.length, (int index) => start + index);
final List<Line> result = List<Line>.generate(code.length, (int index) => start + index);
if (preamble != null)
result.insert(0, null);
if (postamble != null)
@@ -105,15 +105,15 @@ Future<Null> main(List<String> arguments) async {
bool keepMain = false;
final List<String> buffer = <String>[];
try {
final File mainDart = new File(path.join(tempDir.path, 'main.dart'));
final File pubSpec = new File(path.join(tempDir.path, 'pubspec.yaml'));
final File analysisOptions = new File(path.join(tempDir.path, 'analysis_options.yaml'));
final File mainDart = File(path.join(tempDir.path, 'main.dart'));
final File pubSpec = File(path.join(tempDir.path, 'pubspec.yaml'));
final File analysisOptions = File(path.join(tempDir.path, 'analysis_options.yaml'));
Directory flutterPackage;
if (arguments.length == 1) {
// Used for testing.
flutterPackage = new Directory(arguments.single);
flutterPackage = Directory(arguments.single);
} else {
flutterPackage = new Directory(path.join(_flutterRoot, 'packages', 'flutter', 'lib'));
flutterPackage = Directory(path.join(_flutterRoot, 'packages', 'flutter', 'lib'));
}
final List<Section> sections = <Section>[];
int sampleCodeSections = 0;
@@ -161,7 +161,7 @@ Future<Null> main(List<String> arguments) async {
}
} else if (trimmedLine == '/// ```dart') {
assert(block.isEmpty);
startLine = new Line(file.path, lineNumber + 1, line.indexOf(kDartDocPrefixWithSpace) + kDartDocPrefixWithSpace.length);
startLine = Line(file.path, lineNumber + 1, line.indexOf(kDartDocPrefixWithSpace) + kDartDocPrefixWithSpace.length);
inDart = true;
foundDart = true;
}
@@ -170,7 +170,7 @@ Future<Null> main(List<String> arguments) async {
if (!inSampleSection) {
if (line == '// Examples can assume:') {
assert(block.isEmpty);
startLine = new Line(file.path, lineNumber + 1, 3);
startLine = Line(file.path, lineNumber + 1, 3);
inPreamble = true;
} else if (trimmedLine == '/// ## Sample code' ||
trimmedLine.startsWith('/// ## Sample code:') ||
@@ -199,7 +199,7 @@ Future<Null> main(List<String> arguments) async {
}
}
buffer.add('');
final List<Line> lines = new List<Line>.filled(buffer.length, null, growable: true);
final List<Line> lines = List<Line>.filled(buffer.length, null, growable: true);
for (Section section in sections) {
buffer.addAll(section.strings);
lines.addAll(section.lines);
@@ -247,7 +247,7 @@ linter:
errors.removeAt(0);
int errorCount = 0;
final String kBullet = Platform.isWindows ? ' - ' : ' • ';
final RegExp errorPattern = new RegExp('^ +([a-z]+)$kBullet(.+)$kBullet(.+):([0-9]+):([0-9]+)$kBullet([-a-z_]+)\$', caseSensitive: false);
final RegExp errorPattern = RegExp('^ +([a-z]+)$kBullet(.+)$kBullet(.+):([0-9]+):([0-9]+)$kBullet([-a-z_]+)\$', caseSensitive: false);
for (String error in errors) {
final Match parts = errorPattern.matchAsPrefix(error);
if (parts != null) {
@@ -315,7 +315,7 @@ linter:
exit(exitCode);
}
final RegExp _constructorRegExp = new RegExp(r'[A-Z][a-zA-Z0-9<>.]*\(');
final RegExp _constructorRegExp = RegExp(r'[A-Z][a-zA-Z0-9<>.]*\(');
int _expressionId = 0;
@@ -324,12 +324,12 @@ void processBlock(Line line, List<String> block, List<Section> sections) {
throw '$line: Empty ```dart block in sample code.';
if (block.first.startsWith('new ') || block.first.startsWith('const ') || block.first.startsWith(_constructorRegExp)) {
_expressionId += 1;
sections.add(new Section(line, 'dynamic expression$_expressionId = ', block.toList(), ';'));
sections.add(Section(line, 'dynamic expression$_expressionId = ', block.toList(), ';'));
} else if (block.first.startsWith('await ')) {
_expressionId += 1;
sections.add(new Section(line, 'Future<Null> expression$_expressionId() async { ', block.toList(), ' }'));
sections.add(Section(line, 'Future<Null> expression$_expressionId() async { ', block.toList(), ' }'));
} else if (block.first.startsWith('class ') || block.first.startsWith('enum ')) {
sections.add(new Section(line, null, block.toList(), null));
sections.add(Section(line, null, block.toList(), null));
} else {
final List<String> buffer = <String>[];
int subblocks = 0;
@@ -354,7 +354,7 @@ void processBlock(Line line, List<String> block, List<Section> sections) {
if (subline != null)
processBlock(subline, buffer, sections);
} else {
sections.add(new Section(line, null, block.toList(), null));
sections.add(Section(line, null, block.toList(), null));
}
}
block.clear();

View File

@@ -94,7 +94,7 @@ Future<Null> _verifyInternationalizations() async {
);
final String localizationsFile = path.join('packages', 'flutter_localizations', 'lib', 'src', 'l10n', 'localizations.dart');
final String expectedResult = await new File(localizationsFile).readAsString();
final String expectedResult = await File(localizationsFile).readAsString();
if (genResult.stdout.trim() != expectedResult.trim()) {
stderr
@@ -153,7 +153,7 @@ Future<Null> _checkForTrailingSpaces() async {
// Only include files that actually exist, so that we don't try and grep for
// nonexistent files, which can occur when files are deleted or moved.
final List<String> changedFiles = changedFilesResult.stdout.split('\n').where((String filename) {
return new File(filename).existsSync();
return File(filename).existsSync();
}).toList();
if (changedFiles.isNotEmpty) {
await runCommand('grep',
@@ -197,7 +197,7 @@ Future<EvalResult> _evalCommand(String executable, List<String> arguments, {
}
printProgress('RUNNING', relativeWorkingDir, commandDescription);
final DateTime start = new DateTime.now();
final DateTime start = DateTime.now();
final Process process = await Process.start(executable, arguments,
workingDirectory: workingDirectory,
environment: environment,
@@ -206,7 +206,7 @@ Future<EvalResult> _evalCommand(String executable, List<String> arguments, {
final Future<List<List<int>>> savedStdout = process.stdout.toList();
final Future<List<List<int>>> savedStderr = process.stderr.toList();
final int exitCode = await process.exitCode;
final EvalResult result = new EvalResult(
final EvalResult result = EvalResult(
stdout: utf8.decode((await savedStdout).expand((List<int> ints) => ints).toList()),
stderr: utf8.decode((await savedStderr).expand((List<int> ints) => ints).toList()),
exitCode: exitCode,
@@ -240,7 +240,7 @@ Future<Null> _runFlutterAnalyze(String workingDirectory, {
Future<Null> _verifyNoTestPackageImports(String workingDirectory) async {
// TODO(ianh): Remove this whole test once https://github.com/dart-lang/matcher/issues/98 is fixed.
final List<String> shims = <String>[];
final List<String> errors = new Directory(workingDirectory)
final List<String> errors = Directory(workingDirectory)
.listSync(recursive: true)
.where((FileSystemEntity entity) {
return entity is File && entity.path.endsWith('.dart');
@@ -320,11 +320,11 @@ Future<Null> _verifyNoBadImportsInFlutter(String workingDirectory) async {
final String libPath = path.join(workingDirectory, 'packages', 'flutter', 'lib');
final String srcPath = path.join(workingDirectory, 'packages', 'flutter', 'lib', 'src');
// Verify there's one libPath/*.dart for each srcPath/*/.
final List<String> packages = new Directory(libPath).listSync()
final List<String> packages = Directory(libPath).listSync()
.where((FileSystemEntity entity) => entity is File && path.extension(entity.path) == '.dart')
.map<String>((FileSystemEntity entity) => path.basenameWithoutExtension(entity.path))
.toList()..sort();
final List<String> directories = new Directory(srcPath).listSync()
final List<String> directories = Directory(srcPath).listSync()
.whereType<Directory>()
.map<String>((Directory entity) => path.basename(entity.path))
.toList()..sort();
@@ -384,14 +384,14 @@ bool _matches<T>(List<T> a, List<T> b) {
return true;
}
final RegExp _importPattern = new RegExp(r"import 'package:flutter/([^.]+)\.dart'");
final RegExp _importMetaPattern = new RegExp(r"import 'package:meta/meta.dart'");
final RegExp _importPattern = RegExp(r"import 'package:flutter/([^.]+)\.dart'");
final RegExp _importMetaPattern = RegExp(r"import 'package:meta/meta.dart'");
Set<String> _findDependencies(String srcPath, List<String> errors, { bool checkForMeta = false }) {
return new Directory(srcPath).listSync(recursive: true).where((FileSystemEntity entity) {
return Directory(srcPath).listSync(recursive: true).where((FileSystemEntity entity) {
return entity is File && path.extension(entity.path) == '.dart';
}).map<Set<String>>((FileSystemEntity entity) {
final Set<String> result = new Set<String>();
final Set<String> result = Set<String>();
final File file = entity;
for (String line in file.readAsLinesSync()) {
Match match = _importPattern.firstMatch(line);
@@ -409,7 +409,7 @@ Set<String> _findDependencies(String srcPath, List<String> errors, { bool checkF
}
return result;
}).reduce((Set<String> value, Set<String> element) {
value ??= new Set<String>();
value ??= Set<String>();
value.addAll(element);
return value;
});
@@ -424,7 +424,7 @@ List<T> _deepSearch<T>(Map<T, Set<T>> map, T start, [ Set<T> seen ]) {
final List<T> result = _deepSearch(
map,
key,
(seen == null ? new Set<T>.from(<T>[start]) : new Set<T>.from(seen))..add(key),
(seen == null ? Set<T>.from(<T>[start]) : Set<T>.from(seen))..add(key),
);
if (result != null) {
result.insert(0, start);
@@ -441,7 +441,7 @@ List<T> _deepSearch<T>(Map<T, Set<T>> map, T start, [ Set<T> seen ]) {
Future<Null> _verifyNoBadImportsInFlutterTools(String workingDirectory) async {
final List<String> errors = <String>[];
for (FileSystemEntity entity in new Directory(path.join(workingDirectory, 'packages', 'flutter_tools', 'lib'))
for (FileSystemEntity entity in Directory(path.join(workingDirectory, 'packages', 'flutter_tools', 'lib'))
.listSync(recursive: true)
.where((FileSystemEntity entity) => entity is File && path.extension(entity.path) == '.dart')) {
final File file = entity;
@@ -464,7 +464,7 @@ Future<Null> _verifyNoBadImportsInFlutterTools(String workingDirectory) async {
}
Future<Null> _verifyGeneratedPluginRegistrants(String flutterRoot) async {
final Directory flutterRootDir = new Directory(flutterRoot);
final Directory flutterRootDir = Directory(flutterRoot);
final Map<String, List<File>> packageToRegistrants = <String, List<File>>{};
@@ -478,7 +478,7 @@ Future<Null> _verifyGeneratedPluginRegistrants(String flutterRoot) async {
}
}
final Set<String> outOfDate = new Set<String>();
final Set<String> outOfDate = Set<String>();
for (String package in packageToRegistrants.keys) {
final Map<File, String> fileToContent = <File, String>{};
@@ -510,11 +510,11 @@ Future<Null> _verifyGeneratedPluginRegistrants(String flutterRoot) async {
String _getPackageFor(File entity, Directory flutterRootDir) {
for (Directory dir = entity.parent; dir != flutterRootDir; dir = dir.parent) {
if (new File(path.join(dir.path, 'pubspec.yaml')).existsSync()) {
if (File(path.join(dir.path, 'pubspec.yaml')).existsSync()) {
return dir.path;
}
}
throw new ArgumentError('$entity is not within a dart package.');
throw ArgumentError('$entity is not within a dart package.');
}
bool _isGeneratedPluginRegistrant(File file) {

View File

@@ -68,7 +68,7 @@ Branch fromBranchName(String name) {
case 'release':
return Branch.release;
default:
throw new ArgumentError('Invalid branch name.');
throw ArgumentError('Invalid branch name.');
}
}
@@ -82,7 +82,7 @@ class ProcessRunner {
this.defaultWorkingDirectory,
this.platform = const LocalPlatform(),
}) : processManager = processManager ?? const LocalProcessManager() {
environment = new Map<String, String>.from(platform.environment);
environment = Map<String, String>.from(platform.environment);
}
/// The platform to use for a starting environment.
@@ -119,8 +119,8 @@ class ProcessRunner {
stderr.write('Running "${commandLine.join(' ')}" in ${workingDirectory.path}.\n');
}
final List<int> output = <int>[];
final Completer<Null> stdoutComplete = new Completer<Null>();
final Completer<Null> stderrComplete = new Completer<Null>();
final Completer<Null> stdoutComplete = Completer<Null>();
final Completer<Null> stderrComplete = Completer<Null>();
Process process;
Future<int> allComplete() async {
await stderrComplete.future;
@@ -156,19 +156,19 @@ class ProcessRunner {
} on ProcessException catch (e) {
final String message = 'Running "${commandLine.join(' ')}" in ${workingDirectory.path} '
'failed with:\n${e.toString()}';
throw new ProcessRunnerException(message);
throw ProcessRunnerException(message);
} on ArgumentError catch (e) {
final String message = 'Running "${commandLine.join(' ')}" in ${workingDirectory.path} '
'failed with:\n${e.toString()}';
throw new ProcessRunnerException(message);
throw ProcessRunnerException(message);
}
final int exitCode = await allComplete();
if (exitCode != 0 && !failOk) {
final String message = 'Running "${commandLine.join(' ')}" in ${workingDirectory.path} failed';
throw new ProcessRunnerException(
throw ProcessRunnerException(
message,
new ProcessResult(0, exitCode, null, 'returned $exitCode'),
ProcessResult(0, exitCode, null, 'returned $exitCode'),
);
}
return utf8.decoder.convert(output).trim();
@@ -197,9 +197,9 @@ class ArchiveCreator {
this.platform = const LocalPlatform(),
HttpReader httpReader,
}) : assert(revision.length == 40),
flutterRoot = new Directory(path.join(tempDir.path, 'flutter')),
flutterRoot = Directory(path.join(tempDir.path, 'flutter')),
httpReader = httpReader ?? http.readBytes,
_processRunner = new ProcessRunner(
_processRunner = ProcessRunner(
processManager: processManager,
subprocessOutput: subprocessOutput,
platform: platform,
@@ -276,7 +276,7 @@ class ArchiveCreator {
/// Performs all of the steps needed to create an archive.
Future<File> createArchive() async {
assert(_version != null, 'Must run initializeRepo before createArchive');
_outputFile = new File(path.join(outputDir.absolute.path, _archiveName));
_outputFile = File(path.join(outputDir.absolute.path, _archiveName));
await _installMinGitIfNeeded();
await _populateCaches();
await _archiveFiles(_outputFile);
@@ -308,11 +308,11 @@ class ArchiveCreator {
return;
}
final Uint8List data = await httpReader(_minGitUri);
final File gitFile = new File(path.join(tempDir.absolute.path, 'mingit.zip'));
final File gitFile = File(path.join(tempDir.absolute.path, 'mingit.zip'));
await gitFile.writeAsBytes(data, flush: true);
final Directory minGitPath =
new Directory(path.join(flutterRoot.absolute.path, 'bin', 'mingit'));
Directory(path.join(flutterRoot.absolute.path, 'bin', 'mingit'));
await minGitPath.create(recursive: true);
await _unzipArchive(gitFile, workingDirectory: minGitPath);
}
@@ -367,7 +367,7 @@ class ArchiveCreator {
/// Unpacks the given zip file into the currentDirectory (if set), or the
/// same directory as the archive.
Future<String> _unzipArchive(File archive, {Directory workingDirectory}) {
workingDirectory ??= new Directory(path.dirname(archive.absolute.path));
workingDirectory ??= Directory(path.dirname(archive.absolute.path));
List<String> commandLine;
if (platform.isWindows) {
commandLine = <String>[
@@ -407,7 +407,7 @@ class ArchiveCreator {
}
return _processRunner.runProcess(
commandLine,
workingDirectory: new Directory(path.dirname(source.absolute.path)),
workingDirectory: Directory(path.dirname(source.absolute.path)),
);
}
@@ -418,7 +418,7 @@ class ArchiveCreator {
'cJf',
output.absolute.path,
path.basename(source.absolute.path),
], workingDirectory: new Directory(path.dirname(source.absolute.path)));
], workingDirectory: Directory(path.dirname(source.absolute.path)));
}
}
@@ -435,7 +435,7 @@ class ArchivePublisher {
}) : assert(revision.length == 40),
platformName = platform.operatingSystem.toLowerCase(),
metadataGsPath = '$gsReleaseFolder/${getMetadataFilename(platform)}',
_processRunner = new ProcessRunner(
_processRunner = ProcessRunner(
processManager: processManager,
subprocessOutput: subprocessOutput,
);
@@ -475,7 +475,7 @@ class ArchivePublisher {
newEntry['hash'] = revision;
newEntry['channel'] = branchName;
newEntry['version'] = version;
newEntry['release_date'] = new DateTime.now().toUtc().toIso8601String();
newEntry['release_date'] = DateTime.now().toUtc().toIso8601String();
newEntry['archive'] = destinationArchivePath;
// Search for any entries with the same hash and channel and remove them.
@@ -502,20 +502,20 @@ class ArchivePublisher {
// Windows wants to echo the commands that execute in gsutil.bat to the
// stdout when we do that. So, we copy the file locally and then read it
// back in.
final File metadataFile = new File(
final File metadataFile = File(
path.join(tempDir.absolute.path, getMetadataFilename(platform)),
);
await _runGsUtil(<String>['cp', metadataGsPath, metadataFile.absolute.path]);
final String currentMetadata = metadataFile.readAsStringSync();
if (currentMetadata.isEmpty) {
throw new ProcessRunnerException('Empty metadata received from server');
throw ProcessRunnerException('Empty metadata received from server');
}
Map<String, dynamic> jsonData;
try {
jsonData = json.decode(currentMetadata);
} on FormatException catch (e) {
throw new ProcessRunnerException('Unable to parse JSON metadata received from cloud: $e');
throw ProcessRunnerException('Unable to parse JSON metadata received from cloud: $e');
}
jsonData = _addRelease(jsonData);
@@ -570,7 +570,7 @@ class ArchivePublisher {
/// Note that archives contain the executables and customizations for the
/// platform that they are created on.
Future<Null> main(List<String> argList) async {
final ArgParser argParser = new ArgParser();
final ArgParser argParser = ArgParser();
argParser.addOption(
'temp_dir',
defaultsTo: null,
@@ -643,7 +643,7 @@ Future<Null> main(List<String> argList) async {
tempDir = Directory.systemTemp.createTempSync('flutter_package.');
removeTempDir = true;
} else {
tempDir = new Directory(args['temp_dir']);
tempDir = Directory(args['temp_dir']);
if (!tempDir.existsSync()) {
errorExit("Temporary directory ${args['temp_dir']} doesn't exist.");
}
@@ -653,21 +653,21 @@ Future<Null> main(List<String> argList) async {
if (args['output'] == null) {
outputDir = tempDir;
} else {
outputDir = new Directory(args['output']);
outputDir = Directory(args['output']);
if (!outputDir.existsSync()) {
outputDir.createSync(recursive: true);
}
}
final Branch branch = fromBranchName(args['branch']);
final ArchiveCreator creator = new ArchiveCreator(tempDir, outputDir, revision, branch);
final ArchiveCreator creator = ArchiveCreator(tempDir, outputDir, revision, branch);
int exitCode = 0;
String message;
try {
final String version = await creator.initializeRepo();
final File outputFile = await creator.createArchive();
if (args['publish']) {
final ArchivePublisher publisher = new ArchivePublisher(
final ArchivePublisher publisher = ArchivePublisher(
tempDir,
revision,
branch,

View File

@@ -23,7 +23,7 @@ const String clock = '🕐';
const Duration _kLongTimeout = Duration(minutes: 45);
String elapsedTime(DateTime start) {
return new DateTime.now().difference(start).toString();
return DateTime.now().difference(start).toString();
}
void printProgress(String action, String workingDir, String command) {
@@ -48,7 +48,7 @@ Future<Null> runCommand(String executable, List<String> arguments, {
}
printProgress('RUNNING', relativeWorkingDir, commandDescription);
final DateTime start = new DateTime.now();
final DateTime start = DateTime.now();
final Process process = await Process.start(executable, arguments,
workingDirectory: workingDirectory,
environment: environment,

View File

@@ -173,7 +173,7 @@ Future<Null> _runTests() async {
}
Future<Null> _runCoverage() async {
final File coverageFile = new File(path.join(flutterRoot, 'packages', 'flutter', 'coverage', 'lcov.info'));
final File coverageFile = File(path.join(flutterRoot, 'packages', 'flutter', 'coverage', 'lcov.info'));
if (!coverageFile.existsSync()) {
print('${red}Coverage file not found.$reset');
print('Expected to find: ${coverageFile.absolute}');
@@ -209,7 +209,7 @@ Future<Null> _pubRunTest(
if (testPath != null)
args.add(testPath);
final Map<String, String> pubEnvironment = <String, String>{};
if (new Directory(pubCache).existsSync()) {
if (Directory(pubCache).existsSync()) {
pubEnvironment['PUB_CACHE'] = pubCache;
}
if (enableFlutterToolAsserts) {
@@ -274,20 +274,20 @@ Future<Null> _runFlutterTest(String workingDirectory, {
}
Future<Null> _verifyVersion(String filename) async {
if (!new File(filename).existsSync()) {
if (!File(filename).existsSync()) {
print('$redLine');
print('The version logic failed to create the Flutter version file.');
print('$redLine');
exit(1);
}
final String version = await new File(filename).readAsString();
final String version = await File(filename).readAsString();
if (version == '0.0.0-unknown') {
print('$redLine');
print('The version logic failed to determine the Flutter version.');
print('$redLine');
exit(1);
}
final RegExp pattern = new RegExp(r'^[0-9]+\.[0-9]+\.[0-9]+(-pre\.[0-9]+)?$');
final RegExp pattern = RegExp(r'^[0-9]+\.[0-9]+\.[0-9]+(-pre\.[0-9]+)?$');
if (!version.contains(pattern)) {
print('$redLine');
print('The version logic generated an invalid version string.');

View File

@@ -15,10 +15,10 @@ void main() {
);
final List<String> stdout = await process.stdout.transform(utf8.decoder).transform(const LineSplitter()).toList();
final List<String> stderr = await process.stderr.transform(utf8.decoder).transform(const LineSplitter()).toList();
final Match line = new RegExp(r'^(.+)/main\.dart:[0-9]+:[0-9]+: .+$').matchAsPrefix(stdout[1]);
final Match line = RegExp(r'^(.+)/main\.dart:[0-9]+:[0-9]+: .+$').matchAsPrefix(stdout[1]);
expect(line, isNot(isNull));
final String directory = line.group(1);
new Directory(directory).deleteSync(recursive: true);
Directory(directory).deleteSync(recursive: true);
expect(await process.exitCode, 1);
expect(stderr, isEmpty);
expect(stdout, <String>[

View File

@@ -13,7 +13,7 @@ export 'package:test/test.dart' hide TypeMatcher, isInstanceOf;
// TODO(ianh): Remove this file 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
Matcher isInstanceOf<T>() => 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

View File

@@ -36,7 +36,7 @@ class FakeProcessManager extends Mock implements ProcessManager {
_fakeResults = <String, List<ProcessResult>>{};
for (String key in value.keys) {
_fakeResults[key] = <ProcessResult>[]
..addAll(value[key] ?? <ProcessResult>[new ProcessResult(0, 0, '', '')]);
..addAll(value[key] ?? <ProcessResult>[ProcessResult(0, 0, '', '')]);
}
}
@@ -63,11 +63,11 @@ class FakeProcessManager extends Mock implements ProcessManager {
}
FakeProcess _popProcess(List<String> command) =>
new FakeProcess(_popResult(command), stdinResults: stdinResults);
FakeProcess(_popResult(command), stdinResults: stdinResults);
Future<Process> _nextProcess(Invocation invocation) async {
invocations.add(invocation);
return new Future<Process>.value(_popProcess(invocation.positionalArguments[0]));
return Future<Process>.value(_popProcess(invocation.positionalArguments[0]));
}
ProcessResult _nextResultSync(Invocation invocation) {
@@ -77,7 +77,7 @@ class FakeProcessManager extends Mock implements ProcessManager {
Future<ProcessResult> _nextResult(Invocation invocation) async {
invocations.add(invocation);
return new Future<ProcessResult>.value(_popResult(invocation.positionalArguments[0]));
return Future<ProcessResult>.value(_popResult(invocation.positionalArguments[0]));
}
void _setupMock() {
@@ -118,10 +118,10 @@ class FakeProcessManager extends Mock implements ProcessManager {
/// A fake process that can be used to interact with a process "started" by the FakeProcessManager.
class FakeProcess extends Mock implements Process {
FakeProcess(ProcessResult result, {void stdinResults(String input)})
: stdoutStream = new Stream<List<int>>.fromIterable(<List<int>>[result.stdout.codeUnits]),
stderrStream = new Stream<List<int>>.fromIterable(<List<int>>[result.stderr.codeUnits]),
: stdoutStream = Stream<List<int>>.fromIterable(<List<int>>[result.stdout.codeUnits]),
stderrStream = Stream<List<int>>.fromIterable(<List<int>>[result.stderr.codeUnits]),
desiredExitCode = result.exitCode,
stdinSink = new IOSink(new StringStreamConsumer(stdinResults)) {
stdinSink = IOSink(StringStreamConsumer(stdinResults)) {
_setupMock();
}
@@ -135,7 +135,7 @@ class FakeProcess extends Mock implements Process {
}
@override
Future<int> get exitCode => new Future<int>.value(desiredExitCode);
Future<int> get exitCode => Future<int>.value(desiredExitCode);
@override
int get pid => 0;
@@ -167,14 +167,14 @@ class StringStreamConsumer implements StreamConsumer<List<int>> {
@override
Future<dynamic> addStream(Stream<List<int>> value) {
streams.add(value);
completers.add(new Completer<dynamic>());
completers.add(Completer<dynamic>());
subscriptions.add(
value.listen((List<int> data) {
sendString(utf8.decode(data));
}),
);
subscriptions.last.onDone(() => completers.last.complete(null));
return new Future<dynamic>.value(null);
return Future<dynamic>.value(null);
}
@override
@@ -185,6 +185,6 @@ class StringStreamConsumer implements StreamConsumer<List<int>> {
completers.clear();
streams.clear();
subscriptions.clear();
return new Future<dynamic>.value(null);
return Future<dynamic>.value(null);
}
}

View File

@@ -19,7 +19,7 @@ void main() {
}
setUp(() async {
processManager = new FakeProcessManager(stdinResults: _captureStdin);
processManager = FakeProcessManager(stdinResults: _captureStdin);
});
tearDown(() async {});
@@ -27,10 +27,10 @@ void main() {
test('start works', () async {
final Map<String, List<ProcessResult>> calls = <String, List<ProcessResult>>{
'gsutil acl get gs://flutter_infra/releases/releases.json': <ProcessResult>[
new ProcessResult(0, 0, 'output1', '')
ProcessResult(0, 0, 'output1', '')
],
'gsutil cat gs://flutter_infra/releases/releases.json': <ProcessResult>[
new ProcessResult(0, 0, 'output2', '')
ProcessResult(0, 0, 'output2', '')
],
};
processManager.fakeResults = calls;
@@ -49,10 +49,10 @@ void main() {
test('run works', () async {
final Map<String, List<ProcessResult>> calls = <String, List<ProcessResult>>{
'gsutil acl get gs://flutter_infra/releases/releases.json': <ProcessResult>[
new ProcessResult(0, 0, 'output1', '')
ProcessResult(0, 0, 'output1', '')
],
'gsutil cat gs://flutter_infra/releases/releases.json': <ProcessResult>[
new ProcessResult(0, 0, 'output2', '')
ProcessResult(0, 0, 'output2', '')
],
};
processManager.fakeResults = calls;
@@ -66,10 +66,10 @@ void main() {
test('runSync works', () async {
final Map<String, List<ProcessResult>> calls = <String, List<ProcessResult>>{
'gsutil acl get gs://flutter_infra/releases/releases.json': <ProcessResult>[
new ProcessResult(0, 0, 'output1', '')
ProcessResult(0, 0, 'output1', '')
],
'gsutil cat gs://flutter_infra/releases/releases.json': <ProcessResult>[
new ProcessResult(0, 0, 'output2', '')
ProcessResult(0, 0, 'output2', '')
],
};
processManager.fakeResults = calls;
@@ -83,10 +83,10 @@ void main() {
test('captures stdin', () async {
final Map<String, List<ProcessResult>> calls = <String, List<ProcessResult>>{
'gsutil acl get gs://flutter_infra/releases/releases.json': <ProcessResult>[
new ProcessResult(0, 0, 'output1', '')
ProcessResult(0, 0, 'output1', '')
],
'gsutil cat gs://flutter_infra/releases/releases.json': <ProcessResult>[
new ProcessResult(0, 0, 'output2', '')
ProcessResult(0, 0, 'output2', '')
],
};
processManager.fakeResults = calls;

View File

@@ -20,7 +20,7 @@ void main() {
test('Throws on missing executable', () async {
// Uses a *real* process manager, since we want to know what happens if
// it can't find an executable.
final ProcessRunner processRunner = new ProcessRunner(subprocessOutput: false);
final ProcessRunner processRunner = ProcessRunner(subprocessOutput: false);
expect(
expectAsync1((List<String> commandLine) async {
return processRunner.runProcess(commandLine);
@@ -36,27 +36,27 @@ void main() {
}
});
for (String platformName in <String>['macos', 'linux', 'windows']) {
final FakePlatform platform = new FakePlatform(
final FakePlatform platform = FakePlatform(
operatingSystem: platformName,
environment: <String, String>{},
);
group('ProcessRunner for $platform', () {
test('Returns stdout', () async {
final FakeProcessManager fakeProcessManager = new FakeProcessManager();
final FakeProcessManager fakeProcessManager = FakeProcessManager();
fakeProcessManager.fakeResults = <String, List<ProcessResult>>{
'echo test': <ProcessResult>[new ProcessResult(0, 0, 'output', 'error')],
'echo test': <ProcessResult>[ProcessResult(0, 0, 'output', 'error')],
};
final ProcessRunner processRunner = new ProcessRunner(
final ProcessRunner processRunner = ProcessRunner(
subprocessOutput: false, platform: platform, processManager: fakeProcessManager);
final String output = await processRunner.runProcess(<String>['echo', 'test']);
expect(output, equals('output'));
});
test('Throws on process failure', () async {
final FakeProcessManager fakeProcessManager = new FakeProcessManager();
final FakeProcessManager fakeProcessManager = FakeProcessManager();
fakeProcessManager.fakeResults = <String, List<ProcessResult>>{
'echo test': <ProcessResult>[new ProcessResult(0, -1, 'output', 'error')],
'echo test': <ProcessResult>[ProcessResult(0, -1, 'output', 'error')],
};
final ProcessRunner processRunner = new ProcessRunner(
final ProcessRunner processRunner = ProcessRunner(
subprocessOutput: false, platform: platform, processManager: fakeProcessManager);
expect(
expectAsync1((List<String> commandLine) async {
@@ -75,17 +75,17 @@ void main() {
String flutter;
Future<Uint8List> fakeHttpReader(Uri url, {Map<String, String> headers}) {
return new Future<Uint8List>.value(new Uint8List(0));
return Future<Uint8List>.value(Uint8List(0));
}
setUp(() async {
processManager = new FakeProcessManager();
processManager = FakeProcessManager();
args.clear();
namedArgs.clear();
tempDir = Directory.systemTemp.createTempSync('flutter_prepage_package_test.');
flutterDir = new Directory(path.join(tempDir.path, 'flutter'));
flutterDir = Directory(path.join(tempDir.path, 'flutter'));
flutterDir.createSync(recursive: true);
creator = new ArchiveCreator(
creator = ArchiveCreator(
tempDir,
tempDir,
testRef,
@@ -108,7 +108,7 @@ void main() {
'git clone -b dev https://chromium.googlesource.com/external/github.com/flutter/flutter': null,
'git reset --hard $testRef': null,
'git remote set-url origin https://github.com/flutter/flutter.git': null,
'git describe --tags --abbrev=0': <ProcessResult>[new ProcessResult(0, 0, 'v1.2.3', '')],
'git describe --tags --abbrev=0': <ProcessResult>[ProcessResult(0, 0, 'v1.2.3', '')],
};
if (platform.isWindows) {
calls['7za x ${path.join(tempDir.path, 'mingit.zip')}'] = null;
@@ -151,7 +151,7 @@ void main() {
'git clone -b dev https://chromium.googlesource.com/external/github.com/flutter/flutter': null,
'git reset --hard $testRef': null,
'git remote set-url origin https://github.com/flutter/flutter.git': null,
'git describe --tags --abbrev=0': <ProcessResult>[new ProcessResult(0, 0, 'v1.2.3', '')],
'git describe --tags --abbrev=0': <ProcessResult>[ProcessResult(0, 0, 'v1.2.3', '')],
};
if (platform.isWindows) {
calls['7za x ${path.join(tempDir.path, 'mingit.zip')}'] = null;
@@ -176,7 +176,7 @@ void main() {
calls['tar cJf $archiveName flutter'] = null;
}
processManager.fakeResults = calls;
creator = new ArchiveCreator(
creator = ArchiveCreator(
tempDir,
tempDir,
testRef,
@@ -194,8 +194,8 @@ void main() {
test('throws when a command errors out', () async {
final Map<String, List<ProcessResult>> calls = <String, List<ProcessResult>>{
'git clone -b dev https://chromium.googlesource.com/external/github.com/flutter/flutter':
<ProcessResult>[new ProcessResult(0, 0, 'output1', '')],
'git reset --hard $testRef': <ProcessResult>[new ProcessResult(0, -1, 'output2', '')],
<ProcessResult>[ProcessResult(0, 0, 'output1', '')],
'git reset --hard $testRef': <ProcessResult>[ProcessResult(0, -1, 'output2', '')],
};
processManager.fakeResults = calls;
expect(expectAsync0(creator.initializeRepo),
@@ -208,7 +208,7 @@ void main() {
Directory tempDir;
setUp(() async {
processManager = new FakeProcessManager();
processManager = FakeProcessManager();
tempDir = Directory.systemTemp.createTempSync('flutter_prepage_package_test.');
});
@@ -255,7 +255,7 @@ void main() {
]
}
''';
new File(jsonPath).writeAsStringSync(releasesJson);
File(jsonPath).writeAsStringSync(releasesJson);
final Map<String, List<ProcessResult>> calls = <String, List<ProcessResult>>{
'gsutil rm $gsArchivePath': null,
'gsutil -h Content-Type:$archiveMime cp $archivePath $gsArchivePath': null,
@@ -264,9 +264,9 @@ void main() {
'gsutil -h Content-Type:application/json cp $jsonPath $gsJsonPath': null,
};
processManager.fakeResults = calls;
final File outputFile = new File(path.join(tempDir.absolute.path, archiveName));
final File outputFile = File(path.join(tempDir.absolute.path, archiveName));
assert(tempDir.existsSync());
final ArchivePublisher publisher = new ArchivePublisher(
final ArchivePublisher publisher = ArchivePublisher(
tempDir,
testRef,
Branch.release,
@@ -279,7 +279,7 @@ void main() {
assert(tempDir.existsSync());
await publisher.publishArchive();
processManager.verifyCalls(calls.keys.toList());
final File releaseFile = new File(jsonPath);
final File releaseFile = File(jsonPath);
expect(releaseFile.existsSync(), isTrue);
final String contents = releaseFile.readAsStringSync();
// Make sure new data is added.
@@ -299,7 +299,7 @@ void main() {
// Make sure the new entry is first (and hopefully it takes less than a
// minute to go from publishArchive above to this line!).
expect(
new DateTime.now().difference(DateTime.parse(releases[0]['release_date'])),
DateTime.now().difference(DateTime.parse(releases[0]['release_date'])),
lessThan(const Duration(minutes: 1)),
);
const JsonEncoder encoder = JsonEncoder.withIndent(' ');