Updated linter rules in cocoon (#2288)
* Updated linter rules to use final locals.
* Formatting.
* Adding linter rules to top level.
* Formatting.
* Adding linter changes to global analysis options so all cocoon packages follow same rules.
* Adding unawaited to dart futures.
diff --git a/analysis_options.yaml b/analysis_options.yaml
index 4f5a9c5..4cf6349 100644
--- a/analysis_options.yaml
+++ b/analysis_options.yaml
@@ -43,3 +43,6 @@
rules:
use_super_parameters: true
prefer_final_fields: true
+ prefer_final_locals: true
+ require_trailing_commas: true
+ unawaited_futures: true
diff --git a/analyze/analyze.dart b/analyze/analyze.dart
index 694ccbf..7dd6c9c 100644
--- a/analyze/analyze.dart
+++ b/analyze/analyze.dart
@@ -125,8 +125,10 @@
pending.addAll(entity.listSync());
}
}
- assert(matches >= minimumMatches,
- 'Expected to find at least $minimumMatches files with extension ".$extension" in "$workingDirectory", but only found $matches.');
+ assert(
+ matches >= minimumMatches,
+ 'Expected to find at least $minimumMatches files with extension ".$extension" in "$workingDirectory", but only found $matches.',
+ );
}
class EvalResult {
diff --git a/app_dart/bin/server.dart b/app_dart/bin/server.dart
index d0dbc37..168a21b 100644
--- a/app_dart/bin/server.dart
+++ b/app_dart/bin/server.dart
@@ -274,34 +274,38 @@
'/readiness_check': ReadinessCheck(config: config),
};
- return await runAppEngine((HttpRequest request) async {
- if (handlers.containsKey(request.uri.path)) {
- final RequestHandler<dynamic> handler = handlers[request.uri.path]!;
- await handler.service(request);
- } else {
- /// Requests with query parameters and anchors need to be trimmed to get the file path.
- // TODO(chillers): Use toFilePath(), https://github.com/dart-lang/sdk/issues/39373
- final int queryIndex = request.uri.path.contains('?') ? request.uri.path.indexOf('?') : request.uri.path.length;
- final int anchorIndex =
- request.uri.path.contains('#') ? request.uri.path.indexOf('#') : request.uri.path.length;
+ return await runAppEngine(
+ (HttpRequest request) async {
+ if (handlers.containsKey(request.uri.path)) {
+ final RequestHandler<dynamic> handler = handlers[request.uri.path]!;
+ await handler.service(request);
+ } else {
+ /// Requests with query parameters and anchors need to be trimmed to get the file path.
+ // TODO(chillers): Use toFilePath(), https://github.com/dart-lang/sdk/issues/39373
+ final int queryIndex =
+ request.uri.path.contains('?') ? request.uri.path.indexOf('?') : request.uri.path.length;
+ final int anchorIndex =
+ request.uri.path.contains('#') ? request.uri.path.indexOf('#') : request.uri.path.length;
- /// Trim to the first instance of an anchor or query.
- final int trimIndex = min(queryIndex, anchorIndex);
- final String filePath = request.uri.path.substring(0, trimIndex);
+ /// Trim to the first instance of an anchor or query.
+ final int trimIndex = min(queryIndex, anchorIndex);
+ final String filePath = request.uri.path.substring(0, trimIndex);
- const Map<String, String> redirects = <String, String>{
- '/build.html': '/#/build',
- };
- if (redirects.containsKey(filePath)) {
- request.response.statusCode = HttpStatus.permanentRedirect;
- return await request.response.redirect(Uri.parse(redirects[filePath]!));
+ const Map<String, String> redirects = <String, String>{
+ '/build.html': '/#/build',
+ };
+ if (redirects.containsKey(filePath)) {
+ request.response.statusCode = HttpStatus.permanentRedirect;
+ return await request.response.redirect(Uri.parse(redirects[filePath]!));
+ }
+
+ await StaticFileHandler(filePath, config: config).service(request);
}
-
- await StaticFileHandler(filePath, config: config).service(request);
- }
- }, onAcceptingConnections: (InternetAddress address, int port) {
- final String host = address.isLoopback ? 'localhost' : address.host;
- print('Serving requests at http://$host:$port/');
- });
+ },
+ onAcceptingConnections: (InternetAddress address, int port) {
+ final String host = address.isLoopback ? 'localhost' : address.host;
+ print('Serving requests at http://$host:$port/');
+ },
+ );
});
}
diff --git a/app_dart/bin/validate_scheduler_config.dart b/app_dart/bin/validate_scheduler_config.dart
index bc736c8..3b3fb11 100644
--- a/app_dart/bin/validate_scheduler_config.dart
+++ b/app_dart/bin/validate_scheduler_config.dart
@@ -23,9 +23,11 @@
final YamlMap configYaml = loadYaml(configFile.readAsStringSync()) as YamlMap;
final pb.SchedulerConfig unCheckedSchedulerConfig = pb.SchedulerConfig()..mergeFromProto3Json(configYaml);
- print(CiYaml(
- slug: Config.flutterSlug,
- branch: Config.defaultBranch(Config.flutterSlug),
- config: unCheckedSchedulerConfig,
- ).config);
+ print(
+ CiYaml(
+ slug: Config.flutterSlug,
+ branch: Config.defaultBranch(Config.flutterSlug),
+ config: unCheckedSchedulerConfig,
+ ).config,
+ );
}
diff --git a/app_dart/integration_test/validate_all_ci_configs_test.dart b/app_dart/integration_test/validate_all_ci_configs_test.dart
index 4f0c300..69f2f03 100644
--- a/app_dart/integration_test/validate_all_ci_configs_test.dart
+++ b/app_dart/integration_test/validate_all_ci_configs_test.dart
@@ -47,50 +47,57 @@
}
});
- test('validate enabled branches of $config', () async {
- final String configContent = await githubFileContent(
- config.slug,
- kCiYamlPath,
- httpClientProvider: () => http.Client(),
- ref: config.branch,
- );
- final YamlMap configYaml = loadYaml(configContent) as YamlMap;
- final pb.SchedulerConfig schedulerConfig = pb.SchedulerConfig()..mergeFromProto3Json(configYaml);
+ test(
+ 'validate enabled branches of $config',
+ () async {
+ final String configContent = await githubFileContent(
+ config.slug,
+ kCiYamlPath,
+ httpClientProvider: () => http.Client(),
+ ref: config.branch,
+ );
+ final YamlMap configYaml = loadYaml(configContent) as YamlMap;
+ final pb.SchedulerConfig schedulerConfig = pb.SchedulerConfig()..mergeFromProto3Json(configYaml);
- final List<String> githubBranches = getBranchesForRepository(config.slug);
+ final List<String> githubBranches = getBranchesForRepository(config.slug);
- final Map<String, bool> validEnabledBranches = <String, bool>{};
- // Add config wide enabled branches
- for (String enabledBranch in schedulerConfig.enabledBranches) {
- validEnabledBranches[enabledBranch] = false;
- }
- // Add all target specific enabled branches
- for (pb.Target target in schedulerConfig.targets) {
- for (String enabledBranch in target.enabledBranches) {
+ final Map<String, bool> validEnabledBranches = <String, bool>{};
+ // Add config wide enabled branches
+ for (String enabledBranch in schedulerConfig.enabledBranches) {
validEnabledBranches[enabledBranch] = false;
}
- }
-
- // N^2 scan to verify all enabled branch patterns match an exist branch on the repo.
- for (String enabledBranch in validEnabledBranches.keys) {
- for (String githubBranch in githubBranches) {
- if (CiYaml.enabledBranchesMatchesCurrentBranch(<String>[enabledBranch], githubBranch)) {
- validEnabledBranches[enabledBranch] = true;
+ // Add all target specific enabled branches
+ for (pb.Target target in schedulerConfig.targets) {
+ for (String enabledBranch in target.enabledBranches) {
+ validEnabledBranches[enabledBranch] = false;
}
}
- }
- if (config.slug.name == 'engine') {
- print(githubBranches);
- print(validEnabledBranches);
- }
+ // N^2 scan to verify all enabled branch patterns match an exist branch on the repo.
+ for (String enabledBranch in validEnabledBranches.keys) {
+ for (String githubBranch in githubBranches) {
+ if (CiYaml.enabledBranchesMatchesCurrentBranch(<String>[enabledBranch], githubBranch)) {
+ validEnabledBranches[enabledBranch] = true;
+ }
+ }
+ }
- // Verify the enabled branches
- for (String enabledBranch in validEnabledBranches.keys) {
- expect(validEnabledBranches[enabledBranch], isTrue,
- reason: '$enabledBranch does not match to a branch in ${config.slug.fullName}');
- }
- }, skip: config.slug.name == 'flutter');
+ if (config.slug.name == 'engine') {
+ print(githubBranches);
+ print(validEnabledBranches);
+ }
+
+ // Verify the enabled branches
+ for (String enabledBranch in validEnabledBranches.keys) {
+ expect(
+ validEnabledBranches[enabledBranch],
+ isTrue,
+ reason: '$enabledBranch does not match to a branch in ${config.slug.fullName}',
+ );
+ }
+ },
+ skip: config.slug.name == 'flutter',
+ );
}
}
diff --git a/app_dart/integration_test/validate_test_ownership_test.dart b/app_dart/integration_test/validate_test_ownership_test.dart
index f9bfc15..6710c62 100644
--- a/app_dart/integration_test/validate_test_ownership_test.dart
+++ b/app_dart/integration_test/validate_test_ownership_test.dart
@@ -24,8 +24,8 @@
const String taskExecutable = 'bin/validate_task_ownership.dart';
final List<String> taskArgs = <String>[config.slug.name, config.branch];
- ProcessManager processManager = const LocalProcessManager();
- Process process = await processManager.start(
+ const ProcessManager processManager = LocalProcessManager();
+ final Process process = await processManager.start(
<String>[dart, taskExecutable, ...taskArgs],
workingDirectory: Directory.current.path,
);
diff --git a/app_dart/lib/src/foundation/github_checks_util.dart b/app_dart/lib/src/foundation/github_checks_util.dart
index 7f0a383..6edbb69 100644
--- a/app_dart/lib/src/foundation/github_checks_util.dart
+++ b/app_dart/lib/src/foundation/github_checks_util.dart
@@ -55,17 +55,20 @@
maxAttempts: 3,
delayFactor: Duration(seconds: 2),
);
- return r.retry(() async {
- final github.GitHub gitHubClient = await cocoonConfig.createGitHubClient(slug: slug);
- await gitHubClient.checks.checkRuns.updateCheckRun(
- slug,
- checkRun,
- status: status,
- conclusion: conclusion,
- detailsUrl: detailsUrl,
- output: output,
- );
- }, retryIf: (Exception e) => e is github.GitHubError || e is SocketException);
+ return r.retry(
+ () async {
+ final github.GitHub gitHubClient = await cocoonConfig.createGitHubClient(slug: slug);
+ await gitHubClient.checks.checkRuns.updateCheckRun(
+ slug,
+ checkRun,
+ status: status,
+ conclusion: conclusion,
+ detailsUrl: detailsUrl,
+ output: output,
+ );
+ },
+ retryIf: (Exception e) => e is github.GitHubError || e is SocketException,
+ );
}
Future<github.CheckRun> getCheckRun(
@@ -77,13 +80,16 @@
maxAttempts: 3,
delayFactor: Duration(seconds: 2),
);
- return r.retry(() async {
- final github.GitHub gitHubClient = await cocoonConfig.createGitHubClient(slug: slug);
- return await gitHubClient.checks.checkRuns.getCheckRun(
- slug,
- checkRunId: id!,
- );
- }, retryIf: (Exception e) => e is github.GitHubError || e is SocketException);
+ return r.retry(
+ () async {
+ final github.GitHub gitHubClient = await cocoonConfig.createGitHubClient(slug: slug);
+ return await gitHubClient.checks.checkRuns.getCheckRun(
+ slug,
+ checkRunId: id!,
+ );
+ },
+ retryIf: (Exception e) => e is github.GitHubError || e is SocketException,
+ );
}
/// Sends a request to GitHub's Checks API to create a new [github.CheckRun].
@@ -102,18 +108,19 @@
maxAttempts: 3,
delayFactor: Duration(seconds: 2),
);
- return r.retry(() async {
- return _createCheckRun(
- cocoonConfig!,
- slug,
- sha,
- name,
- output: output,
- );
- },
- retryIf: (Exception e) => e is github.GitHubError || e is SocketException,
- onRetry: (Exception e) =>
- log.warning('createCheckRun fails for slug: ${slug.fullName}, sha: $sha, name: $name'));
+ return r.retry(
+ () async {
+ return _createCheckRun(
+ cocoonConfig!,
+ slug,
+ sha,
+ name,
+ output: output,
+ );
+ },
+ retryIf: (Exception e) => e is github.GitHubError || e is SocketException,
+ onRetry: (Exception e) => log.warning('createCheckRun fails for slug: ${slug.fullName}, sha: $sha, name: $name'),
+ );
}
Future<github.CheckRun> _createCheckRun(
diff --git a/app_dart/lib/src/model/appengine/key_helper.dart b/app_dart/lib/src/model/appengine/key_helper.dart
index 001e443..f5d6be4 100644
--- a/app_dart/lib/src/model/appengine/key_helper.dart
+++ b/app_dart/lib/src/model/appengine/key_helper.dart
@@ -133,18 +133,20 @@
path.insert(0, current);
}
return Path()
- ..element.addAll(path.map<Path_Element>((Key<dynamic> key) {
- final Path_Element element = Path_Element();
- if (key.type != null) {
- element.type = types.containsKey(key.type) ? types[key.type!]!.name! : key.type.toString();
- }
- final Object? id = key.id;
- if (id is String) {
- element.name = id;
- } else if (id is int) {
- element.id = Int64(id);
- }
- return element;
- }));
+ ..element.addAll(
+ path.map<Path_Element>((Key<dynamic> key) {
+ final Path_Element element = Path_Element();
+ if (key.type != null) {
+ element.type = types.containsKey(key.type) ? types[key.type!]!.name! : key.type.toString();
+ }
+ final Object? id = key.id;
+ if (id is String) {
+ element.name = id;
+ } else if (id is int) {
+ element.id = Int64(id);
+ }
+ return element;
+ }),
+ );
}
}
diff --git a/app_dart/lib/src/model/ci_yaml/ci_yaml.dart b/app_dart/lib/src/model/ci_yaml/ci_yaml.dart
index 78b9ea1..4079cd9 100644
--- a/app_dart/lib/src/model/ci_yaml/ci_yaml.dart
+++ b/app_dart/lib/src/model/ci_yaml/ci_yaml.dart
@@ -69,11 +69,13 @@
return initialTargets.toList();
}
- Iterable<Target> get _targets => config.targets.map((pb.Target target) => Target(
- schedulerConfig: config,
- value: target,
- slug: slug,
- ));
+ Iterable<Target> get _targets => config.targets.map(
+ (pb.Target target) => Target(
+ schedulerConfig: config,
+ value: target,
+ slug: slug,
+ ),
+ );
/// Get an unfiltered list of all [targets] that are found in the ci.yaml file.
List<Target> get targets => _targets.toList();
@@ -157,7 +159,8 @@
// link to wiki - https://github.com/flutter/flutter/wiki/Reducing-Test-Flakiness#adding-a-new-devicelab-test
if (totTargets.isNotEmpty && !totTargets.contains(target.name) && target.bringup != true) {
exceptions.add(
- 'ERROR: ${target.name} is a new builder added. it needs to be marked bringup: true\nIf ci.yaml wasn\'t changed, try `git fetch upstream && git merge upstream/master`');
+ 'ERROR: ${target.name} is a new builder added. it needs to be marked bringup: true\nIf ci.yaml wasn\'t changed, try `git fetch upstream && git merge upstream/master`',
+ );
continue;
}
targetGraph[target.name] = <pb.Target>[];
@@ -211,13 +214,13 @@
final List<String> exceptions = <String>[];
/// Decoded will contain a list of maps for the dependencies found.
- List<dynamic> decoded = json.decode(dependencyJsonString) as List<dynamic>;
+ final List<dynamic> decoded = json.decode(dependencyJsonString) as List<dynamic>;
for (Map<String, dynamic> depMap in decoded) {
if (!depMap.containsKey('version')) {
exceptions.add('ERROR: dependency ${depMap['dependency']} must have a version.');
} else {
- String version = depMap['version'] as String;
+ final String version = depMap['version'] as String;
if (version.isEmpty || version == 'latest') {
exceptions
.add('ERROR: dependency ${depMap['dependency']} must have a non empty, non "latest" version supplied.');
diff --git a/app_dart/lib/src/model/ci_yaml/target.dart b/app_dart/lib/src/model/ci_yaml/target.dart
index 812083b..0306e82 100644
--- a/app_dart/lib/src/model/ci_yaml/target.dart
+++ b/app_dart/lib/src/model/ci_yaml/target.dart
@@ -53,7 +53,7 @@
final Map<String, Object> platformDimensions = _getPlatformDimensions();
for (String key in platformDimensions.keys) {
- String value = platformDimensions[key].toString();
+ final String value = platformDimensions[key].toString();
dimensionsMap[key] = RequestedDimension(key: key, value: value);
}
@@ -62,14 +62,14 @@
// remove this logic after dimensions are supported in ci.yaml files
for (String dimension in dimensionList) {
if (properties.containsKey(dimension)) {
- String value = properties[dimension].toString();
+ final String value = properties[dimension].toString();
dimensionsMap[dimension] = RequestedDimension(key: dimension, value: value);
}
}
final Map<String, Object> targetDimensions = _getTargetDimensions();
for (String key in targetDimensions.keys) {
- String value = targetDimensions[key].toString();
+ final String value = targetDimensions[key].toString();
dimensionsMap[key] = RequestedDimension(key: key, value: value);
}
@@ -93,7 +93,7 @@
///
/// Return an empty list if no tags are found.
List<String> get tags {
- Map<String, Object> properties = getProperties();
+ final Map<String, Object> properties = getProperties();
return (properties.containsKey('tags')) ? (properties['tags'] as List).map((e) => e as String).toList() : [];
}
diff --git a/app_dart/lib/src/model/luci/buildbucket.dart b/app_dart/lib/src/model/luci/buildbucket.dart
index f063d8e..88bebad 100644
--- a/app_dart/lib/src/model/luci/buildbucket.dart
+++ b/app_dart/lib/src/model/luci/buildbucket.dart
@@ -56,10 +56,12 @@
this.searchBuilds,
this.scheduleBuild,
this.cancelBuild,
- }) : assert((getBuild != null && searchBuilds == null && scheduleBuild == null && cancelBuild == null) ||
- (getBuild == null && searchBuilds != null && scheduleBuild == null && cancelBuild == null) ||
- (getBuild == null && searchBuilds == null && scheduleBuild != null && cancelBuild == null) ||
- (getBuild == null && searchBuilds == null && scheduleBuild == null && cancelBuild != null));
+ }) : assert(
+ (getBuild != null && searchBuilds == null && scheduleBuild == null && cancelBuild == null) ||
+ (getBuild == null && searchBuilds != null && scheduleBuild == null && cancelBuild == null) ||
+ (getBuild == null && searchBuilds == null && scheduleBuild != null && cancelBuild == null) ||
+ (getBuild == null && searchBuilds == null && scheduleBuild == null && cancelBuild != null),
+ );
/// Creates a [Request] object from JSON.
static Request fromJson(Map<String, dynamic> json) => _$RequestFromJson(json);
@@ -122,7 +124,8 @@
this.cancelBuild,
this.error,
}) : assert(
- getBuild != null || searchBuilds != null || scheduleBuild != null || cancelBuild != null || error != null);
+ getBuild != null || searchBuilds != null || scheduleBuild != null || cancelBuild != null || error != null,
+ );
/// Creates a [Response] from JSON.
static Response fromJson(Map<String, dynamic> json) => _$ResponseFromJson(json);
@@ -170,8 +173,10 @@
this.builderId,
this.buildNumber,
this.fields,
- }) : assert((id == null && builderId != null && buildNumber != null) ||
- (id != null && builderId == null && buildNumber == null));
+ }) : assert(
+ (id == null && builderId != null && buildNumber != null) ||
+ (id != null && builderId == null && buildNumber == null),
+ );
/// Creates a [GetBuildRequest] from JSON.
static GetBuildRequest fromJson(Map<String, dynamic> json) => _$GetBuildRequestFromJson(json);
diff --git a/app_dart/lib/src/request_handlers/check_flaky_builders.dart b/app_dart/lib/src/request_handlers/check_flaky_builders.dart
index c678596..958a88b 100644
--- a/app_dart/lib/src/request_handlers/check_flaky_builders.dart
+++ b/app_dart/lib/src/request_handlers/check_flaky_builders.dart
@@ -105,8 +105,12 @@
/// 3. The builder is not in [ignoredBuilders].
/// 4. The flaky issue of the builder is closed if there is one.
/// 5. Does not have any existing pr against the builder.
- Future<List<_BuilderInfo>> _getEligibleFlakyBuilders(GithubService gitHub, RepositorySlug slug,
- {required String content, required CiYaml ciYaml}) async {
+ Future<List<_BuilderInfo>> _getEligibleFlakyBuilders(
+ GithubService gitHub,
+ RepositorySlug slug, {
+ required String content,
+ required CiYaml ciYaml,
+ }) async {
final YamlMap ci = loadYaml(content) as YamlMap;
final YamlList targets = ci[kCiYamlTargetsKey] as YamlList;
final List<YamlMap?> flakyTargets = targets
@@ -169,7 +173,11 @@
final String modifiedContent = _deflakeBuilderInContent(ciContent, info.name);
final GitReference masterRef = await gitHub.getReference(slug, kMasterRefs);
final DeflakePullRequestBuilder prBuilder = DeflakePullRequestBuilder(
- name: info.name, recordNumber: kRecordNumber, ownership: testOwnership, issue: info.existingIssue);
+ name: info.name,
+ recordNumber: kRecordNumber,
+ ownership: testOwnership,
+ issue: info.existingIssue,
+ );
final PullRequest pullRequest = await gitHub.createPullRequest(
slug,
title: prBuilder.pullRequestTitle,
diff --git a/app_dart/lib/src/request_handlers/file_flaky_issue_and_pr.dart b/app_dart/lib/src/request_handlers/file_flaky_issue_and_pr.dart
index 1decf11..307de14 100644
--- a/app_dart/lib/src/request_handlers/file_flaky_issue_and_pr.dart
+++ b/app_dart/lib/src/request_handlers/file_flaky_issue_and_pr.dart
@@ -62,12 +62,13 @@
gitHub,
slug,
builderDetail: BuilderDetail(
- statistic: statistic,
- existingIssue: nameToExistingIssue[statistic.name],
- existingPullRequest: nameToExistingPR[statistic.name],
- isMarkedFlaky: _getIsMarkedFlaky(statistic.name, ci!),
- type: type,
- ownership: getTestOwnership(statistic.name, type, testOwnerContent)),
+ statistic: statistic,
+ existingIssue: nameToExistingIssue[statistic.name],
+ existingPullRequest: nameToExistingPR[statistic.name],
+ isMarkedFlaky: _getIsMarkedFlaky(statistic.name, ci!),
+ type: type,
+ ownership: getTestOwnership(statistic.name, type, testOwnerContent),
+ ),
);
}
return Body.forJson(const <String, dynamic>{
@@ -95,28 +96,31 @@
return;
}
final String modifiedContent = _marksBuildFlakyInContent(
- await gitHub.getFileContent(
- slug,
- kCiYamlPath,
- ),
- builderDetail.statistic.name,
- issue.htmlUrl);
+ await gitHub.getFileContent(
+ slug,
+ kCiYamlPath,
+ ),
+ builderDetail.statistic.name,
+ issue.htmlUrl,
+ );
final GitReference masterRef = await gitHub.getReference(slug, kMasterRefs);
final PullRequestBuilder prBuilder =
PullRequestBuilder(statistic: builderDetail.statistic, ownership: builderDetail.ownership, issue: issue);
- final PullRequest pullRequest = await gitHub.createPullRequest(slug,
- title: prBuilder.pullRequestTitle,
- body: prBuilder.pullRequestBody,
- commitMessage: prBuilder.pullRequestTitle,
- baseRef: masterRef,
- entries: <CreateGitTreeEntry>[
- CreateGitTreeEntry(
- kCiYamlPath,
- kModifyMode,
- kModifyType,
- content: modifiedContent,
- )
- ]);
+ final PullRequest pullRequest = await gitHub.createPullRequest(
+ slug,
+ title: prBuilder.pullRequestTitle,
+ body: prBuilder.pullRequestBody,
+ commitMessage: prBuilder.pullRequestTitle,
+ baseRef: masterRef,
+ entries: <CreateGitTreeEntry>[
+ CreateGitTreeEntry(
+ kCiYamlPath,
+ kModifyMode,
+ kModifyType,
+ content: modifiedContent,
+ )
+ ],
+ );
await gitHub.assignReviewer(slug, reviewer: prBuilder.pullRequestReviewer, pullRequestNumber: pullRequest.number);
}
diff --git a/app_dart/lib/src/request_handlers/get_branches.dart b/app_dart/lib/src/request_handlers/get_branches.dart
index a020572..3b81d80 100644
--- a/app_dart/lib/src/request_handlers/get_branches.dart
+++ b/app_dart/lib/src/request_handlers/get_branches.dart
@@ -54,8 +54,9 @@
final List<Branch> branches = await datastore
.queryBranches()
- .where((Branch b) =>
- DateTime.now().millisecondsSinceEpoch - b.lastActivity! < kActiveBranchActivity.inMilliseconds)
+ .where(
+ (Branch b) => DateTime.now().millisecondsSinceEpoch - b.lastActivity! < kActiveBranchActivity.inMilliseconds,
+ )
.toList();
return Body.forJson(branches);
}
diff --git a/app_dart/lib/src/request_handlers/get_green_commits.dart b/app_dart/lib/src/request_handlers/get_green_commits.dart
index e8a0ce7..8a3adba 100644
--- a/app_dart/lib/src/request_handlers/get_green_commits.dart
+++ b/app_dart/lib/src/request_handlers/get_green_commits.dart
@@ -69,8 +69,10 @@
}
bool everyNonFlakyTaskSucceed(CommitStatus status) {
- return status.stages.every((Stage stage) => stage.tasks
- .where((Task task) => !task.isFlaky!)
- .every((Task nonFlakyTask) => nonFlakyTask.status == Task.statusSucceeded));
+ return status.stages.every(
+ (Stage stage) => stage.tasks
+ .where((Task task) => !task.isFlaky!)
+ .every((Task nonFlakyTask) => nonFlakyTask.status == Task.statusSucceeded),
+ );
}
}
diff --git a/app_dart/lib/src/request_handlers/get_release_branches.dart b/app_dart/lib/src/request_handlers/get_release_branches.dart
index e313dcb..f698e2f 100644
--- a/app_dart/lib/src/request_handlers/get_release_branches.dart
+++ b/app_dart/lib/src/request_handlers/get_release_branches.dart
@@ -41,7 +41,7 @@
Future<Body> get() async {
final GitHub github = await config.createGitHubClient(slug: Config.flutterSlug);
final GithubService githubService = GithubService(github);
- List<Map<String, String>> branchNames =
+ final List<Map<String, String>> branchNames =
await branchService.getReleaseBranches(githubService: githubService, slug: Config.flutterSlug);
return Body.forJson(branchNames);
}
diff --git a/app_dart/lib/src/request_handlers/get_status.dart b/app_dart/lib/src/request_handlers/get_status.dart
index 49ee363..3e29791 100644
--- a/app_dart/lib/src/request_handlers/get_status.dart
+++ b/app_dart/lib/src/request_handlers/get_status.dart
@@ -52,7 +52,8 @@
slug: slug,
)
.map<SerializableCommitStatus>(
- (CommitStatus status) => SerializableCommitStatus(status, keyHelper.encode(status.commit.key)))
+ (CommitStatus status) => SerializableCommitStatus(status, keyHelper.encode(status.commit.key)),
+ )
.toList();
return Body.forJson(<String, dynamic>{
@@ -69,8 +70,10 @@
if (encodedLastCommitKey != null) {
final Key<String> ownerKey = keyHelper.decode(encodedLastCommitKey) as Key<String>;
- final Commit commit = await datastore.db.lookupValue<Commit>(ownerKey,
- orElse: () => throw NotFoundException('Failed to find commit with key $ownerKey'));
+ final Commit commit = await datastore.db.lookupValue<Commit>(
+ ownerKey,
+ orElse: () => throw NotFoundException('Failed to find commit with key $ownerKey'),
+ );
lastCommitTimestamp = commit.timestamp!;
}
diff --git a/app_dart/lib/src/request_handlers/github/webhook_subscription.dart b/app_dart/lib/src/request_handlers/github/webhook_subscription.dart
index a93fad8..ed8c7ae 100644
--- a/app_dart/lib/src/request_handlers/github/webhook_subscription.dart
+++ b/app_dart/lib/src/request_handlers/github/webhook_subscription.dart
@@ -160,7 +160,8 @@
final RepositorySlug slug = pullRequestEvent.repository!.slug();
log.info(
- 'Scheduling tasks if mergeable(${pr.mergeable}): owner=${slug.owner} repo=${slug.name} and pr=${pr.number}');
+ 'Scheduling tasks if mergeable(${pr.mergeable}): owner=${slug.owner} repo=${slug.name} and pr=${pr.number}',
+ );
// The mergeable flag may be null. False indicates there's a merge conflict,
// null indicates unknown. Err on the side of allowing the job to run.
diff --git a/app_dart/lib/src/request_handlers/postsubmit_luci_subscription.dart b/app_dart/lib/src/request_handlers/postsubmit_luci_subscription.dart
index 7db236a..50f178d 100644
--- a/app_dart/lib/src/request_handlers/postsubmit_luci_subscription.dart
+++ b/app_dart/lib/src/request_handlers/postsubmit_luci_subscription.dart
@@ -80,7 +80,7 @@
// create the slug from the data in the message and send the check status
// update.
- RepositorySlug slug = RepositorySlug(
+ final RepositorySlug slug = RepositorySlug(
userData['repo_owner'] as String,
userData['repo_name'] as String,
);
diff --git a/app_dart/lib/src/request_handlers/push_gold_status_to_github.dart b/app_dart/lib/src/request_handlers/push_gold_status_to_github.dart
index d0f34f6..e774586 100644
--- a/app_dart/lib/src/request_handlers/push_gold_status_to_github.dart
+++ b/app_dart/lib/src/request_handlers/push_gold_status_to_github.dart
@@ -157,12 +157,11 @@
// Get Gold status.
final String goldStatus = await _getGoldStatus(slug, pr);
statusRequest = _createStatus(
- goldStatus,
- goldStatus == GithubGoldStatusUpdate.statusRunning
- ? config.flutterGoldChanges
- : config.flutterGoldSuccess,
- slug,
- pr.number!);
+ goldStatus,
+ goldStatus == GithubGoldStatusUpdate.statusRunning ? config.flutterGoldChanges : config.flutterGoldSuccess,
+ slug,
+ pr.number!,
+ );
log.fine('New status for potential update: ${statusRequest.state}, ${statusRequest.description}');
if (goldStatus == GithubGoldStatusUpdate.statusRunning &&
!await _alreadyCommented(gitHubClient, pr, slug, config.flutterGoldCommentID(pr))) {
diff --git a/app_dart/lib/src/request_handlers/refresh_cirrus_status.dart b/app_dart/lib/src/request_handlers/refresh_cirrus_status.dart
index 49c27c5..e8002af 100644
--- a/app_dart/lib/src/request_handlers/refresh_cirrus_status.dart
+++ b/app_dart/lib/src/request_handlers/refresh_cirrus_status.dart
@@ -74,9 +74,9 @@
}
final Map<String, dynamic> searchBuild = searchBuilds.first as Map<String, dynamic>;
tasks.addAll((searchBuild['latestGroupTasks'] as List<dynamic>).cast<Map<String, dynamic>>());
- String? id = searchBuild['id'] as String?;
+ final String? id = searchBuild['id'] as String?;
log.info('Cirrus searchBuild id for flutter/$name, commit: $sha: $id');
- String? branch = searchBuild['branch'] as String?;
+ final String? branch = searchBuild['branch'] as String?;
return CirrusResult(id, branch, tasks);
}
diff --git a/app_dart/lib/src/request_handlers/scheduler/batch_backfiller.dart b/app_dart/lib/src/request_handlers/scheduler/batch_backfiller.dart
index e17455c..a0d2643 100644
--- a/app_dart/lib/src/request_handlers/scheduler/batch_backfiller.dart
+++ b/app_dart/lib/src/request_handlers/scheduler/batch_backfiller.dart
@@ -87,7 +87,8 @@
transaction.queueMutations(inserts: backfillTasks);
await transaction.commit();
log.fine(
- 'Updated ${backfillTasks.length} tasks: ${backfillTasks.map((e) => e.name).toList()} when backfilling.');
+ 'Updated ${backfillTasks.length} tasks: ${backfillTasks.map((e) => e.name).toList()} when backfilling.',
+ );
});
// Schedule all builds asynchronously.
// Schedule after db updates to avoid duplicate scheduling when db update fails.
@@ -107,10 +108,12 @@
tuple.second.task,
tuple.third,
);
- futures.add(scheduler.luciBuildService.schedulePostsubmitBuilds(
- commit: tuple.second.commit,
- toBeScheduled: [toBeScheduled],
- ));
+ futures.add(
+ scheduler.luciBuildService.schedulePostsubmitBuilds(
+ commit: tuple.second.commit,
+ toBeScheduled: [toBeScheduled],
+ ),
+ );
}
return futures;
}
diff --git a/app_dart/lib/src/request_handlers/update_branches.dart b/app_dart/lib/src/request_handlers/update_branches.dart
index 8943f8d..72366c5 100644
--- a/app_dart/lib/src/request_handlers/update_branches.dart
+++ b/app_dart/lib/src/request_handlers/update_branches.dart
@@ -61,19 +61,21 @@
final List<md.Branch> branches = await datastore
.queryBranches()
- .where((md.Branch b) =>
- DateTime.now().millisecondsSinceEpoch - b.lastActivity! < kActiveBranchActivityPeriod.inMilliseconds)
+ .where(
+ (md.Branch b) =>
+ DateTime.now().millisecondsSinceEpoch - b.lastActivity! < kActiveBranchActivityPeriod.inMilliseconds,
+ )
.toList();
return Body.forJson(branches);
}
Future<void> _updateBranchesForAllRepos(Config config, DatastoreService datastore) async {
- DateTime timeNow = DateTime.now();
+ final DateTime timeNow = DateTime.now();
processManager ??= const LocalProcessManager();
final Set<RepositorySlug> slugs = config.supportedRepos;
for (RepositorySlug slug in slugs) {
- ProcessResult result =
+ final ProcessResult result =
processManager!.runSync(['git', 'ls-remote', '--heads', 'git@github.com:flutter/${slug.name}']);
// https://docs.microsoft.com/en-us/windows/win32/debug/system-error-codes--0-499- only a exit code of 0 is good for windows
// for mac or linux, exit code in the range 0 to 255 is good
@@ -81,9 +83,9 @@
((Platform.isMacOS || Platform.isLinux) && result.exitCode < 0)) {
throw const FormatException('returned exit code from git ls-remote is bad');
}
- List<String> shaAndName = (result.stdout as String).trim().split(RegExp(' |\t|\r?\n'));
- List<String> branchShas = [];
- List<String> branchNames = [];
+ final List<String> shaAndName = (result.stdout as String).trim().split(RegExp(' |\t|\r?\n'));
+ final List<String> branchShas = [];
+ final List<String> branchNames = [];
for (int i = 0; i < shaAndName.length; i += 2) {
branchShas.add(shaAndName[i]);
branchNames.add(shaAndName[i + 1].replaceAll('refs/heads/', ''));
@@ -94,12 +96,18 @@
return;
}
- Future<void> _updateBranchesForRepo(List<String> branchShas, List<String> branchNames, GitHub github,
- RepositorySlug slug, DatastoreService datastore, DateTime timeNow) async {
- List<md.Branch> updatedBranches = [];
+ Future<void> _updateBranchesForRepo(
+ List<String> branchShas,
+ List<String> branchNames,
+ GitHub github,
+ RepositorySlug slug,
+ DatastoreService datastore,
+ DateTime timeNow,
+ ) async {
+ final List<md.Branch> updatedBranches = [];
for (int i = 0; i < branchShas.length; i += 1) {
final RepositoryCommit branchCommit = await github.repositories.getCommit(slug, branchShas[i]);
- int lastUpdate = branchCommit.commit!.committer!.date!.millisecondsSinceEpoch;
+ final int lastUpdate = branchCommit.commit!.committer!.date!.millisecondsSinceEpoch;
if (lastUpdate > timeNow.subtract(kActiveBranchActivityPeriod).millisecondsSinceEpoch) {
final String id = '${slug.fullName}/${branchNames[i]}';
final Key<String> key = datastore.db.emptyKey.append<String>(Branch, id: id);
diff --git a/app_dart/lib/src/request_handlers/update_existing_flaky_issues.dart b/app_dart/lib/src/request_handlers/update_existing_flaky_issues.dart
index a25caf0..b9ffda1 100644
--- a/app_dart/lib/src/request_handlers/update_existing_flaky_issues.dart
+++ b/app_dart/lib/src/request_handlers/update_existing_flaky_issues.dart
@@ -44,10 +44,12 @@
CiYaml? localCiYaml = ciYaml;
if (localCiYaml == null) {
- final YamlMap? ci = loadYaml(await gitHub.getFileContent(
- slug,
- kCiYamlPath,
- )) as YamlMap?;
+ final YamlMap? ci = loadYaml(
+ await gitHub.getFileContent(
+ slug,
+ kCiYamlPath,
+ ),
+ ) as YamlMap?;
final pb.SchedulerConfig unCheckedSchedulerConfig = pb.SchedulerConfig()..mergeFromProto3Json(ci);
localCiYaml = CiYaml(
slug: slug,
diff --git a/app_dart/lib/src/request_handlers/vacuum_github_commits.dart b/app_dart/lib/src/request_handlers/vacuum_github_commits.dart
index 78a1125..3d814a4 100644
--- a/app_dart/lib/src/request_handlers/vacuum_github_commits.dart
+++ b/app_dart/lib/src/request_handlers/vacuum_github_commits.dart
@@ -67,8 +67,10 @@
// Do not try to add recent commits as they may already be processed
// by cocoon, which can cause race conditions.
commits = commits
- .where((gh.RepositoryCommit commit) =>
- commit.commit!.committer!.date!.millisecondsSinceEpoch < queryBefore.millisecondsSinceEpoch)
+ .where(
+ (gh.RepositoryCommit commit) =>
+ commit.commit!.committer!.date!.millisecondsSinceEpoch < queryBefore.millisecondsSinceEpoch,
+ )
.toList();
} on gh.GitHubError catch (error) {
log.severe('$error');
@@ -79,23 +81,29 @@
/// Convert [gh.RepositoryCommit] to Cocoon's [Commit] format.
Future<List<Commit>> _toDatastoreCommit(
- gh.RepositorySlug slug, List<gh.RepositoryCommit> commits, DatastoreService? datastore, String branch) async {
+ gh.RepositorySlug slug,
+ List<gh.RepositoryCommit> commits,
+ DatastoreService? datastore,
+ String branch,
+ ) async {
final List<Commit> recentCommits = <Commit>[];
for (gh.RepositoryCommit commit in commits) {
final String id = '${slug.fullName}/$branch/${commit.sha}';
final Key<String> key = datastore!.db.emptyKey.append<String>(Commit, id: id);
- recentCommits.add(Commit(
- key: key,
- timestamp: commit.commit!.committer!.date!.millisecondsSinceEpoch,
- repository: slug.fullName,
- sha: commit.sha!,
- author: commit.author!.login!,
- authorAvatarUrl: commit.author!.avatarUrl!,
- // The field has a size of 1500 we need to ensure the commit message
- // is at most 1500 chars long.
- message: truncate(commit.commit!.message!, 1490, omission: '...'),
- branch: branch,
- ));
+ recentCommits.add(
+ Commit(
+ key: key,
+ timestamp: commit.commit!.committer!.date!.millisecondsSinceEpoch,
+ repository: slug.fullName,
+ sha: commit.sha!,
+ author: commit.author!.login!,
+ authorAvatarUrl: commit.author!.avatarUrl!,
+ // The field has a size of 1500 we need to ensure the commit message
+ // is at most 1500 chars long.
+ message: truncate(commit.commit!.message!, 1490, omission: '...'),
+ branch: branch,
+ ),
+ );
}
return recentCommits;
}
diff --git a/app_dart/lib/src/request_handling/api_request_handler.dart b/app_dart/lib/src/request_handling/api_request_handler.dart
index f43b738..b20e178 100644
--- a/app_dart/lib/src/request_handling/api_request_handler.dart
+++ b/app_dart/lib/src/request_handling/api_request_handler.dart
@@ -146,13 +146,16 @@
}
}
- await runZoned<Future<void>>(() async {
- await super.service(request);
- }, zoneValues: <ApiKey<dynamic>, Object?>{
- ApiKey.authContext: context,
- ApiKey.requestBody: Uint8List.fromList(body),
- ApiKey.requestData: requestData,
- });
+ await runZoned<Future<void>>(
+ () async {
+ await super.service(request);
+ },
+ zoneValues: <ApiKey<dynamic>, Object?>{
+ ApiKey.authContext: context,
+ ApiKey.requestBody: Uint8List.fromList(body),
+ ApiKey.requestData: requestData,
+ },
+ );
}
}
diff --git a/app_dart/lib/src/request_handling/authentication.dart b/app_dart/lib/src/request_handling/authentication.dart
index 69d2fd7..21d99ee 100644
--- a/app_dart/lib/src/request_handling/authentication.dart
+++ b/app_dart/lib/src/request_handling/authentication.dart
@@ -105,13 +105,15 @@
final String? idTokenFromHeader = request.headers.value('X-Flutter-IdToken');
final http.Client client = httpClientProvider();
try {
- final http.Response verifyTokenResponse = await client.get(Uri.https(
- 'oauth2.googleapis.com',
- '/tokeninfo',
- <String, String?>{
- tokenType: idTokenFromHeader,
- },
- ));
+ final http.Response verifyTokenResponse = await client.get(
+ Uri.https(
+ 'oauth2.googleapis.com',
+ '/tokeninfo',
+ <String, String?>{
+ tokenType: idTokenFromHeader,
+ },
+ ),
+ );
if (verifyTokenResponse.statusCode != HttpStatus.ok) {
/// Google Auth API returns a message in the response body explaining why
diff --git a/app_dart/lib/src/request_handling/no_auth_request_handler.dart b/app_dart/lib/src/request_handling/no_auth_request_handler.dart
index d2a6026..92a5244 100644
--- a/app_dart/lib/src/request_handling/no_auth_request_handler.dart
+++ b/app_dart/lib/src/request_handling/no_auth_request_handler.dart
@@ -98,12 +98,15 @@
}
}
- await runZoned<Future<void>>(() async {
- await super.service(request);
- }, zoneValues: <NoAuthKey<dynamic>, Object?>{
- NoAuthKey.requestBody: Uint8List.fromList(body),
- NoAuthKey.requestData: requestData,
- });
+ await runZoned<Future<void>>(
+ () async {
+ await super.service(request);
+ },
+ zoneValues: <NoAuthKey<dynamic>, Object?>{
+ NoAuthKey.requestBody: Uint8List.fromList(body),
+ NoAuthKey.requestData: requestData,
+ },
+ );
}
}
diff --git a/app_dart/lib/src/request_handling/pubsub.dart b/app_dart/lib/src/request_handling/pubsub.dart
index c5d42f3..e9deacc 100644
--- a/app_dart/lib/src/request_handling/pubsub.dart
+++ b/app_dart/lib/src/request_handling/pubsub.dart
@@ -21,16 +21,20 @@
final HttpClientProvider httpClientProvider;
Future<void> publish(String topic, dynamic json) async {
- final Client httpClient = await clientViaApplicationDefaultCredentials(scopes: <String>[
- PubsubApi.pubsubScope,
- ]);
+ final Client httpClient = await clientViaApplicationDefaultCredentials(
+ scopes: <String>[
+ PubsubApi.pubsubScope,
+ ],
+ );
final PubsubApi pubsubApi = PubsubApi(httpClient);
final String messageData = jsonEncode(json);
final List<int> messageBytes = utf8.encode(messageData);
final String messageBase64 = base64Encode(messageBytes);
- final PublishRequest request = PublishRequest(messages: <PubsubMessage>[
- PubsubMessage(data: messageBase64),
- ]);
+ final PublishRequest request = PublishRequest(
+ messages: <PubsubMessage>[
+ PubsubMessage(data: messageBase64),
+ ],
+ );
final String fullTopicName = 'projects/flutter-dashboard/topics/$topic';
final PublishResponse response = await pubsubApi.projects.topics.publish(request, fullTopicName);
log.info('pubsub response messageId=${response.messageIds}');
diff --git a/app_dart/lib/src/request_handling/request_handler.dart b/app_dart/lib/src/request_handling/request_handler.dart
index 8e57bf4..2577b4c 100644
--- a/app_dart/lib/src/request_handling/request_handler.dart
+++ b/app_dart/lib/src/request_handling/request_handler.dart
@@ -39,46 +39,49 @@
HttpRequest request, {
Future<void> Function(HttpStatusException)? onError,
}) {
- return runZoned<Future<void>>(() async {
- final HttpResponse response = request.response;
- try {
+ return runZoned<Future<void>>(
+ () async {
+ final HttpResponse response = request.response;
try {
- T body;
- switch (request.method) {
- case 'GET':
- body = await get();
- break;
- case 'POST':
- body = await post();
- break;
- default:
- throw MethodNotAllowed(request.method);
+ try {
+ T body;
+ switch (request.method) {
+ case 'GET':
+ body = await get();
+ break;
+ case 'POST':
+ body = await post();
+ break;
+ default:
+ throw MethodNotAllowed(request.method);
+ }
+ await _respond(body: body);
+ httpClient?.close();
+ return;
+ } on HttpStatusException {
+ rethrow;
+ } catch (error, stackTrace) {
+ log.severe('$error\n$stackTrace');
+ throw InternalServerError('$error\n$stackTrace');
}
- await _respond(body: body);
- httpClient?.close();
+ } on HttpStatusException catch (error) {
+ if (onError != null) {
+ await onError(error);
+ }
+ response
+ ..statusCode = error.statusCode
+ ..write(error.message);
+ await response.flush();
+ await response.close();
return;
- } on HttpStatusException {
- rethrow;
- } catch (error, stackTrace) {
- log.severe('$error\n$stackTrace');
- throw InternalServerError('$error\n$stackTrace');
}
- } on HttpStatusException catch (error) {
- if (onError != null) {
- await onError(error);
- }
- response
- ..statusCode = error.statusCode
- ..write(error.message);
- await response.flush();
- await response.close();
- return;
- }
- }, zoneValues: <RequestKey<dynamic>, Object>{
- RequestKey.request: request,
- RequestKey.response: request.response,
- RequestKey.httpClient: httpClient ?? http.Client(),
- });
+ },
+ zoneValues: <RequestKey<dynamic>, Object>{
+ RequestKey.request: request,
+ RequestKey.response: request.response,
+ RequestKey.httpClient: httpClient ?? http.Client(),
+ },
+ );
}
/// Responds (using [response]) with the specified [status] and optional
diff --git a/app_dart/lib/src/request_handling/swarming_authentication.dart b/app_dart/lib/src/request_handling/swarming_authentication.dart
index a6d9ce0..4362e94 100644
--- a/app_dart/lib/src/request_handling/swarming_authentication.dart
+++ b/app_dart/lib/src/request_handling/swarming_authentication.dart
@@ -69,19 +69,23 @@
/// if they belong to a LUCI prod service account.
///
/// If LUCI auth adds id tokens, we can switch to that and remove this.
- Future<AuthenticatedContext> authenticateAccessToken(String accessToken,
- {required ClientContext clientContext}) async {
+ Future<AuthenticatedContext> authenticateAccessToken(
+ String accessToken, {
+ required ClientContext clientContext,
+ }) async {
// Authenticate as a signed-in Google account via OAuth id token.
final Client client = httpClientProvider();
try {
log.fine('Sending token request to Google OAuth');
- final Response verifyTokenResponse = await client.get(Uri.https(
- 'oauth2.googleapis.com',
- '/tokeninfo',
- <String, String>{
- 'access_token': accessToken,
- },
- ));
+ final Response verifyTokenResponse = await client.get(
+ Uri.https(
+ 'oauth2.googleapis.com',
+ '/tokeninfo',
+ <String, String>{
+ 'access_token': accessToken,
+ },
+ ),
+ );
if (verifyTokenResponse.statusCode != HttpStatus.ok) {
/// Google Auth API returns a message in the response body explaining why
diff --git a/app_dart/lib/src/service/bigquery.dart b/app_dart/lib/src/service/bigquery.dart
index 650362a..7c7e9d4 100644
--- a/app_dart/lib/src/service/bigquery.dart
+++ b/app_dart/lib/src/service/bigquery.dart
@@ -108,8 +108,11 @@
///
/// See getBuilderStatisticQuery to get the detail information about the table
/// schema
- Future<List<BuilderStatistic>> listBuilderStatistic(String projectId,
- {int limit = 100, String bucket = 'prod'}) async {
+ Future<List<BuilderStatistic>> listBuilderStatistic(
+ String projectId, {
+ int limit = 100,
+ String bucket = 'prod',
+ }) async {
final JobsResource jobsResource = await defaultJobs();
final QueryRequest query = QueryRequest.fromJson(<String, Object>{
'query': bucket == 'staging' ? getStagingBuilderStatisticQuery : getBuilderStatisticQuery,
@@ -135,16 +138,18 @@
List<String>? succeededBuilds = (row.f![4].v as String?)?.split(', ');
succeededBuilds?.sort();
succeededBuilds = succeededBuilds?.reversed.toList();
- result.add(BuilderStatistic(
- name: builder,
- flakyRate: double.parse(row.f![7].v as String),
- flakyBuilds: flakyBuilds ?? const <String>[],
- succeededBuilds: succeededBuilds ?? const <String>[],
- recentCommit: row.f![5].v as String?,
- flakyBuildOfRecentCommit: row.f![6].v as String?,
- flakyNumber: int.parse(row.f![1].v as String),
- totalNumber: int.parse(row.f![2].v as String),
- ));
+ result.add(
+ BuilderStatistic(
+ name: builder,
+ flakyRate: double.parse(row.f![7].v as String),
+ flakyBuilds: flakyBuilds ?? const <String>[],
+ succeededBuilds: succeededBuilds ?? const <String>[],
+ recentCommit: row.f![5].v as String?,
+ flakyBuildOfRecentCommit: row.f![6].v as String?,
+ flakyNumber: int.parse(row.f![1].v as String),
+ totalNumber: int.parse(row.f![2].v as String),
+ ),
+ );
}
return result;
}
@@ -186,11 +191,13 @@
return result;
}
for (final TableRow row in response.rows!) {
- result.add(BuilderRecord(
- commit: row.f![0].v as String,
- isFlaky: row.f![1].v as String != '0',
- isFailed: row.f![2].v as String != '0',
- ));
+ result.add(
+ BuilderRecord(
+ commit: row.f![0].v as String,
+ isFlaky: row.f![1].v as String != '0',
+ isFailed: row.f![2].v as String != '0',
+ ),
+ );
}
return result;
}
diff --git a/app_dart/lib/src/service/branch_service.dart b/app_dart/lib/src/service/branch_service.dart
index 3d11185..4409367 100644
--- a/app_dart/lib/src/service/branch_service.dart
+++ b/app_dart/lib/src/service/branch_service.dart
@@ -88,8 +88,11 @@
/// short timespan, and require the release manager to CP onto the recipes branch (in the case of reverts).
Future<void> branchFlutterRecipes(String branch) async {
final gh.RepositorySlug recipesSlug = gh.RepositorySlug('flutter', 'recipes');
- if ((await gerritService.branches('${recipesSlug.owner}-review.googlesource.com', recipesSlug.name,
- filterRegex: branch))
+ if ((await gerritService.branches(
+ '${recipesSlug.owner}-review.googlesource.com',
+ recipesSlug.name,
+ filterRegex: branch,
+ ))
.contains(branch)) {
// subString is a regex, and can return multiple matches
log.warning('$branch already exists for $recipesSlug');
@@ -122,7 +125,7 @@
required GithubService githubService,
required gh.RepositorySlug slug,
}) async {
- List<gh.Branch> branches = await githubService.github.repositories.listBranches(slug).toList();
+ final List<gh.Branch> branches = await githubService.github.repositories.listBranches(slug).toList();
final String latestCandidateBranch = await _getLatestCandidateBranch(
github: githubService.github,
slug: slug,
@@ -175,18 +178,18 @@
required List<gh.Branch> branches,
}) async {
final RegExp candidateBranchName = RegExp(r'flutter-\d+\.\d+-candidate\.\d+');
- List<gh.Branch> devBranches = branches.where((gh.Branch b) => candidateBranchName.hasMatch(b.name!)).toList();
+ final List<gh.Branch> devBranches = branches.where((gh.Branch b) => candidateBranchName.hasMatch(b.name!)).toList();
devBranches.sort((b, a) => (_versionSum(a.name!)).compareTo(_versionSum(b.name!)));
- String devBranchName = devBranches.take(1).single.name!;
+ final String devBranchName = devBranches.take(1).single.name!;
return devBranchName;
}
/// Helper function to convert candidate branch versions to numbers for comparison.
int _versionSum(String tagOrBranchName) {
- List<String> digits = tagOrBranchName.replaceAll(r'flutter|candidate', '0').split(RegExp(r'\.|\-'));
+ final List<String> digits = tagOrBranchName.replaceAll(r'flutter|candidate', '0').split(RegExp(r'\.|\-'));
int versionSum = 0;
for (String digit in digits) {
- int? d = int.tryParse(digit);
+ final int? d = int.tryParse(digit);
if (d == null) {
continue;
}
diff --git a/app_dart/lib/src/service/buildbucket.dart b/app_dart/lib/src/service/buildbucket.dart
index 40cf2b9..fabcc90 100644
--- a/app_dart/lib/src/service/buildbucket.dart
+++ b/app_dart/lib/src/service/buildbucket.dart
@@ -67,15 +67,20 @@
final Uri url = Uri.parse('$buildBucketUri$path');
final AccessToken? token = await accessTokenService?.createAccessToken();
- final http.Response response = await httpClient.post(url, body: json.encode(request), headers: <String, String>{
- HttpHeaders.contentTypeHeader: 'application/json',
- HttpHeaders.acceptHeader: 'application/json',
- if (token != null) HttpHeaders.authorizationHeader: '${token.type} ${token.data}',
- });
+ final http.Response response = await httpClient.post(
+ url,
+ body: json.encode(request),
+ headers: <String, String>{
+ HttpHeaders.contentTypeHeader: 'application/json',
+ HttpHeaders.acceptHeader: 'application/json',
+ if (token != null) HttpHeaders.authorizationHeader: '${token.type} ${token.data}',
+ },
+ );
if (response.statusCode < 300) {
return responseFromJson(
- json.decode(response.body.substring(kRpcResponseGarbage.length)) as Map<String, dynamic>?);
+ json.decode(response.body.substring(kRpcResponseGarbage.length)) as Map<String, dynamic>?,
+ );
}
throw BuildBucketException(response.statusCode, response.body);
}
diff --git a/app_dart/lib/src/service/datastore.dart b/app_dart/lib/src/service/datastore.dart
index 5a589de..dfa9897 100644
--- a/app_dart/lib/src/service/datastore.dart
+++ b/app_dart/lib/src/service/datastore.dart
@@ -195,8 +195,10 @@
/// occurs in app engine. When multiple records exist, the latest one
/// is returned.
if (previousStatusUpdates.length > 1) {
- return previousStatusUpdates.reduce((GithubBuildStatusUpdate current, GithubBuildStatusUpdate next) =>
- current.updateTimeMillis! < next.updateTimeMillis! ? next : current);
+ return previousStatusUpdates.reduce(
+ (GithubBuildStatusUpdate current, GithubBuildStatusUpdate next) =>
+ current.updateTimeMillis! < next.updateTimeMillis! ? next : current,
+ );
}
return previousStatusUpdates.single;
}
@@ -242,45 +244,57 @@
Future<void> insert(List<Model<dynamic>> rows) async {
final List<List<Model<dynamic>>> shards = await shard(rows);
for (List<Model<dynamic>> shard in shards) {
- await runTransactionWithRetries(() async {
- await db.withTransaction<void>((Transaction transaction) async {
- transaction.queueMutations(inserts: shard);
- await transaction.commit();
- });
- }, retryOptions: retryOptions);
+ await runTransactionWithRetries(
+ () async {
+ await db.withTransaction<void>((Transaction transaction) async {
+ transaction.queueMutations(inserts: shard);
+ await transaction.commit();
+ });
+ },
+ retryOptions: retryOptions,
+ );
}
}
/// Looks up registers by [keys].
Future<List<T?>> lookupByKey<T extends Model<dynamic>>(List<Key<dynamic>> keys) async {
List<T?> results = <T>[];
- await runTransactionWithRetries(() async {
- await db.withTransaction<void>((Transaction transaction) async {
- results = await transaction.lookup<T>(keys);
- });
- }, retryOptions: retryOptions);
+ await runTransactionWithRetries(
+ () async {
+ await db.withTransaction<void>((Transaction transaction) async {
+ results = await transaction.lookup<T>(keys);
+ });
+ },
+ retryOptions: retryOptions,
+ );
return results;
}
/// Looks up registers by value using a single [key].
Future<T> lookupByValue<T extends Model<dynamic>>(Key<dynamic> key, {T Function()? orElse}) async {
late T result;
- await runTransactionWithRetries(() async {
- await db.withTransaction<void>((Transaction transaction) async {
- result = await db.lookupValue<T>(key, orElse: orElse);
- });
- }, retryOptions: retryOptions);
+ await runTransactionWithRetries(
+ () async {
+ await db.withTransaction<void>((Transaction transaction) async {
+ result = await db.lookupValue<T>(key, orElse: orElse);
+ });
+ },
+ retryOptions: retryOptions,
+ );
return result;
}
/// Runs a function inside a transaction providing a [Transaction] parameter.
Future<T?> withTransaction<T>(Future<T> Function(Transaction) handler) async {
T? result;
- await runTransactionWithRetries(() async {
- await db.withTransaction<void>((Transaction transaction) async {
- result = await handler(transaction);
- });
- }, retryOptions: retryOptions);
+ await runTransactionWithRetries(
+ () async {
+ await db.withTransaction<void>((Transaction transaction) async {
+ result = await handler(transaction);
+ });
+ },
+ retryOptions: retryOptions,
+ );
return result;
}
}
diff --git a/app_dart/lib/src/service/github_checks_service.dart b/app_dart/lib/src/service/github_checks_service.dart
index 42f48fa..b7bfe24 100644
--- a/app_dart/lib/src/service/github_checks_service.dart
+++ b/app_dart/lib/src/service/github_checks_service.dart
@@ -40,7 +40,10 @@
/// https://docs.github.com/en/rest/reference/checks#create-a-check-suite
/// https://docs.github.com/en/rest/reference/checks#rerequest-a-check-suite
Future<void> handleCheckSuite(
- github.PullRequest pullRequest, CheckSuiteEvent checkSuiteEvent, Scheduler scheduler) async {
+ github.PullRequest pullRequest,
+ CheckSuiteEvent checkSuiteEvent,
+ Scheduler scheduler,
+ ) async {
switch (checkSuiteEvent.action) {
case 'requested':
// Trigger all try builders.
diff --git a/app_dart/lib/src/service/github_service.dart b/app_dart/lib/src/service/github_service.dart
index 1ea5524..129d681 100644
--- a/app_dart/lib/src/service/github_service.dart
+++ b/app_dart/lib/src/service/github_service.dart
@@ -70,9 +70,10 @@
..commit = (GitCommit()
..message = commit['commit']['message'] as String?
..committer = (GitCommitUser(
- commit['commit']['author']['name'] as String?,
- commit['commit']['author']['email'] as String?,
- DateTime.parse(commit['commit']['author']['date'] as String))));
+ commit['commit']['author']['name'] as String?,
+ commit['commit']['author']['email'] as String?,
+ DateTime.parse(commit['commit']['author']['date'] as String),
+ )));
}).toList();
}
@@ -217,8 +218,11 @@
}) async {
ArgumentError.checkNotNull(slug);
ArgumentError.checkNotNull(issueNumber);
- final Response response = await github.request('PUT', '/repos/${slug.fullName}/issues/$issueNumber/labels',
- body: GitHubJson.encode(labels));
+ final Response response = await github.request(
+ 'PUT',
+ '/repos/${slug.fullName}/issues/$issueNumber/labels',
+ body: GitHubJson.encode(labels),
+ );
final List<dynamic> body = jsonDecode(response.body) as List<dynamic>;
return body.map((dynamic it) => IssueLabel.fromJson(it as Map<String, dynamic>)).toList();
}
diff --git a/app_dart/lib/src/service/luci_build_service.dart b/app_dart/lib/src/service/luci_build_service.dart
index bcb0d96..d018c32 100644
--- a/app_dart/lib/src/service/luci_build_service.dart
+++ b/app_dart/lib/src/service/luci_build_service.dart
@@ -95,21 +95,25 @@
String bucket,
Map<String, List<String>> tags,
) async {
- final BatchResponse batch = await buildBucketClient.batch(BatchRequest(requests: <Request>[
- Request(
- searchBuilds: SearchBuildsRequest(
- predicate: BuildPredicate(
- builderId: BuilderId(
- project: 'flutter',
- bucket: bucket,
- builder: builderName,
+ final BatchResponse batch = await buildBucketClient.batch(
+ BatchRequest(
+ requests: <Request>[
+ Request(
+ searchBuilds: SearchBuildsRequest(
+ predicate: BuildPredicate(
+ builderId: BuilderId(
+ project: 'flutter',
+ bucket: bucket,
+ builder: builderName,
+ ),
+ tags: tags,
+ ),
+ fields: 'builds.*.id,builds.*.builder,builds.*.tags,builds.*.status,builds.*.input.properties',
),
- tags: tags,
),
- fields: 'builds.*.id,builds.*.builder,builds.*.tags,builds.*.status,builds.*.input.properties',
- ),
+ ],
),
- ]));
+ );
final Iterable<Build> builds = batch.responses!
.map((Response response) => response.searchBuilds)
.expand((SearchBuildsResponse? response) => response!.builds ?? <Build>[]);
@@ -121,42 +125,46 @@
Future<Map<String?, Build?>> tryBuildsForPullRequest(
github.PullRequest pullRequest,
) async {
- final BatchResponse batch = await buildBucketClient.batch(BatchRequest(requests: <Request>[
- // Builds created by Cocoon
- Request(
- searchBuilds: SearchBuildsRequest(
- predicate: BuildPredicate(
- builderId: const BuilderId(
- project: 'flutter',
- bucket: 'try',
+ final BatchResponse batch = await buildBucketClient.batch(
+ BatchRequest(
+ requests: <Request>[
+ // Builds created by Cocoon
+ Request(
+ searchBuilds: SearchBuildsRequest(
+ predicate: BuildPredicate(
+ builderId: const BuilderId(
+ project: 'flutter',
+ bucket: 'try',
+ ),
+ createdBy: 'cocoon',
+ tags: <String, List<String>>{
+ 'buildset': <String>['pr/git/${pullRequest.number}'],
+ 'github_link': <String>[
+ 'https://github.com/${pullRequest.base!.repo!.fullName}/pull/${pullRequest.number}'
+ ],
+ 'user_agent': const <String>['flutter-cocoon'],
+ },
+ ),
),
- createdBy: 'cocoon',
- tags: <String, List<String>>{
- 'buildset': <String>['pr/git/${pullRequest.number}'],
- 'github_link': <String>[
- 'https://github.com/${pullRequest.base!.repo!.fullName}/pull/${pullRequest.number}'
- ],
- 'user_agent': const <String>['flutter-cocoon'],
- },
),
- ),
- ),
- // Builds created by recipe (via swarming create task)
- Request(
- searchBuilds: SearchBuildsRequest(
- predicate: BuildPredicate(
- builderId: const BuilderId(
- project: 'flutter',
- bucket: 'try',
+ // Builds created by recipe (via swarming create task)
+ Request(
+ searchBuilds: SearchBuildsRequest(
+ predicate: BuildPredicate(
+ builderId: const BuilderId(
+ project: 'flutter',
+ bucket: 'try',
+ ),
+ tags: <String, List<String>>{
+ 'buildset': <String>['pr/git/${pullRequest.number}'],
+ 'user_agent': const <String>['recipe'],
+ },
+ ),
),
- tags: <String, List<String>>{
- 'buildset': <String>['pr/git/${pullRequest.number}'],
- 'user_agent': const <String>['recipe'],
- },
),
- ),
+ ],
),
- ]));
+ );
final Iterable<Build> builds = batch.responses!
.map((Response response) => response.searchBuilds)
.expand((SearchBuildsResponse? response) => response?.builds ?? <Build>[]);
@@ -193,8 +201,10 @@
}
final Map<String?, Build?> tryBuilds = await tryBuildsForPullRequest(pullRequest);
- final Iterable<Build?> runningOrCompletedBuilds = tryBuilds.values.where((Build? build) =>
- build?.status == Status.scheduled || build?.status == Status.started || build?.status == Status.success);
+ final Iterable<Build?> runningOrCompletedBuilds = tryBuilds.values.where(
+ (Build? build) =>
+ build?.status == Status.scheduled || build?.status == Status.started || build?.status == Status.success,
+ );
final List<Target> targetsToSchedule = <Target>[];
for (Target target in targets) {
if (runningOrCompletedBuilds.any((Build? build) => build?.builderId.builder == target.value.name)) {
@@ -243,26 +253,29 @@
userData['builder_name'] = target.value.name;
}
- Map<String, List<String>> tags = <String, List<String>>{
+ final Map<String, List<String>> tags = <String, List<String>>{
'github_checkrun': <String>[checkRun.id.toString()],
};
- Map<String, Object> properties = target.getProperties();
+ final Map<String, Object> properties = target.getProperties();
properties.putIfAbsent('git_branch', () => pullRequest.base!.ref!.replaceAll('refs/heads/', ''));
- requests.add(Request(
+ requests.add(
+ Request(
scheduleBuild: _createPresubmitScheduleBuild(
- slug: slug,
- sha: pullRequest.head!.sha!,
- //Use target.value.name here otherwise tests will die due to null checkRun.name.
- checkName: target.value.name,
- pullRequestNumber: pullRequest.number!,
- cipdVersion: cipdVersion,
- userData: userData,
- properties: properties,
- tags: tags,
- dimensions: target.getDimensions(),
- )));
+ slug: slug,
+ sha: pullRequest.head!.sha!,
+ //Use target.value.name here otherwise tests will die due to null checkRun.name.
+ checkName: target.value.name,
+ pullRequestNumber: pullRequest.number!,
+ cipdVersion: cipdVersion,
+ userData: userData,
+ properties: properties,
+ tags: tags,
+ dimensions: target.getDimensions(),
+ ),
+ ),
+ );
}
final Iterable<List<Request>> requestPartitions = await shard(requests, config.schedulingShardSize);
@@ -323,24 +336,26 @@
// is expecting just the last part after "."(prod).
final String bucketName = buildPushMessage.build!.bucket!.split('.').last;
final Map<String, dynamic>? userData = jsonDecode(buildPushMessage.userData!) as Map<String, dynamic>?;
- await buildBucketClient.scheduleBuild(ScheduleBuildRequest(
- builderId: BuilderId(
- project: buildPushMessage.build!.project,
- bucket: bucketName,
- builder: builderName,
+ await buildBucketClient.scheduleBuild(
+ ScheduleBuildRequest(
+ builderId: BuilderId(
+ project: buildPushMessage.build!.project,
+ bucket: bucketName,
+ builder: builderName,
+ ),
+ tags: <String, List<String>>{
+ 'buildset': buildPushMessage.build!.tagsByName('buildset'),
+ 'user_agent': buildPushMessage.build!.tagsByName('user_agent'),
+ 'github_link': buildPushMessage.build!.tagsByName('github_link'),
+ },
+ properties:
+ (buildPushMessage.build!.buildParameters!['properties'] as Map<String, dynamic>).cast<String, String>(),
+ notify: NotificationConfig(
+ pubsubTopic: 'projects/flutter-dashboard/topics/luci-builds',
+ userData: json.encode(userData),
+ ),
),
- tags: <String, List<String>>{
- 'buildset': buildPushMessage.build!.tagsByName('buildset'),
- 'user_agent': buildPushMessage.build!.tagsByName('user_agent'),
- 'github_link': buildPushMessage.build!.tagsByName('github_link'),
- },
- properties:
- (buildPushMessage.build!.buildParameters!['properties'] as Map<String, dynamic>).cast<String, String>(),
- notify: NotificationConfig(
- pubsubTopic: 'projects/flutter-dashboard/topics/luci-builds',
- userData: json.encode(userData),
- ),
- ));
+ );
return true;
}
@@ -368,18 +383,19 @@
final String cipdVersion = build.tags!['cipd_version']![0]!;
final int prNumber = int.parse(prString.split('/')[2]);
- Map<String, dynamic> userData = <String, dynamic>{'check_run_id': githubCheckRun.id};
- Map<String, dynamic>? properties = build.input!.properties;
+ final Map<String, dynamic> userData = <String, dynamic>{'check_run_id': githubCheckRun.id};
+ final Map<String, dynamic>? properties = build.input!.properties;
log.info('input ${build.input!} properties $properties');
- ScheduleBuildRequest scheduleBuildRequest = _createPresubmitScheduleBuild(
- slug: slug,
- sha: sha,
- checkName: checkName,
- pullRequestNumber: prNumber,
- cipdVersion: cipdVersion,
- properties: properties,
- userData: userData);
+ final ScheduleBuildRequest scheduleBuildRequest = _createPresubmitScheduleBuild(
+ slug: slug,
+ sha: sha,
+ checkName: checkName,
+ pullRequestNumber: prNumber,
+ cipdVersion: cipdVersion,
+ properties: properties,
+ userData: userData,
+ );
final Build scheduleBuild = await buildBucketClient.scheduleBuild(scheduleBuildRequest);
@@ -400,7 +416,7 @@
String project = 'flutter',
String bucket = 'prod',
}) async {
- Set<String> availableBuilderSet = <String>{};
+ final Set<String> availableBuilderSet = <String>{};
String? token;
do {
final ListBuildersResponse listBuildersResponse =
@@ -480,8 +496,9 @@
processedTags['cipd_version'] = <String>[cipdVersion];
final NotificationConfig notificationConfig = NotificationConfig(
- pubsubTopic: 'projects/flutter-dashboard/topics/luci-builds',
- userData: base64Encode(json.encode(processedUserData).codeUnits));
+ pubsubTopic: 'projects/flutter-dashboard/topics/luci-builds',
+ userData: base64Encode(json.encode(processedUserData).codeUnits),
+ );
final Map<String, dynamic> exec = <String, dynamic>{'cipdVersion': cipdVersion};
diff --git a/app_dart/lib/src/service/scheduler.dart b/app_dart/lib/src/service/scheduler.dart
index dd7707f..d33a6f0 100644
--- a/app_dart/lib/src/service/scheduler.dart
+++ b/app_dart/lib/src/service/scheduler.dart
@@ -168,10 +168,12 @@
Future<void> _batchScheduleBuilds(Commit commit, List<Tuple<Target, Task, int>> toBeScheduled) async {
final List<Future<void>> futures = <Future<void>>[];
for (int i = 0; i < toBeScheduled.length; i += config.batchSize) {
- futures.add(luciBuildService.schedulePostsubmitBuilds(
- commit: commit,
- toBeScheduled: toBeScheduled.sublist(i, min(i + config.batchSize, toBeScheduled.length)),
- ));
+ futures.add(
+ luciBuildService.schedulePostsubmitBuilds(
+ commit: commit,
+ toBeScheduled: toBeScheduled.sublist(i, min(i + config.batchSize, toBeScheduled.length)),
+ ),
+ );
}
await Future.wait<void>(futures);
}
@@ -252,7 +254,7 @@
retryOptions: retryOptions,
);
final YamlMap configYaml = loadYaml(configContent) as YamlMap;
- pb.SchedulerConfig schedulerConfig = pb.SchedulerConfig()..mergeFromProto3Json(configYaml);
+ final pb.SchedulerConfig schedulerConfig = pb.SchedulerConfig()..mergeFromProto3Json(configYaml);
return schedulerConfig.writeToBuffer();
}
@@ -338,7 +340,8 @@
);
}
log.info(
- 'Finished triggering builds for: pr ${pullRequest.number}, commit ${pullRequest.base!.sha}, branch ${pullRequest.head!.ref} and slug ${pullRequest.base!.repo!.slug()}}');
+ 'Finished triggering builds for: pr ${pullRequest.number}, commit ${pullRequest.base!.sha}, branch ${pullRequest.head!.ref} and slug ${pullRequest.base!.repo!.slug()}}',
+ );
}
/// If [builderTriggerList] is specificed, return only builders that are contained in [presubmitTarget].
@@ -402,8 +405,10 @@
ciYaml = await getCiYaml(commit);
}
- final Iterable<Target> presubmitTargets = ciYaml.presubmitTargets.where((Target target) =>
- target.value.scheduler == pb.SchedulerSystem.luci || target.value.scheduler == pb.SchedulerSystem.cocoon);
+ final Iterable<Target> presubmitTargets = ciYaml.presubmitTargets.where(
+ (Target target) =>
+ target.value.scheduler == pb.SchedulerSystem.luci || target.value.scheduler == pb.SchedulerSystem.cocoon,
+ );
// Release branches should run every test.
if (pullRequest.base!.ref != Config.defaultBranch(pullRequest.base!.repo!.slug())) {
return presubmitTargets.toList();
diff --git a/app_dart/test/foundation/utils_test.dart b/app_dart/test/foundation/utils_test.dart
index 77ab5a2..18e60b9 100644
--- a/app_dart/test/foundation/utils_test.dart
+++ b/app_dart/test/foundation/utils_test.dart
@@ -153,17 +153,18 @@
final List<LogRecord> records = <LogRecord>[];
log.onRecord.listen((LogRecord record) => records.add(record));
await expectLater(
- githubFileContent(
- RepositorySlug('flutter', 'cocoon'),
- 'branches.txt',
- httpClientProvider: () => branchHttpClient,
- retryOptions: const RetryOptions(
- maxAttempts: 3,
- delayFactor: Duration.zero,
- maxDelay: Duration.zero,
- ),
+ githubFileContent(
+ RepositorySlug('flutter', 'cocoon'),
+ 'branches.txt',
+ httpClientProvider: () => branchHttpClient,
+ retryOptions: const RetryOptions(
+ maxAttempts: 3,
+ delayFactor: Duration.zero,
+ maxDelay: Duration.zero,
),
- throwsA(isA<HttpException>()));
+ ),
+ throwsA(isA<HttpException>()),
+ );
// It will request from GitHub 3 times, fallback to GoB, then fail.
expect(retry, 6);
expect(records.where((LogRecord record) => record.level == Level.WARNING), isNotEmpty);
diff --git a/app_dart/test/model/ci_yaml/ci_yaml_test.dart b/app_dart/test/model/ci_yaml/ci_yaml_test.dart
index a15a1ce..920626b 100644
--- a/app_dart/test/model/ci_yaml/ci_yaml_test.dart
+++ b/app_dart/test/model/ci_yaml/ci_yaml_test.dart
@@ -15,15 +15,20 @@
final List<EnabledBranchesRegexTest> tests = <EnabledBranchesRegexTest>[
EnabledBranchesRegexTest('matches main', 'main', <String>['main']),
EnabledBranchesRegexTest(
- 'matches candidate branch', 'flutter-2.4-candidate.3', <String>['flutter-\\d+\\.\\d+-candidate\\.\\d+']),
+ 'matches candidate branch',
+ 'flutter-2.4-candidate.3',
+ <String>['flutter-\\d+\\.\\d+-candidate\\.\\d+'],
+ ),
EnabledBranchesRegexTest('matches main when not first pattern', 'main', <String>['dev', 'main']),
EnabledBranchesRegexTest('does not do partial matches', 'super-main', <String>['main'], false),
];
for (EnabledBranchesRegexTest regexTest in tests) {
test(regexTest.name, () {
- expect(CiYaml.enabledBranchesMatchesCurrentBranch(regexTest.enabledBranches, regexTest.branch),
- regexTest.expectation);
+ expect(
+ CiYaml.enabledBranchesMatchesCurrentBranch(regexTest.enabledBranches, regexTest.branch),
+ regexTest.expectation,
+ );
});
}
});
@@ -39,7 +44,8 @@
validatePinnedVersion('[{"dependency": "open_jdk", "version": "11"}]');
validatePinnedVersion('[{"dependency": "android_sdk", "version": "version:31v8"}]');
validatePinnedVersion(
- '[{"dependency": "goldctl", "version": "git_revision:3a77d0b12c697a840ca0c7705208e8622dc94603"}]');
+ '[{"dependency": "goldctl", "version": "git_revision:3a77d0b12c697a840ca0c7705208e8622dc94603"}]',
+ );
});
group('Validate un-pinned version operation.', () {
diff --git a/app_dart/test/model/ci_yaml/target_test.dart b/app_dart/test/model/ci_yaml/target_test.dart
index 2916016..9306439 100644
--- a/app_dart/test/model/ci_yaml/target_test.dart
+++ b/app_dart/test/model/ci_yaml/target_test.dart
@@ -370,8 +370,10 @@
});
test('non-cocoon scheduler targets return omit policy', () {
- expect(generateTarget(1, platform: 'Linux_android', schedulerSystem: pb.SchedulerSystem.luci).schedulerPolicy,
- isA<OmitPolicy>());
+ expect(
+ generateTarget(1, platform: 'Linux_android', schedulerSystem: pb.SchedulerSystem.luci).schedulerPolicy,
+ isA<OmitPolicy>(),
+ );
});
test('vm cocoon targets return batch policy', () {
diff --git a/app_dart/test/model/stage_test.dart b/app_dart/test/model/stage_test.dart
index 53c6b98..207db5a 100644
--- a/app_dart/test/model/stage_test.dart
+++ b/app_dart/test/model/stage_test.dart
@@ -40,95 +40,119 @@
test('taskStatus', () {
expect(
- buildStage(statuses: <String>[
- Task.statusSucceeded,
- ]).taskStatus,
+ buildStage(
+ statuses: <String>[
+ Task.statusSucceeded,
+ ],
+ ).taskStatus,
Task.statusSucceeded,
);
expect(
- buildStage(statuses: <String>[
- Task.statusSucceeded,
- Task.statusSucceeded,
- Task.statusFailed,
- ]).taskStatus,
+ buildStage(
+ statuses: <String>[
+ Task.statusSucceeded,
+ Task.statusSucceeded,
+ Task.statusFailed,
+ ],
+ ).taskStatus,
Task.statusFailed,
);
expect(
- buildStage(statuses: <String>[
- Task.statusNew,
- Task.statusFailed,
- Task.statusNew,
- ]).taskStatus,
+ buildStage(
+ statuses: <String>[
+ Task.statusNew,
+ Task.statusFailed,
+ Task.statusNew,
+ ],
+ ).taskStatus,
Task.statusFailed,
);
expect(
- buildStage(statuses: <String>[
- Task.statusInProgress,
- Task.statusFailed,
- Task.statusInProgress,
- ]).taskStatus,
+ buildStage(
+ statuses: <String>[
+ Task.statusInProgress,
+ Task.statusFailed,
+ Task.statusInProgress,
+ ],
+ ).taskStatus,
Task.statusFailed,
);
expect(
- buildStage(statuses: <String>[
- Task.statusSucceeded,
- Task.statusFailed,
- Task.statusSucceeded,
- ]).taskStatus,
+ buildStage(
+ statuses: <String>[
+ Task.statusSucceeded,
+ Task.statusFailed,
+ Task.statusSucceeded,
+ ],
+ ).taskStatus,
Task.statusFailed,
);
expect(
- buildStage(statuses: <String>[
- Task.statusNew,
- Task.statusFailed,
- Task.statusInProgress,
- Task.statusSucceeded,
- ]).taskStatus,
+ buildStage(
+ statuses: <String>[
+ Task.statusNew,
+ Task.statusFailed,
+ Task.statusInProgress,
+ Task.statusSucceeded,
+ ],
+ ).taskStatus,
Task.statusFailed,
);
expect(
- buildStage(statuses: <String>[
- Task.statusNew,
- Task.statusInProgress,
- Task.statusNew,
- ]).taskStatus,
+ buildStage(
+ statuses: <String>[
+ Task.statusNew,
+ Task.statusInProgress,
+ Task.statusNew,
+ ],
+ ).taskStatus,
Task.statusInProgress,
);
expect(
- buildStage(statuses: <String>[
- Task.statusNew,
- Task.statusSucceeded,
- Task.statusNew,
- ]).taskStatus,
+ buildStage(
+ statuses: <String>[
+ Task.statusNew,
+ Task.statusSucceeded,
+ Task.statusNew,
+ ],
+ ).taskStatus,
Task.statusInProgress,
);
expect(
- buildStage(statuses: <String>[
- Task.statusSucceeded,
- Task.statusSucceeded,
- Task.statusInProgress,
- ]).taskStatus,
+ buildStage(
+ statuses: <String>[
+ Task.statusSucceeded,
+ Task.statusSucceeded,
+ Task.statusInProgress,
+ ],
+ ).taskStatus,
Task.statusInProgress,
);
expect(
- buildStage(statuses: <String>[
- Task.statusNew,
- Task.statusNew,
- ]).taskStatus,
+ buildStage(
+ statuses: <String>[
+ Task.statusNew,
+ Task.statusNew,
+ ],
+ ).taskStatus,
Task.statusNew,
);
expect(
- buildStage(statuses: <String>[
- Task.statusInProgress,
- Task.statusInProgress,
- ]).taskStatus,
+ buildStage(
+ statuses: <String>[
+ Task.statusInProgress,
+ Task.statusInProgress,
+ ],
+ ).taskStatus,
Task.statusInProgress,
);
expect(
- buildStage(statuses: <String>[
- Task.statusSucceeded,
- Task.statusSucceeded,
- ]).taskStatus,
+ buildStage(
+ statuses: <String>[
+ Task.statusSucceeded,
+ Task.statusSucceeded,
+ ],
+ ).taskStatus,
Task.statusSucceeded,
);
});
@@ -140,11 +164,12 @@
expect(() => (StageBuilder()..name = 'name').build(), throwsStateError);
expect(() => (StageBuilder()..commit = generateCommit(1)).build(), throwsStateError);
expect(
- () => (StageBuilder()
- ..name = 'name'
- ..commit = generateCommit(1))
- .build(),
- throwsStateError);
+ () => (StageBuilder()
+ ..name = 'name'
+ ..commit = generateCommit(1))
+ .build(),
+ throwsStateError,
+ );
});
});
}
diff --git a/app_dart/test/request_handlers/check_flaky_builders_test.dart b/app_dart/test/request_handlers/check_flaky_builders_test.dart
index 17669f3..9c5357f 100644
--- a/app_dart/test/request_handlers/check_flaky_builders_test.dart
+++ b/app_dart/test/request_handlers/check_flaky_builders_test.dart
@@ -64,20 +64,26 @@
mockGitService = MockGitService();
mockUsersService = MockUsersService();
// when gets the content of .ci.yaml
- when(mockRepositoriesService.getContents(
- captureAny,
- kCiYamlPath,
- )).thenAnswer((Invocation invocation) {
+ when(
+ mockRepositoriesService.getContents(
+ captureAny,
+ kCiYamlPath,
+ ),
+ ).thenAnswer((Invocation invocation) {
return Future<RepositoryContents>.value(
- RepositoryContents(file: GitHubFile(content: gitHubEncode(ciYamlContent))));
+ RepositoryContents(file: GitHubFile(content: gitHubEncode(ciYamlContent))),
+ );
});
// when gets the content of TESTOWNERS
- when(mockRepositoriesService.getContents(
- captureAny,
- kTestOwnerPath,
- )).thenAnswer((Invocation invocation) {
+ when(
+ mockRepositoriesService.getContents(
+ captureAny,
+ kTestOwnerPath,
+ ),
+ ).thenAnswer((Invocation invocation) {
return Future<RepositoryContents>.value(
- RepositoryContents(file: GitHubFile(content: gitHubEncode(testOwnersContent))));
+ RepositoryContents(file: GitHubFile(content: gitHubEncode(testOwnersContent))),
+ );
});
// when gets existing marks flaky prs.
when(mockPullRequestsService.list(captureAny)).thenAnswer((Invocation invocation) {
@@ -98,16 +104,18 @@
return Future<CurrentUser>.value(result);
});
// when assigns pull request reviewer.
- when(mockGitHubClient.postJSON<Map<String, dynamic>, PullRequest>(
- captureAny,
- statusCode: captureAnyNamed('statusCode'),
- fail: captureAnyNamed('fail'),
- headers: captureAnyNamed('headers'),
- params: captureAnyNamed('params'),
- convert: captureAnyNamed('convert'),
- body: captureAnyNamed('body'),
- preview: captureAnyNamed('preview'),
- )).thenAnswer((Invocation invocation) {
+ when(
+ mockGitHubClient.postJSON<Map<String, dynamic>, PullRequest>(
+ captureAny,
+ statusCode: captureAnyNamed('statusCode'),
+ fail: captureAnyNamed('fail'),
+ headers: captureAnyNamed('headers'),
+ params: captureAnyNamed('params'),
+ convert: captureAnyNamed('convert'),
+ body: captureAnyNamed('body'),
+ preview: captureAnyNamed('preview'),
+ ),
+ ).thenAnswer((Invocation invocation) {
return Future<PullRequest>.value(PullRequest());
});
when(mockGitHubClient.repositories).thenReturn(mockRepositoriesService);
@@ -129,9 +137,13 @@
test('Can create pr if the flaky test is no longer flaky with a closed issue', () async {
// When queries flaky data from BigQuery.
- when(mockBigqueryService.listRecentBuildRecordsForBuilder(kBigQueryProjectId,
- builder: captureAnyNamed('builder'), limit: captureAnyNamed('limit')))
- .thenAnswer((Invocation invocation) {
+ when(
+ mockBigqueryService.listRecentBuildRecordsForBuilder(
+ kBigQueryProjectId,
+ builder: captureAnyNamed('builder'),
+ limit: captureAnyNamed('limit'),
+ ),
+ ).thenAnswer((Invocation invocation) {
return Future<List<BuilderRecord>>.value(semanticsIntegrationTestRecordsAllPassed);
});
// When queries flaky data from BigQuery.
@@ -167,9 +179,13 @@
.single as Map<String, dynamic>;
// Verify BigQuery is called correctly.
- List<dynamic> captured = verify(mockBigqueryService.listRecentBuildRecordsForBuilder(captureAny,
- builder: captureAnyNamed('builder'), limit: captureAnyNamed('limit')))
- .captured;
+ List<dynamic> captured = verify(
+ mockBigqueryService.listRecentBuildRecordsForBuilder(
+ captureAny,
+ builder: captureAnyNamed('builder'),
+ limit: captureAnyNamed('limit'),
+ ),
+ ).captured;
expect(captured.length, 3);
expect(captured[0].toString(), kBigQueryProjectId);
expect(captured[1] as String?, expectedSemanticsIntegrationTestBuilderName);
@@ -232,17 +248,24 @@
test('Can create pr if the flaky test is no longer flaky without an issue', () async {
// when gets the content of .ci.yaml
- when(mockRepositoriesService.getContents(
- captureAny,
- kCiYamlPath,
- )).thenAnswer((Invocation invocation) {
+ when(
+ mockRepositoriesService.getContents(
+ captureAny,
+ kCiYamlPath,
+ ),
+ ).thenAnswer((Invocation invocation) {
return Future<RepositoryContents>.value(
- RepositoryContents(file: GitHubFile(content: gitHubEncode(ciYamlContentNoIssue))));
+ RepositoryContents(file: GitHubFile(content: gitHubEncode(ciYamlContentNoIssue))),
+ );
});
// When queries flaky data from BigQuery.
- when(mockBigqueryService.listRecentBuildRecordsForBuilder(kBigQueryProjectId,
- builder: captureAnyNamed('builder'), limit: captureAnyNamed('limit')))
- .thenAnswer((Invocation invocation) {
+ when(
+ mockBigqueryService.listRecentBuildRecordsForBuilder(
+ kBigQueryProjectId,
+ builder: captureAnyNamed('builder'),
+ limit: captureAnyNamed('limit'),
+ ),
+ ).thenAnswer((Invocation invocation) {
return Future<List<BuilderRecord>>.value(semanticsIntegrationTestRecordsAllPassed);
});
// When queries flaky data from BigQuery.
@@ -274,9 +297,13 @@
.single as Map<String, dynamic>;
// Verify BigQuery is called correctly.
- List<dynamic> captured = verify(mockBigqueryService.listRecentBuildRecordsForBuilder(captureAny,
- builder: captureAnyNamed('builder'), limit: captureAnyNamed('limit')))
- .captured;
+ List<dynamic> captured = verify(
+ mockBigqueryService.listRecentBuildRecordsForBuilder(
+ captureAny,
+ builder: captureAnyNamed('builder'),
+ limit: captureAnyNamed('limit'),
+ ),
+ ).captured;
expect(captured.length, 3);
expect(captured[0].toString(), kBigQueryProjectId);
expect(captured[1] as String?, expectedSemanticsIntegrationTestBuilderName);
@@ -336,12 +363,15 @@
test('Do not create PR if the builder is in the ignored list', () async {
// when gets the content of .ci.yaml
- when(mockRepositoriesService.getContents(
- captureAny,
- kCiYamlPath,
- )).thenAnswer((Invocation invocation) {
+ when(
+ mockRepositoriesService.getContents(
+ captureAny,
+ kCiYamlPath,
+ ),
+ ).thenAnswer((Invocation invocation) {
return Future<RepositoryContents>.value(
- RepositoryContents(file: GitHubFile(content: gitHubEncode(ciYamlContentFlakyInIgnoreList))));
+ RepositoryContents(file: GitHubFile(content: gitHubEncode(ciYamlContentFlakyInIgnoreList))),
+ );
});
// When queries flaky data from BigQuery.
when(mockBigqueryService.listBuilderStatistic(kBigQueryProjectId, bucket: 'staging'))
@@ -362,9 +392,13 @@
test('Do not create pr if the issue is still open', () async {
// When queries flaky data from BigQuery.
- when(mockBigqueryService.listRecentBuildRecordsForBuilder(kBigQueryProjectId,
- builder: captureAnyNamed('builder'), limit: captureAnyNamed('limit')))
- .thenAnswer((Invocation invocation) {
+ when(
+ mockBigqueryService.listRecentBuildRecordsForBuilder(
+ kBigQueryProjectId,
+ builder: captureAnyNamed('builder'),
+ limit: captureAnyNamed('limit'),
+ ),
+ ).thenAnswer((Invocation invocation) {
return Future<List<BuilderRecord>>.value(semanticsIntegrationTestRecordsAllPassed);
});
// When queries flaky data from BigQuery.
@@ -397,18 +431,24 @@
test('Do not create pr and do not create issue if the records have flaky runs and there is an open issue',
() async {
// When queries flaky data from BigQuery.
- when(mockBigqueryService.listRecentBuildRecordsForBuilder(kBigQueryProjectId,
- builder: captureAnyNamed('builder'), limit: captureAnyNamed('limit')))
- .thenAnswer((Invocation invocation) {
+ when(
+ mockBigqueryService.listRecentBuildRecordsForBuilder(
+ kBigQueryProjectId,
+ builder: captureAnyNamed('builder'),
+ limit: captureAnyNamed('limit'),
+ ),
+ ).thenAnswer((Invocation invocation) {
return Future<List<BuilderRecord>>.value(semanticsIntegrationTestRecordsFlaky);
});
// When get issue
when(mockIssuesService.get(captureAny, captureAny)).thenAnswer((_) {
- return Future<Issue>.value(Issue(
- state: 'closed',
- htmlUrl: existingIssueURL,
- closedAt: DateTime.now().subtract(const Duration(days: kGracePeriodForClosedFlake - 1)),
- ));
+ return Future<Issue>.value(
+ Issue(
+ state: 'closed',
+ htmlUrl: existingIssueURL,
+ closedAt: DateTime.now().subtract(const Duration(days: kGracePeriodForClosedFlake - 1)),
+ ),
+ );
});
// When queries flaky data from BigQuery.
when(mockBigqueryService.listBuilderStatistic(kBigQueryProjectId, bucket: 'staging'))
@@ -435,10 +475,12 @@
() async {
// When get issue
when(mockIssuesService.get(captureAny, captureAny)).thenAnswer((_) {
- return Future<Issue>.value(Issue(
- state: 'open',
- htmlUrl: existingIssueURL,
- ));
+ return Future<Issue>.value(
+ Issue(
+ state: 'open',
+ htmlUrl: existingIssueURL,
+ ),
+ );
});
// When queries flaky data from BigQuery.
when(mockBigqueryService.listBuilderStatistic(kBigQueryProjectId, bucket: 'staging'))
@@ -463,9 +505,13 @@
test('Do not create pr if the records have failed runs', () async {
// When queries flaky data from BigQuery.
- when(mockBigqueryService.listRecentBuildRecordsForBuilder(kBigQueryProjectId,
- builder: captureAnyNamed('builder'), limit: captureAnyNamed('limit')))
- .thenAnswer((Invocation invocation) {
+ when(
+ mockBigqueryService.listRecentBuildRecordsForBuilder(
+ kBigQueryProjectId,
+ builder: captureAnyNamed('builder'),
+ limit: captureAnyNamed('limit'),
+ ),
+ ).thenAnswer((Invocation invocation) {
return Future<List<BuilderRecord>>.value(semanticsIntegrationTestRecordsFailed);
});
// When queries flaky data from BigQuery.
@@ -475,8 +521,13 @@
});
// When get issue
when(mockIssuesService.get(captureAny, captureAny)).thenAnswer((_) {
- return Future<Issue>.value(Issue(
- state: 'closed', htmlUrl: existingIssueURL, closedAt: DateTime.now().subtract(const Duration(days: 50))));
+ return Future<Issue>.value(
+ Issue(
+ state: 'closed',
+ htmlUrl: existingIssueURL,
+ closedAt: DateTime.now().subtract(const Duration(days: 50)),
+ ),
+ );
});
CheckFlakyBuilders.kRecordNumber = semanticsIntegrationTestRecordsFailed.length;
@@ -486,9 +537,13 @@
.single as Map<String, dynamic>;
// Verify BigQuery is called correctly.
- List<dynamic> captured = verify(mockBigqueryService.listRecentBuildRecordsForBuilder(captureAny,
- builder: captureAnyNamed('builder'), limit: captureAnyNamed('limit')))
- .captured;
+ List<dynamic> captured = verify(
+ mockBigqueryService.listRecentBuildRecordsForBuilder(
+ captureAny,
+ builder: captureAnyNamed('builder'),
+ limit: captureAnyNamed('limit'),
+ ),
+ ).captured;
expect(captured.length, 3);
expect(captured[0].toString(), kBigQueryProjectId);
expect(captured[1] as String?, expectedSemanticsIntegrationTestBuilderName);
@@ -508,9 +563,13 @@
test('Do not create pr if there is an open one', () async {
// When queries flaky data from BigQuery.
- when(mockBigqueryService.listRecentBuildRecordsForBuilder(kBigQueryProjectId,
- builder: captureAnyNamed('builder'), limit: captureAnyNamed('limit')))
- .thenAnswer((Invocation invocation) {
+ when(
+ mockBigqueryService.listRecentBuildRecordsForBuilder(
+ kBigQueryProjectId,
+ builder: captureAnyNamed('builder'),
+ limit: captureAnyNamed('limit'),
+ ),
+ ).thenAnswer((Invocation invocation) {
return Future<List<BuilderRecord>>.value(semanticsIntegrationTestRecordsAllPassed);
});
// When queries flaky data from BigQuery.
@@ -541,9 +600,13 @@
test('Do not create pr if not enough records', () async {
// When queries flaky data from BigQuery.
- when(mockBigqueryService.listRecentBuildRecordsForBuilder(kBigQueryProjectId,
- builder: captureAnyNamed('builder'), limit: captureAnyNamed('limit')))
- .thenAnswer((Invocation invocation) {
+ when(
+ mockBigqueryService.listRecentBuildRecordsForBuilder(
+ kBigQueryProjectId,
+ builder: captureAnyNamed('builder'),
+ limit: captureAnyNamed('limit'),
+ ),
+ ).thenAnswer((Invocation invocation) {
return Future<List<BuilderRecord>>.value(semanticsIntegrationTestRecordsAllPassed);
});
// When queries flaky data from BigQuery.
@@ -553,8 +616,13 @@
});
// When get issue
when(mockIssuesService.get(captureAny, captureAny)).thenAnswer((_) {
- return Future<Issue>.value(Issue(
- state: 'closed', htmlUrl: existingIssueURL, closedAt: DateTime.now().subtract(const Duration(days: 50))));
+ return Future<Issue>.value(
+ Issue(
+ state: 'closed',
+ htmlUrl: existingIssueURL,
+ closedAt: DateTime.now().subtract(const Duration(days: 50)),
+ ),
+ );
});
CheckFlakyBuilders.kRecordNumber = semanticsIntegrationTestRecordsAllPassed.length + 1;
@@ -564,9 +632,13 @@
.single as Map<String, dynamic>;
// Verify BigQuery is called correctly.
- List<dynamic> captured = verify(mockBigqueryService.listRecentBuildRecordsForBuilder(captureAny,
- builder: captureAnyNamed('builder'), limit: captureAnyNamed('limit')))
- .captured;
+ List<dynamic> captured = verify(
+ mockBigqueryService.listRecentBuildRecordsForBuilder(
+ captureAny,
+ builder: captureAnyNamed('builder'),
+ limit: captureAnyNamed('limit'),
+ ),
+ ).captured;
expect(captured.length, 3);
expect(captured[0].toString(), kBigQueryProjectId);
expect(captured[1] as String?, expectedSemanticsIntegrationTestBuilderName);
diff --git a/app_dart/test/request_handlers/file_flaky_issue_and_pr_test.dart b/app_dart/test/request_handlers/file_flaky_issue_and_pr_test.dart
index 1b2f2c6..72e85c9 100644
--- a/app_dart/test/request_handlers/file_flaky_issue_and_pr_test.dart
+++ b/app_dart/test/request_handlers/file_flaky_issue_and_pr_test.dart
@@ -63,20 +63,26 @@
mockGitService = MockGitService();
mockUsersService = MockUsersService();
// when gets the content of .ci.yaml
- when(mockRepositoriesService.getContents(
- captureAny,
- kCiYamlPath,
- )).thenAnswer((Invocation invocation) {
+ when(
+ mockRepositoriesService.getContents(
+ captureAny,
+ kCiYamlPath,
+ ),
+ ).thenAnswer((Invocation invocation) {
return Future<RepositoryContents>.value(
- RepositoryContents(file: GitHubFile(content: gitHubEncode(ciYamlContent))));
+ RepositoryContents(file: GitHubFile(content: gitHubEncode(ciYamlContent))),
+ );
});
// when gets the content of TESTOWNERS
- when(mockRepositoriesService.getContents(
- captureAny,
- kTestOwnerPath,
- )).thenAnswer((Invocation invocation) {
+ when(
+ mockRepositoriesService.getContents(
+ captureAny,
+ kTestOwnerPath,
+ ),
+ ).thenAnswer((Invocation invocation) {
return Future<RepositoryContents>.value(
- RepositoryContents(file: GitHubFile(content: gitHubEncode(testOwnersContent))));
+ RepositoryContents(file: GitHubFile(content: gitHubEncode(testOwnersContent))),
+ );
});
when(mockIssuesService.create(any, any)).thenAnswer((_) async => Issue());
// when gets existing flaky issues.
@@ -103,16 +109,18 @@
return Future<CurrentUser>.value(result);
});
// when assigns pull request reviewer.
- when(mockGitHubClient.postJSON<Map<String, dynamic>, PullRequest>(
- captureAny,
- statusCode: captureAnyNamed('statusCode'),
- fail: captureAnyNamed('fail'),
- headers: captureAnyNamed('headers'),
- params: captureAnyNamed('params'),
- convert: captureAnyNamed('convert'),
- body: captureAnyNamed('body'),
- preview: captureAnyNamed('preview'),
- )).thenAnswer((Invocation invocation) {
+ when(
+ mockGitHubClient.postJSON<Map<String, dynamic>, PullRequest>(
+ captureAny,
+ statusCode: captureAnyNamed('statusCode'),
+ fail: captureAnyNamed('fail'),
+ headers: captureAnyNamed('headers'),
+ params: captureAnyNamed('params'),
+ convert: captureAnyNamed('convert'),
+ body: captureAnyNamed('body'),
+ preview: captureAnyNamed('preview'),
+ ),
+ ).thenAnswer((Invocation invocation) {
return Future<PullRequest>.value(PullRequest());
});
when(mockGitHubClient.repositories).thenReturn(mockRepositoriesService);
@@ -172,8 +180,10 @@
expect(issueRequest.title, expectedSemanticsIntegrationTestResponseTitle);
expect(issueRequest.body, expectedSemanticsIntegrationTestResponseBody);
expect(issueRequest.assignee, expectedSemanticsIntegrationTestResponseAssignee);
- expect(const ListEquality<String>().equals(issueRequest.labels, expectedSemanticsIntegrationTestResponseLabels),
- isTrue);
+ expect(
+ const ListEquality<String>().equals(issueRequest.labels, expectedSemanticsIntegrationTestResponseLabels),
+ isTrue,
+ );
// Verify tree is created correctly.
captured = verify(mockGitService.createTree(captureAny, captureAny)).captured;
@@ -351,7 +361,9 @@
.thenAnswer((Invocation invocation) {
return Stream<Issue>.fromIterable(<Issue>[
Issue(
- title: expectedSemanticsIntegrationTestResponseTitle, body: expectedSemanticsIntegrationTestResponseBody)
+ title: expectedSemanticsIntegrationTestResponseTitle,
+ body: expectedSemanticsIntegrationTestResponseBody,
+ )
]);
});
// When creates git tree
@@ -471,8 +483,10 @@
expect(issueRequest.title, expectedSemanticsIntegrationTestResponseTitle);
expect(issueRequest.body, expectedSemanticsIntegrationTestResponseBody);
expect(issueRequest.assignee, expectedSemanticsIntegrationTestResponseAssignee);
- expect(const ListEquality<String>().equals(issueRequest.labels, expectedSemanticsIntegrationTestResponseLabels),
- isTrue);
+ expect(
+ const ListEquality<String>().equals(issueRequest.labels, expectedSemanticsIntegrationTestResponseLabels),
+ isTrue,
+ );
expect(result['Status'], 'success');
});
@@ -483,12 +497,15 @@
return Future<List<BuilderStatistic>>.value(semanticsIntegrationTestResponse);
});
// when gets the content of .ci.yaml
- when(mockRepositoriesService.getContents(
- captureAny,
- kCiYamlPath,
- )).thenAnswer((Invocation invocation) {
+ when(
+ mockRepositoriesService.getContents(
+ captureAny,
+ kCiYamlPath,
+ ),
+ ).thenAnswer((Invocation invocation) {
return Future<RepositoryContents>.value(
- RepositoryContents(file: GitHubFile(content: gitHubEncode(ciYamlContentAlreadyFlaky))));
+ RepositoryContents(file: GitHubFile(content: gitHubEncode(ciYamlContentAlreadyFlaky))),
+ );
});
final Map<String, dynamic> result = await utf8.decoder
diff --git a/app_dart/test/request_handlers/flaky_handler_utiles_test.dart b/app_dart/test/request_handlers/flaky_handler_utiles_test.dart
index 0618211..e6a0089 100644
--- a/app_dart/test/request_handlers/flaky_handler_utiles_test.dart
+++ b/app_dart/test/request_handlers/flaky_handler_utiles_test.dart
@@ -97,23 +97,30 @@
const String expectedHtml = 'https://someurl';
// when gets existing marks flaky prs.
when(mockPullRequestsService.list(captureAny)).thenAnswer((Invocation invocation) {
- return Stream<PullRequest>.value(PullRequest(
- htmlUrl: expectedHtml,
- body: '''
+ return Stream<PullRequest>.value(
+ PullRequest(
+ htmlUrl: expectedHtml,
+ body: '''
<!-- meta-tags: To be used by the automation script only, DO NOT MODIFY.
{
"name"
}
-->''',
- ));
+ ),
+ );
});
when(mockGitHubClient.pullRequests).thenReturn(mockPullRequestsService);
final FakeConfig config = FakeConfig(
githubService: GithubService(mockGitHubClient),
);
- expect(() => getExistingPRs(config.githubService!, Config.flutterSlug), throwsA(predicate<String>((String e) {
- return e.contains('Unable to parse body of $expectedHtml');
- })));
+ expect(
+ () => getExistingPRs(config.githubService!, Config.flutterSlug),
+ throwsA(
+ predicate<String>((String e) {
+ return e.contains('Unable to parse body of $expectedHtml');
+ }),
+ ),
+ );
});
test('handles PRs with empty body message', () async {
@@ -121,9 +128,11 @@
final MockPullRequestsService mockPullRequestsService = MockPullRequestsService();
const String expectedHtml = 'https://someurl';
when(mockPullRequestsService.list(captureAny)).thenAnswer((Invocation invocation) {
- return Stream<PullRequest>.value(PullRequest(
- htmlUrl: expectedHtml,
- ));
+ return Stream<PullRequest>.value(
+ PullRequest(
+ htmlUrl: expectedHtml,
+ ),
+ );
});
when(mockGitHubClient.pullRequests).thenReturn(mockPullRequestsService);
final FakeConfig config = FakeConfig(
diff --git a/app_dart/test/request_handlers/flush_cache_test.dart b/app_dart/test/request_handlers/flush_cache_test.dart
index 05e65f0..21246a8 100644
--- a/app_dart/test/request_handlers/flush_cache_test.dart
+++ b/app_dart/test/request_handlers/flush_cache_test.dart
@@ -41,9 +41,11 @@
Uint8List.fromList('123'.codeUnits),
);
- tester.request = FakeHttpRequest(queryParametersValue: <String, String>{
- FlushCache.cacheKeyParam: cacheKey,
- });
+ tester.request = FakeHttpRequest(
+ queryParametersValue: <String, String>{
+ FlushCache.cacheKeyParam: cacheKey,
+ },
+ );
await tester.get(handler);
expect(await cache.getOrCreate(Config.configCacheName, cacheKey), null);
@@ -54,9 +56,11 @@
});
test('raises error if cache key does not exist', () async {
- tester.request = FakeHttpRequest(queryParametersValue: <String, String>{
- FlushCache.cacheKeyParam: 'abc',
- });
+ tester.request = FakeHttpRequest(
+ queryParametersValue: <String, String>{
+ FlushCache.cacheKeyParam: 'abc',
+ },
+ );
expect(tester.get(handler), throwsA(isA<NotFoundException>()));
});
});
diff --git a/app_dart/test/request_handlers/get_branches_test.dart b/app_dart/test/request_handlers/get_branches_test.dart
index ce2ec6d..b382e66 100644
--- a/app_dart/test/request_handlers/get_branches_test.dart
+++ b/app_dart/test/request_handlers/get_branches_test.dart
@@ -48,7 +48,7 @@
);
const String id = 'flutter/flutter/branch-created-old';
- int lastActivity = DateTime.tryParse("2019-05-15T15:20:56Z")!.millisecondsSinceEpoch;
+ final int lastActivity = DateTime.tryParse("2019-05-15T15:20:56Z")!.millisecondsSinceEpoch;
final Key<String> branchKey = db.emptyKey.append<String>(Branch, id: id);
final Branch currentBranch = Branch(
key: branchKey,
@@ -68,7 +68,7 @@
expect(db.values.values.whereType<Branch>().length, 1);
const String id = 'flutter/flutter/branch-created-now';
- int lastActivity = DateTime.now().millisecondsSinceEpoch;
+ final int lastActivity = DateTime.now().millisecondsSinceEpoch;
final Key<String> branchKey = db.emptyKey.append<String>(Branch, id: id);
final Branch currentBranch = Branch(
key: branchKey,
diff --git a/app_dart/test/request_handlers/get_green_commits_test.dart b/app_dart/test/request_handlers/get_green_commits_test.dart
index fd2ea0b..6a33909 100644
--- a/app_dart/test/request_handlers/get_green_commits_test.dart
+++ b/app_dart/test/request_handlers/get_green_commits_test.dart
@@ -46,12 +46,24 @@
final Stage stageOneSucceed =
Stage('cocoon', commit1, [task1Succeed], Task.statusInProgress); // should scceed, since task 1 succeed
- final Stage stageFailed = Stage('luci', commit1, [task1Succeed, task2Failed],
- Task.statusInProgress); // should fail, since task 1 succeed and task2 fail
- final Stage stageMultipleSucceed = Stage('cocoon', commit2, [task1Succeed, task4SucceedFlaky],
- Task.statusInProgress); // should succeed, since both task 1 and task 4 succeed
- final Stage stageFailedFlaky = Stage('luci', commit2, [task1Succeed, task3FailedFlaky],
- Task.statusInProgress); // should succeed, even though it includes task 3
+ final Stage stageFailed = Stage(
+ 'luci',
+ commit1,
+ [task1Succeed, task2Failed],
+ Task.statusInProgress,
+ ); // should fail, since task 1 succeed and task2 fail
+ final Stage stageMultipleSucceed = Stage(
+ 'cocoon',
+ commit2,
+ [task1Succeed, task4SucceedFlaky],
+ Task.statusInProgress,
+ ); // should succeed, since both task 1 and task 4 succeed
+ final Stage stageFailedFlaky = Stage(
+ 'luci',
+ commit2,
+ [task1Succeed, task3FailedFlaky],
+ Task.statusInProgress,
+ ); // should succeed, even though it includes task 3
Future<List<T?>?> decodeHandlerBody<T>() async {
final Body body = await tester.get(handler);
@@ -79,10 +91,12 @@
});
test('should return commits with all tasks succeed', () async {
- buildStatusService = FakeBuildStatusService(commitStatuses: <CommitStatus>[
- CommitStatus(commit1, <Stage>[stageOneSucceed]),
- CommitStatus(commit2, <Stage>[stageOneSucceed, stageMultipleSucceed])
- ]);
+ buildStatusService = FakeBuildStatusService(
+ commitStatuses: <CommitStatus>[
+ CommitStatus(commit1, <Stage>[stageOneSucceed]),
+ CommitStatus(commit2, <Stage>[stageOneSucceed, stageMultipleSucceed])
+ ],
+ );
handler = GetGreenCommits(
config: config,
datastoreProvider: (DatastoreDB db) => DatastoreService(config.db, 5),
@@ -99,10 +113,12 @@
});
test('should fail commits that have failed task without [bringup: true] label', () async {
- buildStatusService = FakeBuildStatusService(commitStatuses: <CommitStatus>[
- CommitStatus(commit1, <Stage>[stageFailed]),
- CommitStatus(commit2, <Stage>[stageOneSucceed, stageMultipleSucceed])
- ]);
+ buildStatusService = FakeBuildStatusService(
+ commitStatuses: <CommitStatus>[
+ CommitStatus(commit1, <Stage>[stageFailed]),
+ CommitStatus(commit2, <Stage>[stageOneSucceed, stageMultipleSucceed])
+ ],
+ );
handler = GetGreenCommits(
config: config,
datastoreProvider: (DatastoreDB db) => DatastoreService(config.db, 5),
@@ -116,10 +132,12 @@
});
test('should return commits with failed tasks but with `bringup: true` label', () async {
- buildStatusService = FakeBuildStatusService(commitStatuses: <CommitStatus>[
- CommitStatus(commit1, <Stage>[stageFailed]),
- CommitStatus(commit2, <Stage>[stageFailedFlaky])
- ]);
+ buildStatusService = FakeBuildStatusService(
+ commitStatuses: <CommitStatus>[
+ CommitStatus(commit1, <Stage>[stageFailed]),
+ CommitStatus(commit2, <Stage>[stageFailedFlaky])
+ ],
+ );
handler = GetGreenCommits(
config: config,
datastoreProvider: (DatastoreDB db) => DatastoreService(config.db, 5),
@@ -133,10 +151,12 @@
});
test('should return commits with both flaky and succeeded tasks', () async {
- buildStatusService = FakeBuildStatusService(commitStatuses: <CommitStatus>[
- CommitStatus(commit1, <Stage>[stageOneSucceed, stageMultipleSucceed]),
- CommitStatus(commit2, <Stage>[stageOneSucceed, stageFailedFlaky])
- ]);
+ buildStatusService = FakeBuildStatusService(
+ commitStatuses: <CommitStatus>[
+ CommitStatus(commit1, <Stage>[stageOneSucceed, stageMultipleSucceed]),
+ CommitStatus(commit2, <Stage>[stageOneSucceed, stageFailedFlaky])
+ ],
+ );
handler = GetGreenCommits(
config: config,
datastoreProvider: (DatastoreDB db) => DatastoreService(config.db, 5),
@@ -153,12 +173,16 @@
});
test('should return branched commits', () async {
- buildStatusService = FakeBuildStatusService(commitStatuses: <CommitStatus>[
- CommitStatus(commitBranched, <Stage>[stageOneSucceed]),
- ]);
- tester.request = FakeHttpRequest(queryParametersValue: <String, String>{
- GetGreenCommits.kBranchParam: commitBranched.branch!,
- });
+ buildStatusService = FakeBuildStatusService(
+ commitStatuses: <CommitStatus>[
+ CommitStatus(commitBranched, <Stage>[stageOneSucceed]),
+ ],
+ );
+ tester.request = FakeHttpRequest(
+ queryParametersValue: <String, String>{
+ GetGreenCommits.kBranchParam: commitBranched.branch!,
+ },
+ );
handler = GetGreenCommits(
config: config,
datastoreProvider: (DatastoreDB db) => DatastoreService(config.db, 5),
diff --git a/app_dart/test/request_handlers/get_status_test.dart b/app_dart/test/request_handlers/get_status_test.dart
index efb5630..c7b0f64 100644
--- a/app_dart/test/request_handlers/get_status_test.dart
+++ b/app_dart/test/request_handlers/get_status_test.dart
@@ -48,19 +48,21 @@
buildStatusProvider: (_) => buildStatusService,
);
commit1 = Commit(
- key: config.db.emptyKey.append(Commit, id: 'flutter/flutter/ea28a9c34dc701de891eaf74503ca4717019f829'),
- repository: 'flutter/flutter',
- sha: 'ea28a9c34dc701de891eaf74503ca4717019f829',
- timestamp: 3,
- message: 'test message 1',
- branch: 'master');
+ key: config.db.emptyKey.append(Commit, id: 'flutter/flutter/ea28a9c34dc701de891eaf74503ca4717019f829'),
+ repository: 'flutter/flutter',
+ sha: 'ea28a9c34dc701de891eaf74503ca4717019f829',
+ timestamp: 3,
+ message: 'test message 1',
+ branch: 'master',
+ );
commit2 = Commit(
- key: config.db.emptyKey.append(Commit, id: 'flutter/flutter/d5b0b3c8d1c5fd89302089077ccabbcfaae045e4'),
- repository: 'flutter/flutter',
- sha: 'd5b0b3c8d1c5fd89302089077ccabbcfaae045e4',
- timestamp: 1,
- message: 'test message 2',
- branch: 'master');
+ key: config.db.emptyKey.append(Commit, id: 'flutter/flutter/d5b0b3c8d1c5fd89302089077ccabbcfaae045e4'),
+ repository: 'flutter/flutter',
+ sha: 'd5b0b3c8d1c5fd89302089077ccabbcfaae045e4',
+ timestamp: 1,
+ message: 'test message 2',
+ branch: 'master',
+ );
});
test('no statuses', () async {
@@ -71,10 +73,9 @@
test('reports statuses without input commit key', () async {
config.db.values[commit1.key] = commit1;
config.db.values[commit2.key] = commit2;
- buildStatusService = FakeBuildStatusService(commitStatuses: <CommitStatus>[
- CommitStatus(commit1, const <Stage>[]),
- CommitStatus(commit2, const <Stage>[])
- ]);
+ buildStatusService = FakeBuildStatusService(
+ commitStatuses: <CommitStatus>[CommitStatus(commit1, const <Stage>[]), CommitStatus(commit2, const <Stage>[])],
+ );
handler = GetStatus(
config: config,
datastoreProvider: (DatastoreDB db) => DatastoreService(config.db, 5),
@@ -88,25 +89,26 @@
test('reports statuses with input commit key', () async {
final Commit commit1 = Commit(
- key: config.db.emptyKey.append(Commit, id: 'flutter/flutter/ea28a9c34dc701de891eaf74503ca4717019f829'),
- repository: 'flutter/flutter',
- sha: 'ea28a9c34dc701de891eaf74503ca4717019f829',
- timestamp: 3,
- message: 'test message 1',
- branch: 'master');
+ key: config.db.emptyKey.append(Commit, id: 'flutter/flutter/ea28a9c34dc701de891eaf74503ca4717019f829'),
+ repository: 'flutter/flutter',
+ sha: 'ea28a9c34dc701de891eaf74503ca4717019f829',
+ timestamp: 3,
+ message: 'test message 1',
+ branch: 'master',
+ );
final Commit commit2 = Commit(
- key: config.db.emptyKey.append(Commit, id: 'flutter/flutter/d5b0b3c8d1c5fd89302089077ccabbcfaae045e4'),
- repository: 'flutter/flutter',
- sha: 'd5b0b3c8d1c5fd89302089077ccabbcfaae045e4',
- timestamp: 1,
- message: 'test message 2',
- branch: 'master');
+ key: config.db.emptyKey.append(Commit, id: 'flutter/flutter/d5b0b3c8d1c5fd89302089077ccabbcfaae045e4'),
+ repository: 'flutter/flutter',
+ sha: 'd5b0b3c8d1c5fd89302089077ccabbcfaae045e4',
+ timestamp: 1,
+ message: 'test message 2',
+ branch: 'master',
+ );
config.db.values[commit1.key] = commit1;
config.db.values[commit2.key] = commit2;
- buildStatusService = FakeBuildStatusService(commitStatuses: <CommitStatus>[
- CommitStatus(commit1, const <Stage>[]),
- CommitStatus(commit2, const <Stage>[])
- ]);
+ buildStatusService = FakeBuildStatusService(
+ commitStatuses: <CommitStatus>[CommitStatus(commit1, const <Stage>[]), CommitStatus(commit2, const <Stage>[])],
+ );
handler = GetStatus(
config: config,
datastoreProvider: (DatastoreDB db) => DatastoreService(config.db, 5),
@@ -116,9 +118,11 @@
const String expectedLastCommitKeyEncoded =
'ahNzfmZsdXR0ZXItZGFzaGJvYXJkckcLEglDaGVja2xpc3QiOGZsdXR0ZXIvZmx1dHRlci9lYTI4YTljMzRkYzcwMWRlODkxZWFmNzQ1MDNjYTQ3MTcwMTlmODI5DA';
- tester.request = FakeHttpRequest(queryParametersValue: <String, String>{
- GetStatus.kLastCommitKeyParam: expectedLastCommitKeyEncoded,
- });
+ tester.request = FakeHttpRequest(
+ queryParametersValue: <String, String>{
+ GetStatus.kLastCommitKeyParam: expectedLastCommitKeyEncoded,
+ },
+ );
final Map<String, dynamic> result = (await decodeHandlerBody())!;
expect(result['Statuses'].first, <String, dynamic>{
@@ -144,10 +148,9 @@
commit2.branch = 'flutter-1.1-candidate.1';
config.db.values[commit1.key] = commit1;
config.db.values[commit2.key] = commit2;
- buildStatusService = FakeBuildStatusService(commitStatuses: <CommitStatus>[
- CommitStatus(commit1, const <Stage>[]),
- CommitStatus(commit2, const <Stage>[])
- ]);
+ buildStatusService = FakeBuildStatusService(
+ commitStatuses: <CommitStatus>[CommitStatus(commit1, const <Stage>[]), CommitStatus(commit2, const <Stage>[])],
+ );
handler = GetStatus(
config: config,
datastoreProvider: (DatastoreDB db) => DatastoreService(config.db, 5),
@@ -158,9 +161,11 @@
expect(config.db.values.length, 2);
- tester.request = FakeHttpRequest(queryParametersValue: <String, String>{
- GetStatus.kBranchParam: branch,
- });
+ tester.request = FakeHttpRequest(
+ queryParametersValue: <String, String>{
+ GetStatus.kBranchParam: branch,
+ },
+ );
final Map<String, dynamic> result = (await decodeHandlerBody())!;
expect(result['Statuses'].length, 1);
diff --git a/app_dart/test/request_handlers/github/webhook_subscription_test.dart b/app_dart/test/request_handlers/github/webhook_subscription_test.dart
index 4bc36cf..636bdb8 100644
--- a/app_dart/test/request_handlers/github/webhook_subscription_test.dart
+++ b/app_dart/test/request_handlers/github/webhook_subscription_test.dart
@@ -130,17 +130,21 @@
await tester.post(webhook);
- verify(pullRequestsService.edit(
- Config.flutterSlug,
- issueNumber,
- state: 'closed',
- )).called(1);
+ verify(
+ pullRequestsService.edit(
+ Config.flutterSlug,
+ issueNumber,
+ state: 'closed',
+ ),
+ ).called(1);
- verify(issuesService.createComment(
- Config.flutterSlug,
- issueNumber,
- argThat(contains(config.wrongHeadBranchPullRequestMessageValue)),
- )).called(1);
+ verify(
+ issuesService.createComment(
+ Config.flutterSlug,
+ issueNumber,
+ argThat(contains(config.wrongHeadBranchPullRequestMessageValue)),
+ ),
+ ).called(1);
});
test('No action against candidate branches', () async {
@@ -166,17 +170,21 @@
await tester.post(webhook);
- verifyNever(pullRequestsService.edit(
- Config.flutterSlug,
- issueNumber,
- base: kDefaultBranchName,
- ));
+ verifyNever(
+ pullRequestsService.edit(
+ Config.flutterSlug,
+ issueNumber,
+ base: kDefaultBranchName,
+ ),
+ );
- verifyNever(issuesService.createComment(
- Config.flutterSlug,
- issueNumber,
- argThat(contains('-> master')),
- ));
+ verifyNever(
+ issuesService.createComment(
+ Config.flutterSlug,
+ issueNumber,
+ argThat(contains('-> master')),
+ ),
+ );
});
test('Acts on opened against dev', () async {
@@ -202,17 +210,21 @@
await tester.post(webhook);
- verify(pullRequestsService.edit(
- Config.flutterSlug,
- issueNumber,
- base: kDefaultBranchName,
- )).called(1);
+ verify(
+ pullRequestsService.edit(
+ Config.flutterSlug,
+ issueNumber,
+ base: kDefaultBranchName,
+ ),
+ ).called(1);
- verify(issuesService.createComment(
- Config.flutterSlug,
- issueNumber,
- argThat(contains('dev -> master')),
- )).called(1);
+ verify(
+ issuesService.createComment(
+ Config.flutterSlug,
+ issueNumber,
+ argThat(contains('dev -> master')),
+ ),
+ ).called(1);
});
test('Acts on opened against master when default is main', () async {
@@ -239,17 +251,21 @@
await tester.post(webhook);
- verify(pullRequestsService.edit(
- Config.engineSlug,
- issueNumber,
- base: 'main',
- )).called(1);
+ verify(
+ pullRequestsService.edit(
+ Config.engineSlug,
+ issueNumber,
+ base: 'main',
+ ),
+ ).called(1);
- verify(issuesService.createComment(
- Config.engineSlug,
- issueNumber,
- argThat(contains('master -> main')),
- )).called(1);
+ verify(
+ issuesService.createComment(
+ Config.engineSlug,
+ issueNumber,
+ argThat(contains('master -> main')),
+ ),
+ ).called(1);
});
// We already schedule checks when a draft is opened, don't need to re-test
@@ -337,32 +353,42 @@
await tester.post(webhook);
- verifyNever(pullRequestsService.edit(
- Config.flutterSlug,
- issueNumber,
- base: kDefaultBranchName,
- ));
+ verifyNever(
+ pullRequestsService.edit(
+ Config.flutterSlug,
+ issueNumber,
+ base: kDefaultBranchName,
+ ),
+ );
- verifyNever(issuesService.createComment(
- Config.flutterSlug,
- issueNumber,
- argThat(contains(config.wrongBaseBranchPullRequestMessage)),
- ));
+ verifyNever(
+ issuesService.createComment(
+ Config.flutterSlug,
+ issueNumber,
+ argThat(contains(config.wrongBaseBranchPullRequestMessage)),
+ ),
+ );
});
group('getLabelsForFrameworkPath', () {
test('Only the team label is applied to pubspec.yaml', () {
- expect(GithubWebhookSubscription.getLabelsForFrameworkPath('packages/flutter_tools/pubspec.yaml'),
- <String>{'team'});
+ expect(
+ GithubWebhookSubscription.getLabelsForFrameworkPath('packages/flutter_tools/pubspec.yaml'),
+ <String>{'team'},
+ );
});
test('Tool label applied', () {
- expect(GithubWebhookSubscription.getLabelsForFrameworkPath('packages/flutter_tools/hot_reload.dart'),
- contains('tool'));
expect(
- GithubWebhookSubscription.getLabelsForFrameworkPath(
- 'packages/fuchsia_remote_debug_protocol/hot_reload.dart'),
- contains('tool'));
+ GithubWebhookSubscription.getLabelsForFrameworkPath('packages/flutter_tools/hot_reload.dart'),
+ contains('tool'),
+ );
+ expect(
+ GithubWebhookSubscription.getLabelsForFrameworkPath(
+ 'packages/fuchsia_remote_debug_protocol/hot_reload.dart',
+ ),
+ contains('tool'),
+ );
});
test('iOS label applied', () {
@@ -377,151 +403,225 @@
});
test('Framework label applied', () {
- expect(GithubWebhookSubscription.getLabelsForFrameworkPath('packages/flutter/lib/widget.dart'),
- contains('framework'));
- expect(GithubWebhookSubscription.getLabelsForFrameworkPath('packages/flutter_test/lib/tester.dart'),
- contains('framework'));
- expect(GithubWebhookSubscription.getLabelsForFrameworkPath('packages/flutter_driver/lib/driver.dart'),
- contains('framework'));
- expect(GithubWebhookSubscription.getLabelsForFrameworkPath('packages/flutter_goldens/lib/flutter_goldens.dart'),
- contains('framework'));
expect(
- GithubWebhookSubscription.getLabelsForFrameworkPath('packages/flutter_goldens_client/lib/skia_client.dart'),
- contains('framework'));
+ GithubWebhookSubscription.getLabelsForFrameworkPath('packages/flutter/lib/widget.dart'),
+ contains('framework'),
+ );
+ expect(
+ GithubWebhookSubscription.getLabelsForFrameworkPath('packages/flutter_test/lib/tester.dart'),
+ contains('framework'),
+ );
+ expect(
+ GithubWebhookSubscription.getLabelsForFrameworkPath('packages/flutter_driver/lib/driver.dart'),
+ contains('framework'),
+ );
+ expect(
+ GithubWebhookSubscription.getLabelsForFrameworkPath('packages/flutter_goldens/lib/flutter_goldens.dart'),
+ contains('framework'),
+ );
+ expect(
+ GithubWebhookSubscription.getLabelsForFrameworkPath('packages/flutter_goldens_client/lib/skia_client.dart'),
+ contains('framework'),
+ );
});
test('Material label applied', () {
- expect(GithubWebhookSubscription.getLabelsForFrameworkPath('foo/bar/baz/material/design.dart'),
- contains('f: material design'));
+ expect(
+ GithubWebhookSubscription.getLabelsForFrameworkPath('foo/bar/baz/material/design.dart'),
+ contains('f: material design'),
+ );
});
test('Cupertino label applied', () {
- expect(GithubWebhookSubscription.getLabelsForFrameworkPath('foo/bar/baz/cupertino/design.dart'),
- contains('f: cupertino'));
+ expect(
+ GithubWebhookSubscription.getLabelsForFrameworkPath('foo/bar/baz/cupertino/design.dart'),
+ contains('f: cupertino'),
+ );
});
test('i18n label applied', () {
- expect(GithubWebhookSubscription.getLabelsForFrameworkPath('packages/flutter_localizations/allo.dart'),
- contains('a: internationalization'));
+ expect(
+ GithubWebhookSubscription.getLabelsForFrameworkPath('packages/flutter_localizations/allo.dart'),
+ contains('a: internationalization'),
+ );
});
test('Tests label applied', () {
- expect(GithubWebhookSubscription.getLabelsForFrameworkPath('packages/flutter_test/lib/tester.dart'),
- contains('a: tests'));
- expect(GithubWebhookSubscription.getLabelsForFrameworkPath('packages/flutter_driver/lib/driver.dart'),
- contains('a: tests'));
- expect(GithubWebhookSubscription.getLabelsForFrameworkPath('packages/flutter_goldens/lib/flutter_goldens.dart'),
- contains('a: tests'));
expect(
- GithubWebhookSubscription.getLabelsForFrameworkPath('packages/flutter_goldens_client/lib/skia_client.dart'),
- contains('a: tests'));
+ GithubWebhookSubscription.getLabelsForFrameworkPath('packages/flutter_test/lib/tester.dart'),
+ contains('a: tests'),
+ );
+ expect(
+ GithubWebhookSubscription.getLabelsForFrameworkPath('packages/flutter_driver/lib/driver.dart'),
+ contains('a: tests'),
+ );
+ expect(
+ GithubWebhookSubscription.getLabelsForFrameworkPath('packages/flutter_goldens/lib/flutter_goldens.dart'),
+ contains('a: tests'),
+ );
+ expect(
+ GithubWebhookSubscription.getLabelsForFrameworkPath('packages/flutter_goldens_client/lib/skia_client.dart'),
+ contains('a: tests'),
+ );
});
test('a11y label applied', () {
- expect(GithubWebhookSubscription.getLabelsForFrameworkPath('foo/bar/baz/semantics/voiceover.dart'),
- contains('a: accessibility'));
- expect(GithubWebhookSubscription.getLabelsForFrameworkPath('foo/bar/baz/accessibility/voiceover.dart'),
- contains('a: accessibility'));
+ expect(
+ GithubWebhookSubscription.getLabelsForFrameworkPath('foo/bar/baz/semantics/voiceover.dart'),
+ contains('a: accessibility'),
+ );
+ expect(
+ GithubWebhookSubscription.getLabelsForFrameworkPath('foo/bar/baz/accessibility/voiceover.dart'),
+ contains('a: accessibility'),
+ );
});
test('Examples label applied', () {
expect(
- GithubWebhookSubscription.getLabelsForFrameworkPath('examples/foo/bar/baz.dart'), contains('d: examples'));
+ GithubWebhookSubscription.getLabelsForFrameworkPath('examples/foo/bar/baz.dart'),
+ contains('d: examples'),
+ );
});
test('API Docs label applied', () {
- expect(GithubWebhookSubscription.getLabelsForFrameworkPath('examples/api/bar/baz.dart'),
- <String>['d: examples', 'team', 'd: api docs', 'documentation']);
+ expect(
+ GithubWebhookSubscription.getLabelsForFrameworkPath('examples/api/bar/baz.dart'),
+ <String>['d: examples', 'team', 'd: api docs', 'documentation'],
+ );
});
test('Gallery label applied', () {
- expect(GithubWebhookSubscription.getLabelsForFrameworkPath('examples/flutter_gallery/lib/gallery.dart'),
- contains('team: gallery'));
+ expect(
+ GithubWebhookSubscription.getLabelsForFrameworkPath('examples/flutter_gallery/lib/gallery.dart'),
+ contains('team: gallery'),
+ );
});
test('Team label applied', () {
expect(GithubWebhookSubscription.getLabelsForFrameworkPath('dev/foo/bar/baz.dart'), contains('team'));
expect(GithubWebhookSubscription.getLabelsForFrameworkPath('examples/foo/bar/baz.dart'), contains('team'));
- expect(GithubWebhookSubscription.getLabelsForFrameworkPath('packages/flutter_goldens/lib/flutter_goldens.dart'),
- contains('team'));
expect(
- GithubWebhookSubscription.getLabelsForFrameworkPath('packages/flutter_goldens_client/lib/skia_client.dart'),
- contains('team'));
- expect(GithubWebhookSubscription.getLabelsForFrameworkPath('packages/flutter/lib/fix_data.yaml'),
- contains('team'));
+ GithubWebhookSubscription.getLabelsForFrameworkPath('packages/flutter_goldens/lib/flutter_goldens.dart'),
+ contains('team'),
+ );
+ expect(
+ GithubWebhookSubscription.getLabelsForFrameworkPath('packages/flutter_goldens_client/lib/skia_client.dart'),
+ contains('team'),
+ );
+ expect(
+ GithubWebhookSubscription.getLabelsForFrameworkPath('packages/flutter/lib/fix_data.yaml'),
+ contains('team'),
+ );
expect(GithubWebhookSubscription.getLabelsForFrameworkPath('packages/flutter/test_fixes'), contains('team'));
- expect(GithubWebhookSubscription.getLabelsForFrameworkPath('packages/flutter/test_fixes/material.expect'),
- contains('team'));
+ expect(
+ GithubWebhookSubscription.getLabelsForFrameworkPath('packages/flutter/test_fixes/material.expect'),
+ contains('team'),
+ );
});
test('tech-debt label applied', () {
- expect(GithubWebhookSubscription.getLabelsForFrameworkPath('packages/flutter/lib/fix_data.yaml'),
- contains('tech-debt'));
expect(
- GithubWebhookSubscription.getLabelsForFrameworkPath('packages/flutter/test_fixes'), contains('tech-debt'));
- expect(GithubWebhookSubscription.getLabelsForFrameworkPath('packages/flutter/test_fixes/material.expect'),
- contains('tech-debt'));
+ GithubWebhookSubscription.getLabelsForFrameworkPath('packages/flutter/lib/fix_data.yaml'),
+ contains('tech-debt'),
+ );
+ expect(
+ GithubWebhookSubscription.getLabelsForFrameworkPath('packages/flutter/test_fixes'),
+ contains('tech-debt'),
+ );
+ expect(
+ GithubWebhookSubscription.getLabelsForFrameworkPath('packages/flutter/test_fixes/material.expect'),
+ contains('tech-debt'),
+ );
});
test('gestures label applied', () {
- expect(GithubWebhookSubscription.getLabelsForFrameworkPath('packages/flutter/lib/src/gestures'),
- contains('f: gestures'));
+ expect(
+ GithubWebhookSubscription.getLabelsForFrameworkPath('packages/flutter/lib/src/gestures'),
+ contains('f: gestures'),
+ );
});
test('focus label applied', () {
- expect(GithubWebhookSubscription.getLabelsForFrameworkPath('packages/flutter/lib/src/widgets/focus_node.dart'),
- contains('f: focus'));
- expect(GithubWebhookSubscription.getLabelsForFrameworkPath('packages/flutter/lib/src/widgets/focus_scope.dart'),
- contains('f: focus'));
expect(
- GithubWebhookSubscription.getLabelsForFrameworkPath('packages/flutter/lib/src/widgets/focus_manager.dart'),
- contains('f: focus'));
+ GithubWebhookSubscription.getLabelsForFrameworkPath('packages/flutter/lib/src/widgets/focus_node.dart'),
+ contains('f: focus'),
+ );
+ expect(
+ GithubWebhookSubscription.getLabelsForFrameworkPath('packages/flutter/lib/src/widgets/focus_scope.dart'),
+ contains('f: focus'),
+ );
+ expect(
+ GithubWebhookSubscription.getLabelsForFrameworkPath('packages/flutter/lib/src/widgets/focus_manager.dart'),
+ contains('f: focus'),
+ );
});
test('routes label applied', () {
- expect(GithubWebhookSubscription.getLabelsForFrameworkPath('packages/flutter/lib/src/widgets/router.dart'),
- contains('f: routes'));
- expect(GithubWebhookSubscription.getLabelsForFrameworkPath('packages/flutter/lib/src/widgets/routes.dart'),
- contains('f: routes'));
- expect(GithubWebhookSubscription.getLabelsForFrameworkPath('packages/flutter/lib/src/widgets/navigator.dart'),
- contains('f: routes'));
+ expect(
+ GithubWebhookSubscription.getLabelsForFrameworkPath('packages/flutter/lib/src/widgets/router.dart'),
+ contains('f: routes'),
+ );
+ expect(
+ GithubWebhookSubscription.getLabelsForFrameworkPath('packages/flutter/lib/src/widgets/routes.dart'),
+ contains('f: routes'),
+ );
+ expect(
+ GithubWebhookSubscription.getLabelsForFrameworkPath('packages/flutter/lib/src/widgets/navigator.dart'),
+ contains('f: routes'),
+ );
});
test('text input label applied', () {
expect(
- GithubWebhookSubscription.getLabelsForFrameworkPath(
- 'dev/integration_tests/web_e2e_tests/test_driver/text_editing_integration.dart'),
- contains('a: text input'));
+ GithubWebhookSubscription.getLabelsForFrameworkPath(
+ 'dev/integration_tests/web_e2e_tests/test_driver/text_editing_integration.dart',
+ ),
+ contains('a: text input'),
+ );
expect(
- GithubWebhookSubscription.getLabelsForFrameworkPath(
- 'packages/flutter/lib/src/widgets/text_editing_action.dart'),
- contains('a: text input'));
+ GithubWebhookSubscription.getLabelsForFrameworkPath(
+ 'packages/flutter/lib/src/widgets/text_editing_action.dart',
+ ),
+ contains('a: text input'),
+ );
});
test('animation label applied', () {
- expect(GithubWebhookSubscription.getLabelsForFrameworkPath('packages/flutter/lib/src/animation'),
- contains('a: animation'));
+ expect(
+ GithubWebhookSubscription.getLabelsForFrameworkPath('packages/flutter/lib/src/animation'),
+ contains('a: animation'),
+ );
});
test('scrolling label applied', () {
- expect(GithubWebhookSubscription.getLabelsForFrameworkPath('packages/flutter/lib/src/widgets/sliver.dart'),
- contains('f: scrolling'));
- expect(GithubWebhookSubscription.getLabelsForFrameworkPath('packages/flutter/lib/src/material/scrollbar.dart'),
- contains('f: scrolling'));
- expect(GithubWebhookSubscription.getLabelsForFrameworkPath('packages/flutter/lib/src/rendering/viewport.dart'),
- contains('f: scrolling'));
+ expect(
+ GithubWebhookSubscription.getLabelsForFrameworkPath('packages/flutter/lib/src/widgets/sliver.dart'),
+ contains('f: scrolling'),
+ );
+ expect(
+ GithubWebhookSubscription.getLabelsForFrameworkPath('packages/flutter/lib/src/material/scrollbar.dart'),
+ contains('f: scrolling'),
+ );
+ expect(
+ GithubWebhookSubscription.getLabelsForFrameworkPath('packages/flutter/lib/src/rendering/viewport.dart'),
+ contains('f: scrolling'),
+ );
});
test('integration_test label is/isn\'t applied', () {
// Label does not apply to integration tests outside of the
// integration_test package.
expect(
- GithubWebhookSubscription.getLabelsForFrameworkPath(
- 'dev/integration_tests/web_e2e_tests/test_driver/text_editing_integration.dart'),
- <String>{'team', 'a: text input'});
+ GithubWebhookSubscription.getLabelsForFrameworkPath(
+ 'dev/integration_tests/web_e2e_tests/test_driver/text_editing_integration.dart',
+ ),
+ <String>{'team', 'a: text input'},
+ );
// Label applies to integration_test package
- expect(GithubWebhookSubscription.getLabelsForFrameworkPath('packages/integration_test/lib/common.dart'),
- contains('integration_test'));
+ expect(
+ GithubWebhookSubscription.getLabelsForFrameworkPath('packages/integration_test/lib/common.dart'),
+ contains('integration_test'),
+ );
});
});
@@ -531,43 +631,59 @@
});
test('platform-android applied for Android embedder', () {
- expect(GithubWebhookSubscription.getLabelsForEnginePath('shell/platform/android/RIsForRhubarbPie.java'),
- contains('platform-android'));
+ expect(
+ GithubWebhookSubscription.getLabelsForEnginePath('shell/platform/android/RIsForRhubarbPie.java'),
+ contains('platform-android'),
+ );
});
test('platform-ios and platform-macos applied for common Darwin code', () {
- expect(GithubWebhookSubscription.getLabelsForEnginePath('shell/platform/darwin/common/ThinkDifferent.mm'),
- containsAll(<String>['platform-ios', 'platform-macos']));
+ expect(
+ GithubWebhookSubscription.getLabelsForEnginePath('shell/platform/darwin/common/ThinkDifferent.mm'),
+ containsAll(<String>['platform-ios', 'platform-macos']),
+ );
});
test('platform-ios and platform-ios applied for iOS embedder', () {
- expect(GithubWebhookSubscription.getLabelsForEnginePath('shell/platform/darwin/ios/BackButton.mm'),
- contains('platform-ios'));
+ expect(
+ GithubWebhookSubscription.getLabelsForEnginePath('shell/platform/darwin/ios/BackButton.mm'),
+ contains('platform-ios'),
+ );
});
test('platform-macos applied for macOS embedder', () {
- expect(GithubWebhookSubscription.getLabelsForEnginePath('shell/platform/darwin/macos/PhysicalEscapeKey.mm'),
- contains('platform-macos'));
+ expect(
+ GithubWebhookSubscription.getLabelsForEnginePath('shell/platform/darwin/macos/PhysicalEscapeKey.mm'),
+ contains('platform-macos'),
+ );
});
test('platform-fuchsia applied for fuchsia embedder', () {
- expect(GithubWebhookSubscription.getLabelsForEnginePath('shell/platform/fuchsia/spell_checker.cc'),
- contains('platform-fuchsia'));
+ expect(
+ GithubWebhookSubscription.getLabelsForEnginePath('shell/platform/fuchsia/spell_checker.cc'),
+ contains('platform-fuchsia'),
+ );
});
test('platform-linux applied for linux embedder', () {
- expect(GithubWebhookSubscription.getLabelsForEnginePath('shell/platform/linux/systemd_integration.cc'),
- contains('platform-linux'));
+ expect(
+ GithubWebhookSubscription.getLabelsForEnginePath('shell/platform/linux/systemd_integration.cc'),
+ contains('platform-linux'),
+ );
});
test('platform-windows applied for windows embedder', () {
- expect(GithubWebhookSubscription.getLabelsForEnginePath('shell/platform/windows/start_menu.cc'),
- contains('platform-windows'));
+ expect(
+ GithubWebhookSubscription.getLabelsForEnginePath('shell/platform/windows/start_menu.cc'),
+ contains('platform-windows'),
+ );
});
test('platform-web applied for web paths', () {
expect(
- GithubWebhookSubscription.getLabelsForEnginePath('lib/web_ui/shadow_dom.dart'), contains('platform-web'));
+ GithubWebhookSubscription.getLabelsForEnginePath('lib/web_ui/shadow_dom.dart'),
+ contains('platform-web'),
+ );
expect(GithubWebhookSubscription.getLabelsForEnginePath('web_sdk/'), contains('platform-web'));
});
});
@@ -654,21 +770,25 @@
await tester.post(webhook);
- verify(issuesService.addLabelsToIssue(
- Config.flutterSlug,
- issueNumber,
- <String>['framework'],
- )).called(1);
+ verify(
+ issuesService.addLabelsToIssue(
+ Config.flutterSlug,
+ issueNumber,
+ <String>['framework'],
+ ),
+ ).called(1);
- verify(issuesService.createComment(
- Config.flutterSlug,
- issueNumber,
- argThat(contains(config.missingTestsPullRequestMessageValue)),
- )).called(1);
+ verify(
+ issuesService.createComment(
+ Config.flutterSlug,
+ issueNumber,
+ argThat(contains(config.missingTestsPullRequestMessageValue)),
+ ),
+ ).called(1);
});
group("Auto-roller accounts do not label Framework PR with test label or comment.", () {
- Set<String> inputs = {
+ final Set<String> inputs = {
'skia-flutter-autoroll',
'dependabot',
};
@@ -699,17 +819,21 @@
await tester.post(webhook);
- verify(issuesService.addLabelsToIssue(
- slug,
- issueNumber,
- <String>['framework'],
- )).called(1);
+ verify(
+ issuesService.addLabelsToIssue(
+ slug,
+ issueNumber,
+ <String>['framework'],
+ ),
+ ).called(1);
- verifyNever(issuesService.createComment(
- slug,
- issueNumber,
- argThat(contains(config.missingTestsPullRequestMessageValue)),
- ));
+ verifyNever(
+ issuesService.createComment(
+ slug,
+ issueNumber,
+ argThat(contains(config.missingTestsPullRequestMessageValue)),
+ ),
+ );
});
}
});
@@ -738,17 +862,21 @@
await tester.post(webhook);
- verifyNever(issuesService.addLabelsToIssue(
- slug,
- issueNumber,
- <String>['framework'],
- ));
+ verifyNever(
+ issuesService.addLabelsToIssue(
+ slug,
+ issueNumber,
+ <String>['framework'],
+ ),
+ );
- verifyNever(issuesService.createComment(
- slug,
- issueNumber,
- argThat(contains(config.missingTestsPullRequestMessageValue)),
- ));
+ verifyNever(
+ issuesService.createComment(
+ slug,
+ issueNumber,
+ argThat(contains(config.missingTestsPullRequestMessageValue)),
+ ),
+ );
});
test('Framework does not label PR with no tests label if file is test exempt', () async {
@@ -774,17 +902,21 @@
await tester.post(webhook);
- verifyNever(issuesService.addLabelsToIssue(
- slug,
- issueNumber,
- <String>['framework'],
- ));
+ verifyNever(
+ issuesService.addLabelsToIssue(
+ slug,
+ issueNumber,
+ <String>['framework'],
+ ),
+ );
- verifyNever(issuesService.createComment(
- slug,
- issueNumber,
- argThat(contains(config.missingTestsPullRequestMessageValue)),
- ));
+ verifyNever(
+ issuesService.createComment(
+ slug,
+ issueNumber,
+ argThat(contains(config.missingTestsPullRequestMessageValue)),
+ ),
+ );
});
test('Framework labels PRs, comment if no tests including hit_test.dart file', () async {
@@ -813,17 +945,21 @@
await tester.post(webhook);
- verify(issuesService.addLabelsToIssue(
- slug,
- issueNumber,
- <String>['framework', 'f: gestures'],
- )).called(1);
+ verify(
+ issuesService.addLabelsToIssue(
+ slug,
+ issueNumber,
+ <String>['framework', 'f: gestures'],
+ ),
+ ).called(1);
- verify(issuesService.createComment(
- slug,
- issueNumber,
- argThat(contains(config.missingTestsPullRequestMessageValue)),
- )).called(1);
+ verify(
+ issuesService.createComment(
+ slug,
+ issueNumber,
+ argThat(contains(config.missingTestsPullRequestMessageValue)),
+ ),
+ ).called(1);
});
test('Framework labels PRs, no dart files', () async {
@@ -843,17 +979,21 @@
await tester.post(webhook);
- verify(issuesService.addLabelsToIssue(
- slug,
- issueNumber,
- <String>['framework'],
- )).called(1);
+ verify(
+ issuesService.addLabelsToIssue(
+ slug,
+ issueNumber,
+ <String>['framework'],
+ ),
+ ).called(1);
- verifyNever(issuesService.createComment(
- slug,
- issueNumber,
- any,
- ));
+ verifyNever(
+ issuesService.createComment(
+ slug,
+ issueNumber,
+ any,
+ ),
+ );
});
test('Framework labels PRs, no comment if tests', () async {
@@ -882,29 +1022,33 @@
await tester.post(webhook);
- verify(issuesService.addLabelsToIssue(
- slug,
- issueNumber,
- <String>[
- 'framework',
- 'a: accessibility',
- 'tool',
- 'a: tests',
- 'd: examples',
- 'team',
- 'team: gallery',
- 'engine',
- 'f: cupertino',
- 'f: material design',
- 'a: internationalization',
- ],
- )).called(1);
+ verify(
+ issuesService.addLabelsToIssue(
+ slug,
+ issueNumber,
+ <String>[
+ 'framework',
+ 'a: accessibility',
+ 'tool',
+ 'a: tests',
+ 'd: examples',
+ 'team',
+ 'team: gallery',
+ 'engine',
+ 'f: cupertino',
+ 'f: material design',
+ 'a: internationalization',
+ ],
+ ),
+ ).called(1);
- verifyNever(issuesService.createComment(
- slug,
- issueNumber,
- argThat(contains(config.missingTestsPullRequestMessageValue)),
- ));
+ verifyNever(
+ issuesService.createComment(
+ slug,
+ issueNumber,
+ argThat(contains(config.missingTestsPullRequestMessageValue)),
+ ),
+ );
});
test('Framework labels dart fix PRs, no comment if tests', () async {
@@ -925,17 +1069,21 @@
await tester.post(webhook);
- verify(issuesService.addLabelsToIssue(
- slug,
- issueNumber,
- <String>['team', 'tech-debt', 'framework', 'f: material design'],
- )).called(1);
+ verify(
+ issuesService.addLabelsToIssue(
+ slug,
+ issueNumber,
+ <String>['team', 'tech-debt', 'framework', 'f: material design'],
+ ),
+ ).called(1);
- verifyNever(issuesService.createComment(
- slug,
- issueNumber,
- argThat(contains(config.missingTestsPullRequestMessageValue)),
- ));
+ verifyNever(
+ issuesService.createComment(
+ slug,
+ issueNumber,
+ argThat(contains(config.missingTestsPullRequestMessageValue)),
+ ),
+ );
});
test('Framework labels bot PR, no comment', () async {
@@ -957,17 +1105,21 @@
await tester.post(webhook);
- verify(issuesService.addLabelsToIssue(
- slug,
- issueNumber,
- <String>['tool', 'framework', 'a: tests', 'team', 'tech-debt', 'team: flakes'],
- )).called(1);
+ verify(
+ issuesService.addLabelsToIssue(
+ slug,
+ issueNumber,
+ <String>['tool', 'framework', 'a: tests', 'team', 'tech-debt', 'team: flakes'],
+ ),
+ ).called(1);
- verifyNever(issuesService.createComment(
- slug,
- issueNumber,
- argThat(contains(config.missingTestsPullRequestMessageValue)),
- ));
+ verifyNever(
+ issuesService.createComment(
+ slug,
+ issueNumber,
+ argThat(contains(config.missingTestsPullRequestMessageValue)),
+ ),
+ );
});
test('Framework labels deletion only PR, no test request', () async {
@@ -991,18 +1143,22 @@
await tester.post(webhook);
- verify(issuesService.addLabelsToIssue(
- slug,
- issueNumber,
- <String>['framework'],
- )).called(1);
+ verify(
+ issuesService.addLabelsToIssue(
+ slug,
+ issueNumber,
+ <String>['framework'],
+ ),
+ ).called(1);
// The PR here is only deleting code, so no test comment.
- verifyNever(issuesService.createComment(
- slug,
- issueNumber,
- argThat(contains(config.missingTestsPullRequestMessageValue)),
- ));
+ verifyNever(
+ issuesService.createComment(
+ slug,
+ issueNumber,
+ argThat(contains(config.missingTestsPullRequestMessageValue)),
+ ),
+ );
});
test('PR with additions and deletions is commented and labeled', () async {
@@ -1026,17 +1182,21 @@
await tester.post(webhook);
- verify(issuesService.addLabelsToIssue(
- slug,
- issueNumber,
- <String>['framework'],
- )).called(1);
+ verify(
+ issuesService.addLabelsToIssue(
+ slug,
+ issueNumber,
+ <String>['framework'],
+ ),
+ ).called(1);
- verify(issuesService.createComment(
- slug,
- issueNumber,
- argThat(contains(config.missingTestsPullRequestMessageValue)),
- )).called(1);
+ verify(
+ issuesService.createComment(
+ slug,
+ issueNumber,
+ argThat(contains(config.missingTestsPullRequestMessageValue)),
+ ),
+ ).called(1);
});
test('Framework no comment if code has only devicelab test', () async {
@@ -1057,11 +1217,13 @@
await tester.post(webhook);
- verifyNever(issuesService.createComment(
- slug,
- issueNumber,
- argThat(contains(config.missingTestsPullRequestMessageValue)),
- ));
+ verifyNever(
+ issuesService.createComment(
+ slug,
+ issueNumber,
+ argThat(contains(config.missingTestsPullRequestMessageValue)),
+ ),
+ );
});
test('Framework no comment if only dev bots or devicelab changed', () async {
@@ -1079,11 +1241,13 @@
await tester.post(webhook);
- verifyNever(issuesService.createComment(
- Config.flutterSlug,
- issueNumber,
- argThat(contains(config.missingTestsPullRequestMessageValue)),
- ));
+ verifyNever(
+ issuesService.createComment(
+ Config.flutterSlug,
+ issueNumber,
+ argThat(contains(config.missingTestsPullRequestMessageValue)),
+ ),
+ );
});
test('Framework no comment if only .gitignore changed', () async {
@@ -1099,11 +1263,13 @@
await tester.post(webhook);
- verifyNever(issuesService.createComment(
- any,
- issueNumber,
- argThat(contains(config.missingTestsPullRequestMessageValue)),
- ));
+ verifyNever(
+ issuesService.createComment(
+ any,
+ issueNumber,
+ argThat(contains(config.missingTestsPullRequestMessageValue)),
+ ),
+ );
});
test('Framework no test comment if Objective-C test changed', () async {
@@ -1122,11 +1288,13 @@
await tester.post(webhook);
- verifyNever(issuesService.createComment(
- Config.flutterSlug,
- issueNumber,
- argThat(contains(config.missingTestsPullRequestMessageValue)),
- ));
+ verifyNever(
+ issuesService.createComment(
+ Config.flutterSlug,
+ issueNumber,
+ argThat(contains(config.missingTestsPullRequestMessageValue)),
+ ),
+ );
});
test('Framework no comment if only AUTHORS changed', () async {
@@ -1144,11 +1312,13 @@
await tester.post(webhook);
- verifyNever(issuesService.createComment(
- Config.flutterSlug,
- issueNumber,
- argThat(contains(config.missingTestsPullRequestMessageValue)),
- ));
+ verifyNever(
+ issuesService.createComment(
+ Config.flutterSlug,
+ issueNumber,
+ argThat(contains(config.missingTestsPullRequestMessageValue)),
+ ),
+ );
});
test('Framework no comment if only ci.yaml and cirrus.yml changed', () async {
@@ -1169,11 +1339,13 @@
await tester.post(webhook);
- verifyNever(issuesService.createComment(
- slug,
- issueNumber,
- argThat(contains(config.missingTestsPullRequestMessageValue)),
- ));
+ verifyNever(
+ issuesService.createComment(
+ slug,
+ issueNumber,
+ argThat(contains(config.missingTestsPullRequestMessageValue)),
+ ),
+ );
});
test('Framework no comment if only analysis options changed', () async {
@@ -1189,11 +1361,13 @@
await tester.post(webhook);
- verifyNever(issuesService.createComment(
- slug,
- issueNumber,
- argThat(contains(config.missingTestsPullRequestMessageValue)),
- ));
+ verifyNever(
+ issuesService.createComment(
+ slug,
+ issueNumber,
+ argThat(contains(config.missingTestsPullRequestMessageValue)),
+ ),
+ );
});
test('Framework no comment if only CODEOWNERS changed', () async {
@@ -1209,11 +1383,13 @@
await tester.post(webhook);
- verifyNever(issuesService.createComment(
- slug,
- issueNumber,
- argThat(contains(config.missingTestsPullRequestMessageValue)),
- ));
+ verifyNever(
+ issuesService.createComment(
+ slug,
+ issueNumber,
+ argThat(contains(config.missingTestsPullRequestMessageValue)),
+ ),
+ );
});
test('Framework no comment if only comments changed', () async {
@@ -1246,11 +1422,13 @@
await tester.post(webhook);
- verifyNever(issuesService.createComment(
- slug,
- issueNumber,
- argThat(contains(config.missingTestsPullRequestMessageValue)),
- ));
+ verifyNever(
+ issuesService.createComment(
+ slug,
+ issueNumber,
+ argThat(contains(config.missingTestsPullRequestMessageValue)),
+ ),
+ );
});
test('Framework labels PRs, no comment if tests (dev/bots/test.dart)', () async {
@@ -1274,11 +1452,13 @@
await tester.post(webhook);
- verifyNever(issuesService.createComment(
- Config.flutterSlug,
- issueNumber,
- argThat(contains(config.missingTestsPullRequestMessageValue)),
- ));
+ verifyNever(
+ issuesService.createComment(
+ Config.flutterSlug,
+ issueNumber,
+ argThat(contains(config.missingTestsPullRequestMessageValue)),
+ ),
+ );
});
test('Framework labels PRs, no comment if tests (dev/bots/analyze.dart)', () async {
@@ -1303,11 +1483,13 @@
await tester.post(webhook);
- verifyNever(issuesService.createComment(
- slug,
- issueNumber,
- argThat(contains(config.missingTestsPullRequestMessageValue)),
- ));
+ verifyNever(
+ issuesService.createComment(
+ slug,
+ issueNumber,
+ argThat(contains(config.missingTestsPullRequestMessageValue)),
+ ),
+ );
});
test('Framework labels PRs, apply label but no comment when rolling engine version', () async {
@@ -1332,17 +1514,21 @@
await tester.post(webhook);
- verify(issuesService.addLabelsToIssue(
- Config.flutterSlug,
- issueNumber,
- <String>['engine'],
- )).called(1);
+ verify(
+ issuesService.addLabelsToIssue(
+ Config.flutterSlug,
+ issueNumber,
+ <String>['engine'],
+ ),
+ ).called(1);
- verifyNever(issuesService.createComment(
- Config.flutterSlug,
- issueNumber,
- argThat(contains(config.missingTestsPullRequestMessageValue)),
- ));
+ verifyNever(
+ issuesService.createComment(
+ Config.flutterSlug,
+ issueNumber,
+ argThat(contains(config.missingTestsPullRequestMessageValue)),
+ ),
+ );
});
test('Engine labels PRs, comment and labels if no tests', () async {
@@ -1369,27 +1555,33 @@
await tester.post(webhook);
- verify(issuesService.addLabelsToIssue(
- slug,
- issueNumber,
- <String>['platform-ios'],
- )).called(1);
+ verify(
+ issuesService.addLabelsToIssue(
+ slug,
+ issueNumber,
+ <String>['platform-ios'],
+ ),
+ ).called(1);
- verify(issuesService.createComment(
- slug,
- issueNumber,
- argThat(contains(config.missingTestsPullRequestMessageValue)),
- )).called(1);
+ verify(
+ issuesService.createComment(
+ slug,
+ issueNumber,
+ argThat(contains(config.missingTestsPullRequestMessageValue)),
+ ),
+ ).called(1);
- verify(issuesService.addLabelsToIssue(
- slug,
- issueNumber,
- <String>['needs tests'],
- )).called(1);
+ verify(
+ issuesService.addLabelsToIssue(
+ slug,
+ issueNumber,
+ <String>['needs tests'],
+ ),
+ ).called(1);
});
group("Auto-roller accounts do not label Engine PR with test label or comment.", () {
- Set<String> inputs = {
+ final Set<String> inputs = {
'engine-flutter-autoroll',
'dependabot',
};
@@ -1419,23 +1611,29 @@
await tester.post(webhook);
- verify(issuesService.addLabelsToIssue(
- Config.engineSlug,
- issueNumber,
- <String>['platform-ios'],
- )).called(1);
+ verify(
+ issuesService.addLabelsToIssue(
+ Config.engineSlug,
+ issueNumber,
+ <String>['platform-ios'],
+ ),
+ ).called(1);
- verifyNever(issuesService.createComment(
- Config.engineSlug,
- issueNumber,
- argThat(contains(config.missingTestsPullRequestMessageValue)),
- ));
+ verifyNever(
+ issuesService.createComment(
+ Config.engineSlug,
+ issueNumber,
+ argThat(contains(config.missingTestsPullRequestMessageValue)),
+ ),
+ );
- verifyNever(issuesService.addLabelsToIssue(
- Config.engineSlug,
- issueNumber,
- <String>['needs tests'],
- ));
+ verifyNever(
+ issuesService.addLabelsToIssue(
+ Config.engineSlug,
+ issueNumber,
+ <String>['needs tests'],
+ ),
+ );
});
}
});
@@ -1464,23 +1662,29 @@
await tester.post(webhook);
- verifyNever(issuesService.addLabelsToIssue(
- Config.engineSlug,
- issueNumber,
- <String>['platform-ios'],
- ));
+ verifyNever(
+ issuesService.addLabelsToIssue(
+ Config.engineSlug,
+ issueNumber,
+ <String>['platform-ios'],
+ ),
+ );
- verifyNever(issuesService.createComment(
- Config.engineSlug,
- issueNumber,
- argThat(contains(config.missingTestsPullRequestMessageValue)),
- ));
+ verifyNever(
+ issuesService.createComment(
+ Config.engineSlug,
+ issueNumber,
+ argThat(contains(config.missingTestsPullRequestMessageValue)),
+ ),
+ );
- verifyNever(issuesService.addLabelsToIssue(
- Config.engineSlug,
- issueNumber,
- <String>['needs tests'],
- ));
+ verifyNever(
+ issuesService.addLabelsToIssue(
+ Config.engineSlug,
+ issueNumber,
+ <String>['needs tests'],
+ ),
+ );
});
test('Engine labels PRs, no code files', () async {
@@ -1501,17 +1705,21 @@
await tester.post(webhook);
- verifyNever(issuesService.addLabelsToIssue(
- Config.engineSlug,
- issueNumber,
- any,
- ));
+ verifyNever(
+ issuesService.addLabelsToIssue(
+ Config.engineSlug,
+ issueNumber,
+ any,
+ ),
+ );
- verifyNever(issuesService.createComment(
- Config.engineSlug,
- issueNumber,
- any,
- ));
+ verifyNever(
+ issuesService.createComment(
+ Config.engineSlug,
+ issueNumber,
+ any,
+ ),
+ );
});
test('Engine labels PRs, no comment if Java tests', () async {
@@ -1532,19 +1740,23 @@
await tester.post(webhook);
- verify(issuesService.addLabelsToIssue(
- Config.engineSlug,
- issueNumber,
- <String>[
- 'platform-android',
- ],
- )).called(1);
+ verify(
+ issuesService.addLabelsToIssue(
+ Config.engineSlug,
+ issueNumber,
+ <String>[
+ 'platform-android',
+ ],
+ ),
+ ).called(1);
- verifyNever(issuesService.createComment(
- Config.engineSlug,
- issueNumber,
- argThat(contains(config.missingTestsPullRequestMessageValue)),
- ));
+ verifyNever(
+ issuesService.createComment(
+ Config.engineSlug,
+ issueNumber,
+ argThat(contains(config.missingTestsPullRequestMessageValue)),
+ ),
+ );
});
test('Engine labels PRs, no comment if cc tests', () async {
@@ -1565,17 +1777,21 @@
await tester.post(webhook);
- verifyNever(issuesService.addLabelsToIssue(
- Config.engineSlug,
- issueNumber,
- any,
- ));
+ verifyNever(
+ issuesService.addLabelsToIssue(
+ Config.engineSlug,
+ issueNumber,
+ any,
+ ),
+ );
- verifyNever(issuesService.createComment(
- Config.engineSlug,
- issueNumber,
- argThat(contains(config.missingTestsPullRequestMessageValue)),
- ));
+ verifyNever(
+ issuesService.createComment(
+ Config.engineSlug,
+ issueNumber,
+ argThat(contains(config.missingTestsPullRequestMessageValue)),
+ ),
+ );
});
test('Engine labels PRs, no comment if cc becnhmarks', () async {
@@ -1596,17 +1812,21 @@
await tester.post(webhook);
- verifyNever(issuesService.addLabelsToIssue(
- Config.engineSlug,
- issueNumber,
- any,
- ));
+ verifyNever(
+ issuesService.addLabelsToIssue(
+ Config.engineSlug,
+ issueNumber,
+ any,
+ ),
+ );
- verifyNever(issuesService.createComment(
- Config.engineSlug,
- issueNumber,
- argThat(contains(config.missingTestsPullRequestMessageValue)),
- ));
+ verifyNever(
+ issuesService.createComment(
+ Config.engineSlug,
+ issueNumber,
+ argThat(contains(config.missingTestsPullRequestMessageValue)),
+ ),
+ );
});
test('Engine labels PRs, no comments if pr is for release branches', () async {
@@ -1633,17 +1853,21 @@
await tester.post(webhook);
- verify(issuesService.addLabelsToIssue(
- Config.engineSlug,
- issueNumber,
- <String>['platform-ios'],
- )).called(1);
+ verify(
+ issuesService.addLabelsToIssue(
+ Config.engineSlug,
+ issueNumber,
+ <String>['platform-ios'],
+ ),
+ ).called(1);
- verifyNever(issuesService.createComment(
- Config.engineSlug,
- issueNumber,
- argThat(contains(config.missingTestsPullRequestMessageValue)),
- ));
+ verifyNever(
+ issuesService.createComment(
+ Config.engineSlug,
+ issueNumber,
+ argThat(contains(config.missingTestsPullRequestMessageValue)),
+ ),
+ );
});
test('Engine does not comment for comment-only changes', () async {
@@ -1679,11 +1903,13 @@
await tester.post(webhook);
- verifyNever(issuesService.createComment(
- Config.engineSlug,
- issueNumber,
- argThat(contains(config.missingTestsPullRequestMessageValue)),
- ));
+ verifyNever(
+ issuesService.createComment(
+ Config.engineSlug,
+ issueNumber,
+ argThat(contains(config.missingTestsPullRequestMessageValue)),
+ ),
+ );
});
test('No labels when only pubspec.yaml changes', () async {
@@ -1703,17 +1929,21 @@
await tester.post(webhook);
- verify(issuesService.addLabelsToIssue(
- Config.flutterSlug,
- issueNumber,
- <String>['team'],
- )).called(1);
+ verify(
+ issuesService.addLabelsToIssue(
+ Config.flutterSlug,
+ issueNumber,
+ <String>['team'],
+ ),
+ ).called(1);
- verifyNever(issuesService.createComment(
- Config.flutterSlug,
- issueNumber,
- argThat(contains(config.missingTestsPullRequestMessageValue)),
- ));
+ verifyNever(
+ issuesService.createComment(
+ Config.flutterSlug,
+ issueNumber,
+ argThat(contains(config.missingTestsPullRequestMessageValue)),
+ ),
+ );
});
test('Plugins comments and labels if no tests and no patch info', () async {
@@ -1739,21 +1969,25 @@
await tester.post(webhook);
- verify(issuesService.createComment(
- Config.pluginsSlug,
- issueNumber,
- argThat(contains(config.missingTestsPullRequestMessageValue)),
- )).called(1);
+ verify(
+ issuesService.createComment(
+ Config.pluginsSlug,
+ issueNumber,
+ argThat(contains(config.missingTestsPullRequestMessageValue)),
+ ),
+ ).called(1);
- verify(issuesService.addLabelsToIssue(
- Config.pluginsSlug,
- issueNumber,
- <String>['needs tests'],
- )).called(1);
+ verify(
+ issuesService.addLabelsToIssue(
+ Config.pluginsSlug,
+ issueNumber,
+ <String>['needs tests'],
+ ),
+ ).called(1);
});
group('Plugins does not comment and label if author is an autoroller account.', () {
- Set<String> inputs = {
+ final Set<String> inputs = {
'engine-flutter-autoroll',
'skia-flutter-autoroll',
'dependabot',
@@ -1784,17 +2018,21 @@
await tester.post(webhook);
- verifyNever(issuesService.createComment(
- Config.pluginsSlug,
- issueNumber,
- argThat(contains(config.missingTestsPullRequestMessageValue)),
- ));
+ verifyNever(
+ issuesService.createComment(
+ Config.pluginsSlug,
+ issueNumber,
+ argThat(contains(config.missingTestsPullRequestMessageValue)),
+ ),
+ );
- verifyNever(issuesService.addLabelsToIssue(
- Config.pluginsSlug,
- issueNumber,
- <String>['needs tests'],
- ));
+ verifyNever(
+ issuesService.addLabelsToIssue(
+ Config.pluginsSlug,
+ issueNumber,
+ <String>['needs tests'],
+ ),
+ );
});
}
});
@@ -1823,17 +2061,21 @@
await tester.post(webhook);
- verifyNever(issuesService.createComment(
- Config.pluginsSlug,
- issueNumber,
- argThat(contains(config.missingTestsPullRequestMessageValue)),
- ));
+ verifyNever(
+ issuesService.createComment(
+ Config.pluginsSlug,
+ issueNumber,
+ argThat(contains(config.missingTestsPullRequestMessageValue)),
+ ),
+ );
- verifyNever(issuesService.addLabelsToIssue(
- Config.pluginsSlug,
- issueNumber,
- any,
- ));
+ verifyNever(
+ issuesService.addLabelsToIssue(
+ Config.pluginsSlug,
+ issueNumber,
+ any,
+ ),
+ );
});
test('Plugins comments and labels for code change', () async {
@@ -1877,17 +2119,21 @@
await tester.post(webhook);
- verify(issuesService.createComment(
- Config.pluginsSlug,
- issueNumber,
- argThat(contains(config.missingTestsPullRequestMessageValue)),
- )).called(1);
+ verify(
+ issuesService.createComment(
+ Config.pluginsSlug,
+ issueNumber,
+ argThat(contains(config.missingTestsPullRequestMessageValue)),
+ ),
+ ).called(1);
- verify(issuesService.addLabelsToIssue(
- Config.pluginsSlug,
- issueNumber,
- <String>['needs tests'],
- )).called(1);
+ verify(
+ issuesService.addLabelsToIssue(
+ Config.pluginsSlug,
+ issueNumber,
+ <String>['needs tests'],
+ ),
+ ).called(1);
});
test('Plugins comments and labels for code removal with comment addition', () async {
@@ -1929,17 +2175,21 @@
await tester.post(webhook);
- verify(issuesService.createComment(
- Config.pluginsSlug,
- issueNumber,
- argThat(contains(config.missingTestsPullRequestMessageValue)),
- )).called(1);
+ verify(
+ issuesService.createComment(
+ Config.pluginsSlug,
+ issueNumber,
+ argThat(contains(config.missingTestsPullRequestMessageValue)),
+ ),
+ ).called(1);
- verify(issuesService.addLabelsToIssue(
- Config.pluginsSlug,
- issueNumber,
- <String>['needs tests'],
- )).called(1);
+ verify(
+ issuesService.addLabelsToIssue(
+ Config.pluginsSlug,
+ issueNumber,
+ <String>['needs tests'],
+ ),
+ ).called(1);
});
test('Plugins does not comment for comment-only changes', () async {
@@ -1975,11 +2225,13 @@
await tester.post(webhook);
- verifyNever(issuesService.createComment(
- Config.pluginsSlug,
- issueNumber,
- argThat(contains(config.missingTestsPullRequestMessageValue)),
- ));
+ verifyNever(
+ issuesService.createComment(
+ Config.pluginsSlug,
+ issueNumber,
+ argThat(contains(config.missingTestsPullRequestMessageValue)),
+ ),
+ );
});
test('Plugins does not comment if Dart tests', () async {
@@ -1999,11 +2251,13 @@
await tester.post(webhook);
- verifyNever(issuesService.createComment(
- Config.pluginsSlug,
- issueNumber,
- argThat(contains(config.missingTestsPullRequestMessageValue)),
- ));
+ verifyNever(
+ issuesService.createComment(
+ Config.pluginsSlug,
+ issueNumber,
+ argThat(contains(config.missingTestsPullRequestMessageValue)),
+ ),
+ );
});
test('Plugins does not comment if Android unit tests', () async {
@@ -2023,11 +2277,13 @@
await tester.post(webhook);
- verifyNever(issuesService.createComment(
- Config.pluginsSlug,
- issueNumber,
- argThat(contains(config.missingTestsPullRequestMessageValue)),
- ));
+ verifyNever(
+ issuesService.createComment(
+ Config.pluginsSlug,
+ issueNumber,
+ argThat(contains(config.missingTestsPullRequestMessageValue)),
+ ),
+ );
});
test('Plugins does not comment if Android UI tests', () async {
@@ -2047,11 +2303,13 @@
await tester.post(webhook);
- verifyNever(issuesService.createComment(
- Config.pluginsSlug,
- issueNumber,
- argThat(contains(config.missingTestsPullRequestMessageValue)),
- ));
+ verifyNever(
+ issuesService.createComment(
+ Config.pluginsSlug,
+ issueNumber,
+ argThat(contains(config.missingTestsPullRequestMessageValue)),
+ ),
+ );
});
test('Plugins does not comment if iOS/macOS unit tests', () async {
@@ -2071,11 +2329,13 @@
await tester.post(webhook);
- verifyNever(issuesService.createComment(
- Config.pluginsSlug,
- issueNumber,
- argThat(contains(config.missingTestsPullRequestMessageValue)),
- ));
+ verifyNever(
+ issuesService.createComment(
+ Config.pluginsSlug,
+ issueNumber,
+ argThat(contains(config.missingTestsPullRequestMessageValue)),
+ ),
+ );
});
test('Plugins does not comment if iOS/macOS UI tests', () async {
@@ -2095,11 +2355,13 @@
await tester.post(webhook);
- verifyNever(issuesService.createComment(
- Config.pluginsSlug,
- issueNumber,
- argThat(contains(config.missingTestsPullRequestMessageValue)),
- ));
+ verifyNever(
+ issuesService.createComment(
+ Config.pluginsSlug,
+ issueNumber,
+ argThat(contains(config.missingTestsPullRequestMessageValue)),
+ ),
+ );
});
test('Plugins does not comment if Windows tests', () async {
@@ -2119,11 +2381,13 @@
await tester.post(webhook);
- verifyNever(issuesService.createComment(
- Config.pluginsSlug,
- issueNumber,
- argThat(contains(config.missingTestsPullRequestMessageValue)),
- ));
+ verifyNever(
+ issuesService.createComment(
+ Config.pluginsSlug,
+ issueNumber,
+ argThat(contains(config.missingTestsPullRequestMessageValue)),
+ ),
+ );
});
test('Plugins does not comment if Linux tests', () async {
@@ -2143,11 +2407,13 @@
await tester.post(webhook);
- verifyNever(issuesService.createComment(
- Config.pluginsSlug,
- issueNumber,
- argThat(contains(config.missingTestsPullRequestMessageValue)),
- ));
+ verifyNever(
+ issuesService.createComment(
+ Config.pluginsSlug,
+ issueNumber,
+ argThat(contains(config.missingTestsPullRequestMessageValue)),
+ ),
+ );
});
test('Packages comments and labels if no tests', () async {
@@ -2172,17 +2438,21 @@
await tester.post(webhook);
- verify(issuesService.createComment(
- Config.packagesSlug,
- issueNumber,
- argThat(contains(config.missingTestsPullRequestMessageValue)),
- )).called(1);
+ verify(
+ issuesService.createComment(
+ Config.packagesSlug,
+ issueNumber,
+ argThat(contains(config.missingTestsPullRequestMessageValue)),
+ ),
+ ).called(1);
- verify(issuesService.addLabelsToIssue(
- Config.packagesSlug,
- issueNumber,
- <String>['needs tests'],
- )).called(1);
+ verify(
+ issuesService.addLabelsToIssue(
+ Config.packagesSlug,
+ issueNumber,
+ <String>['needs tests'],
+ ),
+ ).called(1);
});
test('Packages do not comment or label if pr is for release branches', () async {
@@ -2210,17 +2480,21 @@
await tester.post(webhook);
- verifyNever(issuesService.createComment(
- Config.packagesSlug,
- issueNumber,
- argThat(contains(config.missingTestsPullRequestMessageValue)),
- ));
+ verifyNever(
+ issuesService.createComment(
+ Config.packagesSlug,
+ issueNumber,
+ argThat(contains(config.missingTestsPullRequestMessageValue)),
+ ),
+ );
- verifyNever(issuesService.addLabelsToIssue(
- Config.packagesSlug,
- issueNumber,
- any,
- ));
+ verifyNever(
+ issuesService.addLabelsToIssue(
+ Config.packagesSlug,
+ issueNumber,
+ any,
+ ),
+ );
});
test('Packages does not comment if Dart tests', () async {
@@ -2241,11 +2515,13 @@
await tester.post(webhook);
- verifyNever(issuesService.createComment(
- Config.packagesSlug,
- issueNumber,
- argThat(contains(config.missingTestsPullRequestMessageValue)),
- ));
+ verifyNever(
+ issuesService.createComment(
+ Config.packagesSlug,
+ issueNumber,
+ argThat(contains(config.missingTestsPullRequestMessageValue)),
+ ),
+ );
});
test('Packages does not comment for custom test driver', () async {
@@ -2266,11 +2542,13 @@
await tester.post(webhook);
- verifyNever(issuesService.createComment(
- Config.packagesSlug,
- issueNumber,
- argThat(contains(config.missingTestsPullRequestMessageValue)),
- ));
+ verifyNever(
+ issuesService.createComment(
+ Config.packagesSlug,
+ issueNumber,
+ argThat(contains(config.missingTestsPullRequestMessageValue)),
+ ),
+ );
});
test('Schedule tasks when pull request is closed and merged', () async {
@@ -2296,18 +2574,21 @@
isDraft: true,
);
- when(pullRequestsService.listFiles(Config.flutterSlug, issueNumber))
- .thenAnswer((_) => Stream<PullRequestFile>.value(
- PullRequestFile()..filename = 'some_change.dart',
- ));
+ when(pullRequestsService.listFiles(Config.flutterSlug, issueNumber)).thenAnswer(
+ (_) => Stream<PullRequestFile>.value(
+ PullRequestFile()..filename = 'some_change.dart',
+ ),
+ );
await tester.post(webhook);
- verifyNever(issuesService.createComment(
- Config.flutterSlug,
- issueNumber,
- argThat(contains(config.missingTestsPullRequestMessageValue)),
- ));
+ verifyNever(
+ issuesService.createComment(
+ Config.flutterSlug,
+ issueNumber,
+ argThat(contains(config.missingTestsPullRequestMessageValue)),
+ ),
+ );
});
test('Will not spawn comments if they have already been made.', () async {
@@ -2332,17 +2613,21 @@
await tester.post(webhook);
- verify(issuesService.addLabelsToIssue(
- Config.flutterSlug,
- issueNumber,
- <String>['framework'],
- )).called(1);
+ verify(
+ issuesService.addLabelsToIssue(
+ Config.flutterSlug,
+ issueNumber,
+ <String>['framework'],
+ ),
+ ).called(1);
- verifyNever(issuesService.createComment(
- Config.flutterSlug,
- issueNumber,
- argThat(contains(config.missingTestsPullRequestMessageValue)),
- ));
+ verifyNever(
+ issuesService.createComment(
+ Config.flutterSlug,
+ issueNumber,
+ argThat(contains(config.missingTestsPullRequestMessageValue)),
+ ),
+ );
});
test('Skips labeling or commenting on autorolls', () async {
@@ -2356,11 +2641,13 @@
await tester.post(webhook);
- verifyNever(issuesService.createComment(
- any,
- issueNumber,
- any,
- ));
+ verifyNever(
+ issuesService.createComment(
+ any,
+ issueNumber,
+ any,
+ ),
+ );
});
test('Comments on PR but does not schedule builds for unmergeable PRs', () async {
@@ -2373,11 +2660,13 @@
);
await tester.post(webhook);
- verify(issuesService.createComment(
- Config.flutterSlug,
- issueNumber,
- config.mergeConflictPullRequestMessage,
- ));
+ verify(
+ issuesService.createComment(
+ Config.flutterSlug,
+ issueNumber,
+ config.mergeConflictPullRequestMessage,
+ ),
+ );
});
test('When synchronized, cancels existing builds and schedules new ones', () async {
@@ -2487,11 +2776,13 @@
mergeable: false,
);
await tester.post(webhook);
- verify(issuesService.createComment(
- Config.flutterSlug,
- issueNumber,
- config.mergeConflictPullRequestMessage,
- ));
+ verify(
+ issuesService.createComment(
+ Config.flutterSlug,
+ issueNumber,
+ config.mergeConflictPullRequestMessage,
+ ),
+ );
});
test('When synchronized, cancels existing builds and schedules new ones', () async {
diff --git a/app_dart/test/request_handlers/push_build_status_to_github_test.dart b/app_dart/test/request_handlers/push_build_status_to_github_test.dart
index ba8a4b5..17eff2f 100644
--- a/app_dart/test/request_handlers/push_build_status_to_github_test.dart
+++ b/app_dart/test/request_handlers/push_build_status_to_github_test.dart
@@ -115,10 +115,14 @@
});
test('only if pull request is for the default branch', () async {
- when(pullRequestsService.list(any)).thenAnswer((_) => Stream<PullRequest>.value(generatePullRequest(
+ when(pullRequestsService.list(any)).thenAnswer(
+ (_) => Stream<PullRequest>.value(
+ generatePullRequest(
id: 1,
branch: 'flutter-2.15-candidate.3',
- )));
+ ),
+ ),
+ );
buildStatusService.cumulativeStatus = BuildStatus.success();
await tester.get<Body>(handler);
verifyNever(repositoriesService.createStatus(any, any, any));
diff --git a/app_dart/test/request_handlers/push_gold_status_to_github_test.dart b/app_dart/test/request_handlers/push_gold_status_to_github_test.dart
index c661743..fd66b03 100644
--- a/app_dart/test/request_handlers/push_gold_status_to_github_test.dart
+++ b/app_dart/test/request_handlers/push_gold_status_to_github_test.dart
@@ -160,7 +160,12 @@
});
GithubGoldStatusUpdate newStatusUpdate(
- RepositorySlug slug, PullRequest pr, String statusUpdate, String sha, String description) {
+ RepositorySlug slug,
+ PullRequest pr,
+ String statusUpdate,
+ String sha,
+ String description,
+ ) {
return GithubGoldStatusUpdate(
key: db.emptyKey.append(GithubGoldStatusUpdate, id: pr.number),
status: statusUpdate,
@@ -219,31 +224,39 @@
expect(records.where((LogRecord record) => record.level == Level.SEVERE), isEmpty);
// Should not apply labels or make comments
- verifyNever(issuesService.addLabelsToIssue(
- slug,
- flutterPr.number!,
- <String>[
- kGoldenFileLabel,
- ],
- ));
- verifyNever(issuesService.addLabelsToIssue(
- engineSlug,
- enginePr.number!,
- <String>[
- kGoldenFileLabel,
- ],
- ));
+ verifyNever(
+ issuesService.addLabelsToIssue(
+ slug,
+ flutterPr.number!,
+ <String>[
+ kGoldenFileLabel,
+ ],
+ ),
+ );
+ verifyNever(
+ issuesService.addLabelsToIssue(
+ engineSlug,
+ enginePr.number!,
+ <String>[
+ kGoldenFileLabel,
+ ],
+ ),
+ );
- verifyNever(issuesService.createComment(
- slug,
- flutterPr.number!,
- argThat(contains(config.flutterGoldCommentID(flutterPr))),
- ));
- verifyNever(issuesService.createComment(
- engineSlug,
- enginePr.number!,
- argThat(contains(config.flutterGoldCommentID(enginePr))),
- ));
+ verifyNever(
+ issuesService.createComment(
+ slug,
+ flutterPr.number!,
+ argThat(contains(config.flutterGoldCommentID(flutterPr))),
+ ),
+ );
+ verifyNever(
+ issuesService.createComment(
+ engineSlug,
+ enginePr.number!,
+ argThat(contains(config.flutterGoldCommentID(enginePr))),
+ ),
+ );
});
test('if there are no framework tests for this PR, exclude web builds', () async {
@@ -260,19 +273,23 @@
expect(records.where((LogRecord record) => record.level == Level.SEVERE), isEmpty);
// Should not apply labels or make comments
- verifyNever(issuesService.addLabelsToIssue(
- slug,
- pr.number!,
- <String>[
- kGoldenFileLabel,
- ],
- ));
+ verifyNever(
+ issuesService.addLabelsToIssue(
+ slug,
+ pr.number!,
+ <String>[
+ kGoldenFileLabel,
+ ],
+ ),
+ );
- verifyNever(issuesService.createComment(
- slug,
- pr.number!,
- argThat(contains(config.flutterGoldCommentID(pr))),
- ));
+ verifyNever(
+ issuesService.createComment(
+ slug,
+ pr.number!,
+ argThat(contains(config.flutterGoldCommentID(pr))),
+ ),
+ );
});
test('same commit, checks running, last status running', () async {
@@ -301,19 +318,23 @@
expect(records.where((LogRecord record) => record.level == Level.SEVERE), isEmpty);
// Should not apply labels or make comments
- verifyNever(issuesService.addLabelsToIssue(
- slug,
- pr.number!,
- <String>[
- kGoldenFileLabel,
- ],
- ));
+ verifyNever(
+ issuesService.addLabelsToIssue(
+ slug,
+ pr.number!,
+ <String>[
+ kGoldenFileLabel,
+ ],
+ ),
+ );
- verifyNever(issuesService.createComment(
- slug,
- pr.number!,
- argThat(contains(config.flutterGoldCommentID(pr))),
- ));
+ verifyNever(
+ issuesService.createComment(
+ slug,
+ pr.number!,
+ argThat(contains(config.flutterGoldCommentID(pr))),
+ ),
+ );
});
test('same commit, checks complete, last status complete', () async {
@@ -342,19 +363,23 @@
expect(records.where((LogRecord record) => record.level == Level.SEVERE), isEmpty);
// Should not apply labels or make comments
- verifyNever(issuesService.addLabelsToIssue(
- slug,
- pr.number!,
- <String>[
- kGoldenFileLabel,
- ],
- ));
+ verifyNever(
+ issuesService.addLabelsToIssue(
+ slug,
+ pr.number!,
+ <String>[
+ kGoldenFileLabel,
+ ],
+ ),
+ );
- verifyNever(issuesService.createComment(
- slug,
- pr.number!,
- argThat(contains(config.flutterGoldCommentID(pr))),
- ));
+ verifyNever(
+ issuesService.createComment(
+ slug,
+ pr.number!,
+ argThat(contains(config.flutterGoldCommentID(pr))),
+ ),
+ );
});
test('same commit, checks complete, last status & gold status is running/awaiting triage, should not comment',
@@ -435,31 +460,39 @@
expect(records.where((LogRecord record) => record.level == Level.SEVERE), isEmpty);
// Should not apply labels or make comments
- verifyNever(issuesService.addLabelsToIssue(
- slug,
- pr.number!,
- <String>[
- kGoldenFileLabel,
- ],
- ));
- verifyNever(issuesService.addLabelsToIssue(
- engineSlug,
- enginePr.number!,
- <String>[
- kGoldenFileLabel,
- ],
- ));
+ verifyNever(
+ issuesService.addLabelsToIssue(
+ slug,
+ pr.number!,
+ <String>[
+ kGoldenFileLabel,
+ ],
+ ),
+ );
+ verifyNever(
+ issuesService.addLabelsToIssue(
+ engineSlug,
+ enginePr.number!,
+ <String>[
+ kGoldenFileLabel,
+ ],
+ ),
+ );
- verifyNever(issuesService.createComment(
- slug,
- pr.number!,
- argThat(contains(config.flutterGoldCommentID(pr))),
- ));
- verifyNever(issuesService.createComment(
- engineSlug,
- enginePr.number!,
- argThat(contains(config.flutterGoldCommentID(enginePr))),
- ));
+ verifyNever(
+ issuesService.createComment(
+ slug,
+ pr.number!,
+ argThat(contains(config.flutterGoldCommentID(pr))),
+ ),
+ );
+ verifyNever(
+ issuesService.createComment(
+ engineSlug,
+ enginePr.number!,
+ argThat(contains(config.flutterGoldCommentID(enginePr))),
+ ),
+ );
});
test('does nothing for branches not staged to land on main/master', () async {
@@ -481,19 +514,23 @@
expect(records.where((LogRecord record) => record.level == Level.SEVERE), isEmpty);
// Should not apply labels or make comments
- verifyNever(issuesService.addLabelsToIssue(
- slug,
- pr.number!,
- <String>[
- kGoldenFileLabel,
- ],
- ));
+ verifyNever(
+ issuesService.addLabelsToIssue(
+ slug,
+ pr.number!,
+ <String>[
+ kGoldenFileLabel,
+ ],
+ ),
+ );
- verifyNever(issuesService.createComment(
- slug,
- pr.number!,
- argThat(contains(config.flutterGoldCommentID(pr))),
- ));
+ verifyNever(
+ issuesService.createComment(
+ slug,
+ pr.number!,
+ argThat(contains(config.flutterGoldCommentID(pr))),
+ ),
+ );
});
test('does not post for draft PRs, does not query Gold', () async {
@@ -515,19 +552,23 @@
expect(records.where((LogRecord record) => record.level == Level.SEVERE), isEmpty);
// Should not apply labels or make comments
- verifyNever(issuesService.addLabelsToIssue(
- slug,
- pr.number!,
- <String>[
- kGoldenFileLabel,
- ],
- ));
+ verifyNever(
+ issuesService.addLabelsToIssue(
+ slug,
+ pr.number!,
+ <String>[
+ kGoldenFileLabel,
+ ],
+ ),
+ );
- verifyNever(issuesService.createComment(
- slug,
- pr.number!,
- any,
- ));
+ verifyNever(
+ issuesService.createComment(
+ slug,
+ pr.number!,
+ any,
+ ),
+ );
});
test('does not post for draft PRs, does not query Gold', () async {
@@ -549,19 +590,23 @@
expect(records.where((LogRecord record) => record.level == Level.SEVERE), isEmpty);
// Should not apply labels or make comments
- verifyNever(issuesService.addLabelsToIssue(
- slug,
- pr.number!,
- <String>[
- kGoldenFileLabel,
- ],
- ));
+ verifyNever(
+ issuesService.addLabelsToIssue(
+ slug,
+ pr.number!,
+ <String>[
+ kGoldenFileLabel,
+ ],
+ ),
+ );
- verifyNever(issuesService.createComment(
- slug,
- pr.number!,
- any,
- ));
+ verifyNever(
+ issuesService.createComment(
+ slug,
+ pr.number!,
+ any,
+ ),
+ );
});
test('does not post for stale PRs, does not query Gold, stale comment', () async {
@@ -591,19 +636,23 @@
expect(records.where((LogRecord record) => record.level == Level.SEVERE), isEmpty);
// Should not apply labels, should comment to update
- verifyNever(issuesService.addLabelsToIssue(
- slug,
- pr.number!,
- <String>[
- kGoldenFileLabel,
- ],
- ));
+ verifyNever(
+ issuesService.addLabelsToIssue(
+ slug,
+ pr.number!,
+ <String>[
+ kGoldenFileLabel,
+ ],
+ ),
+ );
- verify(issuesService.createComment(
- slug,
- pr.number!,
- argThat(contains(config.flutterGoldStalePRValue)),
- )).called(1);
+ verify(
+ issuesService.createComment(
+ slug,
+ pr.number!,
+ argThat(contains(config.flutterGoldStalePRValue)),
+ ),
+ ).called(1);
});
test('will only comment once on stale PRs', () async {
@@ -633,19 +682,23 @@
expect(records.where((LogRecord record) => record.level == Level.SEVERE), isEmpty);
// Should not apply labels or make comments
- verifyNever(issuesService.addLabelsToIssue(
- slug,
- pr.number!,
- <String>[
- kGoldenFileLabel,
- ],
- ));
+ verifyNever(
+ issuesService.addLabelsToIssue(
+ slug,
+ pr.number!,
+ <String>[
+ kGoldenFileLabel,
+ ],
+ ),
+ );
- verifyNever(issuesService.createComment(
- slug,
- pr.number!,
- any,
- ));
+ verifyNever(
+ issuesService.createComment(
+ slug,
+ pr.number!,
+ any,
+ ),
+ );
});
test('will not fire off stale warning for non-framework PRs', () async {
@@ -675,19 +728,23 @@
expect(records.where((LogRecord record) => record.level == Level.SEVERE), isEmpty);
// Should not apply labels or make comments
- verifyNever(issuesService.addLabelsToIssue(
- slug,
- pr.number!,
- <String>[
- kGoldenFileLabel,
- ],
- ));
+ verifyNever(
+ issuesService.addLabelsToIssue(
+ slug,
+ pr.number!,
+ <String>[
+ kGoldenFileLabel,
+ ],
+ ),
+ );
- verifyNever(issuesService.createComment(
- slug,
- pr.number!,
- any,
- ));
+ verifyNever(
+ issuesService.createComment(
+ slug,
+ pr.number!,
+ any,
+ ),
+ );
});
});
@@ -723,31 +780,39 @@
expect(records.where((LogRecord record) => record.level == Level.SEVERE), isEmpty);
// Should not apply labels or make comments
- verifyNever(issuesService.addLabelsToIssue(
- slug,
- flutterPr.number!,
- <String>[
- kGoldenFileLabel,
- ],
- ));
- verifyNever(issuesService.addLabelsToIssue(
- engineSlug,
- enginePr.number!,
- <String>[
- kGoldenFileLabel,
- ],
- ));
+ verifyNever(
+ issuesService.addLabelsToIssue(
+ slug,
+ flutterPr.number!,
+ <String>[
+ kGoldenFileLabel,
+ ],
+ ),
+ );
+ verifyNever(
+ issuesService.addLabelsToIssue(
+ engineSlug,
+ enginePr.number!,
+ <String>[
+ kGoldenFileLabel,
+ ],
+ ),
+ );
- verifyNever(issuesService.createComment(
- slug,
- flutterPr.number!,
- argThat(contains(config.flutterGoldCommentID(flutterPr))),
- ));
- verifyNever(issuesService.createComment(
- engineSlug,
- enginePr.number!,
- argThat(contains(config.flutterGoldCommentID(enginePr))),
- ));
+ verifyNever(
+ issuesService.createComment(
+ slug,
+ flutterPr.number!,
+ argThat(contains(config.flutterGoldCommentID(flutterPr))),
+ ),
+ );
+ verifyNever(
+ issuesService.createComment(
+ engineSlug,
+ enginePr.number!,
+ argThat(contains(config.flutterGoldCommentID(enginePr))),
+ ),
+ );
});
test('new commit, checks complete, no changes detected', () async {
@@ -792,19 +857,23 @@
expect(records.where((LogRecord record) => record.level == Level.SEVERE), isEmpty);
// Should not label or comment
- verifyNever(issuesService.addLabelsToIssue(
- slug,
- pr.number!,
- <String>[
- kGoldenFileLabel,
- ],
- ));
+ verifyNever(
+ issuesService.addLabelsToIssue(
+ slug,
+ pr.number!,
+ <String>[
+ kGoldenFileLabel,
+ ],
+ ),
+ );
- verifyNever(issuesService.createComment(
- slug,
- pr.number!,
- argThat(contains(config.flutterGoldCommentID(pr))),
- ));
+ verifyNever(
+ issuesService.createComment(
+ slug,
+ pr.number!,
+ argThat(contains(config.flutterGoldCommentID(pr))),
+ ),
+ );
});
test('new commit, checks complete, change detected, should comment', () async {
@@ -856,19 +925,23 @@
expect(records.where((LogRecord record) => record.level == Level.SEVERE), isEmpty);
// Should label and comment
- verify(issuesService.addLabelsToIssue(
- slug,
- pr.number!,
- <String>[
- kGoldenFileLabel,
- ],
- )).called(1);
+ verify(
+ issuesService.addLabelsToIssue(
+ slug,
+ pr.number!,
+ <String>[
+ kGoldenFileLabel,
+ ],
+ ),
+ ).called(1);
- verify(issuesService.createComment(
- slug,
- pr.number!,
- argThat(contains(config.flutterGoldCommentID(pr))),
- )).called(1);
+ verify(
+ issuesService.createComment(
+ slug,
+ pr.number!,
+ argThat(contains(config.flutterGoldCommentID(pr))),
+ ),
+ ).called(1);
});
test('same commit, checks complete, last status was waiting & gold status is needing triage, should comment',
@@ -921,19 +994,23 @@
expect(records.where((LogRecord record) => record.level == Level.SEVERE), isEmpty);
// Should apply labels and make comment
- verify(issuesService.addLabelsToIssue(
- slug,
- pr.number!,
- <String>[
- kGoldenFileLabel,
- ],
- )).called(1);
+ verify(
+ issuesService.addLabelsToIssue(
+ slug,
+ pr.number!,
+ <String>[
+ kGoldenFileLabel,
+ ],
+ ),
+ ).called(1);
- verify(issuesService.createComment(
- slug,
- pr.number!,
- argThat(contains(config.flutterGoldCommentID(pr))),
- )).called(1);
+ verify(
+ issuesService.createComment(
+ slug,
+ pr.number!,
+ argThat(contains(config.flutterGoldCommentID(pr))),
+ ),
+ ).called(1);
});
test('uses shorter comment after first comment to reduce noise', () async {
@@ -985,29 +1062,37 @@
expect(records.where((LogRecord record) => record.level == Level.SEVERE), isEmpty);
// Should apply labels and make comment
- verify(issuesService.addLabelsToIssue(
- slug,
- pr.number!,
- <String>[
- kGoldenFileLabel,
- ],
- )).called(1);
+ verify(
+ issuesService.addLabelsToIssue(
+ slug,
+ pr.number!,
+ <String>[
+ kGoldenFileLabel,
+ ],
+ ),
+ ).called(1);
- verify(issuesService.createComment(
- slug,
- pr.number!,
- argThat(contains(config.flutterGoldFollowUpAlertValue)),
- )).called(1);
- verifyNever(issuesService.createComment(
- slug,
- pr.number!,
- argThat(contains(config.flutterGoldInitialAlertValue)),
- ));
- verifyNever(issuesService.createComment(
- slug,
- pr.number!,
- argThat(contains(config.flutterGoldAlertConstantValue)),
- ));
+ verify(
+ issuesService.createComment(
+ slug,
+ pr.number!,
+ argThat(contains(config.flutterGoldFollowUpAlertValue)),
+ ),
+ ).called(1);
+ verifyNever(
+ issuesService.createComment(
+ slug,
+ pr.number!,
+ argThat(contains(config.flutterGoldInitialAlertValue)),
+ ),
+ );
+ verifyNever(
+ issuesService.createComment(
+ slug,
+ pr.number!,
+ argThat(contains(config.flutterGoldAlertConstantValue)),
+ ),
+ );
});
test('same commit, checks complete, new status, should not comment', () async {
@@ -1059,19 +1144,23 @@
expect(records.where((LogRecord record) => record.level == Level.SEVERE), isEmpty);
// Should not label or comment
- verifyNever(issuesService.addLabelsToIssue(
- slug,
- pr.number!,
- <String>[
- kGoldenFileLabel,
- ],
- ));
+ verifyNever(
+ issuesService.addLabelsToIssue(
+ slug,
+ pr.number!,
+ <String>[
+ kGoldenFileLabel,
+ ],
+ ),
+ );
- verifyNever(issuesService.createComment(
- slug,
- pr.number!,
- argThat(contains(config.flutterGoldCommentID(pr))),
- ));
+ verifyNever(
+ issuesService.createComment(
+ slug,
+ pr.number!,
+ argThat(contains(config.flutterGoldCommentID(pr))),
+ ),
+ );
});
test('will inform contributor of unresolved check for ATF draft status', () async {
@@ -1099,19 +1188,23 @@
expect(records.where((LogRecord record) => record.level == Level.SEVERE), isEmpty);
// Should not apply labels or make comments
- verifyNever(issuesService.addLabelsToIssue(
- slug,
- pr.number!,
- <String>[
- kGoldenFileLabel,
- ],
- ));
+ verifyNever(
+ issuesService.addLabelsToIssue(
+ slug,
+ pr.number!,
+ <String>[
+ kGoldenFileLabel,
+ ],
+ ),
+ );
- verify(issuesService.createComment(
- slug,
- pr.number!,
- argThat(contains(config.flutterGoldDraftChangeValue)),
- )).called(1);
+ verify(
+ issuesService.createComment(
+ slug,
+ pr.number!,
+ argThat(contains(config.flutterGoldDraftChangeValue)),
+ ),
+ ).called(1);
});
test('will only inform contributor of unresolved check for ATF draft status once', () async {
@@ -1139,19 +1232,23 @@
expect(records.where((LogRecord record) => record.level == Level.SEVERE), isEmpty);
// Should not apply labels or make comments
- verifyNever(issuesService.addLabelsToIssue(
- slug,
- pr.number!,
- <String>[
- kGoldenFileLabel,
- ],
- ));
+ verifyNever(
+ issuesService.addLabelsToIssue(
+ slug,
+ pr.number!,
+ <String>[
+ kGoldenFileLabel,
+ ],
+ ),
+ );
- verifyNever(issuesService.createComment(
- slug,
- pr.number!,
- argThat(contains(config.flutterGoldDraftChangeValue)),
- ));
+ verifyNever(
+ issuesService.createComment(
+ slug,
+ pr.number!,
+ argThat(contains(config.flutterGoldDraftChangeValue)),
+ ),
+ );
});
test('delivers pending state for failing checks, does not query Gold', () async {
@@ -1174,19 +1271,23 @@
expect(records.where((LogRecord record) => record.level == Level.SEVERE), isEmpty);
// Should not apply labels or make comments
- verifyNever(issuesService.addLabelsToIssue(
- slug,
- pr.number!,
- <String>[
- kGoldenFileLabel,
- ],
- ));
+ verifyNever(
+ issuesService.addLabelsToIssue(
+ slug,
+ pr.number!,
+ <String>[
+ kGoldenFileLabel,
+ ],
+ ),
+ );
- verifyNever(issuesService.createComment(
- slug,
- pr.number!,
- argThat(contains(config.flutterGoldCommentID(pr))),
- ));
+ verifyNever(
+ issuesService.createComment(
+ slug,
+ pr.number!,
+ argThat(contains(config.flutterGoldCommentID(pr))),
+ ),
+ );
});
});
@@ -1198,7 +1299,12 @@
followUpPR,
];
final GithubGoldStatusUpdate completedStatus = newStatusUpdate(
- slug, completedPR, GithubGoldStatusUpdate.statusCompleted, 'abc', config.flutterGoldSuccessValue!);
+ slug,
+ completedPR,
+ GithubGoldStatusUpdate.statusCompleted,
+ 'abc',
+ config.flutterGoldSuccessValue!,
+ );
final GithubGoldStatusUpdate followUpStatus = newStatusUpdate(slug, followUpPR, '', '', '');
db.values[completedStatus.key] = completedStatus;
db.values[followUpStatus.key] = followUpStatus;
@@ -1279,19 +1385,23 @@
expect(records.where((LogRecord record) => record.level == Level.SEVERE), isEmpty);
// Should not apply labels or make comments
- verifyNever(issuesService.addLabelsToIssue(
- slug,
- pr.number!,
- <String>[
- kGoldenFileLabel,
- ],
- ));
+ verifyNever(
+ issuesService.addLabelsToIssue(
+ slug,
+ pr.number!,
+ <String>[
+ kGoldenFileLabel,
+ ],
+ ),
+ );
- verifyNever(issuesService.createComment(
- slug,
- pr.number!,
- argThat(contains(config.flutterGoldCommentID(pr))),
- ));
+ verifyNever(
+ issuesService.createComment(
+ slug,
+ pr.number!,
+ argThat(contains(config.flutterGoldCommentID(pr))),
+ ),
+ );
});
test('uses the correct Gold endpoint to get status', () async {
diff --git a/app_dart/test/request_handlers/refresh_cirrus_status_test.dart b/app_dart/test/request_handlers/refresh_cirrus_status_test.dart
index fab6ebc..a4dbc7c 100644
--- a/app_dart/test/request_handlers/refresh_cirrus_status_test.dart
+++ b/app_dart/test/request_handlers/refresh_cirrus_status_test.dart
@@ -8,7 +8,7 @@
void main() {
group('RefreshCirrusStatus', () {
Map<String, dynamic>? data;
- List<Map<String, dynamic>> tasks = <Map<String, dynamic>>[];
+ final List<Map<String, dynamic>> tasks = <Map<String, dynamic>>[];
setUp(() {
data = dataWithMultipleBuilds;
});
diff --git a/app_dart/test/request_handlers/reset_prod_task_test.dart b/app_dart/test/request_handlers/reset_prod_task_test.dart
index 12737ec..f49830e 100644
--- a/app_dart/test/request_handlers/reset_prod_task_test.dart
+++ b/app_dart/test/request_handlers/reset_prod_task_test.dart
@@ -64,14 +64,16 @@
'Key': config.keyHelper.encode(task.key),
};
- when(mockLuciBuildService.checkRerunBuilder(
- commit: anyNamed('commit'),
- datastore: anyNamed('datastore'),
- task: anyNamed('task'),
- target: anyNamed('target'),
- tags: anyNamed('tags'),
- ignoreChecks: true,
- )).thenAnswer((_) async => true);
+ when(
+ mockLuciBuildService.checkRerunBuilder(
+ commit: anyNamed('commit'),
+ datastore: anyNamed('datastore'),
+ task: anyNamed('task'),
+ target: anyNamed('target'),
+ tags: anyNamed('tags'),
+ ignoreChecks: true,
+ ),
+ ).thenAnswer((_) async => true);
});
test('Schedule new task', () async {
config.db.values[task.key] = task;
@@ -108,14 +110,16 @@
});
test('Fails if task is not rerun', () async {
- when(mockLuciBuildService.checkRerunBuilder(
- commit: anyNamed('commit'),
- datastore: anyNamed('datastore'),
- task: anyNamed('task'),
- target: anyNamed('target'),
- tags: anyNamed('tags'),
- ignoreChecks: true,
- )).thenAnswer((_) async => false);
+ when(
+ mockLuciBuildService.checkRerunBuilder(
+ commit: anyNamed('commit'),
+ datastore: anyNamed('datastore'),
+ task: anyNamed('task'),
+ target: anyNamed('target'),
+ tags: anyNamed('tags'),
+ ignoreChecks: true,
+ ),
+ ).thenAnswer((_) async => false);
config.db.values[task.key] = task;
config.db.values[commit.key] = commit;
expect(() => tester.post(handler), throwsA(isA<InternalServerError>()));
diff --git a/app_dart/test/request_handlers/reset_try_task_test.dart b/app_dart/test/request_handlers/reset_try_task_test.dart
index 5b5a4da..5a6adbf 100644
--- a/app_dart/test/request_handlers/reset_try_task_test.dart
+++ b/app_dart/test/request_handlers/reset_try_task_test.dart
@@ -53,16 +53,20 @@
});
test('Empty repo', () async {
- tester.request = FakeHttpRequest(queryParametersValue: <String, String>{
- 'pr': '123',
- });
+ tester.request = FakeHttpRequest(
+ queryParametersValue: <String, String>{
+ 'pr': '123',
+ },
+ );
expect(() => tester.get(handler), throwsA(isA<BadRequestException>()));
});
test('Empty pr', () async {
- tester.request = FakeHttpRequest(queryParametersValue: <String, String>{
- 'repo': 'flutter',
- });
+ tester.request = FakeHttpRequest(
+ queryParametersValue: <String, String>{
+ 'repo': 'flutter',
+ },
+ );
expect(() => tester.get(handler), throwsA(isA<BadRequestException>()));
});
@@ -74,10 +78,12 @@
'check_suite': <String, dynamic>{'id': 2},
});
});
- tester.request = FakeHttpRequest(queryParametersValue: <String, String>{
- ResetTryTask.kRepoParam: 'flutter',
- ResetTryTask.kPullRequestNumberParam: '123',
- });
+ tester.request = FakeHttpRequest(
+ queryParametersValue: <String, String>{
+ ResetTryTask.kRepoParam: 'flutter',
+ ResetTryTask.kPullRequestNumberParam: '123',
+ },
+ );
expect(await tester.get(handler), Body.empty);
});
diff --git a/app_dart/test/request_handlers/scheduler/batch_backfiller_test.dart b/app_dart/test/request_handlers/scheduler/batch_backfiller_test.dart
index cb77181..dfc70ec 100644
--- a/app_dart/test/request_handlers/scheduler/batch_backfiller_test.dart
+++ b/app_dart/test/request_handlers/scheduler/batch_backfiller_test.dart
@@ -50,7 +50,7 @@
});
test('does not backfill on completed task column', () async {
- List<Task> allGreen = <Task>[
+ final List<Task> allGreen = <Task>[
generateTask(1, name: 'Linux_android A', status: Task.statusSucceeded),
generateTask(2, name: 'Linux_android A', status: Task.statusSucceeded),
generateTask(3, name: 'Linux_android A', status: Task.statusSucceeded),
@@ -61,7 +61,7 @@
});
test('does not backfill when there is a running task', () async {
- List<Task> middleTaskInProgress = <Task>[
+ final List<Task> middleTaskInProgress = <Task>[
generateTask(1, name: 'Linux_android A', status: Task.statusNew),
generateTask(2, name: 'Linux_android A', status: Task.statusInProgress),
generateTask(3, name: 'Linux_android A', status: Task.statusNew),
@@ -72,7 +72,7 @@
});
test('backfills latest task', () async {
- List<Task> allGray = <Task>[
+ final List<Task> allGray = <Task>[
generateTask(1, name: 'Linux_android A', status: Task.statusNew),
generateTask(2, name: 'Linux_android A', status: Task.statusNew),
generateTask(3, name: 'Linux_android A', status: Task.statusNew),
@@ -86,7 +86,7 @@
});
test('backfills earlier failed task with higher priority', () async {
- List<Task> allGray = <Task>[
+ final List<Task> allGray = <Task>[
generateTask(1, name: 'Linux_android A', status: Task.statusNew),
generateTask(2, name: 'Linux_android A', status: Task.statusNew),
generateTask(3, name: 'Linux_android A', status: Task.statusFailed),
@@ -100,7 +100,7 @@
});
test('backfills older task', () async {
- List<Task> oldestGray = <Task>[
+ final List<Task> oldestGray = <Task>[
generateTask(1, name: 'Linux_android A', status: Task.statusSucceeded),
generateTask(2, name: 'Linux_android A', status: Task.statusSucceeded),
generateTask(3, name: 'Linux_android A', status: Task.statusNew),
@@ -111,7 +111,7 @@
});
test('updates task as in-progress after backfilling', () async {
- List<Task> oldestGray = <Task>[
+ final List<Task> oldestGray = <Task>[
generateTask(1, name: 'Linux_android A', status: Task.statusSucceeded),
generateTask(2, name: 'Linux_android A', status: Task.statusSucceeded),
generateTask(3, name: 'Linux_android A', status: Task.statusNew),
@@ -127,7 +127,7 @@
test('skip scheduling builds if datastore commit fails', () async {
db.commitException = true;
- List<Task> oldestGray = <Task>[
+ final List<Task> oldestGray = <Task>[
generateTask(1, name: 'Linux_android A', status: Task.statusSucceeded),
generateTask(2, name: 'Linux_android A', status: Task.statusSucceeded),
generateTask(3, name: 'Linux_android A', status: Task.statusNew),
@@ -140,7 +140,7 @@
});
test('backfills only column A when B does need backfill', () async {
- List<Task> scheduleA = <Task>[
+ final List<Task> scheduleA = <Task>[
// Linux_android A
generateTask(1, name: 'Linux_android A', status: Task.statusSucceeded),
generateTask(2, name: 'Linux_android A', status: Task.statusSucceeded),
@@ -156,7 +156,7 @@
});
test('backfills both column A and B', () async {
- List<Task> scheduleA = <Task>[
+ final List<Task> scheduleA = <Task>[
// Linux_android A
generateTask(1, name: 'Linux_android A', status: Task.statusSucceeded),
generateTask(2, name: 'Linux_android A', status: Task.statusSucceeded),
diff --git a/app_dart/test/request_handlers/scheduler/request_subscription_test.dart b/app_dart/test/request_handlers/scheduler/request_subscription_test.dart
index 17bee33..0428343 100644
--- a/app_dart/test/request_handlers/scheduler/request_subscription_test.dart
+++ b/app_dart/test/request_handlers/scheduler/request_subscription_test.dart
@@ -73,15 +73,17 @@
return const BatchResponse();
});
- const BatchRequest request = BatchRequest(requests: <Request>[
- Request(
- scheduleBuild: ScheduleBuildRequest(
- builderId: BuilderId(
- builder: 'Linux A',
+ const BatchRequest request = BatchRequest(
+ requests: <Request>[
+ Request(
+ scheduleBuild: ScheduleBuildRequest(
+ builderId: BuilderId(
+ builder: 'Linux A',
+ ),
),
),
- ),
- ]);
+ ],
+ );
tester.message = push_message.PushMessage(data: base64Encode(utf8.encode(jsonEncode(request))));
final Body body = await tester.post(handler);
expect(body, Body.empty);
@@ -92,15 +94,17 @@
when(buildBucketClient.batch(any)).thenAnswer((_) async {
return const BatchResponse();
});
- const BatchRequest request = BatchRequest(requests: <Request>[
- Request(
- scheduleBuild: ScheduleBuildRequest(
- builderId: BuilderId(
- builder: 'Linux A',
+ const BatchRequest request = BatchRequest(
+ requests: <Request>[
+ Request(
+ scheduleBuild: ScheduleBuildRequest(
+ builderId: BuilderId(
+ builder: 'Linux A',
+ ),
),
),
- ),
- ]);
+ ],
+ );
tester.message = push_message.PushMessage(data: base64Encode(utf8.encode(jsonEncode(request))));
final Body body = await tester.post(handler);
expect(body, isNotNull);
diff --git a/app_dart/test/request_handlers/update_branches_test.dart b/app_dart/test/request_handlers/update_branches_test.dart
index 5d39909..8a9d6ed 100644
--- a/app_dart/test/request_handlers/update_branches_test.dart
+++ b/app_dart/test/request_handlers/update_branches_test.dart
@@ -33,7 +33,7 @@
late MockRepositoriesService mockRepositoriesService;
final MockProcessManager processManager = MockProcessManager();
- String stdoutResult = '72fe8a9ec3af4d76097f09a9c01bf31c62a942aa refs/heads/main';
+ const String stdoutResult = '72fe8a9ec3af4d76097f09a9c01bf31c62a942aa refs/heads/main';
const String testBranchSha = '72fe8a9ec3af4d76097f09a9c01bf31c62a942aa';
Future<T?> decodeHandlerBody<T>() async {
@@ -61,7 +61,7 @@
);
const String id = 'flutter/flutter/main';
- int lastActivity = DateTime.tryParse("2019-05-15T15:20:56Z")!.millisecondsSinceEpoch;
+ final int lastActivity = DateTime.tryParse("2019-05-15T15:20:56Z")!.millisecondsSinceEpoch;
final Key<String> branchKey = db.emptyKey.append<String>(Branch, id: id);
final Branch currentBranch = Branch(
key: branchKey,
@@ -73,14 +73,18 @@
test('should not retrieve branches older than 2 months', () async {
expect(db.values.values.whereType<Branch>().length, 1);
when(mockRepositoriesService.getCommit(any, any)).thenAnswer((Invocation invocation) {
- return Future<RepositoryCommit>.value(RepositoryCommit(
+ return Future<RepositoryCommit>.value(
+ RepositoryCommit(
sha: testBranchSha,
commit: GitCommit(
- committer: GitCommitUser(
- 'dash',
- 'dash@google.com',
- DateTime.now().subtract(const Duration(days: 90)),
- ))));
+ committer: GitCommitUser(
+ 'dash',
+ 'dash@google.com',
+ DateTime.now().subtract(const Duration(days: 90)),
+ ),
+ ),
+ ),
+ );
});
final List<dynamic> result = (await decodeHandlerBody())!;
@@ -92,18 +96,22 @@
// a recent commit is added for each of the 6 repos
when(mockRepositoriesService.getCommit(any, any)).thenAnswer((Invocation invocation) {
- return Future<RepositoryCommit>.value(RepositoryCommit(
+ return Future<RepositoryCommit>.value(
+ RepositoryCommit(
sha: testBranchSha,
commit: GitCommit(
- committer: GitCommitUser(
- 'dash',
- 'dash@google.com',
- DateTime.now(),
- ))));
+ committer: GitCommitUser(
+ 'dash',
+ 'dash@google.com',
+ DateTime.now(),
+ ),
+ ),
+ ),
+ );
});
final List<dynamic> result = (await decodeHandlerBody())!;
- List<String> repos = [];
+ final List<String> repos = [];
for (dynamic k in result) {
repos.add('${k['branch']['repository']}/${k['branch']['branch']}');
}
@@ -116,14 +124,18 @@
expect(db.values.values.whereType<Branch>().length, 1);
when(mockRepositoriesService.getCommit(any, any)).thenAnswer((Invocation invocation) {
- return Future<RepositoryCommit>.value(RepositoryCommit(
+ return Future<RepositoryCommit>.value(
+ RepositoryCommit(
sha: testBranchSha,
commit: GitCommit(
- committer: GitCommitUser(
- 'dash',
- 'dash@google.com',
- DateTime.tryParse('2020-05-15T15:20:56Z'),
- ))));
+ committer: GitCommitUser(
+ 'dash',
+ 'dash@google.com',
+ DateTime.tryParse('2020-05-15T15:20:56Z'),
+ ),
+ ),
+ ),
+ );
});
final List<dynamic> result = (await decodeHandlerBody())!;
@@ -135,14 +147,18 @@
when(processManager.runSync(any)).thenAnswer((Invocation invocation) => ProcessResult(1, -1, stdoutResult, ''));
when(mockRepositoriesService.getCommit(any, any)).thenAnswer((Invocation invocation) {
- return Future<RepositoryCommit>.value(RepositoryCommit(
+ return Future<RepositoryCommit>.value(
+ RepositoryCommit(
sha: testBranchSha,
commit: GitCommit(
- committer: GitCommitUser(
- 'dash',
- 'dash@google.com',
- DateTime.tryParse('2020-05-15T15:20:56Z'),
- ))));
+ committer: GitCommitUser(
+ 'dash',
+ 'dash@google.com',
+ DateTime.tryParse('2020-05-15T15:20:56Z'),
+ ),
+ ),
+ ),
+ );
});
expect(() => decodeHandlerBody<List<dynamic>>(), throwsA(const TypeMatcher<FormatException>()));
diff --git a/app_dart/test/request_handlers/update_existing_flaky_issues_test.dart b/app_dart/test/request_handlers/update_existing_flaky_issues_test.dart
index d8267e7..1a3f395 100644
--- a/app_dart/test/request_handlers/update_existing_flaky_issues_test.dart
+++ b/app_dart/test/request_handlers/update_existing_flaky_issues_test.dart
@@ -57,12 +57,15 @@
});
// when gets the content of TESTOWNERS
- when(mockRepositoriesService.getContents(
- captureAny,
- kTestOwnerPath,
- )).thenAnswer((Invocation invocation) {
+ when(
+ mockRepositoriesService.getContents(
+ captureAny,
+ kTestOwnerPath,
+ ),
+ ).thenAnswer((Invocation invocation) {
return Future<RepositoryContents>.value(
- RepositoryContents(file: GitHubFile(content: gitHubEncode(testOwnersContent))));
+ RepositoryContents(file: GitHubFile(content: gitHubEncode(testOwnersContent))),
+ );
});
when(mockGitHubClient.repositories).thenReturn(mockRepositoriesService);
@@ -115,11 +118,13 @@
});
// when firing github request.
// This is for replacing labels.
- when(mockGitHubClient.request(
- captureAny,
- captureAny,
- body: captureAnyNamed('body'),
- )).thenAnswer((Invocation invocation) {
+ when(
+ mockGitHubClient.request(
+ captureAny,
+ captureAny,
+ body: captureAnyNamed('body'),
+ ),
+ ).thenAnswer((Invocation invocation) {
return Future<Response>.value(Response('[]', 200));
});
final Map<String, dynamic> result = await utf8.decoder
@@ -135,11 +140,13 @@
expect(captured[2], expectedSemanticsIntegrationTestIssueComment);
// Verify labels are applied correctly.
- captured = verify(mockGitHubClient.request(
- captureAny,
- captureAny,
- body: captureAnyNamed('body'),
- )).captured;
+ captured = verify(
+ mockGitHubClient.request(
+ captureAny,
+ captureAny,
+ body: captureAnyNamed('body'),
+ ),
+ ).captured;
expect(captured.length, 3);
expect(captured[0].toString(), 'PUT');
expect(captured[1], '/repos/${Config.flutterSlug.fullName}/issues/$existingIssueNumber/labels');
@@ -180,11 +187,13 @@
});
// when firing github request.
// This is for replacing labels.
- when(mockGitHubClient.request(
- captureAny,
- captureAny,
- body: captureAnyNamed('body'),
- )).thenAnswer((Invocation invocation) {
+ when(
+ mockGitHubClient.request(
+ captureAny,
+ captureAny,
+ body: captureAnyNamed('body'),
+ ),
+ ).thenAnswer((Invocation invocation) {
return Future<Response>.value(Response('[]', 200));
});
final Map<String, dynamic> result = await utf8.decoder
@@ -200,11 +209,13 @@
expect(captured[2], expectedSemanticsIntegrationTestIssueComment);
// Verify labels are applied correctly.
- captured = verify(mockGitHubClient.request(
- captureAny,
- captureAny,
- body: captureAnyNamed('body'),
- )).captured;
+ captured = verify(
+ mockGitHubClient.request(
+ captureAny,
+ captureAny,
+ body: captureAnyNamed('body'),
+ ),
+ ).captured;
expect(captured.length, 3);
expect(captured[0].toString(), 'PUT');
expect(captured[1], '/repos/${Config.flutterSlug.fullName}/issues/$existingIssueNumber/labels');
@@ -245,11 +256,13 @@
});
// when firing github request.
// This is for replacing labels.
- when(mockGitHubClient.request(
- captureAny,
- captureAny,
- body: captureAnyNamed('body'),
- )).thenAnswer((Invocation invocation) {
+ when(
+ mockGitHubClient.request(
+ captureAny,
+ captureAny,
+ body: captureAnyNamed('body'),
+ ),
+ ).thenAnswer((Invocation invocation) {
return Future<Response>.value(Response('[]', 200));
});
final Map<String, dynamic> result = await utf8.decoder
@@ -268,11 +281,13 @@
expect(captured[5], expectedStagingCiyamlTestIssueComment);
// Verify labels are applied correctly.
- captured = verify(mockGitHubClient.request(
- captureAny,
- captureAny,
- body: captureAnyNamed('body'),
- )).captured;
+ captured = verify(
+ mockGitHubClient.request(
+ captureAny,
+ captureAny,
+ body: captureAnyNamed('body'),
+ ),
+ ).captured;
expect(captured.length, 6);
expect(captured[0].toString(), 'PUT');
expect(captured[1], '/repos/${Config.flutterSlug.fullName}/issues/$existingIssueNumber/labels');
@@ -312,11 +327,13 @@
});
// when firing github request.
// This is for replacing labels.
- when(mockGitHubClient.request(
- captureAny,
- captureAny,
- body: captureAnyNamed('body'),
- )).thenAnswer((Invocation invocation) {
+ when(
+ mockGitHubClient.request(
+ captureAny,
+ captureAny,
+ body: captureAnyNamed('body'),
+ ),
+ ).thenAnswer((Invocation invocation) {
return Future<Response>.value(Response('[]', 200));
});
@@ -367,11 +384,13 @@
});
// when firing github request.
// This is for replacing labels.
- when(mockGitHubClient.request(
- captureAny,
- captureAny,
- body: captureAnyNamed('body'),
- )).thenAnswer((Invocation invocation) {
+ when(
+ mockGitHubClient.request(
+ captureAny,
+ captureAny,
+ body: captureAnyNamed('body'),
+ ),
+ ).thenAnswer((Invocation invocation) {
return Future<Response>.value(Response('[]', 200));
});
@@ -388,11 +407,13 @@
expect(captured[2], expectedSemanticsIntegrationTestZeroFlakeIssueComment);
// Verify labels are the same.
- captured = verify(mockGitHubClient.request(
- captureAny,
- captureAny,
- body: captureAnyNamed('body'),
- )).captured;
+ captured = verify(
+ mockGitHubClient.request(
+ captureAny,
+ captureAny,
+ body: captureAnyNamed('body'),
+ ),
+ ).captured;
expect(captured.length, 3);
expect(captured[0].toString(), 'PUT');
expect(captured[1], '/repos/${Config.flutterSlug.fullName}/issues/$existingIssueNumber/labels');
@@ -439,11 +460,13 @@
verifyNever(mockIssuesService.createComment(captureAny, captureAny, captureAny));
// Verify labels are the same.
- verifyNever(mockGitHubClient.request(
- captureAny,
- captureAny,
- body: captureAnyNamed('body'),
- ));
+ verifyNever(
+ mockGitHubClient.request(
+ captureAny,
+ captureAny,
+ body: captureAnyNamed('body'),
+ ),
+ );
expect(result['Status'], 'success');
});
diff --git a/app_dart/test/request_handlers/update_existing_flaky_issues_test_data.dart b/app_dart/test/request_handlers/update_existing_flaky_issues_test_data.dart
index 5b3c821..d8e8446 100644
--- a/app_dart/test/request_handlers/update_existing_flaky_issues_test_data.dart
+++ b/app_dart/test/request_handlers/update_existing_flaky_issues_test_data.dart
@@ -224,13 +224,14 @@
},
),
pb.Target(
- name: 'Mac_android ignore_myflakiness',
- scheduler: pb.SchedulerSystem.luci,
- presubmit: false,
- properties: <String, String>{
- 'ignore_flakiness': 'true',
- 'tags': jsonEncode(['devicelab']),
- }),
+ name: 'Mac_android ignore_myflakiness',
+ scheduler: pb.SchedulerSystem.luci,
+ presubmit: false,
+ properties: <String, String>{
+ 'ignore_flakiness': 'true',
+ 'tags': jsonEncode(['devicelab']),
+ },
+ ),
pb.Target(
name: 'Linux ci_yaml flutter roller',
scheduler: pb.SchedulerSystem.luci,
diff --git a/app_dart/test/request_handlers/vacuum_github_commits_test.dart b/app_dart/test/request_handlers/vacuum_github_commits_test.dart
index 2cc308c..06f556c 100644
--- a/app_dart/test/request_handlers/vacuum_github_commits_test.dart
+++ b/app_dart/test/request_handlers/vacuum_github_commits_test.dart
@@ -45,21 +45,24 @@
final GitCommit gitCommit = GitCommit()
..message = 'commit message'
..committer = committer;
- commits.add(RepositoryCommit()
- ..sha = sha
- ..author = author
- ..commit = gitCommit);
+ commits.add(
+ RepositoryCommit()
+ ..sha = sha
+ ..author = author
+ ..commit = gitCommit,
+ );
}
return commits;
}
Commit shaToCommit(String sha, String branch, RepositorySlug slug) {
return Commit(
- key: db.emptyKey.append(Commit, id: '${slug.fullName}/$branch/$sha'),
- repository: slug.fullName,
- sha: sha,
- branch: branch,
- timestamp: int.parse(sha));
+ key: db.emptyKey.append(Commit, id: '${slug.fullName}/$branch/$sha'),
+ repository: slug.fullName,
+ sha: sha,
+ branch: branch,
+ timestamp: int.parse(sha),
+ );
}
setUp(() {
diff --git a/app_dart/test/request_handling/api_request_handler_test.dart b/app_dart/test/request_handling/api_request_handler_test.dart
index a5a76ef..fc5dcf3 100644
--- a/app_dart/test/request_handling/api_request_handler_test.dart
+++ b/app_dart/test/request_handling/api_request_handler_test.dart
@@ -31,12 +31,15 @@
log.fine(line);
},
);
- runZoned<dynamic>(() {
- return ss.fork(() {
- ss.register(#appengine.logging, log);
- return handler.service(request);
- });
- }, zoneSpecification: spec);
+ runZoned<dynamic>(
+ () {
+ return ss.fork(() {
+ ss.register(#appengine.logging, log);
+ return handler.service(request);
+ });
+ },
+ zoneSpecification: spec,
+ );
});
});
diff --git a/app_dart/test/request_handling/authentication_test.dart b/app_dart/test/request_handling/authentication_test.dart
index 5b0a932..20a375f 100644
--- a/app_dart/test/request_handling/authentication_test.dart
+++ b/app_dart/test/request_handling/authentication_test.dart
@@ -77,11 +77,12 @@
config.oauthClientIdValue = 'client-id';
request.headers.add('X-Flutter-IdToken', 'authenticated');
await expectLater(
- auth.authenticateToken(
- token,
- clientContext: FakeClientContext(),
- ),
- throwsA(isA<Unauthenticated>()));
+ auth.authenticateToken(
+ token,
+ clientContext: FakeClientContext(),
+ ),
+ throwsA(isA<Unauthenticated>()),
+ );
});
test('fails if tokenInfo returns invalid JSON', () async {
@@ -100,11 +101,12 @@
);
config.oauthClientIdValue = 'expected-client-id';
await expectLater(
- auth.authenticateToken(
- token,
- clientContext: FakeClientContext(),
- ),
- throwsA(isA<Unauthenticated>()));
+ auth.authenticateToken(
+ token,
+ clientContext: FakeClientContext(),
+ ),
+ throwsA(isA<Unauthenticated>()),
+ );
});
test('allows different aud for gcloud tokens with google accounts', () async {
@@ -115,11 +117,12 @@
);
config.oauthClientIdValue = 'expected-client-id';
await expectLater(
- auth.authenticateToken(
- token,
- clientContext: FakeClientContext(),
- ),
- throwsA(isA<Unauthenticated>()));
+ auth.authenticateToken(
+ token,
+ clientContext: FakeClientContext(),
+ ),
+ throwsA(isA<Unauthenticated>()),
+ );
});
test('succeeds for google.com auth user', () async {
@@ -142,11 +145,12 @@
TokenInfo(audience: 'client-id', hostedDomain: 'gmail.com', email: 'abc@gmail.com', issued: DateTime.now());
config.oauthClientIdValue = 'client-id';
await expectLater(
- auth.authenticateToken(
- token,
- clientContext: FakeClientContext(),
- ),
- throwsA(isA<Unauthenticated>()));
+ auth.authenticateToken(
+ token,
+ clientContext: FakeClientContext(),
+ ),
+ throwsA(isA<Unauthenticated>()),
+ );
});
test('succeeds for allowed non-Google auth users', () async {
diff --git a/app_dart/test/request_handling/cache_request_handler_test.dart b/app_dart/test/request_handling/cache_request_handler_test.dart
index 9936755..35484ae 100644
--- a/app_dart/test/request_handling/cache_request_handler_test.dart
+++ b/app_dart/test/request_handling/cache_request_handler_test.dart
@@ -27,9 +27,10 @@
setUp(() async {
config = FakeConfig();
tester = RequestHandlerTester(
- request: FakeHttpRequest(
- path: testHttpPath,
- ));
+ request: FakeHttpRequest(
+ path: testHttpPath,
+ ),
+ );
cache = CacheService(inMemory: true);
});
diff --git a/app_dart/test/request_handling/pubsub_authentication_test.dart b/app_dart/test/request_handling/pubsub_authentication_test.dart
index f7d5174..ba1170a 100644
--- a/app_dart/test/request_handling/pubsub_authentication_test.dart
+++ b/app_dart/test/request_handling/pubsub_authentication_test.dart
@@ -37,13 +37,15 @@
for (String allowedAccount in Config.allowedPubsubServiceAccounts) {
test('auth succeeds for $allowedAccount', () async {
- httpClient = MockClient((_) async => http.Response(
- _generateTokenResponse(allowedAccount),
- HttpStatus.ok,
- headers: <String, String>{
- HttpHeaders.contentTypeHeader: 'application/json',
- },
- ));
+ httpClient = MockClient(
+ (_) async => http.Response(
+ _generateTokenResponse(allowedAccount),
+ HttpStatus.ok,
+ headers: <String, String>{
+ HttpHeaders.contentTypeHeader: 'application/json',
+ },
+ ),
+ );
auth = PubsubAuthenticationProvider(
config: config,
clientContextProvider: () => clientContext,
@@ -58,13 +60,15 @@
}
test('auth fails with unauthorized service account', () async {
- httpClient = MockClient((_) async => http.Response(
- _generateTokenResponse('unauthorized@gmail.com'),
- HttpStatus.ok,
- headers: <String, String>{
- HttpHeaders.contentTypeHeader: 'application/json',
- },
- ));
+ httpClient = MockClient(
+ (_) async => http.Response(
+ _generateTokenResponse('unauthorized@gmail.com'),
+ HttpStatus.ok,
+ headers: <String, String>{
+ HttpHeaders.contentTypeHeader: 'application/json',
+ },
+ ),
+ );
auth = PubsubAuthenticationProvider(
config: config,
clientContextProvider: () => clientContext,
@@ -77,13 +81,15 @@
});
test('auth fails with invalid token', () async {
- httpClient = MockClient((_) async => http.Response(
- 'Invalid token',
- HttpStatus.unauthorized,
- headers: <String, String>{
- HttpHeaders.contentTypeHeader: 'application/json',
- },
- ));
+ httpClient = MockClient(
+ (_) async => http.Response(
+ 'Invalid token',
+ HttpStatus.unauthorized,
+ headers: <String, String>{
+ HttpHeaders.contentTypeHeader: 'application/json',
+ },
+ ),
+ );
auth = PubsubAuthenticationProvider(
config: config,
clientContextProvider: () => clientContext,
@@ -96,16 +102,18 @@
});
test('auth fails with expired token', () async {
- httpClient = MockClient((_) async => http.Response(
- _generateTokenResponse(
- Config.allowedPubsubServiceAccounts.first,
- expiresIn: -1,
- ),
- HttpStatus.ok,
- headers: <String, String>{
- HttpHeaders.contentTypeHeader: 'application/json',
- },
- ));
+ httpClient = MockClient(
+ (_) async => http.Response(
+ _generateTokenResponse(
+ Config.allowedPubsubServiceAccounts.first,
+ expiresIn: -1,
+ ),
+ HttpStatus.ok,
+ headers: <String, String>{
+ HttpHeaders.contentTypeHeader: 'application/json',
+ },
+ ),
+ );
auth = PubsubAuthenticationProvider(
config: config,
clientContextProvider: () => clientContext,
diff --git a/app_dart/test/service/bigquery_test.dart b/app_dart/test/service/bigquery_test.dart
index fd1d943..8085fc0 100644
--- a/app_dart/test/service/bigquery_test.dart
+++ b/app_dart/test/service/bigquery_test.dart
@@ -58,7 +58,8 @@
// When queries flaky data from BigQuery.
when(jobsResource.query(captureAny, expectedProjectId)).thenAnswer((Invocation invocation) {
return Future<QueryResponse>.value(
- QueryResponse.fromJson(jsonDecode(jobNotCompleteResponse) as Map<dynamic, dynamic>));
+ QueryResponse.fromJson(jsonDecode(jobNotCompleteResponse) as Map<dynamic, dynamic>),
+ );
});
bool hasError = false;
try {
@@ -74,7 +75,8 @@
// When queries flaky data from BigQuery.
when(jobsResource.query(captureAny, expectedProjectId)).thenAnswer((Invocation invocation) {
return Future<QueryResponse>.value(
- QueryResponse.fromJson(jsonDecode(semanticsIntegrationTestResponse) as Map<dynamic, dynamic>));
+ QueryResponse.fromJson(jsonDecode(semanticsIntegrationTestResponse) as Map<dynamic, dynamic>),
+ );
});
final List<BuilderStatistic> statisticList = await service.listBuilderStatistic(expectedProjectId);
expect(statisticList.length, 1);
@@ -95,7 +97,8 @@
test('return empty build list when bigquery returns no rows', () async {
when(jobsResource.query(captureAny, expectedProjectId)).thenAnswer((Invocation invocation) {
return Future<QueryResponse>.value(
- QueryResponse.fromJson(jsonDecode(noRecordsResponse) as Map<dynamic, dynamic>));
+ QueryResponse.fromJson(jsonDecode(noRecordsResponse) as Map<dynamic, dynamic>),
+ );
});
final List<BuilderRecord> records =
await service.listRecentBuildRecordsForBuilder(expectedProjectId, builder: 'test', limit: 10);
diff --git a/app_dart/test/service/branch_service_test.dart b/app_dart/test/service/branch_service_test.dart
index 883a0ec..084c2e2 100644
--- a/app_dart/test/service/branch_service_test.dart
+++ b/app_dart/test/service/branch_service_test.dart
@@ -70,7 +70,7 @@
expect(db.values.values.whereType<Branch>().length, 0);
const String id = 'flutter/flutter/flutter-2.12-candidate.4';
- int lastActivity = DateTime.tryParse("2019-05-15T15:20:56Z")!.millisecondsSinceEpoch;
+ final int lastActivity = DateTime.tryParse("2019-05-15T15:20:56Z")!.millisecondsSinceEpoch;
final Key<String> branchKey = db.emptyKey.append<String>(Branch, id: id);
final Branch currentBranch = Branch(key: branchKey, lastActivity: lastActivity);
db.values[currentBranch.key] = currentBranch;
@@ -89,7 +89,7 @@
expect(db.values.values.whereType<Branch>().length, 0);
const String id = 'flutter/flutter/flutter-2.12-candidate.4';
- int lastActivity = DateTime.tryParse("2019-05-15T15:20:56Z")!.millisecondsSinceEpoch;
+ final int lastActivity = DateTime.tryParse("2019-05-15T15:20:56Z")!.millisecondsSinceEpoch;
final Key<String> branchKey = db.emptyKey.append<String>(Branch, id: id);
final Branch currentBranch = Branch(key: branchKey, lastActivity: lastActivity);
db.values[currentBranch.key] = currentBranch;
@@ -100,8 +100,10 @@
await branchService.handleCreateRequest(createEvent);
expect(db.values.values.whereType<Branch>().length, 2);
- expect(db.values.values.whereType<Branch>().map<String>((Branch b) => b.name),
- containsAll(<String>['flutter-2.12-candidate.4', 'flutter-2.12-candidate.5']));
+ expect(
+ db.values.values.whereType<Branch>().map<String>((Branch b) => b.name),
+ containsAll(<String>['flutter-2.12-candidate.4', 'flutter-2.12-candidate.5']),
+ );
});
});
@@ -114,12 +116,13 @@
});
test('return beta, stable, and latest candidate branches', () async {
- gh.Branch stableBranch = generateBranch(1, name: 'flutter-2.13-candidate.0', sha: '123stable');
- gh.Branch betaBranch = generateBranch(2, name: 'flutter-3.2-candidate.5', sha: '456beta');
- gh.Branch candidateBranch = generateBranch(3, name: 'flutter-3.4-candidate.5', sha: '789dev');
- gh.Branch candidateBranchOne = generateBranch(4, name: 'flutter-3.3-candidate.9', sha: 'lagerZValue');
- gh.Branch candidateBranchTwo = generateBranch(5, name: 'flutter-2.15-candidate.99', sha: 'superLargeYZvalue');
- gh.Branch candidateBranchThree = generateBranch(6, name: 'flutter-0.5-candidate.0', sha: 'someZeroValues');
+ final gh.Branch stableBranch = generateBranch(1, name: 'flutter-2.13-candidate.0', sha: '123stable');
+ final gh.Branch betaBranch = generateBranch(2, name: 'flutter-3.2-candidate.5', sha: '456beta');
+ final gh.Branch candidateBranch = generateBranch(3, name: 'flutter-3.4-candidate.5', sha: '789dev');
+ final gh.Branch candidateBranchOne = generateBranch(4, name: 'flutter-3.3-candidate.9', sha: 'lagerZValue');
+ final gh.Branch candidateBranchTwo =
+ generateBranch(5, name: 'flutter-2.15-candidate.99', sha: 'superLargeYZvalue');
+ final gh.Branch candidateBranchThree = generateBranch(6, name: 'flutter-0.5-candidate.0', sha: 'someZeroValues');
when(mockRepositoriesService.listBranches(any)).thenAnswer((Invocation invocation) {
return Stream.fromIterable([
@@ -154,15 +157,19 @@
test('does not create branch that already exists', () async {
gerritService.branchesValue = <String>[branch];
- expect(() async => branchService.branchFlutterRecipes(branch),
- throwsExceptionWith<BadRequestException>('$branch already exists'));
+ expect(
+ () async => branchService.branchFlutterRecipes(branch),
+ throwsExceptionWith<BadRequestException>('$branch already exists'),
+ );
});
test('does not create branch if a good branch point cannot be found', () async {
gerritService.commitsValue = <GerritCommit>[];
githubService.listCommitsBranch = (String branch, int ts) => <gh.RepositoryCommit>[];
- expect(() async => branchService.branchFlutterRecipes(branch),
- throwsExceptionWith<InternalServerError>('Failed to find a revision to branch Flutter recipes for $branch'));
+ expect(
+ () async => branchService.branchFlutterRecipes(branch),
+ throwsExceptionWith<InternalServerError>('Failed to find a revision to branch Flutter recipes for $branch'),
+ );
});
test('creates branch', () async {
diff --git a/app_dart/test/service/build_status_provider_test.dart b/app_dart/test/service/build_status_provider_test.dart
index 283addd..846366a 100644
--- a/app_dart/test/service/build_status_provider_test.dart
+++ b/app_dart/test/service/build_status_provider_test.dart
@@ -201,11 +201,12 @@
db.values[commit2.key] = commit2;
final Task task1 = Task(
- key: commit1.key.append(Task, id: 1),
- commitKey: commit1.key,
- name: 'task1',
- status: Task.statusSucceeded,
- stageName: 'stage1');
+ key: commit1.key.append(Task, id: 1),
+ commitKey: commit1.key,
+ name: 'task1',
+ status: Task.statusSucceeded,
+ stageName: 'stage1',
+ );
db.values[task1.key] = task1;
diff --git a/app_dart/test/service/buildbucket_test.dart b/app_dart/test/service/buildbucket_test.dart
index b9eab76..b568910 100644
--- a/app_dart/test/service/buildbucket_test.dart
+++ b/app_dart/test/service/buildbucket_test.dart
@@ -141,22 +141,25 @@
});
test('BatchBuildRequest', () async {
- const BatchRequest request = BatchRequest(requests: <Request>[
- Request(
+ const BatchRequest request = BatchRequest(
+ requests: <Request>[
+ Request(
scheduleBuild: ScheduleBuildRequest(
- builderId: builderId,
- experimental: Trinary.yes,
- tags: <String, List<String>>{
- 'user_agent': <String>['flutter_cocoon'],
- 'flutter_pr': <String>['true', '1'],
- 'cipd_version': <String>['/refs/heads/main'],
- },
- properties: <String, String>{
- 'git_url': 'https://github.com/flutter/flutter',
- 'git_ref': 'refs/pull/1/head',
- },
- ))
- ]);
+ builderId: builderId,
+ experimental: Trinary.yes,
+ tags: <String, List<String>>{
+ 'user_agent': <String>['flutter_cocoon'],
+ 'flutter_pr': <String>['true', '1'],
+ 'cipd_version': <String>['/refs/heads/main'],
+ },
+ properties: <String, String>{
+ 'git_url': 'https://github.com/flutter/flutter',
+ 'git_ref': 'refs/pull/1/head',
+ },
+ ),
+ )
+ ],
+ );
final BatchResponse response = await httpTest<BatchRequest, BatchResponse>(
request,
@@ -175,13 +178,16 @@
});
test('Batch', () async {
- const BatchRequest request = BatchRequest(requests: <Request>[
- Request(
+ const BatchRequest request = BatchRequest(
+ requests: <Request>[
+ Request(
getBuild: GetBuildRequest(
- builderId: builderId,
- buildNumber: 123,
- ))
- ]);
+ builderId: builderId,
+ buildNumber: 123,
+ ),
+ )
+ ],
+ );
final BatchResponse response = await httpTest<BatchRequest, BatchResponse>(
request,
diff --git a/app_dart/test/service/cache_service_test.dart b/app_dart/test/service/cache_service_test.dart
index 1dc4ec4..165d4ea 100644
--- a/app_dart/test/service/cache_service_test.dart
+++ b/app_dart/test/service/cache_service_test.dart
@@ -63,7 +63,8 @@
final Entry<Uint8List> entry = FakeEntry();
// Only on the first call do we want it to throw the exception.
when(mockTestSubcache['does not matter']).thenAnswer(
- (Invocation invocation) => getCallCount++ < 1 ? throw Exception('simulate stream sink error') : entry);
+ (Invocation invocation) => getCallCount++ < 1 ? throw Exception('simulate stream sink error') : entry,
+ );
cache.cacheValue = mockMainCache;
@@ -80,8 +81,10 @@
int getCallCount = 0;
final Entry<Uint8List> entry = FakeEntry();
// Always throw exception until max retries
- when(mockTestSubcache['does not matter']).thenAnswer((Invocation invocation) =>
- getCallCount++ < CacheService.maxCacheGetAttempts ? throw Exception('simulate stream sink error') : entry);
+ when(mockTestSubcache['does not matter']).thenAnswer(
+ (Invocation invocation) =>
+ getCallCount++ < CacheService.maxCacheGetAttempts ? throw Exception('simulate stream sink error') : entry,
+ );
cache.cacheValue = mockMainCache;
diff --git a/app_dart/test/service/datastore_test.dart b/app_dart/test/service/datastore_test.dart
index 2fa08aa..333fd6c 100644
--- a/app_dart/test/service/datastore_test.dart
+++ b/app_dart/test/service/datastore_test.dart
@@ -201,10 +201,13 @@
test('retriesOnGrpcError', () async {
final Counter counter = Counter();
try {
- await runTransactionWithRetries(() async {
- counter.increase();
- throw GrpcError.aborted();
- }, retryOptions: retryOptions);
+ await runTransactionWithRetries(
+ () async {
+ counter.increase();
+ throw GrpcError.aborted();
+ },
+ retryOptions: retryOptions,
+ );
} catch (e) {
expect(e, isA<GrpcError>());
}
@@ -213,10 +216,13 @@
test('retriesTransactionAbortedError', () async {
final Counter counter = Counter();
try {
- await runTransactionWithRetries(() async {
- counter.increase();
- throw gcloud_datastore.TransactionAbortedError();
- }, retryOptions: retryOptions);
+ await runTransactionWithRetries(
+ () async {
+ counter.increase();
+ throw gcloud_datastore.TransactionAbortedError();
+ },
+ retryOptions: retryOptions,
+ );
} catch (e) {
expect(e, isA<gcloud_datastore.TransactionAbortedError>());
}
@@ -224,9 +230,12 @@
});
test('DoesNotRetryOnSuccess', () async {
final Counter counter = Counter();
- await runTransactionWithRetries(() async {
- counter.increase();
- }, retryOptions: retryOptions);
+ await runTransactionWithRetries(
+ () async {
+ counter.increase();
+ },
+ retryOptions: retryOptions,
+ );
expect(counter.value(), equals(1));
});
});
diff --git a/app_dart/test/service/gerrit_service_test.dart b/app_dart/test/service/gerrit_service_test.dart
index e957355..80edcfd 100644
--- a/app_dart/test/service/gerrit_service_test.dart
+++ b/app_dart/test/service/gerrit_service_test.dart
@@ -94,7 +94,10 @@
);
await gerritService.createBranch(
- Config.recipesSlug, 'flutter-2.13-candidate.0', '00439ab49a991db42595f14078adb9811a6f60c6');
+ Config.recipesSlug,
+ 'flutter-2.13-candidate.0',
+ '00439ab49a991db42595f14078adb9811a6f60c6',
+ );
});
test('unexpected response', () async {
@@ -108,8 +111,10 @@
FakeAuthClient(baseClient!),
retryDelay: Duration.zero,
);
- expect(() async => await gerritService.createBranch(Config.recipesSlug, 'flutter-2.13-candidate.0', 'abc'),
- throwsExceptionWith<InternalServerError>('Failed to create branch'));
+ expect(
+ () async => await gerritService.createBranch(Config.recipesSlug, 'flutter-2.13-candidate.0', 'abc'),
+ throwsExceptionWith<InternalServerError>('Failed to create branch'),
+ );
});
test('retries non-200 responses', () async {
@@ -132,7 +137,10 @@
retryDelay: Duration.zero,
);
await gerritService.createBranch(
- Config.recipesSlug, 'flutter-2.13-candidate.0', '00439ab49a991db42595f14078adb9811a6f60c6');
+ Config.recipesSlug,
+ 'flutter-2.13-candidate.0',
+ '00439ab49a991db42595f14078adb9811a6f60c6',
+ );
expect(attempts, 2);
});
});
diff --git a/app_dart/test/service/github_checks_service_test.dart b/app_dart/test/service/github_checks_service_test.dart
index 62a3c86..9161294 100644
--- a/app_dart/test/service/github_checks_service_test.dart
+++ b/app_dart/test/service/github_checks_service_test.dart
@@ -49,8 +49,8 @@
);
checkRun = github.CheckRun.fromJson(
jsonDecode(
- '{"name": "Cocoon", "id": 123, "external_id": "678", "status": "completed", "started_at": "2020-05-10T02:49:31Z", "head_sha": "the_sha", "check_suite": {"id": 456}}')
- as Map<String, dynamic>,
+ '{"name": "Cocoon", "id": 123, "external_id": "678", "status": "completed", "started_at": "2020-05-10T02:49:31Z", "head_sha": "the_sha", "check_suite": {"id": 456}}',
+ ) as Map<String, dynamic>,
);
final Map<String, github.CheckRun> checkRuns = <String, github.CheckRun>{'Cocoon': checkRun};
when(mockGithubChecksUtil.allCheckRuns(any, any)).thenAnswer((_) async {
@@ -66,12 +66,13 @@
.thenAnswer((_) async => generateCheckRun(1));
final PullRequest pullRequest = generatePullRequest(id: 758);
await githubChecksService.handleCheckSuite(pullRequest, checkSuiteEvent, scheduler);
- final List<Target> scheduledTargets = verify(mockLuciBuildService.scheduleTryBuilds(
- targets: captureAnyNamed('targets'),
- pullRequest: anyNamed('pullRequest'),
- checkSuiteEvent: anyNamed('checkSuiteEvent')))
- .captured
- .single as List<Target>;
+ final List<Target> scheduledTargets = verify(
+ mockLuciBuildService.scheduleTryBuilds(
+ targets: captureAnyNamed('targets'),
+ pullRequest: anyNamed('pullRequest'),
+ checkSuiteEvent: anyNamed('checkSuiteEvent'),
+ ),
+ ).captured.single as List<Target>;
final Iterable<String> scheduledTargetNames = scheduledTargets.map((Target target) => target.value.name);
expect(scheduledTargetNames, <String>[
'Linux A',
@@ -90,19 +91,24 @@
});
test('Userdata does not contain check_run_id', () async {
final push_message.BuildPushMessage buildMessage = push_message.BuildPushMessage.fromJson(
- jsonDecode(buildPushMessageJsonTemplate('{\\"retries\\": 1}')) as Map<String, dynamic>);
+ jsonDecode(buildPushMessageJsonTemplate('{\\"retries\\": 1}')) as Map<String, dynamic>,
+ );
final bool success = await githubChecksService.updateCheckStatus(buildMessage, mockLuciBuildService, slug);
expect(success, isFalse);
});
test('Userdata contain check_run_id', () async {
when(mockGithubChecksUtil.getCheckRun(any, any, any)).thenAnswer((_) async => checkRun);
- final push_message.BuildPushMessage buildPushMessage =
- push_message.BuildPushMessage.fromJson(jsonDecode(buildPushMessageJsonTemplate('{\\"check_run_id\\": 1,'
+ final push_message.BuildPushMessage buildPushMessage = push_message.BuildPushMessage.fromJson(
+ jsonDecode(
+ buildPushMessageJsonTemplate('{\\"check_run_id\\": 1,'
'\\"repo_owner\\": \\"flutter\\",'
- '\\"repo_name\\": \\"cocoon\\"}')) as Map<String, dynamic>);
+ '\\"repo_name\\": \\"cocoon\\"}'),
+ ) as Map<String, dynamic>,
+ );
await githubChecksService.updateCheckStatus(buildPushMessage, mockLuciBuildService, slug);
expect(
- verify(mockGithubChecksUtil.updateCheckRun(
+ verify(
+ mockGithubChecksUtil.updateCheckRun(
any,
any,
captureAny,
@@ -110,8 +116,10 @@
conclusion: anyNamed('conclusion'),
detailsUrl: anyNamed('detailsUrl'),
output: anyNamed('output'),
- )).captured,
- <github.CheckRun>[checkRun]);
+ ),
+ ).captured,
+ <github.CheckRun>[checkRun],
+ );
});
});
diff --git a/app_dart/test/service/github_service_test.dart b/app_dart/test/service/github_service_test.dart
index b74acde..104821a 100644
--- a/app_dart/test/service/github_service_test.dart
+++ b/app_dart/test/service/github_service_test.dart
@@ -36,14 +36,16 @@
mockGitHub = MockGitHub();
githubService = GithubService(mockGitHub);
slug = RepositorySlug('flutter', 'flutter');
- final PostExpectation<Future<http.Response>> whenGithubRequest = when(mockGitHub.request(
- 'GET',
- '/repos/${slug.owner}/${slug.name}/commits',
- headers: anyNamed('headers'),
- params: anyNamed('params'),
- body: anyNamed('body'),
- statusCode: anyNamed('statusCode'),
- ));
+ final PostExpectation<Future<http.Response>> whenGithubRequest = when(
+ mockGitHub.request(
+ 'GET',
+ '/repos/${slug.owner}/${slug.name}/commits',
+ headers: anyNamed('headers'),
+ params: anyNamed('params'),
+ body: anyNamed('body'),
+ statusCode: anyNamed('statusCode'),
+ ),
+ );
whenGithubRequest.thenAnswer((_) async {
final List<dynamic> data = <dynamic>[];
for (String sha in shas) {
diff --git a/app_dart/test/service/luci_build_service_test.dart b/app_dart/test/service/luci_build_service_test.dart
index 75d80d4..666f844 100644
--- a/app_dart/test/service/luci_build_service_test.dart
+++ b/app_dart/test/service/luci_build_service_test.dart
@@ -139,10 +139,12 @@
test('with one rpc call', () async {
when(mockBuildBucketClient.listBuilders(any)).thenAnswer((_) async {
- return const ListBuildersResponse(builders: [
- BuilderItem(id: BuilderId(bucket: 'prod', project: 'flutter', builder: 'test1')),
- BuilderItem(id: BuilderId(bucket: 'prod', project: 'flutter', builder: 'test2')),
- ]);
+ return const ListBuildersResponse(
+ builders: [
+ BuilderItem(id: BuilderId(bucket: 'prod', project: 'flutter', builder: 'test1')),
+ BuilderItem(id: BuilderId(bucket: 'prod', project: 'flutter', builder: 'test2')),
+ ],
+ );
});
final Set<String> builders = await service.getAvailableBuilderSet();
expect(builders.length, 2);
@@ -154,15 +156,20 @@
when(mockBuildBucketClient.listBuilders(any)).thenAnswer((_) async {
retries++;
if (retries == 0) {
- return const ListBuildersResponse(builders: [
- BuilderItem(id: BuilderId(bucket: 'prod', project: 'flutter', builder: 'test1')),
- BuilderItem(id: BuilderId(bucket: 'prod', project: 'flutter', builder: 'test2')),
- ], nextPageToken: 'token');
+ return const ListBuildersResponse(
+ builders: [
+ BuilderItem(id: BuilderId(bucket: 'prod', project: 'flutter', builder: 'test1')),
+ BuilderItem(id: BuilderId(bucket: 'prod', project: 'flutter', builder: 'test2')),
+ ],
+ nextPageToken: 'token',
+ );
} else if (retries == 1) {
- return const ListBuildersResponse(builders: [
- BuilderItem(id: BuilderId(bucket: 'prod', project: 'flutter', builder: 'test3')),
- BuilderItem(id: BuilderId(bucket: 'prod', project: 'flutter', builder: 'test4')),
- ]);
+ return const ListBuildersResponse(
+ builders: [
+ BuilderItem(id: BuilderId(bucket: 'prod', project: 'flutter', builder: 'test3')),
+ BuilderItem(id: BuilderId(bucket: 'prod', project: 'flutter', builder: 'test4')),
+ ],
+ );
} else {
return const ListBuildersResponse(builders: []);
}
@@ -319,9 +326,11 @@
targets: targets,
);
expect(
- records.where((LogRecord record) =>
- record.message.contains('Linux 1 has already been scheduled for this pull request')),
- hasLength(1));
+ records.where(
+ (LogRecord record) => record.message.contains('Linux 1 has already been scheduled for this pull request'),
+ ),
+ hasLength(1),
+ );
});
test('try to schedule builds already passed', () async {
@@ -345,9 +354,11 @@
targets: targets,
);
expect(
- records.where((LogRecord record) =>
- record.message.contains('Linux 1 has already been scheduled for this pull request')),
- hasLength(1));
+ records.where(
+ (LogRecord record) => record.message.contains('Linux 1 has already been scheduled for this pull request'),
+ ),
+ hasLength(1),
+ );
});
test('try to schedule builds already scheduled', () async {
when(mockBuildBucketClient.batch(any)).thenAnswer((_) async {
@@ -385,19 +396,21 @@
);
});
await expectLater(
- service.scheduleTryBuilds(
- pullRequest: pullRequest,
- targets: <Target>[],
- ),
- throwsA(isA<InternalServerError>()));
+ service.scheduleTryBuilds(
+ pullRequest: pullRequest,
+ targets: <Target>[],
+ ),
+ throwsA(isA<InternalServerError>()),
+ );
});
test('Try to schedule build on a unsupported repo', () async {
expect(
- () async => await service.scheduleTryBuilds(
- targets: targets,
- pullRequest: generatePullRequest(repo: 'nonsupported'),
- ),
- throwsA(const TypeMatcher<BadRequestException>()));
+ () async => await service.scheduleTryBuilds(
+ targets: targets,
+ pullRequest: generatePullRequest(repo: 'nonsupported'),
+ ),
+ throwsA(const TypeMatcher<BadRequestException>()),
+ );
});
});
@@ -416,14 +429,19 @@
test('schedule postsubmit builds successfully', () async {
final Commit commit = generateCommit(0);
when(mockBuildBucketClient.listBuilders(any)).thenAnswer((_) async {
- return const ListBuildersResponse(builders: [
- BuilderItem(id: BuilderId(bucket: 'prod', project: 'flutter', builder: 'Linux 1')),
- ]);
+ return const ListBuildersResponse(
+ builders: [
+ BuilderItem(id: BuilderId(bucket: 'prod', project: 'flutter', builder: 'Linux 1')),
+ ],
+ );
});
final Tuple<Target, Task, int> toBeScheduled = Tuple<Target, Task, int>(
- generateTarget(1, properties: <String, String>{
- 'os': 'debian-10.12',
- }),
+ generateTarget(
+ 1,
+ properties: <String, String>{
+ 'os': 'debian-10.12',
+ },
+ ),
generateTask(1),
LuciBuildService.kDefaultPriority,
);
@@ -459,8 +477,10 @@
'cipdVersion': 'refs/heads/master',
});
expect(scheduleBuild.dimensions, isNotEmpty);
- expect(scheduleBuild.dimensions!.singleWhere((RequestedDimension dimension) => dimension.key == 'os').value,
- 'debian-10.12');
+ expect(
+ scheduleBuild.dimensions!.singleWhere((RequestedDimension dimension) => dimension.key == 'os').value,
+ 'debian-10.12',
+ );
});
test('schedule postsubmit builds with correct userData for checkRuns', () async {
@@ -468,16 +488,20 @@
.thenAnswer((_) async => generateCheckRun(1, name: 'Linux 1'));
final Commit commit = generateCommit(0, repo: 'packages');
when(mockBuildBucketClient.listBuilders(any)).thenAnswer((_) async {
- return const ListBuildersResponse(builders: [
- BuilderItem(id: BuilderId(bucket: 'prod', project: 'flutter', builder: 'Linux 1')),
- ]);
+ return const ListBuildersResponse(
+ builders: [
+ BuilderItem(id: BuilderId(bucket: 'prod', project: 'flutter', builder: 'Linux 1')),
+ ],
+ );
});
final Tuple<Target, Task, int> toBeScheduled = Tuple<Target, Task, int>(
- generateTarget(1,
- properties: <String, String>{
- 'os': 'debian-10.12',
- },
- slug: RepositorySlug('flutter', 'packages')),
+ generateTarget(
+ 1,
+ properties: <String, String>{
+ 'os': 'debian-10.12',
+ },
+ slug: RepositorySlug('flutter', 'packages'),
+ ),
generateTask(1),
LuciBuildService.kDefaultPriority,
);
@@ -512,21 +536,29 @@
test('Skip non-existing builder', () async {
final Commit commit = generateCommit(0);
when(mockBuildBucketClient.listBuilders(any)).thenAnswer((_) async {
- return const ListBuildersResponse(builders: [
- BuilderItem(id: BuilderId(bucket: 'prod', project: 'flutter', builder: 'Linux 2')),
- ]);
+ return const ListBuildersResponse(
+ builders: [
+ BuilderItem(id: BuilderId(bucket: 'prod', project: 'flutter', builder: 'Linux 2')),
+ ],
+ );
});
final Tuple<Target, Task, int> toBeScheduled1 = Tuple<Target, Task, int>(
- generateTarget(1, properties: <String, String>{
- 'os': 'debian-10.12',
- }),
+ generateTarget(
+ 1,
+ properties: <String, String>{
+ 'os': 'debian-10.12',
+ },
+ ),
generateTask(1),
LuciBuildService.kDefaultPriority,
);
final Tuple<Target, Task, int> toBeScheduled2 = Tuple<Target, Task, int>(
- generateTarget(2, properties: <String, String>{
- 'os': 'debian-10.12',
- }),
+ generateTarget(
+ 2,
+ properties: <String, String>{
+ 'os': 'debian-10.12',
+ },
+ ),
generateTask(1),
LuciBuildService.kDefaultPriority,
);
@@ -584,16 +616,19 @@
);
});
await service.cancelBuilds(pullRequest, 'new builds');
- expect(verify(mockBuildBucketClient.batch(captureAny)).captured[1].requests[0].cancelBuild.toJson(),
- json.decode('{"id": "998", "summaryMarkdown": "new builds"}'));
+ expect(
+ verify(mockBuildBucketClient.batch(captureAny)).captured[1].requests[0].cancelBuild.toJson(),
+ json.decode('{"id": "998", "summaryMarkdown": "new builds"}'),
+ );
});
test('Cancel builds from unsuported repo', () async {
expect(
- () async => await service.cancelBuilds(
- generatePullRequest(repo: 'notsupported'),
- 'new builds',
- ),
- throwsA(const TypeMatcher<BadRequestException>()));
+ () async => await service.cancelBuilds(
+ generatePullRequest(repo: 'notsupported'),
+ 'new builds',
+ ),
+ throwsA(const TypeMatcher<BadRequestException>()),
+ );
});
});
@@ -649,12 +684,14 @@
buildBucketClient: mockBuildBucketClient,
pubsub: pubsub,
);
- final Map<String, dynamic> json = jsonDecode(buildPushMessageString(
- 'COMPLETED',
- result: 'FAILURE',
- builderName: 'Linux Host Engine',
- userData: '{}',
- )) as Map<String, dynamic>;
+ final Map<String, dynamic> json = jsonDecode(
+ buildPushMessageString(
+ 'COMPLETED',
+ result: 'FAILURE',
+ builderName: 'Linux Host Engine',
+ userData: '{}',
+ ),
+ ) as Map<String, dynamic>;
buildPushMessage = push_message.BuildPushMessage.fromJson(json);
});
diff --git a/app_dart/test/service/scheduler/graph_test.dart b/app_dart/test/service/scheduler/graph_test.dart
index cb763e9..5190d9c 100644
--- a/app_dart/test/service/scheduler/graph_test.dart
+++ b/app_dart/test/service/scheduler/graph_test.dart
@@ -48,15 +48,18 @@
- name: A
scheduler: dashatar
''') as YamlMap?;
- expect(() {
- final SchedulerConfig unCheckedSchedulerConfig = SchedulerConfig()
- ..mergeFromProto3Json(targetWithNonexistentScheduler);
- CiYaml(
- slug: Config.flutterSlug,
- branch: Config.defaultBranch(Config.flutterSlug),
- config: unCheckedSchedulerConfig,
- ).config;
- }, throwsA(isA<FormatException>()));
+ expect(
+ () {
+ final SchedulerConfig unCheckedSchedulerConfig = SchedulerConfig()
+ ..mergeFromProto3Json(targetWithNonexistentScheduler);
+ CiYaml(
+ slug: Config.flutterSlug,
+ branch: Config.defaultBranch(Config.flutterSlug),
+ config: unCheckedSchedulerConfig,
+ ).config;
+ },
+ throwsA(isA<FormatException>()),
+ );
});
test('constructs graph with dependency chain', () {
@@ -141,18 +144,19 @@
''') as YamlMap?;
final SchedulerConfig unCheckedSchedulerConfig = SchedulerConfig()..mergeFromProto3Json(configWithCycle);
expect(
- () => CiYaml(
- slug: Config.flutterSlug,
- branch: Config.defaultBranch(Config.flutterSlug),
- config: unCheckedSchedulerConfig,
- ).config,
- throwsA(
- isA<FormatException>().having(
- (FormatException e) => e.toString(),
- 'message',
- contains('ERROR: A depends on B which does not exist'),
- ),
- ));
+ () => CiYaml(
+ slug: Config.flutterSlug,
+ branch: Config.defaultBranch(Config.flutterSlug),
+ config: unCheckedSchedulerConfig,
+ ).config,
+ throwsA(
+ isA<FormatException>().having(
+ (FormatException e) => e.toString(),
+ 'message',
+ contains('ERROR: A depends on B which does not exist'),
+ ),
+ ),
+ );
});
test('fails when there are duplicate targets', () {
@@ -166,18 +170,19 @@
final SchedulerConfig unCheckedSchedulerConfig = SchedulerConfig()
..mergeFromProto3Json(configWithDuplicateTargets);
expect(
- () => CiYaml(
- slug: Config.flutterSlug,
- branch: Config.defaultBranch(Config.flutterSlug),
- config: unCheckedSchedulerConfig,
- ).config,
- throwsA(
- isA<FormatException>().having(
- (FormatException e) => e.toString(),
- 'message',
- contains('ERROR: A already exists in graph'),
- ),
- ));
+ () => CiYaml(
+ slug: Config.flutterSlug,
+ branch: Config.defaultBranch(Config.flutterSlug),
+ config: unCheckedSchedulerConfig,
+ ).config,
+ throwsA(
+ isA<FormatException>().having(
+ (FormatException e) => e.toString(),
+ 'message',
+ contains('ERROR: A already exists in graph'),
+ ),
+ ),
+ );
});
test('fails when there are multiple dependencies', () {
@@ -195,18 +200,19 @@
final SchedulerConfig unCheckedSchedulerConfig = SchedulerConfig()
..mergeFromProto3Json(configWithMultipleDependencies);
expect(
- () => CiYaml(
- slug: Config.flutterSlug,
- branch: Config.defaultBranch(Config.flutterSlug),
- config: unCheckedSchedulerConfig,
- ).config,
- throwsA(
- isA<FormatException>().having(
- (FormatException e) => e.toString(),
- 'message',
- contains('ERROR: C has multiple dependencies which is not supported. Use only one dependency'),
- ),
- ));
+ () => CiYaml(
+ slug: Config.flutterSlug,
+ branch: Config.defaultBranch(Config.flutterSlug),
+ config: unCheckedSchedulerConfig,
+ ).config,
+ throwsA(
+ isA<FormatException>().having(
+ (FormatException e) => e.toString(),
+ 'message',
+ contains('ERROR: C has multiple dependencies which is not supported. Use only one dependency'),
+ ),
+ ),
+ );
});
test('fails when dependency does not exist', () {
@@ -220,18 +226,19 @@
''') as YamlMap?;
final SchedulerConfig unCheckedSchedulerConfig = SchedulerConfig()..mergeFromProto3Json(configWithMissingTarget);
expect(
- () => CiYaml(
- slug: Config.flutterSlug,
- branch: Config.defaultBranch(Config.flutterSlug),
- config: unCheckedSchedulerConfig,
- ).config,
- throwsA(
- isA<FormatException>().having(
- (FormatException e) => e.toString(),
- 'message',
- contains('ERROR: A depends on B which does not exist'),
- ),
- ));
+ () => CiYaml(
+ slug: Config.flutterSlug,
+ branch: Config.defaultBranch(Config.flutterSlug),
+ config: unCheckedSchedulerConfig,
+ ).config,
+ throwsA(
+ isA<FormatException>().having(
+ (FormatException e) => e.toString(),
+ 'message',
+ contains('ERROR: A depends on B which does not exist'),
+ ),
+ ),
+ );
});
});
@@ -239,7 +246,7 @@
late CiYaml? totConfig;
setUp(() {
- YamlMap? totYaml = loadYaml('''
+ final YamlMap? totYaml = loadYaml('''
enabled_branches:
- master
targets:
@@ -262,13 +269,14 @@
''') as YamlMap?;
final SchedulerConfig unCheckedSchedulerConfig = SchedulerConfig()..mergeFromProto3Json(currentYaml);
expect(
- () => CiYaml(
- slug: Config.flutterSlug,
- branch: Config.defaultBranch(Config.flutterSlug),
- config: unCheckedSchedulerConfig,
- totConfig: totConfig,
- ),
- returnsNormally);
+ () => CiYaml(
+ slug: Config.flutterSlug,
+ branch: Config.defaultBranch(Config.flutterSlug),
+ config: unCheckedSchedulerConfig,
+ totConfig: totConfig,
+ ),
+ returnsNormally,
+ );
});
test('succeed when new builder is marked with bringup:true ', () {
@@ -282,13 +290,14 @@
''') as YamlMap?;
final SchedulerConfig unCheckedSchedulerConfig = SchedulerConfig()..mergeFromProto3Json(currentYaml);
expect(
- () => CiYaml(
- slug: Config.flutterSlug,
- branch: Config.defaultBranch(Config.flutterSlug),
- config: unCheckedSchedulerConfig,
- totConfig: totConfig,
- ),
- returnsNormally);
+ () => CiYaml(
+ slug: Config.flutterSlug,
+ branch: Config.defaultBranch(Config.flutterSlug),
+ config: unCheckedSchedulerConfig,
+ totConfig: totConfig,
+ ),
+ returnsNormally,
+ );
});
test('fails when new builder is missing bringup:true ', () {
@@ -301,19 +310,20 @@
''') as YamlMap?;
final SchedulerConfig unCheckedSchedulerConfig = SchedulerConfig()..mergeFromProto3Json(currentYaml);
expect(
- () => CiYaml(
- slug: Config.flutterSlug,
- branch: Config.defaultBranch(Config.flutterSlug),
- config: unCheckedSchedulerConfig,
- totConfig: totConfig,
- ),
- throwsA(
- isA<FormatException>().having(
- (FormatException e) => e.toString(),
- 'message',
- contains('ERROR: B is a new builder added. it needs to be marked bringup: true'),
- ),
- ));
+ () => CiYaml(
+ slug: Config.flutterSlug,
+ branch: Config.defaultBranch(Config.flutterSlug),
+ config: unCheckedSchedulerConfig,
+ totConfig: totConfig,
+ ),
+ throwsA(
+ isA<FormatException>().having(
+ (FormatException e) => e.toString(),
+ 'message',
+ contains('ERROR: B is a new builder added. it needs to be marked bringup: true'),
+ ),
+ ),
+ );
});
test('fails when new builder has bringup set to false ', () {
@@ -327,19 +337,20 @@
''') as YamlMap?;
final SchedulerConfig unCheckedSchedulerConfig = SchedulerConfig()..mergeFromProto3Json(currentYaml);
expect(
- () => CiYaml(
- slug: Config.flutterSlug,
- branch: Config.defaultBranch(Config.flutterSlug),
- config: unCheckedSchedulerConfig,
- totConfig: totConfig,
- ),
- throwsA(
- isA<FormatException>().having(
- (FormatException e) => e.toString(),
- 'message',
- contains('ERROR: B is a new builder added. it needs to be marked bringup: true'),
- ),
- ));
+ () => CiYaml(
+ slug: Config.flutterSlug,
+ branch: Config.defaultBranch(Config.flutterSlug),
+ config: unCheckedSchedulerConfig,
+ totConfig: totConfig,
+ ),
+ throwsA(
+ isA<FormatException>().having(
+ (FormatException e) => e.toString(),
+ 'message',
+ contains('ERROR: B is a new builder added. it needs to be marked bringup: true'),
+ ),
+ ),
+ );
});
});
}
diff --git a/app_dart/test/service/scheduler/policy_test.dart b/app_dart/test/service/scheduler/policy_test.dart
index 7181e4a..4cd169a 100644
--- a/app_dart/test/service/scheduler/policy_test.dart
+++ b/app_dart/test/service/scheduler/policy_test.dart
@@ -68,19 +68,25 @@
test('triggers if less tasks than batch size', () async {
db.addOnQuery<Task>((Iterable<Task> results) => allPending);
expect(
- await policy.triggerPriority(task: generateTask(4), datastore: datastore), LuciBuildService.kDefaultPriority);
+ await policy.triggerPriority(task: generateTask(4), datastore: datastore),
+ LuciBuildService.kDefaultPriority,
+ );
});
test('triggers after batch size', () async {
db.addOnQuery<Task>((Iterable<Task> results) => latestAllPending);
expect(
- await policy.triggerPriority(task: generateTask(7), datastore: datastore), LuciBuildService.kDefaultPriority);
+ await policy.triggerPriority(task: generateTask(7), datastore: datastore),
+ LuciBuildService.kDefaultPriority,
+ );
});
test('triggers with higher priority on recent failures', () async {
db.addOnQuery<Task>((Iterable<Task> results) => latestFailed);
expect(
- await policy.triggerPriority(task: generateTask(7), datastore: datastore), LuciBuildService.kRerunPriority);
+ await policy.triggerPriority(task: generateTask(7), datastore: datastore),
+ LuciBuildService.kRerunPriority,
+ );
});
test('does not trigger when a test was recently scheduled', () async {
@@ -118,13 +124,17 @@
test('triggers every task', () async {
db.addOnQuery<Task>((Iterable<Task> results) => pending);
expect(
- await policy.triggerPriority(task: generateTask(2), datastore: datastore), LuciBuildService.kDefaultPriority);
+ await policy.triggerPriority(task: generateTask(2), datastore: datastore),
+ LuciBuildService.kDefaultPriority,
+ );
});
test('triggers with higher priority on recent failure', () async {
db.addOnQuery<Task>((Iterable<Task> results) => latestFailed);
expect(
- await policy.triggerPriority(task: generateTask(2), datastore: datastore), LuciBuildService.kRerunPriority);
+ await policy.triggerPriority(task: generateTask(2), datastore: datastore),
+ LuciBuildService.kRerunPriority,
+ );
});
});
}
diff --git a/app_dart/test/service/scheduler_test.dart b/app_dart/test/service/scheduler_test.dart
index 2de0703..940eb63 100644
--- a/app_dart/test/service/scheduler_test.dart
+++ b/app_dart/test/service/scheduler_test.dart
@@ -145,17 +145,18 @@
String repo = 'flutter',
}) {
return List<Commit>.generate(
- shas.length,
- (int index) => Commit(
- author: 'Username',
- authorAvatarUrl: 'http://example.org/avatar.jpg',
- branch: 'master',
- key: db.emptyKey.append(Commit, id: 'flutter/$repo/master/${shas[index]}'),
- message: 'commit message',
- repository: 'flutter/$repo',
- sha: shas[index],
- timestamp: DateTime.fromMillisecondsSinceEpoch(int.parse(shas[index])).millisecondsSinceEpoch,
- ));
+ shas.length,
+ (int index) => Commit(
+ author: 'Username',
+ authorAvatarUrl: 'http://example.org/avatar.jpg',
+ branch: 'master',
+ key: db.emptyKey.append(Commit, id: 'flutter/$repo/master/${shas[index]}'),
+ message: 'commit message',
+ repository: 'flutter/$repo',
+ sha: shas[index],
+ timestamp: DateTime.fromMillisecondsSinceEpoch(int.parse(shas[index])).millisecondsSinceEpoch,
+ ),
+ );
}
test('succeeds when GitHub returns no commits', () async {
@@ -230,9 +231,12 @@
test('schedules cocoon based targets', () async {
final MockLuciBuildService luciBuildService = MockLuciBuildService();
- when(luciBuildService.schedulePostsubmitBuilds(
- commit: anyNamed('commit'), toBeScheduled: captureAnyNamed('toBeScheduled')))
- .thenAnswer((_) => Future<void>.value());
+ when(
+ luciBuildService.schedulePostsubmitBuilds(
+ commit: anyNamed('commit'),
+ toBeScheduled: captureAnyNamed('toBeScheduled'),
+ ),
+ ).thenAnswer((_) => Future<void>.value());
buildStatusService =
FakeBuildStatusService(commitStatuses: <CommitStatus>[CommitStatus(generateCommit(1), const <Stage>[])]);
scheduler = Scheduler(
@@ -246,9 +250,12 @@
);
await scheduler.addCommits(createCommitList(<String>['1']));
- final List<dynamic> captured = verify(luciBuildService.schedulePostsubmitBuilds(
- commit: anyNamed('commit'), toBeScheduled: captureAnyNamed('toBeScheduled')))
- .captured;
+ final List<dynamic> captured = verify(
+ luciBuildService.schedulePostsubmitBuilds(
+ commit: anyNamed('commit'),
+ toBeScheduled: captureAnyNamed('toBeScheduled'),
+ ),
+ ).captured;
final List<dynamic> toBeScheduled = captured.first as List<dynamic>;
expect(toBeScheduled.length, 2);
final Iterable<Tuple<Target, Task, int>> tuples =
@@ -270,10 +277,12 @@
pubsub: pubsub,
);
when(mockBuildBucketClient.listBuilders(any)).thenAnswer((_) async {
- return const ListBuildersResponse(builders: [
- BuilderItem(id: BuilderId(bucket: 'prod', project: 'flutter', builder: 'Linux A')),
- BuilderItem(id: BuilderId(bucket: 'prod', project: 'flutter', builder: 'Linux runIf')),
- ]);
+ return const ListBuildersResponse(
+ builders: [
+ BuilderItem(id: BuilderId(bucket: 'prod', project: 'flutter', builder: 'Linux A')),
+ BuilderItem(id: BuilderId(bucket: 'prod', project: 'flutter', builder: 'Linux runIf')),
+ ],
+ );
});
buildStatusService =
FakeBuildStatusService(commitStatuses: <CommitStatus>[CommitStatus(generateCommit(1), const <Stage>[])]);
@@ -379,13 +388,15 @@
group('process check run', () {
test('rerequested ci.yaml check retriggers presubmit', () async {
- when(mockGithubChecksUtil.createCheckRun(
- any,
- any,
- any,
- any,
- output: anyNamed('output'),
- )).thenAnswer((_) async {
+ when(
+ mockGithubChecksUtil.createCheckRun(
+ any,
+ any,
+ any,
+ any,
+ output: anyNamed('output'),
+ ),
+ ).thenAnswer((_) async {
return CheckRun.fromJson(const <String, dynamic>{
'id': 1,
'started_at': '2020-05-10T02:49:31Z',
@@ -397,13 +408,15 @@
checkRunEventJson['check_run']['name'] = Scheduler.kCiYamlCheckName;
final cocoon_checks.CheckRunEvent checkRunEvent = cocoon_checks.CheckRunEvent.fromJson(checkRunEventJson);
expect(await scheduler.processCheckRun(checkRunEvent), true);
- verify(mockGithubChecksUtil.createCheckRun(
- any,
- any,
- any,
- Scheduler.kCiYamlCheckName,
- output: anyNamed('output'),
- ));
+ verify(
+ mockGithubChecksUtil.createCheckRun(
+ any,
+ any,
+ any,
+ Scheduler.kCiYamlCheckName,
+ output: anyNamed('output'),
+ ),
+ );
// Verfies Linux A was created
verify(mockGithubChecksUtil.createCheckRun(any, any, any, any)).called(1);
});
@@ -443,7 +456,8 @@
test('gets only enabled .ci.yaml builds', () async {
httpClient = MockClient((http.Request request) async {
if (request.url.path.contains('.ci.yaml')) {
- return http.Response('''
+ return http.Response(
+ '''
enabled_branches:
- master
targets:
@@ -469,46 +483,58 @@
enabled_branches:
- master
presubmit: true
- ''', 200);
+ ''',
+ 200,
+ );
}
throw Exception('Failed to find ${request.url.path}');
});
final List<Target> presubmitTargets = await scheduler.getPresubmitTargets(pullRequest);
- expect(presubmitTargets.map((Target target) => target.value.name).toList(),
- containsAll(<String>['Linux A', 'Linux C']));
+ expect(
+ presubmitTargets.map((Target target) => target.value.name).toList(),
+ containsAll(<String>['Linux A', 'Linux C']),
+ );
});
test('checks for release branches', () async {
const String branch = 'flutter-1.24-candidate.1';
httpClient = MockClient((http.Request request) async {
if (request.url.path.contains('.ci.yaml')) {
- return http.Response('''
+ return http.Response(
+ '''
enabled_branches:
- master
targets:
- name: Linux A
presubmit: true
scheduler: luci
- ''', 200);
+ ''',
+ 200,
+ );
}
throw Exception('Failed to find ${request.url.path}');
});
- expect(scheduler.getPresubmitTargets(generatePullRequest(branch: branch)),
- throwsA(predicate((Exception e) => e.toString().contains('$branch is not enabled'))));
+ expect(
+ scheduler.getPresubmitTargets(generatePullRequest(branch: branch)),
+ throwsA(predicate((Exception e) => e.toString().contains('$branch is not enabled'))),
+ );
});
test('checks for release branch regex', () async {
const String branch = 'flutter-1.24-candidate.1';
httpClient = MockClient((http.Request request) async {
if (request.url.path.contains('.ci.yaml')) {
- return http.Response('''
+ return http.Response(
+ '''
enabled_branches:
- main
- flutter-\\d+.\\d+-candidate.\\d+
targets:
- name: Linux A
scheduler: luci
- ''', 200);
+ ''',
+ 200,
+ );
}
throw Exception('Failed to find ${request.url.path}');
});
@@ -524,8 +550,9 @@
<dynamic>[
Scheduler.kCiYamlCheckName,
const CheckRunOutput(
- title: Scheduler.kCiYamlCheckName,
- summary: 'If this check is stuck pending, push an empty commit to retrigger the checks'),
+ title: Scheduler.kCiYamlCheckName,
+ summary: 'If this check is stuck pending, push an empty commit to retrigger the checks',
+ ),
'Linux A',
null,
// Linux runIf is not run as this is for tip of tree and the files weren't affected
@@ -564,8 +591,9 @@
<dynamic>[
Scheduler.kCiYamlCheckName,
const CheckRunOutput(
- title: Scheduler.kCiYamlCheckName,
- summary: 'If this check is stuck pending, push an empty commit to retrigger the checks'),
+ title: Scheduler.kCiYamlCheckName,
+ summary: 'If this check is stuck pending, push an empty commit to retrigger the checks',
+ ),
'Linux A',
null,
// runIf requires a diff in dev, so an error will cause it to be triggered
@@ -586,8 +614,9 @@
<dynamic>[
Scheduler.kCiYamlCheckName,
const CheckRunOutput(
- title: Scheduler.kCiYamlCheckName,
- summary: 'If this check is stuck pending, push an empty commit to retrigger the checks'),
+ title: Scheduler.kCiYamlCheckName,
+ summary: 'If this check is stuck pending, push an empty commit to retrigger the checks',
+ ),
'Linux A',
null,
'Linux runIf',
@@ -601,12 +630,18 @@
.thenAnswer((Invocation invocation) async => createCheckRun(id: 0));
await scheduler.triggerPresubmitTargets(pullRequest: pullRequest);
expect(
- verify(mockGithubChecksUtil.updateCheckRun(any, any, any,
- status: captureAnyNamed('status'),
- conclusion: captureAnyNamed('conclusion'),
- output: anyNamed('output')))
- .captured,
- <dynamic>[CheckRunStatus.completed, CheckRunConclusion.success]);
+ verify(
+ mockGithubChecksUtil.updateCheckRun(
+ any,
+ any,
+ any,
+ status: captureAnyNamed('status'),
+ conclusion: captureAnyNamed('conclusion'),
+ output: anyNamed('output'),
+ ),
+ ).captured,
+ <dynamic>[CheckRunStatus.completed, CheckRunConclusion.success],
+ );
});
test('ci.yaml validation fails with empty config', () async {
@@ -618,30 +653,43 @@
});
await scheduler.triggerPresubmitTargets(pullRequest: pullRequest);
expect(
- verify(mockGithubChecksUtil.updateCheckRun(any, any, any,
- status: captureAnyNamed('status'),
- conclusion: captureAnyNamed('conclusion'),
- output: anyNamed('output')))
- .captured,
- <dynamic>[CheckRunStatus.completed, CheckRunConclusion.failure]);
+ verify(
+ mockGithubChecksUtil.updateCheckRun(
+ any,
+ any,
+ any,
+ status: captureAnyNamed('status'),
+ conclusion: captureAnyNamed('conclusion'),
+ output: anyNamed('output'),
+ ),
+ ).captured,
+ <dynamic>[CheckRunStatus.completed, CheckRunConclusion.failure],
+ );
});
test('ci.yaml validation fails on not enabled branch', () async {
final PullRequest pullRequest = generatePullRequest(branch: 'not-valid');
await scheduler.triggerPresubmitTargets(pullRequest: pullRequest);
expect(
- verify(mockGithubChecksUtil.updateCheckRun(any, any, any,
- status: captureAnyNamed('status'),
- conclusion: captureAnyNamed('conclusion'),
- output: anyNamed('output')))
- .captured,
- <dynamic>[CheckRunStatus.completed, CheckRunConclusion.failure]);
+ verify(
+ mockGithubChecksUtil.updateCheckRun(
+ any,
+ any,
+ any,
+ status: captureAnyNamed('status'),
+ conclusion: captureAnyNamed('conclusion'),
+ output: anyNamed('output'),
+ ),
+ ).captured,
+ <dynamic>[CheckRunStatus.completed, CheckRunConclusion.failure],
+ );
});
test('ci.yaml validation fails with config with unknown dependencies', () async {
httpClient = MockClient((http.Request request) async {
if (request.url.path.contains('.ci.yaml')) {
- return http.Response('''
+ return http.Response(
+ '''
enabled_branches:
- master
targets:
@@ -649,18 +697,26 @@
builder: Linux A
dependencies:
- B
- ''', 200);
+ ''',
+ 200,
+ );
}
throw Exception('Failed to find ${request.url.path}');
});
await scheduler.triggerPresubmitTargets(pullRequest: pullRequest);
expect(
- verify(mockGithubChecksUtil.updateCheckRun(any, any, any,
- status: anyNamed('status'), conclusion: anyNamed('conclusion'), output: captureAnyNamed('output')))
- .captured
- .first
- .text,
- 'FormatException: ERROR: A depends on B which does not exist');
+ verify(
+ mockGithubChecksUtil.updateCheckRun(
+ any,
+ any,
+ any,
+ status: anyNamed('status'),
+ conclusion: anyNamed('conclusion'),
+ output: captureAnyNamed('output'),
+ ),
+ ).captured.first.text,
+ 'FormatException: ERROR: A depends on B which does not exist',
+ );
});
test('retries only triggers failed builds only', () async {
@@ -683,21 +739,23 @@
pubsub: pubsub,
),
);
- when(mockBuildbucket.batch(any)).thenAnswer((_) async => BatchResponse(
- responses: <Response>[
- Response(
- searchBuilds: SearchBuildsResponse(
- builds: <Build>[
- generateBuild(1000, name: 'Linux', bucket: 'try'),
- generateBuild(2000, name: 'Linux Coverage', bucket: 'try'),
- generateBuild(3000, name: 'Mac', bucket: 'try', status: Status.scheduled),
- generateBuild(4000, name: 'Windows', bucket: 'try', status: Status.started),
- generateBuild(5000, name: 'Linux A', bucket: 'try', status: Status.failure)
- ],
- ),
+ when(mockBuildbucket.batch(any)).thenAnswer(
+ (_) async => BatchResponse(
+ responses: <Response>[
+ Response(
+ searchBuilds: SearchBuildsResponse(
+ builds: <Build>[
+ generateBuild(1000, name: 'Linux', bucket: 'try'),
+ generateBuild(2000, name: 'Linux Coverage', bucket: 'try'),
+ generateBuild(3000, name: 'Mac', bucket: 'try', status: Status.scheduled),
+ generateBuild(4000, name: 'Windows', bucket: 'try', status: Status.started),
+ generateBuild(5000, name: 'Linux A', bucket: 'try', status: Status.failure)
+ ],
),
- ],
- ));
+ ),
+ ],
+ ),
+ );
when(mockBuildbucket.scheduleBuild(any))
.thenAnswer((_) async => generateBuild(5001, name: 'Linux A', bucket: 'try', status: Status.scheduled));
// Only Linux A should be retried
diff --git a/app_dart/test/src/bigquery/fake_tabledata_resource.dart b/app_dart/test/src/bigquery/fake_tabledata_resource.dart
index bd89751..9b7581f 100644
--- a/app_dart/test/src/bigquery/fake_tabledata_resource.dart
+++ b/app_dart/test/src/bigquery/fake_tabledata_resource.dart
@@ -13,15 +13,27 @@
List<TableDataInsertAllRequestRows>? rows;
@override
Future<TableDataInsertAllResponse> insertAll(
- TableDataInsertAllRequest request, String projectId, String datasetId, String tableId,
- {String? $fields}) async {
+ TableDataInsertAllRequest request,
+ String projectId,
+ String datasetId,
+ String tableId, {
+ String? $fields,
+ }) async {
rows = request.rows;
return TableDataInsertAllResponse.fromJson(<String, String>{});
}
@override
- Future<TableDataList> list(String projectId, String datasetId, String tableId,
- {int? maxResults, String? selectedFields, String? startIndex, String? pageToken, String? $fields}) async {
+ Future<TableDataList> list(
+ String projectId,
+ String datasetId,
+ String tableId, {
+ int? maxResults,
+ String? selectedFields,
+ String? startIndex,
+ String? pageToken,
+ String? $fields,
+ }) async {
final List<Map<String, Object>> tableRowList = <Map<String, Object>>[];
for (TableDataInsertAllRequestRows tableDataInsertAllRequestRows in rows!) {
final dynamic value = tableDataInsertAllRequestRows.json;
diff --git a/app_dart/test/src/datastore/fake_config.dart b/app_dart/test/src/datastore/fake_config.dart
index 0400751..7233616 100644
--- a/app_dart/test/src/datastore/fake_config.dart
+++ b/app_dart/test/src/datastore/fake_config.dart
@@ -286,11 +286,13 @@
if (supportedBranchesValue == null) {
throw Exception('Test must set suportedBranchesValue to be able to use Config.getBranches');
}
- return supportedBranchesValue!.map((String branch) => Branch(
- key: db.emptyKey.append<String>(
- Branch,
- id: '${slug.fullName}/$branch',
- ),
- ));
+ return supportedBranchesValue!.map(
+ (String branch) => Branch(
+ key: db.emptyKey.append<String>(
+ Branch,
+ id: '${slug.fullName}/$branch',
+ ),
+ ),
+ );
}
}
diff --git a/app_dart/test/src/request_handling/api_request_handler_tester.dart b/app_dart/test/src/request_handling/api_request_handler_tester.dart
index ed40fb0..9c8d657 100644
--- a/app_dart/test/src/request_handling/api_request_handler_tester.dart
+++ b/app_dart/test/src/request_handling/api_request_handler_tester.dart
@@ -27,12 +27,15 @@
@protected
Future<T> run<T extends Body>(Future<T> Function() callback) {
return super.run<T>(() {
- return runZoned<Future<T>>(() {
- return callback();
- }, zoneValues: <RequestKey<dynamic>, Object>{
- ApiKey.authContext: context,
- ApiKey.requestData: requestData,
- });
+ return runZoned<Future<T>>(
+ () {
+ return callback();
+ },
+ zoneValues: <RequestKey<dynamic>, Object>{
+ ApiKey.authContext: context,
+ ApiKey.requestData: requestData,
+ },
+ );
});
}
}
diff --git a/app_dart/test/src/request_handling/no_auth_request_handler_tester.dart b/app_dart/test/src/request_handling/no_auth_request_handler_tester.dart
index e161bea..167ca66 100644
--- a/app_dart/test/src/request_handling/no_auth_request_handler_tester.dart
+++ b/app_dart/test/src/request_handling/no_auth_request_handler_tester.dart
@@ -23,11 +23,14 @@
@protected
Future<T> run<T extends Body>(Future<T> Function() callback) {
return super.run<T>(() {
- return runZoned<Future<T>>(() {
- return callback();
- }, zoneValues: <RequestKey<dynamic>, Object>{
- NoAuthKey.requestData: requestData,
- });
+ return runZoned<Future<T>>(
+ () {
+ return callback();
+ },
+ zoneValues: <RequestKey<dynamic>, Object>{
+ NoAuthKey.requestData: requestData,
+ },
+ );
});
}
}
diff --git a/app_dart/test/src/request_handling/request_handler_tester.dart b/app_dart/test/src/request_handling/request_handler_tester.dart
index 8588b71..956b2a4 100644
--- a/app_dart/test/src/request_handling/request_handler_tester.dart
+++ b/app_dart/test/src/request_handling/request_handler_tester.dart
@@ -41,12 +41,15 @@
@protected
Future<T> run<T extends Body>(Future<T> Function() callback) {
- return runZoned<Future<T>>(() {
- return callback();
- }, zoneValues: <RequestKey<dynamic>, Object?>{
- RequestKey.request: request,
- RequestKey.response: response,
- RequestKey.httpClient: httpClient,
- });
+ return runZoned<Future<T>>(
+ () {
+ return callback();
+ },
+ zoneValues: <RequestKey<dynamic>, Object?>{
+ RequestKey.request: request,
+ RequestKey.response: response,
+ RequestKey.httpClient: httpClient,
+ },
+ );
}
}
diff --git a/app_dart/test/src/request_handling/subscription_tester.dart b/app_dart/test/src/request_handling/subscription_tester.dart
index eb6c3ab..d6cf64f 100644
--- a/app_dart/test/src/request_handling/subscription_tester.dart
+++ b/app_dart/test/src/request_handling/subscription_tester.dart
@@ -28,12 +28,15 @@
@protected
Future<T> run<T extends Body>(Future<T> Function() callback) {
return super.run<T>(() {
- return runZoned<Future<T>>(() {
- return callback();
- }, zoneValues: <RequestKey<dynamic>, Object>{
- ApiKey.authContext: context,
- PubSubKey.message: message,
- });
+ return runZoned<Future<T>>(
+ () {
+ return callback();
+ },
+ zoneValues: <RequestKey<dynamic>, Object>{
+ ApiKey.authContext: context,
+ PubSubKey.message: message,
+ },
+ );
});
}
}
diff --git a/app_dart/test/src/service/fake_build_status_provider.dart b/app_dart/test/src/service/fake_build_status_provider.dart
index 64e10e3..1bc7cab 100644
--- a/app_dart/test/src/service/fake_build_status_provider.dart
+++ b/app_dart/test/src/service/fake_build_status_provider.dart
@@ -35,11 +35,15 @@
}
commitStatuses!.sort((CommitStatus a, CommitStatus b) => a.commit.timestamp!.compareTo(b.commit.timestamp!));
- return Stream<CommitStatus>.fromIterable(commitStatuses!.where((CommitStatus commitStatus) =>
- ((commitStatus.commit.timestamp == null || timestamp == null)
- ? true
- : commitStatus.commit.timestamp! < timestamp) &&
- commitStatus.commit.branch == branch));
+ return Stream<CommitStatus>.fromIterable(
+ commitStatuses!.where(
+ (CommitStatus commitStatus) =>
+ ((commitStatus.commit.timestamp == null || timestamp == null)
+ ? true
+ : commitStatus.commit.timestamp! < timestamp) &&
+ commitStatus.commit.branch == branch,
+ ),
+ );
}
@override
diff --git a/app_dart/test/src/service/fake_buildbucket.dart b/app_dart/test/src/service/fake_buildbucket.dart
index 30384ad..b5b4bad 100644
--- a/app_dart/test/src/service/fake_buildbucket.dart
+++ b/app_dart/test/src/service/fake_buildbucket.dart
@@ -105,7 +105,8 @@
project: 'flutter',
builder: 'builder_abc',
),
- summaryMarkdown: request.summaryMarkdown);
+ summaryMarkdown: request.summaryMarkdown,
+ );
@override
Future<Build> getBuild(
@@ -127,20 +128,22 @@
}) async =>
(listBuildersResponse != null)
? await listBuildersResponse!
- : const ListBuildersResponse(builders: <BuilderItem>[
- BuilderItem(
- id: BuilderId(
- bucket: 'prod',
- project: 'flutter',
- builder: 'Linux_android A',
+ : const ListBuildersResponse(
+ builders: <BuilderItem>[
+ BuilderItem(
+ id: BuilderId(
+ bucket: 'prod',
+ project: 'flutter',
+ builder: 'Linux_android A',
+ ),
),
- ),
- BuilderItem(
- id: BuilderId(
- bucket: 'prod',
- project: 'flutter',
- builder: 'Linux_android B',
- ),
- )
- ]);
+ BuilderItem(
+ id: BuilderId(
+ bucket: 'prod',
+ project: 'flutter',
+ builder: 'Linux_android B',
+ ),
+ )
+ ],
+ );
}
diff --git a/app_dart/test/src/service/fake_gerrit_service.dart b/app_dart/test/src/service/fake_gerrit_service.dart
index 8229161..23a82d9 100644
--- a/app_dart/test/src/service/fake_gerrit_service.dart
+++ b/app_dart/test/src/service/fake_gerrit_service.dart
@@ -16,8 +16,9 @@
this.branchesValue = _defaultBranches,
this.commitsValue,
}) : super(
- httpClient:
- MockClient((_) => throw const InternalServerError('FakeGerritService tried to make an http request')));
+ httpClient:
+ MockClient((_) => throw const InternalServerError('FakeGerritService tried to make an http request')),
+ );
List<String> branchesValue;
static const List<String> _defaultBranches = <String>['main'];
diff --git a/app_dart/test/src/service/fake_graphql_client.dart b/app_dart/test/src/service/fake_graphql_client.dart
index 342e9f8..9e1f9b2 100644
--- a/app_dart/test/src/service/fake_graphql_client.dart
+++ b/app_dart/test/src/service/fake_graphql_client.dart
@@ -89,8 +89,11 @@
}
@override
- Future<QueryResult<T>> fetchMore<T>(FetchMoreOptions fetchMoreOptions,
- {required QueryOptions<T> originalOptions, required QueryResult<T> previousResult}) {
+ Future<QueryResult<T>> fetchMore<T>(
+ FetchMoreOptions fetchMoreOptions, {
+ required QueryOptions<T> originalOptions,
+ required QueryResult<T> previousResult,
+ }) {
throw UnimplementedError();
}
diff --git a/app_dart/test/src/service/fake_scheduler.dart b/app_dart/test/src/service/fake_scheduler.dart
index 30c6c63..45a9958 100644
--- a/app_dart/test/src/service/fake_scheduler.dart
+++ b/app_dart/test/src/service/fake_scheduler.dart
@@ -74,42 +74,48 @@
CiYaml exampleConfig = CiYaml(
slug: Config.flutterSlug,
branch: Config.defaultBranch(Config.flutterSlug),
- config: pb.SchedulerConfig(enabledBranches: <String>[
- Config.defaultBranch(Config.flutterSlug),
- ], targets: <pb.Target>[
- pb.Target(
- name: 'Linux A',
- scheduler: pb.SchedulerSystem.luci,
- ),
- pb.Target(
- name: 'Mac A',
- scheduler: pb.SchedulerSystem.luci,
- ),
- pb.Target(
- name: 'Windows A',
- scheduler: pb.SchedulerSystem.luci,
- ),
- pb.Target(
- bringup: false,
- name: 'Google Internal Roll',
- presubmit: false,
- postsubmit: true,
- scheduler: pb.SchedulerSystem.google_internal,
- ),
- ]),
+ config: pb.SchedulerConfig(
+ enabledBranches: <String>[
+ Config.defaultBranch(Config.flutterSlug),
+ ],
+ targets: <pb.Target>[
+ pb.Target(
+ name: 'Linux A',
+ scheduler: pb.SchedulerSystem.luci,
+ ),
+ pb.Target(
+ name: 'Mac A',
+ scheduler: pb.SchedulerSystem.luci,
+ ),
+ pb.Target(
+ name: 'Windows A',
+ scheduler: pb.SchedulerSystem.luci,
+ ),
+ pb.Target(
+ bringup: false,
+ name: 'Google Internal Roll',
+ presubmit: false,
+ postsubmit: true,
+ scheduler: pb.SchedulerSystem.google_internal,
+ ),
+ ],
+ ),
);
CiYaml batchPolicyConfig = CiYaml(
slug: Config.flutterSlug,
branch: Config.defaultBranch(Config.flutterSlug),
- config: pb.SchedulerConfig(enabledBranches: <String>[
- Config.defaultBranch(Config.flutterSlug),
- ], targets: <pb.Target>[
- pb.Target(
- name: 'Linux_android A',
- ),
- pb.Target(
- name: 'Linux_android B',
- ),
- ]),
+ config: pb.SchedulerConfig(
+ enabledBranches: <String>[
+ Config.defaultBranch(Config.flutterSlug),
+ ],
+ targets: <pb.Target>[
+ pb.Target(
+ name: 'Linux_android A',
+ ),
+ pb.Target(
+ name: 'Linux_android B',
+ ),
+ ],
+ ),
);
diff --git a/app_dart/test/src/utilities/entity_generators.dart b/app_dart/test/src/utilities/entity_generators.dart
index aa465b1..07b74fd 100644
--- a/app_dart/test/src/utilities/entity_generators.dart
+++ b/app_dart/test/src/utilities/entity_generators.dart
@@ -209,12 +209,13 @@
number: number,
mergedAt: mergedAt,
base: github.PullRequestHead(
- ref: branch,
- repo: github.Repository(
- fullName: 'flutter/$repo',
- name: repo,
- owner: github.UserInformation('flutter', 1, '', ''),
- )),
+ ref: branch,
+ repo: github.Repository(
+ fullName: 'flutter/$repo',
+ name: repo,
+ owner: github.UserInformation('flutter', 1, '', ''),
+ ),
+ ),
head: github.PullRequestHead(
ref: branch,
sha: sha,
diff --git a/app_dart/test/src/utilities/mocks.mocks.dart b/app_dart/test/src/utilities/mocks.mocks.dart
index e6cd2f1..273de43 100644
--- a/app_dart/test/src/utilities/mocks.mocks.dart
+++ b/app_dart/test/src/utilities/mocks.mocks.dart
@@ -5231,6 +5231,8 @@
_i10.RepositorySlug? slug,
int? number, {
String? message,
+ _i10.MergeMethod? mergeMethod = _i10.MergeMethod.merge,
+ String? requestSha,
}) =>
(super.noSuchMethod(
Invocation.method(
@@ -5239,7 +5241,11 @@
slug,
number,
],
- {#message: message},
+ {
+ #message: message,
+ #mergeMethod: mergeMethod,
+ #requestSha: requestSha,
+ },
),
returnValue: _i17.Future<_i10.PullRequestMerge>.value(_FakePullRequestMerge_53(
this,
@@ -5249,7 +5255,11 @@
slug,
number,
],
- {#message: message},
+ {
+ #message: message,
+ #mergeMethod: mergeMethod,
+ #requestSha: requestSha,
+ },
),
)),
) as _i17.Future<_i10.PullRequestMerge>);
diff --git a/app_dart/test/src/utilities/push_message.dart b/app_dart/test/src/utilities/push_message.dart
index 8bc384e..a267a44 100644
--- a/app_dart/test/src/utilities/push_message.dart
+++ b/app_dart/test/src/utilities/push_message.dart
@@ -63,15 +63,19 @@
String? failureReason,
String? userData,
}) =>
- base64.encode(utf8.encode(buildPushMessageString(
- status,
- result: result,
- builderName: builderName,
- urlParam: urlParam,
- retries: retries,
- failureReason: failureReason,
- userData: userData,
- )));
+ base64.encode(
+ utf8.encode(
+ buildPushMessageString(
+ status,
+ result: result,
+ builderName: builderName,
+ urlParam: urlParam,
+ retries: retries,
+ failureReason: failureReason,
+ userData: userData,
+ ),
+ ),
+ );
String buildPushMessageJsonNoBuildset(
String status, {
@@ -81,14 +85,18 @@
int retries = 0,
String? failureReason,
}) =>
- base64.encode(utf8.encode(buildPushMessageNoBuildsetString(
- status,
- result: result,
- builderName: builderName,
- urlParam: urlParam,
- retries: retries,
- failureReason: failureReason,
- )));
+ base64.encode(
+ utf8.encode(
+ buildPushMessageNoBuildsetString(
+ status,
+ result: result,
+ builderName: builderName,
+ urlParam: urlParam,
+ retries: retries,
+ failureReason: failureReason,
+ ),
+ ),
+ );
String buildPushMessageString(
String status, {
@@ -142,12 +150,14 @@
}''';
}
-String buildPushMessageNoBuildsetString(String status,
- {String? result,
- String builderName = 'Linux Coverage',
- String urlParam = '',
- int retries = 0,
- String? failureReason}) {
+String buildPushMessageNoBuildsetString(
+ String status, {
+ String? result,
+ String builderName = 'Linux Coverage',
+ String urlParam = '',
+ int retries = 0,
+ String? failureReason,
+}) {
return '''{
"build": {
"bucket": "luci.flutter.prod",
diff --git a/app_dart/test/src/utilities/webhook_generators.dart b/app_dart/test/src/utilities/webhook_generators.dart
index 67f6429..a6f05cd 100644
--- a/app_dart/test/src/utilities/webhook_generators.dart
+++ b/app_dart/test/src/utilities/webhook_generators.dart
@@ -894,7 +894,8 @@
}
CreateEvent generateCreateBranchEvent(String branchName, String repository, {bool forked = false}) =>
- CreateEvent.fromJson(jsonDecode('''
+ CreateEvent.fromJson(
+ jsonDecode('''
{
"ref": "$branchName",
"ref_type": "branch",
@@ -1015,4 +1016,5 @@
"type": "User",
"site_admin": false
}
-}''') as Map<String, dynamic>);
+}''') as Map<String, dynamic>,
+ );
diff --git a/auto_submit/analysis_options.yaml b/auto_submit/analysis_options.yaml
index 8801fbf..a200ec8 100644
--- a/auto_submit/analysis_options.yaml
+++ b/auto_submit/analysis_options.yaml
@@ -6,7 +6,4 @@
linter:
rules:
- constant_identifier_names: false # we have all capitalized enums in check_for_waiting_pull_requests_test.dart
- require_trailing_commas: true
- unawaited_futures: true
- prefer_final_fields: true
\ No newline at end of file
+ constant_identifier_names: false # we have all capitalized enums in check_for_waiting_pull_requests_test.dart
\ No newline at end of file
diff --git a/auto_submit/lib/request_handling/pubsub.dart b/auto_submit/lib/request_handling/pubsub.dart
index c448784..91367c2 100644
--- a/auto_submit/lib/request_handling/pubsub.dart
+++ b/auto_submit/lib/request_handling/pubsub.dart
@@ -49,7 +49,7 @@
],
);
final pubsub.PubsubApi pubsubApi = pubsub.PubsubApi(httpClient);
- pubsub.PullRequest pullRequest = pubsub.PullRequest(maxMessages: maxMessages);
+ final pubsub.PullRequest pullRequest = pubsub.PullRequest(maxMessages: maxMessages);
final pubsub.PullResponse pullResponse = await pubsubApi.projects.subscriptions
.pull(pullRequest, 'projects/flutter-dashboard/subscriptions/$subscription');
return pullResponse;
diff --git a/auto_submit/lib/requests/check_pull_request.dart b/auto_submit/lib/requests/check_pull_request.dart
index 2f882cd..8d126fd 100644
--- a/auto_submit/lib/requests/check_pull_request.dart
+++ b/auto_submit/lib/requests/check_pull_request.dart
@@ -44,7 +44,7 @@
return Response.ok('No messages are pulled.');
}
log.info('Processing ${messageList.length} messages');
- ValidationService validationService = ValidationService(config);
+ final ValidationService validationService = ValidationService(config);
final List<Future<void>> futures = <Future<void>>[];
for (pub.ReceivedMessage message in messageList) {
diff --git a/auto_submit/lib/requests/update_revert_issues.dart b/auto_submit/lib/requests/update_revert_issues.dart
index b311392..93f3ae8 100644
--- a/auto_submit/lib/requests/update_revert_issues.dart
+++ b/auto_submit/lib/requests/update_revert_issues.dart
@@ -56,7 +56,7 @@
log.info('Processing review issue# ${revertRequestRecord.reviewIssueNumber}.');
try {
// Get the revert review issue.
- Issue issue = await githubService.getIssue(
+ final Issue issue = await githubService.getIssue(
slug: RepositorySlug(Config.flutter, Config.flutter),
issueNumber: revertRequestRecord.reviewIssueNumber!,
);
diff --git a/auto_submit/lib/service/approver_service.dart b/auto_submit/lib/service/approver_service.dart
index fec68c4..f8feeb7 100644
--- a/auto_submit/lib/service/approver_service.dart
+++ b/auto_submit/lib/service/approver_service.dart
@@ -62,7 +62,7 @@
final gh.RepositorySlug slug = pullRequest.base!.repo!.slug();
final gh.GitHub botClient = await config.createFlutterGitHubBotClient(slug);
- Stream<gh.PullRequestReview> reviews = botClient.pullRequests.listReviews(slug, pullRequest.number!);
+ final Stream<gh.PullRequestReview> reviews = botClient.pullRequests.listReviews(slug, pullRequest.number!);
await for (gh.PullRequestReview review in reviews) {
if (review.user.login == 'fluttergithubbot' && review.state == 'APPROVED') {
// Already approved.
diff --git a/auto_submit/lib/service/bigquery.dart b/auto_submit/lib/service/bigquery.dart
index 795caaa..133a3fe 100644
--- a/auto_submit/lib/service/bigquery.dart
+++ b/auto_submit/lib/service/bigquery.dart
@@ -357,7 +357,7 @@
return <RevertRequestRecord>[];
}
- List<RevertRequestRecord> openReviewRequestIssues = [];
+ final List<RevertRequestRecord> openReviewRequestIssues = [];
for (TableRow tableRow in tableRows) {
openReviewRequestIssues.add(
RevertRequestRecord(
diff --git a/auto_submit/lib/service/config.dart b/auto_submit/lib/service/config.dart
index 4806d3e..977c535 100644
--- a/auto_submit/lib/service/config.dart
+++ b/auto_submit/lib/service/config.dart
@@ -64,7 +64,7 @@
}
Future<GitHub> createGithubClient(RepositorySlug slug) async {
- String token = await generateGithubToken(slug);
+ final String token = await generateGithubToken(slug);
return GitHub(auth: Authentication.withToken(token));
}
@@ -161,7 +161,7 @@
Future<String> _generateGithubJwt() async {
final String rawKey = await secretManager.get(kGithubKey);
- StringBuffer sb = StringBuffer();
+ final StringBuffer sb = StringBuffer();
sb.writeln(rawKey.substring(0, 32));
sb.writeln(rawKey.substring(32, rawKey.length - 30).replaceAll(' ', ' \n'));
sb.writeln(rawKey.substring(rawKey.length - 30, rawKey.length));
@@ -224,7 +224,7 @@
}
Future<Uint8List> _getValueFromSecretManager(String key) async {
- String value = await secretManager.get(key);
+ final String value = await secretManager.get(key);
return Uint8List.fromList(value.codeUnits);
}
}
diff --git a/auto_submit/lib/service/github_service.dart b/auto_submit/lib/service/github_service.dart
index 3eb16bb..471313c 100644
--- a/auto_submit/lib/service/github_service.dart
+++ b/auto_submit/lib/service/github_service.dart
@@ -55,7 +55,7 @@
return listPullRequestFiles;
}
- Stream<PullRequestFile> pullRequestFiles = github.pullRequests.listFiles(slug, pullRequestId);
+ final Stream<PullRequestFile> pullRequestFiles = github.pullRequests.listFiles(slug, pullRequestId);
await for (PullRequestFile file in pullRequestFiles) {
listPullRequestFiles.add(file);
@@ -74,7 +74,7 @@
List<String>? assignees,
String? state,
}) async {
- IssueRequest issueRequest = IssueRequest(
+ final IssueRequest issueRequest = IssueRequest(
title: title,
body: body,
labels: labels,
diff --git a/auto_submit/lib/service/validation_service.dart b/auto_submit/lib/service/validation_service.dart
index 42cee94..b4b68b3 100644
--- a/auto_submit/lib/service/validation_service.dart
+++ b/auto_submit/lib/service/validation_service.dart
@@ -140,7 +140,7 @@
required String ackId,
required PubSub pubsub,
}) async {
- List<ValidationResult> results = <ValidationResult>[];
+ final List<ValidationResult> results = <ValidationResult>[];
/// Runs all the validation defined in the service.
for (Validation validation in validations) {
@@ -397,7 +397,7 @@
log.info('Updated pull request info: ${currentPullRequest.toString()}');
// add a record for the pull request into our metrics tracking
- PullRequestRecord pullRequestRecord = PullRequestRecord(
+ final PullRequestRecord pullRequestRecord = PullRequestRecord(
organization: currentPullRequest.base!.repo!.slug().owner,
repository: currentPullRequest.base!.repo!.slug().name,
author: currentPullRequest.user!.login,
@@ -411,7 +411,7 @@
log.info('Created pull request record: ${pullRequestRecord.toString()}');
try {
- BigqueryService bigqueryService = await config.createBigQueryService();
+ final BigqueryService bigqueryService = await config.createBigQueryService();
await bigqueryService.insertPullRequestRecord(
projectId: Config.flutterGcpProjectId,
pullRequestRecord: pullRequestRecord,
@@ -432,12 +432,12 @@
// Get the updated revert issue.
final github.PullRequest currentPullRequest = await gitHubService.getPullRequest(slug, revertPullRequest.number!);
// Get the original pull request issue.
- String originalPullRequestLink = revertValidation!.extractLinkFromText(revertPullRequest.body)!;
- int originalPullRequestNumber = int.parse(originalPullRequestLink.split('#').elementAt(1));
+ final String originalPullRequestLink = revertValidation!.extractLinkFromText(revertPullRequest.body)!;
+ final int originalPullRequestNumber = int.parse(originalPullRequestLink.split('#').elementAt(1));
// return int.parse(linkSplit.elementAt(1));
final github.PullRequest originalPullRequest = await gitHubService.getPullRequest(slug, originalPullRequestNumber);
- RevertRequestRecord revertRequestRecord = RevertRequestRecord(
+ final RevertRequestRecord revertRequestRecord = RevertRequestRecord(
organization: currentPullRequest.base!.repo!.slug().owner,
repository: currentPullRequest.base!.repo!.slug().name,
author: currentPullRequest.user!.login,
@@ -456,7 +456,7 @@
);
try {
- BigqueryService bigqueryService = await config.createBigQueryService();
+ final BigqueryService bigqueryService = await config.createBigQueryService();
await bigqueryService.insertRevertRequestRecord(
projectId: Config.flutterGcpProjectId,
revertRequestRecord: revertRequestRecord,
diff --git a/auto_submit/lib/validations/approval.dart b/auto_submit/lib/validations/approval.dart
index 77eeea6..fb06260 100644
--- a/auto_submit/lib/validations/approval.dart
+++ b/auto_submit/lib/validations/approval.dart
@@ -23,14 +23,14 @@
final String authorAssociation = pullRequest.authorAssociation!;
final String? author = pullRequest.author!.login;
final List<ReviewNode> reviews = pullRequest.reviews!.nodes!;
- bool approved = config.rollerAccounts.contains(author) ||
+ final bool approved = config.rollerAccounts.contains(author) ||
_checkApproval(
author,
authorAssociation,
reviews,
);
- String message = '- Please get at least one approved review if you are already '
+ const String message = '- Please get at least one approved review if you are already '
'a member or two member reviews if you are not a member before re-applying this '
'label. __Reviewers__: If you left a comment approving, please use '
'the "approve" review action instead.';
diff --git a/auto_submit/lib/validations/change_requested.dart b/auto_submit/lib/validations/change_requested.dart
index cd675c1..1ce4982 100644
--- a/auto_submit/lib/validations/change_requested.dart
+++ b/auto_submit/lib/validations/change_requested.dart
@@ -52,7 +52,7 @@
}
final bool approved = (approvers.length > 1) && changeRequestAuthors.isEmpty;
log.info('PR approved $approved, approvers: $approvers, change request authors: $changeRequestAuthors');
- bool changesRequested = (approvers.length > 1) && changeRequestAuthors.isEmpty;
+ final bool changesRequested = (approvers.length > 1) && changeRequestAuthors.isEmpty;
final StringBuffer buffer = StringBuffer();
for (String? author in changeRequestAuthors) {
diff --git a/auto_submit/lib/validations/ci_successful.dart b/auto_submit/lib/validations/ci_successful.dart
index 61b21d9..4f78ad5 100644
--- a/auto_submit/lib/validations/ci_successful.dart
+++ b/auto_submit/lib/validations/ci_successful.dart
@@ -28,12 +28,12 @@
/// Implements the CI build/tests validations.
Future<ValidationResult> validate(QueryResult result, github.PullRequest messagePullRequest) async {
bool allSuccess = true;
- github.RepositorySlug slug = messagePullRequest.base!.repo!.slug();
+ final github.RepositorySlug slug = messagePullRequest.base!.repo!.slug();
final PullRequest pullRequest = result.repository!.pullRequest!;
- Set<FailureDetail> failures = <FailureDetail>{};
+ final Set<FailureDetail> failures = <FailureDetail>{};
- List<ContextNode> statuses = <ContextNode>[];
- Commit commit = pullRequest.commits!.nodes!.single.commit!;
+ final List<ContextNode> statuses = <ContextNode>[];
+ final Commit commit = pullRequest.commits!.nodes!.single.commit!;
// Recently most of the repositories have migrated away of using the status
// APIs and for those repos commit.status is null.
@@ -60,7 +60,7 @@
final GithubService gitHubService = await config.createGithubService(slug);
final String? sha = commit.oid;
- List<github.CheckRun> checkRuns = <github.CheckRun>[];
+ final List<github.CheckRun> checkRuns = <github.CheckRun>[];
if (messagePullRequest.head != null && sha != null) {
checkRuns.addAll(await gitHubService.getCheckRuns(slug, sha));
}
@@ -79,7 +79,8 @@
'issues identified (or deflake) before re-applying this label.');
}
}
- Action action = labelNames.contains(config.overrideTreeStatusLabel) ? Action.IGNORE_FAILURE : Action.REMOVE_LABEL;
+ final Action action =
+ labelNames.contains(config.overrideTreeStatusLabel) ? Action.IGNORE_FAILURE : Action.REMOVE_LABEL;
return ValidationResult(allSuccess, action, buffer.toString());
}
diff --git a/auto_submit/lib/validations/conflicting.dart b/auto_submit/lib/validations/conflicting.dart
index 77989b0..7d74e6d 100644
--- a/auto_submit/lib/validations/conflicting.dart
+++ b/auto_submit/lib/validations/conflicting.dart
@@ -17,8 +17,8 @@
/// Implements the logic to validate if the PR is in a conflicting state.
Future<ValidationResult> validate(QueryResult result, github.PullRequest messagePullRequest) async {
// This is used to remove the bot label as it requires manual intervention.
- bool result = !(messagePullRequest.mergeable == false);
- String message = '- This commit is not mergeable and has conflicts. Please'
+ final bool result = !(messagePullRequest.mergeable == false);
+ const String message = '- This commit is not mergeable and has conflicts. Please'
' rebase your PR and fix all the conflicts.';
return ValidationResult(result, Action.REMOVE_LABEL, message);
}
diff --git a/auto_submit/lib/validations/empty_checks.dart b/auto_submit/lib/validations/empty_checks.dart
index 33e2819..819d207 100644
--- a/auto_submit/lib/validations/empty_checks.dart
+++ b/auto_submit/lib/validations/empty_checks.dart
@@ -18,13 +18,13 @@
/// Implements the validation to verify the list of checks is not empty.
Future<ValidationResult> validate(QueryResult result, github.PullRequest messagePullRequest) async {
- github.RepositorySlug slug = messagePullRequest.base!.repo!.slug();
+ final github.RepositorySlug slug = messagePullRequest.base!.repo!.slug();
final GithubService gitHubService = await config.createGithubService(slug);
final PullRequest pullRequest = result.repository!.pullRequest!;
- Commit commit = pullRequest.commits!.nodes!.single.commit!;
+ final Commit commit = pullRequest.commits!.nodes!.single.commit!;
final String? sha = commit.oid;
- List<github.CheckRun> checkRuns = await gitHubService.getCheckRuns(slug, sha!);
- String message = '- This commit has no checks. Please check that ci.yaml validation has started'
+ final List<github.CheckRun> checkRuns = await gitHubService.getCheckRuns(slug, sha!);
+ const String message = '- This commit has no checks. Please check that ci.yaml validation has started'
' and there are multiple checks. If not, try uploading an empty commit.';
return ValidationResult(checkRuns.isNotEmpty, Action.REMOVE_LABEL, message);
}
diff --git a/auto_submit/lib/validations/revert.dart b/auto_submit/lib/validations/revert.dart
index 0677221..8ebab91 100644
--- a/auto_submit/lib/validations/revert.dart
+++ b/auto_submit/lib/validations/revert.dart
@@ -28,35 +28,35 @@
final String authorAssociation = pullRequest.authorAssociation!;
final String? author = pullRequest.author!.login;
final auto.Commit commit = pullRequest.commits!.nodes!.single.commit!;
- String? sha = commit.oid;
+ final String? sha = commit.oid;
if (!isValidAuthor(author, authorAssociation)) {
- String message = 'The author $author does not have permissions to make this request.';
+ final String message = 'The author $author does not have permissions to make this request.';
log.info(message);
return ValidationResult(false, Action.REMOVE_LABEL, message);
}
- bool? canMerge = messagePullRequest.mergeable;
+ final bool? canMerge = messagePullRequest.mergeable;
if (canMerge == null || !canMerge) {
- String message =
+ const String message =
'This pull request cannot be merged due to conflicts. Please resolve conflicts and re-add the revert label.';
log.info(message);
return ValidationResult(false, Action.REMOVE_LABEL, message);
}
- String? pullRequestBody = messagePullRequest.body;
- String? revertLink = extractLinkFromText(pullRequestBody);
+ final String? pullRequestBody = messagePullRequest.body;
+ final String? revertLink = extractLinkFromText(pullRequestBody);
if (revertLink == null) {
- String message =
+ const String message =
'A reverts link could not be found or was formatted incorrectly. Format is \'Reverts owner/repo#id\'';
log.info(message);
return ValidationResult(false, Action.REMOVE_LABEL, message);
}
- github.RepositorySlug repositorySlug = _getSlugFromLink(revertLink);
- GithubService githubService = await config.createGithubService(repositorySlug);
+ final github.RepositorySlug repositorySlug = _getSlugFromLink(revertLink);
+ final GithubService githubService = await config.createGithubService(repositorySlug);
- bool requiredChecksCompleted = await waitForRequiredChecks(
+ final bool requiredChecksCompleted = await waitForRequiredChecks(
githubService: githubService,
slug: repositorySlug,
sha: sha!,
@@ -71,10 +71,11 @@
);
}
- int pullRequestId = _getPullRequestNumberFromLink(revertLink);
- github.PullRequest requestToRevert = await githubService.getPullRequest(repositorySlug, pullRequestId);
+ final int pullRequestId = _getPullRequestNumberFromLink(revertLink);
+ final github.PullRequest requestToRevert = await githubService.getPullRequest(repositorySlug, pullRequestId);
- bool requestsMatch = await githubService.comparePullRequests(repositorySlug, requestToRevert, messagePullRequest);
+ final bool requestsMatch =
+ await githubService.comparePullRequests(repositorySlug, requestToRevert, messagePullRequest);
if (requestsMatch) {
return ValidationResult(
@@ -103,7 +104,7 @@
return null;
}
final RegExp regExp = RegExp(r'[Rr]everts[\s]+([-\.a-zA-Z_]+/[-\.a-zA-Z_]+#[0-9]+)', multiLine: true);
- Iterable<RegExpMatch> matches = regExp.allMatches(bodyText);
+ final Iterable<RegExpMatch> matches = regExp.allMatches(bodyText);
if (matches.isNotEmpty && matches.length == 1) {
return matches.elementAt(0).group(1);
@@ -116,15 +117,15 @@
/// Split a reverts link on the '#' then the '/' to get the parts of the repo
/// slug. It is assumed that the link has the format flutter/repo#id.
github.RepositorySlug _getSlugFromLink(String link) {
- List<String> linkSplit = link.split('#');
- List<String> slugSplit = linkSplit.elementAt(0).split('/');
+ final List<String> linkSplit = link.split('#');
+ final List<String> slugSplit = linkSplit.elementAt(0).split('/');
return github.RepositorySlug(slugSplit.elementAt(0), slugSplit.elementAt(1));
}
/// Split a reverts link on the '#' to get the id part of the link.
/// It is assumed that the link has the format flutter/repo#id.
int _getPullRequestNumberFromLink(String link) {
- List<String> linkSplit = link.split('#');
+ final List<String> linkSplit = link.split('#');
return int.parse(linkSplit.elementAt(1));
}
@@ -136,7 +137,7 @@
required String sha,
required List<String> checkNames,
}) async {
- List<github.CheckRun> targetCheckRuns = [];
+ final List<github.CheckRun> targetCheckRuns = [];
for (var element in checkNames) {
targetCheckRuns.addAll(
await githubService.getCheckRunsFiltered(
@@ -180,7 +181,7 @@
GithubService githubService,
github.CheckRun targetCheckRun,
) async {
- List<github.CheckRun> checkRuns = await githubService.getCheckRunsFiltered(
+ final List<github.CheckRun> checkRuns = await githubService.getCheckRunsFiltered(
slug: slug,
ref: targetCheckRun.headSha!,
checkName: targetCheckRun.name,
diff --git a/auto_submit/test/model/auto_submit_query_result_test.dart b/auto_submit/test/model/auto_submit_query_result_test.dart
index c5cc118..abc4527 100644
--- a/auto_submit/test/model/auto_submit_query_result_test.dart
+++ b/auto_submit/test/model/auto_submit_query_result_test.dart
@@ -16,12 +16,12 @@
});
test('repository values', () async {
- Repository repository = queryResult.repository!;
+ final Repository repository = queryResult.repository!;
expect(repository.pullRequest, isNotNull);
});
test('pullRequest values', () async {
- PullRequest pullRequest = queryResult.repository!.pullRequest!;
+ final PullRequest pullRequest = queryResult.repository!.pullRequest!;
expect(pullRequest.author, isNotNull);
expect(pullRequest.authorAssociation, 'MEMBER');
expect(pullRequest.commits, isNotNull);
@@ -31,7 +31,7 @@
});
test('Author values', () async {
- Author author = queryResult.repository!.pullRequest!.author!;
+ final Author author = queryResult.repository!.pullRequest!.author!;
expect(author.login, 'author1');
});
@@ -48,7 +48,7 @@
test('Commits values', () async {
final Commits commits = queryResult.repository!.pullRequest!.commits!;
expect(commits.nodes, isNotNull);
- CommitNode commitNode = commits.nodes!.first;
+ final CommitNode commitNode = commits.nodes!.first;
expect(commitNode.commit, isNotNull);
expect(commitNode.commit!.abbreviatedOid, '4009ecc');
expect(commitNode.commit!.oid, '4009ecc0b6dbf5cb19cb97472147063e7368ec10');
diff --git a/auto_submit/test/model/pull_request_change_type.dart b/auto_submit/test/model/pull_request_change_type.dart
index 1545501..f611a28 100644
--- a/auto_submit/test/model/pull_request_change_type.dart
+++ b/auto_submit/test/model/pull_request_change_type.dart
@@ -6,7 +6,7 @@
import 'package:test/test.dart';
void main() {
- List<String> expectedNames = ['change', 'revert'];
+ final List<String> expectedNames = ['change', 'revert'];
test('Expected string value for enum is returned.', () {
for (PullRequestChangeType prChangeType in PullRequestChangeType.values) {
diff --git a/auto_submit/test/request_handling/authentication_test.dart b/auto_submit/test/request_handling/authentication_test.dart
index 7e53caa..93cbbd5 100644
--- a/auto_submit/test/request_handling/authentication_test.dart
+++ b/auto_submit/test/request_handling/authentication_test.dart
@@ -22,7 +22,7 @@
});
test('succeeds for App Engine cronjobs', () async {
- Map<String, String> header = {'X-Appengine-Cron': 'true'};
+ final Map<String, String> header = {'X-Appengine-Cron': 'true'};
request = Request('POST', Uri.parse('http://localhost/'), headers: header);
final bool result = await auth.authenticate(request);
expect(result, true);
diff --git a/auto_submit/test/requests/check_pull_request_test.dart b/auto_submit/test/requests/check_pull_request_test.dart
index c4826c6..f21f959 100644
--- a/auto_submit/test/requests/check_pull_request_test.dart
+++ b/auto_submit/test/requests/check_pull_request_test.dart
@@ -242,7 +242,7 @@
),
);
- Map<int, RepositorySlug> expectedMergeRequestMap = {};
+ final Map<int, RepositorySlug> expectedMergeRequestMap = {};
expectedMergeRequestMap[0] = RepositorySlug('flutter', 'flutter');
expectedMergeRequestMap[1] = RepositorySlug('flutter', cocoonRepo);
diff --git a/auto_submit/test/requests/github_webhook_test.dart b/auto_submit/test/requests/github_webhook_test.dart
index 061520a..f686a4e 100644
--- a/auto_submit/test/requests/github_webhook_test.dart
+++ b/auto_submit/test/requests/github_webhook_test.dart
@@ -44,7 +44,7 @@
final Response response = await githubWebhook.post(req);
final String resBody = await response.readAsString();
final reqBody = json.decode(resBody) as Map<String, dynamic>;
- List<IssueLabel> labels = PullRequest.fromJson(reqBody['pull_request'] as Map<String, dynamic>).labels!;
+ final List<IssueLabel> labels = PullRequest.fromJson(reqBody['pull_request'] as Map<String, dynamic>).labels!;
expect(labels[0].name, 'cla: yes');
expect(labels[1].name, 'autosubmit');
});
diff --git a/auto_submit/test/requests/update_revert_issues_test.dart b/auto_submit/test/requests/update_revert_issues_test.dart
index baf0196..da026f7 100644
--- a/auto_submit/test/requests/update_revert_issues_test.dart
+++ b/auto_submit/test/requests/update_revert_issues_test.dart
@@ -61,15 +61,15 @@
group('Update issue tests.', () {
test('Open issue is not updated.', () async {
- User user = User(login: 'ricardoamador');
- Issue issue = Issue(
+ final User user = User(login: 'ricardoamador');
+ final Issue issue = Issue(
user: user,
state: 'open',
);
fakeGithubService.githubIssueMock = issue;
- RevertRequestRecord revertRequestRecord = RevertRequestRecord(
+ final RevertRequestRecord revertRequestRecord = RevertRequestRecord(
reviewIssueAssignee: 'keyonghan',
reviewIssueCreatedTimestamp: DateTime.now(),
reviewIssueNumber: 1234,
@@ -81,7 +81,7 @@
);
});
- bool result = await updateRevertReviews.updateIssue(
+ final bool result = await updateRevertReviews.updateIssue(
revertRequestRecord: revertRequestRecord,
bigqueryService: fakeBigqueryService,
githubService: fakeGithubService,
@@ -91,8 +91,8 @@
});
test('Closed issue is updated.', () async {
- User user = User(login: 'ricardoamador');
- Issue issue = Issue(
+ final User user = User(login: 'ricardoamador');
+ final Issue issue = Issue(
user: user,
state: 'closed',
closedAt: DateTime.now(),
@@ -102,7 +102,7 @@
fakeGithubService.githubIssueMock = issue;
- RevertRequestRecord revertRequestRecord = RevertRequestRecord(
+ final RevertRequestRecord revertRequestRecord = RevertRequestRecord(
reviewIssueAssignee: 'keyonghan',
reviewIssueCreatedTimestamp: DateTime.now(),
reviewIssueNumber: 1234,
@@ -114,7 +114,7 @@
);
});
- bool result = await updateRevertReviews.updateIssue(
+ final bool result = await updateRevertReviews.updateIssue(
revertRequestRecord: revertRequestRecord,
bigqueryService: fakeBigqueryService,
githubService: fakeGithubService,
@@ -124,8 +124,8 @@
});
test('Closed issue is not updated on exception.', () async {
- User user = User(login: 'ricardoamador');
- Issue issue = Issue(
+ final User user = User(login: 'ricardoamador');
+ final Issue issue = Issue(
user: user,
state: 'closed',
closedAt: DateTime.now(),
@@ -135,7 +135,7 @@
fakeGithubService.githubIssueMock = issue;
- RevertRequestRecord revertRequestRecord = RevertRequestRecord(
+ final RevertRequestRecord revertRequestRecord = RevertRequestRecord(
reviewIssueAssignee: 'keyonghan',
reviewIssueCreatedTimestamp: DateTime.now(),
reviewIssueNumber: 1234,
@@ -145,7 +145,7 @@
throw BigQueryException('Update of review issue 1234 did not complete.');
});
- bool result = await updateRevertReviews.updateIssue(
+ final bool result = await updateRevertReviews.updateIssue(
revertRequestRecord: revertRequestRecord,
bigqueryService: fakeBigqueryService,
githubService: fakeGithubService,
@@ -163,9 +163,9 @@
);
});
- Response response = await updateRevertReviews.get();
+ final Response response = await updateRevertReviews.get();
expect(response.statusCode, 200);
- String body = await response.readAsString(Encoding.getByName("UTF-8"));
+ final String body = await response.readAsString(Encoding.getByName("UTF-8"));
expect(body, equals('No open revert reviews to update.'));
});
});
diff --git a/auto_submit/test/service/bigquery_test.dart b/auto_submit/test/service/bigquery_test.dart
index cda9ba3..1dc880b 100644
--- a/auto_submit/test/service/bigquery_test.dart
+++ b/auto_submit/test/service/bigquery_test.dart
@@ -201,7 +201,7 @@
);
});
- PullRequestRecord pullRequestRecord = PullRequestRecord(
+ final PullRequestRecord pullRequestRecord = PullRequestRecord(
prCreatedTimestamp: DateTime.fromMillisecondsSinceEpoch(123456789),
prLandedTimestamp: DateTime.fromMillisecondsSinceEpoch(234567890),
organization: 'flutter',
@@ -232,7 +232,7 @@
});
bool hasError = false;
- PullRequestRecord pullRequestRecord = PullRequestRecord(
+ final PullRequestRecord pullRequestRecord = PullRequestRecord(
prCreatedTimestamp: DateTime.fromMillisecondsSinceEpoch(123456789),
prLandedTimestamp: DateTime.fromMillisecondsSinceEpoch(234567890),
organization: 'flutter',
@@ -263,7 +263,7 @@
});
bool hasError = false;
- PullRequestRecord pullRequestRecord = PullRequestRecord(
+ final PullRequestRecord pullRequestRecord = PullRequestRecord(
prCreatedTimestamp: DateTime.fromMillisecondsSinceEpoch(123456789),
prLandedTimestamp: DateTime.fromMillisecondsSinceEpoch(234567890),
organization: 'flutter',
@@ -293,7 +293,7 @@
);
});
- PullRequestRecord pullRequestRecord = await service.selectPullRequestRecordByPrNumber(
+ final PullRequestRecord pullRequestRecord = await service.selectPullRequestRecordByPrNumber(
projectId: expectedProjectId,
prNumber: 345,
repository: 'cocoon',
@@ -454,7 +454,7 @@
);
});
- RevertRequestRecord revertRequestRecord = RevertRequestRecord(
+ final RevertRequestRecord revertRequestRecord = RevertRequestRecord(
organization: 'flutter',
repository: 'cocoon',
author: 'ricardoamador',
@@ -492,7 +492,7 @@
});
bool hasError = false;
- RevertRequestRecord revertRequestRecord = RevertRequestRecord(
+ final RevertRequestRecord revertRequestRecord = RevertRequestRecord(
organization: 'flutter',
repository: 'cocoon',
author: 'ricardoamador',
@@ -529,7 +529,7 @@
);
});
- RevertRequestRecord revertRequestRecord = await service.selectRevertRequestByRevertPrNumber(
+ final RevertRequestRecord revertRequestRecord = await service.selectRevertRequestByRevertPrNumber(
projectId: expectedProjectId,
prNumber: 2048,
repository: 'cocoon',
@@ -703,11 +703,12 @@
);
});
- List<RevertRequestRecord> revertRequestRecordReviewsList = await service.selectOpenReviewRequestIssueRecordsList(
+ final List<RevertRequestRecord> revertRequestRecordReviewsList =
+ await service.selectOpenReviewRequestIssueRecordsList(
projectId: expectedProjectId,
);
- RevertRequestRecord keyongRecord = RevertRequestRecord(
+ final RevertRequestRecord keyongRecord = RevertRequestRecord(
reviewIssueAssignee: 'Keyonghan',
reviewIssueNumber: 2048,
reviewIssueCreatedTimestamp: DateTime.fromMillisecondsSinceEpoch(234567890),
@@ -715,7 +716,7 @@
reviewIssueClosedBy: '',
);
- RevertRequestRecord caseyRecord = RevertRequestRecord(
+ final RevertRequestRecord caseyRecord = RevertRequestRecord(
reviewIssueAssignee: 'caseyhillers',
reviewIssueNumber: 2049,
reviewIssueCreatedTimestamp: DateTime.fromMillisecondsSinceEpoch(234567890),
@@ -748,7 +749,8 @@
);
});
- List<RevertRequestRecord> revertRequestRecordReviewsList = await service.selectOpenReviewRequestIssueRecordsList(
+ final List<RevertRequestRecord> revertRequestRecordReviewsList =
+ await service.selectOpenReviewRequestIssueRecordsList(
projectId: expectedProjectId,
);
diff --git a/auto_submit/test/service/config_test.dart b/auto_submit/test/service/config_test.dart
index fe91e7a..ac38022 100644
--- a/auto_submit/test/service/config_test.dart
+++ b/auto_submit/test/service/config_test.dart
@@ -52,7 +52,7 @@
test('generateGithubToken pulls from cache', () async {
const String configValue = 'githubToken';
final Uint8List cachedValue = Uint8List.fromList(configValue.codeUnits);
- Cache cache = Cache<dynamic>(cacheProvider).withPrefix('config');
+ final Cache cache = Cache<dynamic>(cacheProvider).withPrefix('config');
await cache['githubToken-${flutterSlug.owner}'].set(
cachedValue,
const Duration(minutes: 1),
@@ -67,7 +67,7 @@
final Uint8List flutterValue = Uint8List.fromList(flutterToken.codeUnits);
const String testToken = 'testToken';
final Uint8List testValue = Uint8List.fromList(testToken.codeUnits);
- Cache cache = Cache<dynamic>(cacheProvider).withPrefix('config');
+ final Cache cache = Cache<dynamic>(cacheProvider).withPrefix('config');
await cache['githubToken-${flutterSlug.owner}'].set(
flutterValue,
const Duration(minutes: 1),
@@ -77,8 +77,8 @@
const Duration(minutes: 1),
);
- GitHub flutterClient = await config.createGithubClient(flutterSlug);
- GitHub testClient = await config.createGithubClient(testSlug);
+ final GitHub flutterClient = await config.createGithubClient(flutterSlug);
+ final GitHub testClient = await config.createGithubClient(testSlug);
expect(flutterClient.auth!.token!, flutterToken);
expect(testClient.auth!.token!, testToken);
});
diff --git a/auto_submit/test/service/github_service_test.dart b/auto_submit/test/service/github_service_test.dart
index 484b04b..6bfd46b 100644
--- a/auto_submit/test/service/github_service_test.dart
+++ b/auto_submit/test/service/github_service_test.dart
@@ -60,14 +60,14 @@
test('Merges branch', () async {
when(mockGitHubComparison.behindBy).thenReturn(10);
- PullRequest pullRequest = generatePullRequest();
+ final PullRequest pullRequest = generatePullRequest();
await githubService.autoMergeBranch(pullRequest);
verify(mockResponse.statusCode).called(1);
});
test('Does not merge branch', () async {
when(mockGitHubComparison.behindBy).thenReturn(9);
- PullRequest pullRequest = generatePullRequest();
+ final PullRequest pullRequest = generatePullRequest();
await githubService.autoMergeBranch(pullRequest);
verifyNever(mockResponse.statusCode);
});
diff --git a/auto_submit/test/service/validation_service_test.dart b/auto_submit/test/service/validation_service_test.dart
index 6c5ba14..3525826 100644
--- a/auto_submit/test/service/validation_service_test.dart
+++ b/auto_submit/test/service/validation_service_test.dart
@@ -154,7 +154,7 @@
githubService.pullRequestMock = pullRequest;
unawaited(pubsub.publish('auto-submit-queue-sub', pullRequest));
- auto.QueryResult queryResult = createQueryResult(flutterRequest);
+ final auto.QueryResult queryResult = createQueryResult(flutterRequest);
await validationService.processRevertRequest(
config: config,
diff --git a/auto_submit/test/src/request_handling/fake_pubsub.dart b/auto_submit/test/src/request_handling/fake_pubsub.dart
index a89b198..75d5a4c 100644
--- a/auto_submit/test/src/request_handling/fake_pubsub.dart
+++ b/auto_submit/test/src/request_handling/fake_pubsub.dart
@@ -27,7 +27,7 @@
@override
Future<PullResponse> pull(String subscription, int maxMessages) async {
// The list will be empty if there are no more messages available in the backlog.
- List<ReceivedMessage> receivedMessages = <ReceivedMessage>[];
+ final List<ReceivedMessage> receivedMessages = <ReceivedMessage>[];
iteration++;
if (messagesQueue.isNotEmpty) {
int i = iteration * messageSize;
diff --git a/auto_submit/test/src/service/fake_github_service.dart b/auto_submit/test/src/service/fake_github_service.dart
index e7e8e2d..0895ee5 100644
--- a/auto_submit/test/src/service/fake_github_service.dart
+++ b/auto_submit/test/src/service/fake_github_service.dart
@@ -105,7 +105,7 @@
) async {
final rawBody = json.decode(checkRunsMock!) as Map<String, dynamic>;
final List<dynamic> checkRunsBody = rawBody["check_runs"]! as List<dynamic>;
- List<CheckRun> checkRuns = <CheckRun>[];
+ final List<CheckRun> checkRuns = <CheckRun>[];
if ((checkRunsBody[0] as Map<String, dynamic>).isNotEmpty) {
checkRuns.addAll(
checkRunsBody.map((dynamic checkRun) => CheckRun.fromJson(checkRun as Map<String, dynamic>)).toList(),
@@ -122,9 +122,9 @@
CheckRunStatus? status,
CheckRunFilter? filter,
}) async {
- List<CheckRun> checkRuns = await getCheckRuns(slug, ref);
+ final List<CheckRun> checkRuns = await getCheckRuns(slug, ref);
if (checkName != null) {
- List<CheckRun> checkRunsFilteredByName = [];
+ final List<CheckRun> checkRunsFilteredByName = [];
for (CheckRun checkRun in checkRuns) {
if (checkRun.name == checkName) {
checkRunsFilteredByName.add(checkRun);
@@ -200,12 +200,12 @@
pullRequestData = pullRequestFilesJsonMock as String;
}
- List<PullRequestFile> pullRequestFileList = [];
+ final List<PullRequestFile> pullRequestFileList = [];
- dynamic parsedList = jsonDecode(pullRequestData);
+ final dynamic parsedList = jsonDecode(pullRequestData);
for (dynamic d in parsedList) {
- PullRequestFile file = PullRequestFile.fromJson(d as Map<String, dynamic>);
+ final PullRequestFile file = PullRequestFile.fromJson(d as Map<String, dynamic>);
pullRequestFileList.add(file);
}
@@ -234,8 +234,8 @@
return compareReturnValue;
}
- List<PullRequestFile> revertPullRequestFiles = await getPullRequestFiles(repositorySlug, revert);
- List<PullRequestFile> currentPullRequestFiles = await getPullRequestFiles(repositorySlug, current);
+ final List<PullRequestFile> revertPullRequestFiles = await getPullRequestFiles(repositorySlug, revert);
+ final List<PullRequestFile> currentPullRequestFiles = await getPullRequestFiles(repositorySlug, current);
return validateFileSetsAreEqual(revertPullRequestFiles, currentPullRequestFiles);
}
@@ -268,7 +268,7 @@
// At this point all the files are the same so we can iterate over one list to
// compare changes.
for (PullRequestFile pullRequestFile in changeList1) {
- PullRequestFile pullRequestFileChangeList2 =
+ final PullRequestFile pullRequestFileChangeList2 =
changeList2.firstWhere((element) => element.filename == pullRequestFile.filename);
if (pullRequestFile.changesCount != pullRequestFileChangeList2.changesCount ||
pullRequestFile.additionsCount != pullRequestFileChangeList2.deletionsCount ||
diff --git a/auto_submit/test/validations/ci_successful_test.dart b/auto_submit/test/validations/ci_successful_test.dart
index 68c472f..44fde06 100644
--- a/auto_submit/test/validations/ci_successful_test.dart
+++ b/auto_submit/test/validations/ci_successful_test.dart
@@ -24,16 +24,16 @@
late FakeConfig config;
FakeGithubService githubService = FakeGithubService();
late FakeGraphQLClient githubGraphQLClient;
- MockGitHub gitHub = MockGitHub();
+ final MockGitHub gitHub = MockGitHub();
late github.RepositorySlug slug;
late Set<FailureDetail> failures;
List<ContextNode> getContextNodeListFromJson(final String repositoryStatuses) {
- List<ContextNode> contextNodeList = [];
+ final List<ContextNode> contextNodeList = [];
- Map<String, dynamic> contextNodeMap = jsonDecode(repositoryStatuses) as Map<String, dynamic>;
+ final Map<String, dynamic> contextNodeMap = jsonDecode(repositoryStatuses) as Map<String, dynamic>;
- dynamic statuses = contextNodeMap['statuses'];
+ final dynamic statuses = contextNodeMap['statuses'];
for (Map<String, dynamic> map in statuses) {
contextNodeList.add(ContextNode.fromJson(map));
}
@@ -60,7 +60,7 @@
test('ValidateCheckRuns no failures for skipped conclusion.', () {
githubService.checkRunsData = skippedCheckRunsMock;
final Future<List<github.CheckRun>> checkRunFuture = githubService.getCheckRuns(slug, 'ref');
- bool allSuccess = true;
+ const bool allSuccess = true;
checkRunFuture.then((checkRuns) {
expect(ciSuccessful.validateCheckRuns(slug, checkRuns, failures, allSuccess), isTrue);
@@ -71,7 +71,7 @@
test('ValidateCheckRuns no failures for successful conclusion.', () {
githubService.checkRunsData = checkRunsMock;
final Future<List<github.CheckRun>> checkRunFuture = githubService.getCheckRuns(slug, 'ref');
- bool allSuccess = true;
+ const bool allSuccess = true;
checkRunFuture.then((checkRuns) {
expect(ciSuccessful.validateCheckRuns(slug, checkRuns, failures, allSuccess), isTrue);
@@ -82,7 +82,7 @@
test('ValidateCheckRuns no failure for status completed and neutral conclusion.', () {
githubService.checkRunsData = neutralCheckRunsMock;
final Future<List<github.CheckRun>> checkRunFuture = githubService.getCheckRuns(slug, 'ref');
- bool allSuccess = true;
+ const bool allSuccess = true;
checkRunFuture.then((checkRuns) {
expect(ciSuccessful.validateCheckRuns(slug, checkRuns, failures, allSuccess), isTrue);
@@ -93,7 +93,7 @@
test('ValidateCheckRuns failure detected on status completed no neutral conclusion.', () {
githubService.checkRunsData = failedCheckRunsMock;
final Future<List<github.CheckRun>> checkRunFuture = githubService.getCheckRuns(slug, 'ref');
- bool allSuccess = true;
+ const bool allSuccess = true;
checkRunFuture.then((checkRuns) {
expect(ciSuccessful.validateCheckRuns(slug, checkRuns, failures, allSuccess), isFalse);
@@ -105,7 +105,7 @@
test('ValidateCheckRuns succes with multiple successful check runs.', () {
githubService.checkRunsData = multipleCheckRunsMock;
final Future<List<github.CheckRun>> checkRunFuture = githubService.getCheckRuns(slug, 'ref');
- bool allSuccess = true;
+ const bool allSuccess = true;
checkRunFuture.then((checkRuns) {
expect(ciSuccessful.validateCheckRuns(slug, checkRuns, failures, allSuccess), isTrue);
@@ -116,7 +116,7 @@
test('ValidateCheckRuns failed with multiple check runs.', () {
githubService.checkRunsData = multipleCheckRunsWithFailureMock;
final Future<List<github.CheckRun>> checkRunFuture = githubService.getCheckRuns(slug, 'ref');
- bool allSuccess = true;
+ const bool allSuccess = true;
checkRunFuture.then((checkRuns) {
expect(ciSuccessful.validateCheckRuns(slug, checkRuns, failures, allSuccess), isFalse);
@@ -130,7 +130,7 @@
/// does not cause failure is a candidate to be temporarily ignored.
githubService.checkRunsData = inprogressAndNotFailedCheckRunMock;
final Future<List<github.CheckRun>> checkRunFuture = githubService.getCheckRuns(slug, 'ref');
- bool allSuccess = true;
+ const bool allSuccess = true;
checkRunFuture.then((checkRuns) {
expect(ciSuccessful.validateCheckRuns(slug, checkRuns, failures, allSuccess), isFalse);
@@ -141,7 +141,7 @@
test('ValidateCheckRuns allSuccess false is preserved.', () {
githubService.checkRunsData = multipleCheckRunsWithFailureMock;
final Future<List<github.CheckRun>> checkRunFuture = githubService.getCheckRuns(slug, 'ref');
- bool allSuccess = false;
+ const bool allSuccess = false;
checkRunFuture.then((checkRuns) {
expect(ciSuccessful.validateCheckRuns(slug, checkRuns, failures, allSuccess), isFalse);
@@ -154,7 +154,7 @@
group('validateStatuses', () {
test('Validate successful statuses show as successful.', () {
final List<ContextNode> contextNodeList = getContextNodeListFromJson(repositoryStatusesMock);
- bool allSuccess = true;
+ const bool allSuccess = true;
/// The status must be uppercase as the original code is expecting this.
convertContextNodeStatuses(contextNodeList);
@@ -164,7 +164,7 @@
test('Validate statuses that are not successful but do not cause failure.', () {
final List<ContextNode> contextNodeList = getContextNodeListFromJson(failedAuthorsStatusesMock);
- bool allSuccess = true;
+ const bool allSuccess = true;
final List<String> labelNames = [];
labelNames.add('warning: land on red to fix tree breakage');
@@ -177,7 +177,7 @@
test('Validate failure statuses do not cause failure with not in authors control.', () {
final List<ContextNode> contextNodeList = getContextNodeListFromJson(failedAuthorsStatusesMock);
- bool allSuccess = true;
+ const bool allSuccess = true;
final List<String> labelNames = [];
labelNames.add('Compelling label');
@@ -190,7 +190,7 @@
test('Validate failure statuses cause failures with not in authors control.', () {
final List<ContextNode> contextNodeList = getContextNodeListFromJson(failedNonAuthorsStatusesMock);
- bool allSuccess = true;
+ const bool allSuccess = true;
final List<String> labelNames = [];
labelNames.add('Compelling label');
@@ -204,7 +204,7 @@
test('Validate failure statuses cause failures and preserves false allSuccess.', () {
final List<ContextNode> contextNodeList = getContextNodeListFromJson(failedNonAuthorsStatusesMock);
- bool allSuccess = false;
+ const bool allSuccess = false;
final List<String> labelNames = [];
labelNames.add('Compelling label');
@@ -225,7 +225,7 @@
/// The status must be uppercase as the original code is expecting this.
convertContextNodeStatuses(contextNodeList);
- bool treeStatusFlag = ciSuccessful.treeStatusCheck(slug, contextNodeList);
+ final bool treeStatusFlag = ciSuccessful.treeStatusCheck(slug, contextNodeList);
expect(treeStatusFlag, true);
});
@@ -236,7 +236,7 @@
/// The status must be uppercase as the original code is expecting this.
convertContextNodeStatuses(contextNodeList);
- bool treeStatusFlag = ciSuccessful.treeStatusCheck(slug, contextNodeList);
+ final bool treeStatusFlag = ciSuccessful.treeStatusCheck(slug, contextNodeList);
expect(treeStatusFlag, true);
});
@@ -246,7 +246,7 @@
/// The status must be uppercase as the original code is expecting this.
convertContextNodeStatuses(contextNodeList);
- bool treeStatusFlag = ciSuccessful.treeStatusCheck(slug, contextNodeList);
+ final bool treeStatusFlag = ciSuccessful.treeStatusCheck(slug, contextNodeList);
expect(treeStatusFlag, false);
});
});
@@ -373,7 +373,7 @@
});
test('returns correct message when validation fails', () async {
- PullRequestHelper flutterRequest = PullRequestHelper(
+ final PullRequestHelper flutterRequest = PullRequestHelper(
prNumber: 0,
lastCommitHash: oid,
reviews: <PullRequestReviewHelper>[],
@@ -381,7 +381,7 @@
githubService.checkRunsData = failedCheckRunsMock;
final github.PullRequest pullRequest = generatePullRequest(prNumber: 0, repoName: slug.name);
- QueryResult queryResult = createQueryResult(flutterRequest);
+ final QueryResult queryResult = createQueryResult(flutterRequest);
final ValidationResult validationResult = await ciSuccessful.validate(queryResult, pullRequest);
diff --git a/auto_submit/test/validations/revert_test.dart b/auto_submit/test/validations/revert_test.dart
index 9e72a3b..31e07ee 100644
--- a/auto_submit/test/validations/revert_test.dart
+++ b/auto_submit/test/validations/revert_test.dart
@@ -23,7 +23,7 @@
late FakeConfig config;
late FakeGithubService githubService;
late FakeGraphQLClient githubGraphQLClient;
- MockGitHub gitHub = MockGitHub();
+ final MockGitHub gitHub = MockGitHub();
late Revert revert;
/// Setup objects needed across test groups.
@@ -39,24 +39,24 @@
group('Author validation tests.', () {
test('Validate author association member is valid.', () {
- String authorAssociation = 'MEMBER';
+ const String authorAssociation = 'MEMBER';
assert(revert.isValidAuthor('octocat', authorAssociation));
});
test('Validate author association owner is valid.', () {
- String authorAssociation = 'OWNER';
+ const String authorAssociation = 'OWNER';
assert(revert.isValidAuthor('octocat', authorAssociation));
});
test('Validate author dependabot is valid.', () {
- String author = 'dependabot';
- String authorAssociation = 'NON_MEMBER';
+ const String author = 'dependabot';
+ const String authorAssociation = 'NON_MEMBER';
assert(revert.isValidAuthor(author, authorAssociation));
});
test('Validate autoroller account is valid.', () {
- String author = 'engine-flutter-autoroll';
- String authorAssociation = 'CONTRIBUTOR';
+ const String author = 'engine-flutter-autoroll';
+ const String authorAssociation = 'CONTRIBUTOR';
assert(revert.isValidAuthor(author, authorAssociation));
});
});
@@ -64,7 +64,7 @@
group('Pattern matching for revert text link', () {
test('Link extraction from description is successful.', () {
// input, expected
- Map<String, String> tests = <String, String>{};
+ final Map<String, String> tests = <String, String>{};
tests['Reverts flutter/cocoon#123456'] = 'flutter/cocoon#123456';
tests['Reverts flutter/cocoon#123456'] = 'flutter/cocoon#123456';
tests['Reverts flutter/flutter-intellij#123456'] = 'flutter/flutter-intellij#123456';
@@ -87,14 +87,14 @@
tests['This some text to add flavor before reverts flutter/flutter#8888.'] = 'flutter/flutter#8888';
tests.forEach((key, value) {
- String? linkFound = revert.extractLinkFromText(key);
+ final String? linkFound = revert.extractLinkFromText(key);
assert(linkFound != null);
assert(linkFound == value);
});
});
test('Link extraction from description returns null', () {
- Map<String, String> tests = <String, String>{};
+ final Map<String, String> tests = <String, String>{};
tests['Revert flutter/cocoon#123456'] = '';
tests['revert flutter/cocoon#123456'] = '';
tests['Reverts flutter/cocoon#'] = '';
@@ -110,7 +110,7 @@
tests['This is some text flutter/flutter#456...44'] = '';
tests.forEach((key, value) {
- String? linkFound = revert.extractLinkFromText(key);
+ final String? linkFound = revert.extractLinkFromText(key);
assert(linkFound == null);
});
});
@@ -118,26 +118,26 @@
group('Validate Pull Requests.', () {
test('Validation fails on author validation, returns error.', () async {
- Map<String, dynamic> pullRequestJsonMap = jsonDecode(revertPullRequestJson) as Map<String, dynamic>;
- github.PullRequest revertPullRequest = github.PullRequest.fromJson(pullRequestJsonMap);
+ final Map<String, dynamic> pullRequestJsonMap = jsonDecode(revertPullRequestJson) as Map<String, dynamic>;
+ final github.PullRequest revertPullRequest = github.PullRequest.fromJson(pullRequestJsonMap);
revertPullRequest.authorAssociation = 'CONTRIBUTOR';
final Map<String, dynamic> queryResultJsonDecode =
jsonDecode(queryResultRepositoryContributorJson) as Map<String, dynamic>;
final QueryResult queryResult = QueryResult.fromJson(queryResultJsonDecode);
- ValidationResult validationResult = await revert.validate(queryResult, revertPullRequest);
+ final ValidationResult validationResult = await revert.validate(queryResult, revertPullRequest);
assert(!validationResult.result);
assert(validationResult.action == Action.REMOVE_LABEL);
assert(validationResult.message.contains(RegExp(r'The author.*does not have permissions to make this request.')));
});
test('Validation fails on merge conflict flag.', () async {
- Map<String, dynamic> pullRequestJsonMap = jsonDecode(revertPullRequestJson) as Map<String, dynamic>;
- github.PullRequest revertPullRequest = github.PullRequest.fromJson(pullRequestJsonMap);
+ final Map<String, dynamic> pullRequestJsonMap = jsonDecode(revertPullRequestJson) as Map<String, dynamic>;
+ final github.PullRequest revertPullRequest = github.PullRequest.fromJson(pullRequestJsonMap);
revertPullRequest.mergeable = false;
final Map<String, dynamic> queryResultJsonDecode =
jsonDecode(queryResultRepositoryOwnerJson) as Map<String, dynamic>;
final QueryResult queryResult = QueryResult.fromJson(queryResultJsonDecode);
- ValidationResult validationResult = await revert.validate(queryResult, revertPullRequest);
+ final ValidationResult validationResult = await revert.validate(queryResult, revertPullRequest);
assert(!validationResult.result);
assert(validationResult.action == Action.REMOVE_LABEL);
assert(
@@ -147,13 +147,13 @@
});
test('Validation fails on malformed reverts link in the pr body.', () async {
- Map<String, dynamic> pullRequestJsonMap = jsonDecode(revertPullRequestJson) as Map<String, dynamic>;
- github.PullRequest revertPullRequest = github.PullRequest.fromJson(pullRequestJsonMap);
+ final Map<String, dynamic> pullRequestJsonMap = jsonDecode(revertPullRequestJson) as Map<String, dynamic>;
+ final github.PullRequest revertPullRequest = github.PullRequest.fromJson(pullRequestJsonMap);
revertPullRequest.body = 'Reverting flutter/cocoon#1234';
final Map<String, dynamic> queryResultJsonDecode =
jsonDecode(queryResultRepositoryOwnerJson) as Map<String, dynamic>;
final QueryResult queryResult = QueryResult.fromJson(queryResultJsonDecode);
- ValidationResult validationResult = await revert.validate(queryResult, revertPullRequest);
+ final ValidationResult validationResult = await revert.validate(queryResult, revertPullRequest);
assert(!validationResult.result);
assert(validationResult.action == Action.REMOVE_LABEL);
assert(
@@ -163,14 +163,15 @@
});
test('Validation returns on checkRun that has not completed.', () async {
- Map<String, dynamic> pullRequestJsonMap = jsonDecode(revertPullRequestJson) as Map<String, dynamic>;
- github.PullRequest revertPullRequest = github.PullRequest.fromJson(pullRequestJsonMap);
+ final Map<String, dynamic> pullRequestJsonMap = jsonDecode(revertPullRequestJson) as Map<String, dynamic>;
+ final github.PullRequest revertPullRequest = github.PullRequest.fromJson(pullRequestJsonMap);
final Map<String, dynamic> queryResultJsonDecode =
jsonDecode(queryResultRepositoryOwnerJson) as Map<String, dynamic>;
final QueryResult queryResult = QueryResult.fromJson(queryResultJsonDecode);
- Map<String, dynamic> originalPullRequestJsonMap = jsonDecode(originalPullRequestJson) as Map<String, dynamic>;
- github.PullRequest originalPullRequest = github.PullRequest.fromJson(originalPullRequestJsonMap);
+ final Map<String, dynamic> originalPullRequestJsonMap =
+ jsonDecode(originalPullRequestJson) as Map<String, dynamic>;
+ final github.PullRequest originalPullRequest = github.PullRequest.fromJson(originalPullRequestJsonMap);
githubService.pullRequestData = originalPullRequest;
// code gets the original file list then the current file list.
@@ -189,7 +190,7 @@
maxAttempts: 1,
),
);
- ValidationResult validationResult = await revert.validate(queryResult, revertPullRequest);
+ final ValidationResult validationResult = await revert.validate(queryResult, revertPullRequest);
expect(validationResult.result, isFalse);
expect(validationResult.action, Action.IGNORE_TEMPORARILY);
@@ -197,14 +198,15 @@
});
test('Validation fails on pull request file lists not matching.', () async {
- Map<String, dynamic> pullRequestJsonMap = jsonDecode(revertPullRequestJson) as Map<String, dynamic>;
- github.PullRequest revertPullRequest = github.PullRequest.fromJson(pullRequestJsonMap);
+ final Map<String, dynamic> pullRequestJsonMap = jsonDecode(revertPullRequestJson) as Map<String, dynamic>;
+ final github.PullRequest revertPullRequest = github.PullRequest.fromJson(pullRequestJsonMap);
final Map<String, dynamic> queryResultJsonDecode =
jsonDecode(queryResultRepositoryOwnerJson) as Map<String, dynamic>;
final QueryResult queryResult = QueryResult.fromJson(queryResultJsonDecode);
- Map<String, dynamic> originalPullRequestJsonMap = jsonDecode(originalPullRequestJson) as Map<String, dynamic>;
- github.PullRequest originalPullRequest = github.PullRequest.fromJson(originalPullRequestJsonMap);
+ final Map<String, dynamic> originalPullRequestJsonMap =
+ jsonDecode(originalPullRequestJson) as Map<String, dynamic>;
+ final github.PullRequest originalPullRequest = github.PullRequest.fromJson(originalPullRequestJsonMap);
githubService.pullRequestData = originalPullRequest;
// code gets the original file list then the current file list.
@@ -215,7 +217,7 @@
// Need to set the mock checkRuns for required CheckRun validation
githubService.checkRunsData = ciyamlCheckRun;
- ValidationResult validationResult = await revert.validate(queryResult, revertPullRequest);
+ final ValidationResult validationResult = await revert.validate(queryResult, revertPullRequest);
assert(!validationResult.result);
assert(validationResult.action == Action.REMOVE_LABEL);
assert(
@@ -225,14 +227,15 @@
});
test('Validation is successful.', () async {
- Map<String, dynamic> pullRequestJsonMap = jsonDecode(revertPullRequestJson) as Map<String, dynamic>;
- github.PullRequest revertPullRequest = github.PullRequest.fromJson(pullRequestJsonMap);
+ final Map<String, dynamic> pullRequestJsonMap = jsonDecode(revertPullRequestJson) as Map<String, dynamic>;
+ final github.PullRequest revertPullRequest = github.PullRequest.fromJson(pullRequestJsonMap);
final Map<String, dynamic> queryResultJsonDecode =
jsonDecode(queryResultRepositoryOwnerJson) as Map<String, dynamic>;
final QueryResult queryResult = QueryResult.fromJson(queryResultJsonDecode);
- Map<String, dynamic> originalPullRequestJsonMap = jsonDecode(originalPullRequestJson) as Map<String, dynamic>;
- github.PullRequest originalPullRequest = github.PullRequest.fromJson(originalPullRequestJsonMap);
+ final Map<String, dynamic> originalPullRequestJsonMap =
+ jsonDecode(originalPullRequestJson) as Map<String, dynamic>;
+ final github.PullRequest originalPullRequest = github.PullRequest.fromJson(originalPullRequestJsonMap);
githubService.pullRequestData = originalPullRequest;
// code gets the original file list then the current file list.
@@ -243,7 +246,7 @@
// Need to set the mock checkRuns for required CheckRun validation
githubService.checkRunsData = ciyamlCheckRun;
- ValidationResult validationResult = await revert.validate(queryResult, revertPullRequest);
+ final ValidationResult validationResult = await revert.validate(queryResult, revertPullRequest);
assert(validationResult.result);
assert(validationResult.message == 'Revert request has been verified and will be queued for merge.');
});
diff --git a/codesign/bin/codesign.dart b/codesign/bin/codesign.dart
index 053282c..937ac45 100644
--- a/codesign/bin/codesign.dart
+++ b/codesign/bin/codesign.dart
@@ -65,12 +65,16 @@
Future<void> main(List<String> args) async {
final ArgParser parser = ArgParser();
parser
- ..addFlag(kHelpFlag, help: 'Prints usage info.', callback: (bool value) {
- if (value) {
- stdout.write('${parser.usage}\n');
- exit(1);
- }
- })
+ ..addFlag(
+ kHelpFlag,
+ help: 'Prints usage info.',
+ callback: (bool value) {
+ if (value) {
+ stdout.write('${parser.usage}\n');
+ exit(1);
+ }
+ },
+ )
..addOption(
kCodesignCertNameOption,
help: 'The name of the codesign certificate to be used when codesigning.'
diff --git a/codesign/lib/src/file_codesign_visitor.dart b/codesign/lib/src/file_codesign_visitor.dart
index 8581ef7..cacaea8 100644
--- a/codesign/lib/src/file_codesign_visitor.dart
+++ b/codesign/lib/src/file_codesign_visitor.dart
@@ -140,14 +140,14 @@
'make sure you have provided codesign credentials in a file \n');
}
- String passwordLine = await fileSystem.file(passwordFilePath).readAsString();
- List<String> parsedPasswordLine = passwordLine.split(":");
+ final String passwordLine = await fileSystem.file(passwordFilePath).readAsString();
+ final List<String> parsedPasswordLine = passwordLine.split(":");
if (parsedPasswordLine.length != 2) {
throw CodesignException('$passwordFilePath is not correctly formatted. \n'
'please double check formatting \n');
}
- String passwordName = parsedPasswordLine[0];
- String passwordValue = parsedPasswordLine[1];
+ final String passwordName = parsedPasswordLine[0];
+ final String passwordValue = parsedPasswordLine[1];
if (!availablePasswords.containsKey(passwordName)) {
throw CodesignException('$passwordName is not a password we can process. \n'
'please double check passwords.txt \n');
@@ -246,7 +246,8 @@
log.info('Visiting directory ${directory.absolute.path}');
if (directoriesVisited.contains(directory.absolute.path)) {
log.warning(
- 'Warning! You are visiting a directory that has been visited before, the directory is ${directory.absolute.path}');
+ 'Warning! You are visiting a directory that has been visited before, the directory is ${directory.absolute.path}',
+ );
}
directoriesVisited.add(directory.absolute.path);
final List<FileSystemEntity> entities = await directory.list().toList();
@@ -457,7 +458,8 @@
final io.ProcessResult result = processManager.runSync(args);
if (result.exitCode != 0) {
throw CodesignException(
- 'Command "${args.join(' ')}" failed with exit code ${result.exitCode}\nStdout: ${result.stdout}\nStderr: ${result.stderr}');
+ 'Command "${args.join(' ')}" failed with exit code ${result.exitCode}\nStdout: ${result.stdout}\nStderr: ${result.stderr}',
+ );
}
final String combinedOutput = (result.stdout as String) + (result.stderr as String);
diff --git a/codesign/test/file_codesign_visitor_test.dart b/codesign/test/file_codesign_visitor_test.dart
index 6a596d7..b717b33 100644
--- a/codesign/test/file_codesign_visitor_test.dart
+++ b/codesign/test/file_codesign_visitor_test.dart
@@ -129,10 +129,13 @@
encoding: utf8,
);
- expect(() async {
- await codesignVisitor.readPassword(appSpecificPasswordFilePath);
- await fileSystem.file(appSpecificPasswordFilePath).delete();
- }, returnsNormally);
+ expect(
+ () async {
+ await codesignVisitor.readPassword(appSpecificPasswordFilePath);
+ await fileSystem.file(appSpecificPasswordFilePath).delete();
+ },
+ returnsNormally,
+ );
});
});
@@ -378,7 +381,8 @@
expect(
messages,
contains(
- 'The downloaded file is unzipped from ${rootDirectory.absolute.path}/downloads/remote_artifact.zip to ${rootDirectory.path}/single_artifact'),
+ 'The downloaded file is unzipped from ${rootDirectory.absolute.path}/downloads/remote_artifact.zip to ${rootDirectory.path}/single_artifact',
+ ),
);
expect(
messages,
@@ -395,17 +399,20 @@
expect(
messages,
contains(
- 'uploading xcrun notarytool submit ${rootDirectory.absolute.path}/codesigned_zips/remote_artifact.zip --apple-id $randomString --password $randomString --team-id $randomString'),
+ 'uploading xcrun notarytool submit ${rootDirectory.absolute.path}/codesigned_zips/remote_artifact.zip --apple-id $randomString --password $randomString --team-id $randomString',
+ ),
);
expect(
messages,
contains(
- 'RequestUUID for ${rootDirectory.absolute.path}/codesigned_zips/remote_artifact.zip is: $randomString'),
+ 'RequestUUID for ${rootDirectory.absolute.path}/codesigned_zips/remote_artifact.zip is: $randomString',
+ ),
);
expect(
messages,
contains(
- 'checking notary status with xcrun notarytool info $randomString --password $randomString --apple-id $randomString --team-id $randomString'),
+ 'checking notary status with xcrun notarytool info $randomString --password $randomString --apple-id $randomString --team-id $randomString',
+ ),
);
expect(
messages,
@@ -535,15 +542,16 @@
fileSystem.file(zipFileName).createSync(recursive: true);
processManager.addCommands(<FakeCommand>[
FakeCommand(
- command: <String>[
- 'unzip',
- '${rootDirectory.absolute.path}/remote_zip_2/zip_1',
- '-d',
- '${rootDirectory.absolute.path}/embedded_zip_${zipFileName.hashCode}',
- ],
- onRun: () => fileSystem
- ..file('${rootDirectory.path}/embedded_zip_${zipFileName.hashCode}/file_1').createSync(recursive: true)
- ..file('${rootDirectory.path}/embedded_zip_${zipFileName.hashCode}/file_2').createSync(recursive: true)),
+ command: <String>[
+ 'unzip',
+ '${rootDirectory.absolute.path}/remote_zip_2/zip_1',
+ '-d',
+ '${rootDirectory.absolute.path}/embedded_zip_${zipFileName.hashCode}',
+ ],
+ onRun: () => fileSystem
+ ..file('${rootDirectory.path}/embedded_zip_${zipFileName.hashCode}/file_1').createSync(recursive: true)
+ ..file('${rootDirectory.path}/embedded_zip_${zipFileName.hashCode}/file_2').createSync(recursive: true),
+ ),
FakeCommand(
command: <String>[
'file',
@@ -585,9 +593,11 @@
.map((LogRecord record) => record.message)
.toList();
expect(
- messages,
- contains(
- 'The downloaded file is unzipped from ${rootDirectory.path}/remote_zip_2/zip_1 to ${rootDirectory.path}/embedded_zip_${zipFileName.hashCode}'));
+ messages,
+ contains(
+ 'The downloaded file is unzipped from ${rootDirectory.path}/remote_zip_2/zip_1 to ${rootDirectory.path}/embedded_zip_${zipFileName.hashCode}',
+ ),
+ );
expect(messages, contains('Visiting directory ${rootDirectory.path}/embedded_zip_${zipFileName.hashCode}'));
expect(messages, contains('Child file of directory embedded_zip_${zipFileName.hashCode} is file_1'));
expect(messages, contains('Child file of directory embedded_zip_${zipFileName.hashCode} is file_2'));
@@ -617,15 +627,17 @@
.directory('${rootDirectory.path}/embedded_zip_${zipFileName.hashCode}')
.createSync(recursive: true),
),
- FakeCommand(command: <String>[
- 'zip',
- '--symlinks',
- '--recurse-paths',
- '${rootDirectory.absolute.path}/remote_zip_4/folder_1/zip_1',
- '.',
- '--include',
- '*'
- ]),
+ FakeCommand(
+ command: <String>[
+ 'zip',
+ '--symlinks',
+ '--recurse-paths',
+ '${rootDirectory.absolute.path}/remote_zip_4/folder_1/zip_1',
+ '.',
+ '--include',
+ '*'
+ ],
+ ),
]);
await codesignVisitor.visitDirectory(
@@ -639,11 +651,15 @@
expect(messages, contains('Visiting directory ${rootDirectory.absolute.path}/remote_zip_4'));
expect(messages, contains('Visiting directory ${rootDirectory.absolute.path}/remote_zip_4/folder_1'));
expect(
- messages,
- contains(
- 'The downloaded file is unzipped from ${rootDirectory.path}/remote_zip_4/folder_1/zip_1 to ${rootDirectory.path}/embedded_zip_${zipFileName.hashCode}'));
+ messages,
+ contains(
+ 'The downloaded file is unzipped from ${rootDirectory.path}/remote_zip_4/folder_1/zip_1 to ${rootDirectory.path}/embedded_zip_${zipFileName.hashCode}',
+ ),
+ );
expect(
- messages, contains('Visiting directory ${rootDirectory.absolute.path}/embedded_zip_${zipFileName.hashCode}'));
+ messages,
+ contains('Visiting directory ${rootDirectory.absolute.path}/embedded_zip_${zipFileName.hashCode}'),
+ );
});
test('throw exception when the same directory is visited', () async {
@@ -688,9 +704,11 @@
.map((LogRecord record) => record.message)
.toList();
expect(
- warnings,
- contains(
- 'Warning! You are visiting a directory that has been visited before, the directory is ${rootDirectory.path}/parent_1/child_1'));
+ warnings,
+ contains(
+ 'Warning! You are visiting a directory that has been visited before, the directory is ${rootDirectory.path}/parent_1/child_1',
+ ),
+ );
});
test('visitBinary codesigns binary with / without entitlement', () async {
@@ -835,19 +853,21 @@
);
expect(fileWithEntitlements.length, 3);
expect(
- fileWithEntitlements,
- containsAll(<String>[
- 'file_a',
- 'file_b',
- 'file_c',
- ]));
+ fileWithEntitlements,
+ containsAll(<String>[
+ 'file_a',
+ 'file_b',
+ 'file_c',
+ ]),
+ );
expect(fileWithoutEntitlements.length, 2);
expect(
- fileWithoutEntitlements,
- containsAll(<String>[
- 'file_d',
- 'file_e',
- ]));
+ fileWithoutEntitlements,
+ containsAll(<String>[
+ 'file_d',
+ 'file_e',
+ ]),
+ );
});
test('throw exception when configuration file is missing', () async {
@@ -867,20 +887,22 @@
);
expect(fileWithEntitlements.length, 3);
expect(
- fileWithEntitlements,
- containsAll(<String>[
- 'file_a',
- 'file_b',
- 'file_c',
- ]));
+ fileWithEntitlements,
+ containsAll(<String>[
+ 'file_a',
+ 'file_b',
+ 'file_c',
+ ]),
+ );
expect(
- () => codesignVisitor.parseEntitlements(
- fileSystem.directory('/Users/xilaizhang/Desktop/test_entitlement_2'),
- false,
- ),
- throwsA(
- isA<CodesignException>(),
- ));
+ () => codesignVisitor.parseEntitlements(
+ fileSystem.directory('/Users/xilaizhang/Desktop/test_entitlement_2'),
+ false,
+ ),
+ throwsA(
+ isA<CodesignException>(),
+ ),
+ );
});
});
@@ -1415,8 +1437,10 @@
.toSet();
expect(
messages,
- isNot(contains('code signing dry run has completed, If you intend to upload the artifacts back to'
- ' google cloud storage, please use the --dryrun=false flag to run code signing script.')),
+ isNot(
+ contains('code signing dry run has completed, If you intend to upload the artifacts back to'
+ ' google cloud storage, please use the --dryrun=false flag to run code signing script.'),
+ ),
);
expect(
messages,
diff --git a/codesign/test/src/fake_process_manager.dart b/codesign/test/src/fake_process_manager.dart
index c3e111e..9aca69f 100644
--- a/codesign/test/src/fake_process_manager.dart
+++ b/codesign/test/src/fake_process_manager.dart
@@ -140,9 +140,11 @@
if (_stderr == '') {
stderr = const Stream<List<int>>.empty();
} else if (outputFollowsExit) {
- stderr = Stream<List<int>>.fromFuture(exitCode.then((_) {
- return Future<List<int>>(() => utf8.encode(_stderr));
- }));
+ stderr = Stream<List<int>>.fromFuture(
+ exitCode.then((_) {
+ return Future<List<int>>(() => utf8.encode(_stderr));
+ }),
+ );
} else {
stderr = Stream<List<int>>.value(utf8.encode(_stderr));
}
@@ -150,9 +152,11 @@
if (_stdout == '') {
stdout = const Stream<List<int>>.empty();
} else if (outputFollowsExit) {
- stdout = Stream<List<int>>.fromFuture(exitCode.then((_) {
- return Future<List<int>>(() => utf8.encode(_stdout));
- }));
+ stdout = Stream<List<int>>.fromFuture(
+ exitCode.then((_) {
+ return Future<List<int>>(() => utf8.encode(_stdout));
+ }),
+ );
} else {
stdout = Stream<List<int>>.value(utf8.encode(_stdout));
}
@@ -390,9 +394,12 @@
Map<String, String>? environment,
Encoding? encoding,
) {
- expect(_commands, isNotEmpty,
- reason: 'ProcessManager was told to execute $command (in $workingDirectory) '
- 'but the FakeProcessManager.list expected no more processes.');
+ expect(
+ _commands,
+ isNotEmpty,
+ reason: 'ProcessManager was told to execute $command (in $workingDirectory) '
+ 'but the FakeProcessManager.list expected no more processes.',
+ );
_commands.first._matches(command, workingDirectory, environment, encoding);
return _commands.removeAt(0);
}
@@ -433,6 +440,7 @@
) {
final FakeProcessManager fakeProcessManager = item as FakeProcessManager;
return description.add(
- 'has remaining expectations:\n${fakeProcessManager._remainingExpectations.map((FakeCommand command) => command.command).join('\n')}');
+ 'has remaining expectations:\n${fakeProcessManager._remainingExpectations.map((FakeCommand command) => command.command).join('\n')}',
+ );
}
}
diff --git a/dashboard/lib/build_dashboard_page.dart b/dashboard/lib/build_dashboard_page.dart
index 2e82a55..53184a9 100644
--- a/dashboard/lib/build_dashboard_page.dart
+++ b/dashboard/lib/build_dashboard_page.dart
@@ -368,8 +368,8 @@
@override
Widget build(BuildContext context) {
final bool isDark = Theme.of(context).brightness == Brightness.dark;
- MediaQueryData queryData = MediaQuery.of(context);
- double devicePixelRatio = queryData.devicePixelRatio;
+ final MediaQueryData queryData = MediaQuery.of(context);
+ final double devicePixelRatio = queryData.devicePixelRatio;
_smallScreen = queryData.size.width * devicePixelRatio < screenWidthThreshold;
/// Color of [AppBar] based on [buildState.isTreeBuilding].
diff --git a/dashboard/lib/logic/task_grid_filter.dart b/dashboard/lib/logic/task_grid_filter.dart
index e9a5153..e55f472 100644
--- a/dashboard/lib/logic/task_grid_filter.dart
+++ b/dashboard/lib/logic/task_grid_filter.dart
@@ -171,7 +171,7 @@
return false;
}
- LinkedHashMap<String, bool> orderedOSFilter = LinkedHashMap<String, bool>.of({
+ final LinkedHashMap<String, bool> orderedOSFilter = LinkedHashMap<String, bool>.of({
'ios': _allProperties['showiOS']?.value ?? false,
'android': _allProperties['showAndroid']?.value ?? false,
'mac': _allProperties['showMac']?.value ?? false,
diff --git a/dashboard/lib/service/dev_cocoon.dart b/dashboard/lib/service/dev_cocoon.dart
index db77b48..a811149 100644
--- a/dashboard/lib/service/dev_cocoon.dart
+++ b/dashboard/lib/service/dev_cocoon.dart
@@ -127,7 +127,7 @@
@override
Future<CocoonResponse<List<Branch>>> fetchFlutterBranches() async {
- List<Branch> fakeBranches = <Branch>[];
+ final List<Branch> fakeBranches = <Branch>[];
for (String repo in _repos) {
fakeBranches.add(
Branch()
diff --git a/dashboard/lib/state/build.dart b/dashboard/lib/state/build.dart
index f96af88..1d28b88 100644
--- a/dashboard/lib/state/build.dart
+++ b/dashboard/lib/state/build.dart
@@ -199,9 +199,9 @@
_isTreeBuilding = response.data!.buildStatus == EnumBuildStatus.success;
_failingTasks = response.data!.failingTasks;
if (_isTreeBuilding == false) {
- flutterAppIconsPlugin.setIcon(icon: 'favicon-failure.png');
+ unawaited(flutterAppIconsPlugin.setIcon(icon: 'favicon-failure.png'));
} else {
- flutterAppIconsPlugin.setIcon(icon: 'favicon.png');
+ unawaited(flutterAppIconsPlugin.setIcon(icon: 'favicon.png'));
}
notifyListeners();
}
diff --git a/dashboard/test/utils/fake_build.dart b/dashboard/test/utils/fake_build.dart
index 93e94fd..89500eb 100644
--- a/dashboard/test/utils/fake_build.dart
+++ b/dashboard/test/utils/fake_build.dart
@@ -69,7 +69,7 @@
@override
List<Branch> get branches {
- List<Branch> fakeBranches = <Branch>[];
+ final List<Branch> fakeBranches = <Branch>[];
for (String repo in ['flutter', 'engine', 'cocoon']) {
fakeBranches.add(
Branch()
diff --git a/dashboard/test/widgets/task_grid_test.dart b/dashboard/test/widgets/task_grid_test.dart
index 91cce3e..ba819d1 100644
--- a/dashboard/test/widgets/task_grid_test.dart
+++ b/dashboard/test/widgets/task_grid_test.dart
@@ -588,7 +588,7 @@
});
testWidgets('TaskGrid shows icon for isTestFlaky tasks with multiple attempts', (WidgetTester tester) async {
- Task taskA3 = Task()
+ final Task taskA3 = Task()
..stageName = 'A'
..builderName = '1'
..name = 'A'
@@ -596,7 +596,7 @@
..attempts = 3
..isTestFlaky = true;
- Task taskB1 = Task()
+ final Task taskB1 = Task()
..stageName = 'B'
..builderName = '2'
..name = 'B'
@@ -635,9 +635,9 @@
// check the order of the items. The flaky should be to the left and first.
expect(find.byType(TaskGrid).first, findsAtLeastNWidgets(1));
- LatticeScrollView latticeScrollView = tester.firstWidget(find.byType(LatticeScrollView));
- List<List<LatticeCell>> cells = latticeScrollView.cells;
- List<LatticeCell> myCells = cells.first;
+ final LatticeScrollView latticeScrollView = tester.firstWidget(find.byType(LatticeScrollView));
+ final List<List<LatticeCell>> cells = latticeScrollView.cells;
+ final List<LatticeCell> myCells = cells.first;
expect(myCells.length, 3);
myCells.removeAt(0); // the first element is the github author box.
expect(myCells[0].taskName, 'A');
diff --git a/device_doctor/bin/main.dart b/device_doctor/bin/main.dart
index bbc32a8..0771574 100644
--- a/device_doctor/bin/main.dart
+++ b/device_doctor/bin/main.dart
@@ -38,22 +38,34 @@
Future<void> main(List<String> args) async {
final ArgParser parser = ArgParser();
parser
- ..addFlag('$helpFlag', help: 'Prints usage info.', abbr: 'h', callback: (bool value) {
- if (value) {
- stdout.write('${parser.usage}\n');
- exit(1);
- }
- })
- ..addOption('$actionFlag', help: 'Supported actions.', allowed: supportedOptions, allowedHelp: {
- 'healthcheck': 'Check device health status.',
- 'recovery': 'Clean up and reboot device.',
- 'properties': 'Return device properties/dimensions.'
- })
+ ..addFlag(
+ '$helpFlag',
+ help: 'Prints usage info.',
+ abbr: 'h',
+ callback: (bool value) {
+ if (value) {
+ stdout.write('${parser.usage}\n');
+ exit(1);
+ }
+ },
+ )
+ ..addOption(
+ '$actionFlag',
+ help: 'Supported actions.',
+ allowed: supportedOptions,
+ allowedHelp: {
+ 'healthcheck': 'Check device health status.',
+ 'recovery': 'Clean up and reboot device.',
+ 'properties': 'Return device properties/dimensions.'
+ },
+ )
..addOption('$outputFlag', help: 'Path to the output file')
- ..addOption('$deviceOSFlag',
- help: 'Supported device OS.',
- allowed: supportedDeviceOS,
- allowedHelp: {'android': 'Available for linux, mac, and windows.', 'ios': 'Available for mac.'});
+ ..addOption(
+ '$deviceOSFlag',
+ help: 'Supported device OS.',
+ allowed: supportedDeviceOS,
+ allowedHelp: {'android': 'Available for linux, mac, and windows.', 'ios': 'Available for mac.'},
+ );
final ArgResults argResults = parser.parse(args);
_action = argResults[actionFlag];
diff --git a/device_doctor/lib/src/android_device.dart b/device_doctor/lib/src/android_device.dart
index 8864955..1681a09 100644
--- a/device_doctor/lib/src/android_device.dart
+++ b/device_doctor/lib/src/android_device.dart
@@ -45,13 +45,13 @@
Future<List<String>> _deviceListOutputWithRetries(Duration retryDuration, {ProcessManager? processManager}) async {
const Duration deviceOutputTimeout = Duration(seconds: 15);
- RetryOptions r = RetryOptions(
+ final RetryOptions r = RetryOptions(
maxAttempts: 3,
delayFactor: retryDuration,
);
return await r.retry(
() async {
- String result = await _deviceListOutput(deviceOutputTimeout, processManager: processManager);
+ final String result = await _deviceListOutput(deviceOutputTimeout, processManager: processManager);
return result.trim().split('\n');
},
retryIf: (Exception e) => e is TimeoutException,
@@ -68,11 +68,13 @@
}
@override
- Future<List<AndroidDevice>> discoverDevices(
- {Duration retryDuration = const Duration(seconds: 10), ProcessManager? processManager}) async {
+ Future<List<AndroidDevice>> discoverDevices({
+ Duration retryDuration = const Duration(seconds: 10),
+ ProcessManager? processManager,
+ }) async {
processManager ??= LocalProcessManager();
- List<String> output = await _deviceListOutputWithRetries(retryDuration, processManager: processManager);
- List<String> results = <String>[];
+ final List<String> output = await _deviceListOutputWithRetries(retryDuration, processManager: processManager);
+ final List<String> results = <String>[];
for (String line in output) {
// Skip lines like: * daemon started successfully *
if (line.startsWith('* daemon ')) continue;
@@ -80,10 +82,10 @@
if (line.startsWith('List of devices')) continue;
if (_kDeviceRegex.hasMatch(line)) {
- Match? match = _kDeviceRegex.firstMatch(line);
+ final Match? match = _kDeviceRegex.firstMatch(line);
- String? deviceID = match?[1];
- String? deviceState = match?[2];
+ final String? deviceID = match?[1];
+ final String? deviceState = match?[2];
if (!const ['unauthorized', 'offline'].contains(deviceState)) {
results.add(deviceID!);
@@ -150,8 +152,8 @@
final Map<String, String> deviceProperties = <String, String>{};
final Map<String, String> propertyMap = <String, String>{};
LineSplitter.split(
- await eval('adb', <String>['-s', device.deviceId!, 'shell', 'getprop'], processManager: processManager))
- .forEach((String property) {
+ await eval('adb', <String>['-s', device.deviceId!, 'shell', 'getprop'], processManager: processManager),
+ ).forEach((String property) {
final List<String> propertyList = property.replaceAll('[', '').replaceAll(']', '').split(': ');
/// Deal with entries spanning only one line.
@@ -203,8 +205,10 @@
HealthCheckResult healthCheckResult;
try {
final String result = await eval(
- 'adb', <String>['shell', 'dumpsys', 'power', '|', 'grep', 'mHoldingDisplaySuspendBlocker'],
- processManager: processManager);
+ 'adb',
+ <String>['shell', 'dumpsys', 'power', '|', 'grep', 'mHoldingDisplaySuspendBlocker'],
+ processManager: processManager,
+ );
if (result.trim() == 'mHoldingDisplaySuspendBlocker=true') {
healthCheckResult = HealthCheckResult.success(kScreenOnCheckKey);
} else {
@@ -242,8 +246,10 @@
HealthCheckResult healthCheckResult;
try {
final String result = await eval(
- 'adb', <String>['shell', 'settings', 'get', 'global', 'development_settings_enabled'],
- processManager: processManager);
+ 'adb',
+ <String>['shell', 'settings', 'get', 'global', 'development_settings_enabled'],
+ processManager: processManager,
+ );
// The output of `development_settings_enabled` is `1` when developer mode is on.
if (result == '1') {
healthCheckResult = HealthCheckResult.success(kDeveloperModeCheckKey);
@@ -262,8 +268,11 @@
Future<HealthCheckResult> screenRotationCheck({ProcessManager? processManager}) async {
HealthCheckResult healthCheckResult;
try {
- final String result = await eval('adb', <String>['shell', 'settings', 'get', 'system', 'accelerometer_rotation'],
- processManager: processManager);
+ final String result = await eval(
+ 'adb',
+ <String>['shell', 'settings', 'get', 'system', 'accelerometer_rotation'],
+ processManager: processManager,
+ );
// The output of `screensaver_enabled` is `0` when screensaver mode is off.
if (result == '0') {
healthCheckResult = HealthCheckResult.success(kScreenRotationCheckKey);
@@ -282,8 +291,11 @@
Future<HealthCheckResult> screenSaverCheck({ProcessManager? processManager}) async {
HealthCheckResult healthCheckResult;
try {
- final String result = await eval('adb', <String>['shell', 'settings', 'get', 'secure', 'screensaver_enabled'],
- processManager: processManager);
+ final String result = await eval(
+ 'adb',
+ <String>['shell', 'settings', 'get', 'secure', 'screensaver_enabled'],
+ processManager: processManager,
+ );
// The output of `screensaver_enabled` is `0` when screensaver mode is off.
if (result == '0') {
healthCheckResult = HealthCheckResult.success(kScreenSaverCheckKey);
@@ -303,8 +315,11 @@
// The battery level returns two rows. For example:
// level: 100
// mod level: -1
- final String levelResults = await eval('adb', <String>['shell', 'dumpsys', 'battery', '|', 'grep', 'level'],
- processManager: processManager);
+ final String levelResults = await eval(
+ 'adb',
+ <String>['shell', 'dumpsys', 'battery', '|', 'grep', 'level'],
+ processManager: processManager,
+ );
final RegExp levelRegExp = RegExp('level: (?<level>.+)');
final RegExpMatch? match = levelRegExp.firstMatch(levelResults);
final int level = int.parse(match!.namedGroup('level')!);
@@ -327,14 +342,19 @@
// The battery temperature returns one row. For example:
// temperature: 240
// It means 24°C.
- final String tempResult = await eval('adb', <String>['shell', 'dumpsys', 'battery', '|', 'grep', 'temperature'],
- processManager: processManager);
+ final String tempResult = await eval(
+ 'adb',
+ <String>['shell', 'dumpsys', 'battery', '|', 'grep', 'temperature'],
+ processManager: processManager,
+ );
final RegExp? tempRegExp = RegExp('temperature: (?<temperature>.+)');
final RegExpMatch match = tempRegExp!.firstMatch(tempResult)!;
final int temperature = int.parse(match.namedGroup('temperature')!);
if (temperature > _kBatteryMaxTemperatureInCelsius * 10) {
- healthCheckResult = HealthCheckResult.failure(kBatteryTemperatureCheckKey,
- 'Battery temperature (${(temperature * 0.1).toInt()}°C) is over $_kBatteryMaxTemperatureInCelsius°C');
+ healthCheckResult = HealthCheckResult.failure(
+ kBatteryTemperatureCheckKey,
+ 'Battery temperature (${(temperature * 0.1).toInt()}°C) is over $_kBatteryMaxTemperatureInCelsius°C',
+ );
} else {
healthCheckResult = HealthCheckResult.success(kBatteryTemperatureCheckKey);
}
@@ -373,8 +393,12 @@
Future<bool> killProcesses({ProcessManager? processManager}) async {
processManager ??= LocalProcessManager();
String result;
- result = await eval('adb', <String>['shell', 'dumpsys', 'activity', '|', 'grep', 'top-activity'],
- canFail: true, processManager: processManager);
+ result = await eval(
+ 'adb',
+ <String>['shell', 'dumpsys', 'activity', '|', 'grep', 'top-activity'],
+ canFail: true,
+ processManager: processManager,
+ );
// Skip uninstalling process when no device is available or no application exists.
if (result == 'adb: no devices/emulators found' || result.isEmpty) {
diff --git a/device_doctor/lib/src/health.dart b/device_doctor/lib/src/health.dart
index 599da5e..f1f9a27 100644
--- a/device_doctor/lib/src/health.dart
+++ b/device_doctor/lib/src/health.dart
@@ -30,7 +30,7 @@
// Runs the single XCUITest in infra-dialog.
await inDirectory(dialogDir, () async {
- List<String> command =
+ final List<String> command =
'xcrun xcodebuild -project infra-dialog.xcodeproj -scheme infra-dialog -destination -quiet id=$deviceId test'
.split(' ');
// By default the above command relies on automatic code signing, while on devicelab machines
@@ -41,8 +41,8 @@
command.add("DEVELOPMENT_TEAM=${pl.environment['FLUTTER_XCODE_DEVELOPMENT_TEAM']}");
command.add("PROVISIONING_PROFILE_SPECIFIER=${pl.environment['FLUTTER_XCODE_PROVISIONING_PROFILE_SPECIFIER']}");
}
- Process proc = await pm.start(command, workingDirectory: dialogDir.path);
- int exitCode = await proc.exitCode;
+ final Process proc = await pm.start(command, workingDirectory: dialogDir.path);
+ final int exitCode = await proc.exitCode;
if (exitCode != 0) {
fail('Command "$command" failed with exit code $exitCode.');
}
@@ -64,7 +64,7 @@
@override
String toString() {
- StringBuffer buf = StringBuffer(name);
+ final StringBuffer buf = StringBuffer(name);
buf.writeln(succeeded ? 'succeeded' : 'failed');
if (details != null && details!.trim().isNotEmpty) {
buf.writeln();
@@ -89,7 +89,7 @@
healthcheckMap[kAttachedDeviceHealthcheckKey] = <String, dynamic>{'status': true, 'details': null};
}
for (String deviceID in deviceChecks.keys) {
- List<HealthCheckResult> checks = deviceChecks[deviceID]!;
+ final List<HealthCheckResult> checks = deviceChecks[deviceID]!;
for (HealthCheckResult healthCheckResult in checks) {
final Map<String, dynamic> healthCheckResultMap = <String, dynamic>{
'status': healthCheckResult.succeeded,
diff --git a/device_doctor/lib/src/host_utils.dart b/device_doctor/lib/src/host_utils.dart
index 97b62d9..b51006b 100644
--- a/device_doctor/lib/src/host_utils.dart
+++ b/device_doctor/lib/src/host_utils.dart
@@ -37,7 +37,7 @@
List<String> runningProcessesOnWindows(String processName, {ProcessManager? processManager}) {
processManager ??= LocalProcessManager();
final ProcessResult result = processManager.runSync(<String>['powershell', 'Get-CimInstance', 'Win32_Process']);
- List<String> pids = <String>[];
+ final List<String> pids = <String>[];
if (result.exitCode == 0) {
final String stdoutResult = result.stdout as String;
for (String rawProcess in stdoutResult.split('\n')) {
diff --git a/device_doctor/lib/src/ios_debug_symbol_doctor.dart b/device_doctor/lib/src/ios_debug_symbol_doctor.dart
index 5db83bf..cc0e041 100644
--- a/device_doctor/lib/src/ios_debug_symbol_doctor.dart
+++ b/device_doctor/lib/src/ios_debug_symbol_doctor.dart
@@ -2,6 +2,7 @@
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
+import 'dart:async';
import 'dart:convert';
import 'dart:io' as io;
@@ -117,20 +118,24 @@
'-W', // Wait for the opened application (Xcode) to close
dashboardXcWorkspace.path,
]);
- xcodeFuture.then((io.ProcessResult result) {
- logger.info('Open closed...');
- final String stdout = result.stdout.trim();
- if (stdout.isNotEmpty) {
- logger.info('stdout from `open`:\n$stdout\n');
- }
- final String stderr = result.stderr.trim();
- if (stderr.isNotEmpty) {
- logger.info('stderr from `open`:\n$stderr\n');
- }
- if (result.exitCode != 0) {
- throw Exception('Failed opening Xcode!');
- }
- });
+
+ unawaited(
+ xcodeFuture.then((io.ProcessResult result) {
+ logger.info('Open closed...');
+ final String stdout = result.stdout.trim();
+ if (stdout.isNotEmpty) {
+ logger.info('stdout from `open`:\n$stdout\n');
+ }
+ final String stderr = result.stderr.trim();
+ if (stderr.isNotEmpty) {
+ logger.info('stderr from `open`:\n$stderr\n');
+ }
+ if (result.exitCode != 0) {
+ throw Exception('Failed opening Xcode!');
+ }
+ }),
+ );
+
logger.info('Waiting for $timeoutSeconds seconds');
await Future.delayed(timeout);
logger.info('Waited for $timeoutSeconds seconds, now killing Xcode');
@@ -159,7 +164,7 @@
/// Parse subset of JSON from `parseJson` associated with a particular XCDevice.
factory XCDevice.fromMap(Map<String, Object?> map) {
- Map<String, Object?>? error = map['error'] as Map<String, Object?>?;
+ final Map<String, Object?>? error = map['error'] as Map<String, Object?>?;
// We should only specifically pattern match on known fatal errors, and
// ignore the rest.
bool validError = false;
diff --git a/device_doctor/lib/src/ios_device.dart b/device_doctor/lib/src/ios_device.dart
index 58b2301..0c860af 100644
--- a/device_doctor/lib/src/ios_device.dart
+++ b/device_doctor/lib/src/ios_device.dart
@@ -93,16 +93,23 @@
HealthCheckResult healthCheckResult;
try {
final String? homeDir = Platform.environment['HOME'];
- final String profile = await eval('ls', <String>['$homeDir/Library/MobileDevice/Provisioning\ Profiles'],
- processManager: processManager);
+ final String profile = await eval(
+ 'ls',
+ <String>['$homeDir/Library/MobileDevice/Provisioning\ Profiles'],
+ processManager: processManager,
+ );
final String provisionFileContent = await eval(
- 'security', <String>['cms', '-D', '-i', '$homeDir/Library/MobileDevice/Provisioning\ Profiles/$profile'],
- processManager: processManager);
+ 'security',
+ <String>['cms', '-D', '-i', '$homeDir/Library/MobileDevice/Provisioning\ Profiles/$profile'],
+ processManager: processManager,
+ );
if (provisionFileContent.contains(deviceId!)) {
healthCheckResult = HealthCheckResult.success(kDeviceProvisioningProfileCheckKey);
} else {
healthCheckResult = HealthCheckResult.failure(
- kDeviceProvisioningProfileCheckKey, 'device does not exist in the provisioning profile');
+ kDeviceProvisioningProfileCheckKey,
+ 'device does not exist in the provisioning profile',
+ );
}
} on BuildFailedError catch (error) {
healthCheckResult = HealthCheckResult.failure(kDeviceProvisioningProfileCheckKey, error.toString());
@@ -127,8 +134,10 @@
HealthCheckResult healthCheckResult;
try {
final String batteryCheckResult = await eval(
- 'ideviceinfo', <String>['-q', 'com.apple.mobile.battery', '-k', 'BatteryCurrentCapacity'],
- processManager: processManager);
+ 'ideviceinfo',
+ <String>['-q', 'com.apple.mobile.battery', '-k', 'BatteryCurrentCapacity'],
+ processManager: processManager,
+ );
final int level = int.parse(batteryCheckResult.isEmpty ? '0' : batteryCheckResult);
if (level < _kBatteryMinLevel) {
healthCheckResult =
diff --git a/device_doctor/lib/src/mac.dart b/device_doctor/lib/src/mac.dart
index 1530071..6555309 100644
--- a/device_doctor/lib/src/mac.dart
+++ b/device_doctor/lib/src/mac.dart
@@ -17,8 +17,10 @@
HealthCheckResult healthCheckResult;
try {
final String user = await eval(
- 'defaults', <String>['read', '/Library/Preferences/com.apple.loginwindow', 'autoLoginUser'],
- processManager: processManager);
+ 'defaults',
+ <String>['read', '/Library/Preferences/com.apple.loginwindow', 'autoLoginUser'],
+ processManager: processManager,
+ );
// User `swarming` is expected setup for Mac bot auto login.
if (user == 'swarming') {
healthCheckResult = HealthCheckResult.success(kUserAutoLoginCheckKey);
diff --git a/device_doctor/lib/src/utils.dart b/device_doctor/lib/src/utils.dart
index cab7fd1..bb27ace 100644
--- a/device_doctor/lib/src/utils.dart
+++ b/device_doctor/lib/src/utils.dart
@@ -44,13 +44,21 @@
/// Creates a directory from the given path, or multiple path parts by joining
/// them using OS-specific file path separator.
-Directory dir(String thePath,
- [String? part2, String? part3, String? part4, String? part5, String? part6, String? part7, String? part8]) {
+Directory dir(
+ String thePath, [
+ String? part2,
+ String? part3,
+ String? part4,
+ String? part5,
+ String? part6,
+ String? part7,
+ String? part8,
+]) {
return Directory(path.join(thePath, part2, part3, part4, part5, part6, part7, part8));
}
Future<dynamic> inDirectory(dynamic directory, Future<dynamic> action()) async {
- String previousCwd = path.current;
+ final String previousCwd = path.current;
try {
cd(directory);
return await action();
@@ -73,10 +81,13 @@
}
/// Starts a process for an executable command, and returns the processes.
-Future<Process> startProcess(String executable, List<String> arguments,
- {Map<String, String>? env,
- bool silent = false,
- ProcessManager? processManager = const LocalProcessManager()}) async {
+Future<Process> startProcess(
+ String executable,
+ List<String> arguments, {
+ Map<String, String>? env,
+ bool silent = false,
+ ProcessManager? processManager = const LocalProcessManager(),
+}) async {
late Process proc;
try {
proc = await processManager!
@@ -90,17 +101,21 @@
/// Executes a command and returns its standard output as a String.
///
/// Standard error is redirected to the current process' standard error stream.
-Future<String> eval(String executable, List<String> arguments,
- {Map<String, String>? env,
- bool canFail = false,
- bool silent = false,
- ProcessManager? processManager = const LocalProcessManager()}) async {
- Process proc = await startProcess(executable, arguments, env: env, silent: silent, processManager: processManager);
+Future<String> eval(
+ String executable,
+ List<String> arguments, {
+ Map<String, String>? env,
+ bool canFail = false,
+ bool silent = false,
+ ProcessManager? processManager = const LocalProcessManager(),
+}) async {
+ final Process proc =
+ await startProcess(executable, arguments, env: env, silent: silent, processManager: processManager);
proc.stderr.listen((List<int> data) {
stderr.add(data);
});
- String output = await utf8.decodeStream(proc.stdout);
- int exitCode = await proc.exitCode;
+ final String output = await utf8.decodeStream(proc.stdout);
+ final int exitCode = await proc.exitCode;
if (exitCode != 0 && !canFail) fail('Executable $executable failed with exit code $exitCode.');
diff --git a/device_doctor/test/src/android_device_test.dart b/device_doctor/test/src/android_device_test.dart
index 2ab799a..028226e 100644
--- a/device_doctor/test/src/android_device_test.dart
+++ b/device_doctor/test/src/android_device_test.dart
@@ -30,7 +30,7 @@
});
test('deviceDiscovery no retries', () async {
- StringBuffer sb = StringBuffer();
+ final StringBuffer sb = StringBuffer();
sb.writeln('List of devices attached');
sb.writeln('ZY223JQNMR device');
output = <List<int>>[utf8.encode(sb.toString())];
@@ -38,8 +38,10 @@
when(processManager.start(any, workingDirectory: anyNamed('workingDirectory')))
.thenAnswer((_) => Future.value(process));
- List<Device> devices = await deviceDiscovery.discoverDevices(
- retryDuration: const Duration(seconds: 0), processManager: processManager);
+ final List<Device> devices = await deviceDiscovery.discoverDevices(
+ retryDuration: const Duration(seconds: 0),
+ processManager: processManager,
+ );
expect(devices.length, equals(1));
expect(devices[0].deviceId, equals('ZY223JQNMR'));
});
@@ -47,8 +49,10 @@
test('deviceDiscovery fails', () async {
when(processManager.start(any, workingDirectory: anyNamed('workingDirectory')))
.thenAnswer((_) => throw TimeoutException('test'));
- expect(deviceDiscovery.discoverDevices(retryDuration: const Duration(seconds: 0), processManager: processManager),
- throwsA(TypeMatcher<BuildFailedError>()));
+ expect(
+ deviceDiscovery.discoverDevices(retryDuration: const Duration(seconds: 0), processManager: processManager),
+ throwsA(TypeMatcher<BuildFailedError>()),
+ );
});
});
@@ -83,11 +87,14 @@
''';
property_process = FakeProcess(0, out: <List<int>>[utf8.encode(output)]);
- when(processManager.start(<Object>['adb', '-s', 'ZY223JQNMR', 'shell', 'getprop'],
- workingDirectory: anyNamed('workingDirectory')))
- .thenAnswer((_) => Future.value(property_process));
+ when(
+ processManager.start(
+ <Object>['adb', '-s', 'ZY223JQNMR', 'shell', 'getprop'],
+ workingDirectory: anyNamed('workingDirectory'),
+ ),
+ ).thenAnswer((_) => Future.value(property_process));
- Map<String, String> deviceProperties = await deviceDiscovery
+ final Map<String, String> deviceProperties = await deviceDiscovery
.getDeviceProperties(AndroidDevice(deviceId: 'ZY223JQNMR'), processManager: processManager);
const Map<String, String> expectedProperties = <String, String>{
@@ -113,22 +120,26 @@
test('returns success when adb power service is available', () async {
process = FakeProcess(0);
- when(processManager
- .start(<Object>['adb', 'shell', 'dumpsys', 'power'], workingDirectory: anyNamed('workingDirectory')))
- .thenAnswer((_) => Future.value(process));
+ when(
+ processManager
+ .start(<Object>['adb', 'shell', 'dumpsys', 'power'], workingDirectory: anyNamed('workingDirectory')),
+ ).thenAnswer((_) => Future.value(process));
- HealthCheckResult healthCheckResult = await deviceDiscovery.adbPowerServiceCheck(processManager: processManager);
+ final HealthCheckResult healthCheckResult =
+ await deviceDiscovery.adbPowerServiceCheck(processManager: processManager);
expect(healthCheckResult.succeeded, true);
expect(healthCheckResult.name, kAdbPowerServiceCheckKey);
});
test('returns failure when adb returns none 0 code', () async {
process = FakeProcess(1);
- when(processManager
- .start(<Object>['adb', 'shell', 'dumpsys', 'power'], workingDirectory: anyNamed('workingDirectory')))
- .thenAnswer((_) => Future.value(process));
+ when(
+ processManager
+ .start(<Object>['adb', 'shell', 'dumpsys', 'power'], workingDirectory: anyNamed('workingDirectory')),
+ ).thenAnswer((_) => Future.value(process));
- HealthCheckResult healthCheckResult = await deviceDiscovery.adbPowerServiceCheck(processManager: processManager);
+ final HealthCheckResult healthCheckResult =
+ await deviceDiscovery.adbPowerServiceCheck(processManager: processManager);
expect(healthCheckResult.succeeded, false);
expect(healthCheckResult.name, kAdbPowerServiceCheckKey);
expect(healthCheckResult.details, 'Executable adb failed with exit code 1.');
@@ -149,11 +160,15 @@
test('returns success when developer mode is on', () async {
output = <List<int>>[utf8.encode('1')];
process = FakeProcess(0, out: output);
- when(processManager.start(<Object>['adb', 'shell', 'settings', 'get', 'global', 'development_settings_enabled'],
- workingDirectory: anyNamed('workingDirectory')))
- .thenAnswer((_) => Future.value(process));
+ when(
+ processManager.start(
+ <Object>['adb', 'shell', 'settings', 'get', 'global', 'development_settings_enabled'],
+ workingDirectory: anyNamed('workingDirectory'),
+ ),
+ ).thenAnswer((_) => Future.value(process));
- HealthCheckResult healthCheckResult = await deviceDiscovery.developerModeCheck(processManager: processManager);
+ final HealthCheckResult healthCheckResult =
+ await deviceDiscovery.developerModeCheck(processManager: processManager);
expect(healthCheckResult.succeeded, true);
expect(healthCheckResult.name, kDeveloperModeCheckKey);
});
@@ -161,11 +176,15 @@
test('returns failure when developer mode is off', () async {
output = <List<int>>[utf8.encode('0')];
process = FakeProcess(0, out: output);
- when(processManager.start(<Object>['adb', 'shell', 'settings', 'get', 'global', 'development_settings_enabled'],
- workingDirectory: anyNamed('workingDirectory')))
- .thenAnswer((_) => Future.value(process));
+ when(
+ processManager.start(
+ <Object>['adb', 'shell', 'settings', 'get', 'global', 'development_settings_enabled'],
+ workingDirectory: anyNamed('workingDirectory'),
+ ),
+ ).thenAnswer((_) => Future.value(process));
- HealthCheckResult healthCheckResult = await deviceDiscovery.developerModeCheck(processManager: processManager);
+ final HealthCheckResult healthCheckResult =
+ await deviceDiscovery.developerModeCheck(processManager: processManager);
expect(healthCheckResult.succeeded, false);
expect(healthCheckResult.name, kDeveloperModeCheckKey);
expect(healthCheckResult.details, 'developer mode is off');
@@ -174,11 +193,15 @@
test('returns success when screensaver is off', () async {
output = <List<int>>[utf8.encode('0')];
process = FakeProcess(0, out: output);
- when(processManager.start(<Object>['adb', 'shell', 'settings', 'get', 'secure', 'screensaver_enabled'],
- workingDirectory: anyNamed('workingDirectory')))
- .thenAnswer((_) => Future.value(process));
+ when(
+ processManager.start(
+ <Object>['adb', 'shell', 'settings', 'get', 'secure', 'screensaver_enabled'],
+ workingDirectory: anyNamed('workingDirectory'),
+ ),
+ ).thenAnswer((_) => Future.value(process));
- HealthCheckResult healthCheckResult = await deviceDiscovery.screenSaverCheck(processManager: processManager);
+ final HealthCheckResult healthCheckResult =
+ await deviceDiscovery.screenSaverCheck(processManager: processManager);
expect(healthCheckResult.succeeded, true);
expect(healthCheckResult.name, kScreenSaverCheckKey);
});
@@ -186,11 +209,15 @@
test('returns failure when screensaver is on', () async {
output = <List<int>>[utf8.encode('1')];
process = FakeProcess(0, out: output);
- when(processManager.start(<Object>['adb', 'shell', 'settings', 'get', 'secure', 'screensaver_enabled'],
- workingDirectory: anyNamed('workingDirectory')))
- .thenAnswer((_) => Future.value(process));
+ when(
+ processManager.start(
+ <Object>['adb', 'shell', 'settings', 'get', 'secure', 'screensaver_enabled'],
+ workingDirectory: anyNamed('workingDirectory'),
+ ),
+ ).thenAnswer((_) => Future.value(process));
- HealthCheckResult healthCheckResult = await deviceDiscovery.screenSaverCheck(processManager: processManager);
+ final HealthCheckResult healthCheckResult =
+ await deviceDiscovery.screenSaverCheck(processManager: processManager);
expect(healthCheckResult.succeeded, false);
expect(healthCheckResult.name, kScreenSaverCheckKey);
expect(healthCheckResult.details, 'Screensaver is on');
@@ -198,11 +225,15 @@
test('returns failure when adb return none 0 code', () async {
process = FakeProcess(1);
- when(processManager.start(<Object>['adb', 'shell', 'settings', 'get', 'global', 'development_settings_enabled'],
- workingDirectory: anyNamed('workingDirectory')))
- .thenAnswer((_) => Future.value(process));
+ when(
+ processManager.start(
+ <Object>['adb', 'shell', 'settings', 'get', 'global', 'development_settings_enabled'],
+ workingDirectory: anyNamed('workingDirectory'),
+ ),
+ ).thenAnswer((_) => Future.value(process));
- HealthCheckResult healthCheckResult = await deviceDiscovery.developerModeCheck(processManager: processManager);
+ final HealthCheckResult healthCheckResult =
+ await deviceDiscovery.developerModeCheck(processManager: processManager);
expect(healthCheckResult.succeeded, false);
expect(healthCheckResult.name, kDeveloperModeCheckKey);
expect(healthCheckResult.details, 'Executable adb failed with exit code 1.');
@@ -226,12 +257,14 @@
''';
output = <List<int>>[utf8.encode(screenMessage)];
process = FakeProcess(0, out: output);
- when(processManager.start(
- <Object>['adb', 'shell', 'dumpsys', 'power', '|', 'grep', 'mHoldingDisplaySuspendBlocker'],
- workingDirectory: anyNamed('workingDirectory')))
- .thenAnswer((_) => Future.value(process));
+ when(
+ processManager.start(
+ <Object>['adb', 'shell', 'dumpsys', 'power', '|', 'grep', 'mHoldingDisplaySuspendBlocker'],
+ workingDirectory: anyNamed('workingDirectory'),
+ ),
+ ).thenAnswer((_) => Future.value(process));
- HealthCheckResult healthCheckResult = await deviceDiscovery.screenOnCheck(processManager: processManager);
+ final HealthCheckResult healthCheckResult = await deviceDiscovery.screenOnCheck(processManager: processManager);
expect(healthCheckResult.succeeded, true);
expect(healthCheckResult.name, kScreenOnCheckKey);
});
@@ -242,12 +275,14 @@
''';
output = <List<int>>[utf8.encode(screenMessage)];
process = FakeProcess(0, out: output);
- when(processManager.start(
- <Object>['adb', 'shell', 'dumpsys', 'power', '|', 'grep', 'mHoldingDisplaySuspendBlocker'],
- workingDirectory: anyNamed('workingDirectory')))
- .thenAnswer((_) => Future.value(process));
+ when(
+ processManager.start(
+ <Object>['adb', 'shell', 'dumpsys', 'power', '|', 'grep', 'mHoldingDisplaySuspendBlocker'],
+ workingDirectory: anyNamed('workingDirectory'),
+ ),
+ ).thenAnswer((_) => Future.value(process));
- HealthCheckResult healthCheckResult = await deviceDiscovery.screenOnCheck(processManager: processManager);
+ final HealthCheckResult healthCheckResult = await deviceDiscovery.screenOnCheck(processManager: processManager);
expect(healthCheckResult.succeeded, false);
expect(healthCheckResult.name, kScreenOnCheckKey);
expect(healthCheckResult.details, 'screen is off');
@@ -255,12 +290,14 @@
test('returns failure when adb return non 0 code', () async {
process = FakeProcess(1);
- when(processManager.start(
- <Object>['adb', 'shell', 'dumpsys', 'power', '|', 'grep', 'mHoldingDisplaySuspendBlocker'],
- workingDirectory: anyNamed('workingDirectory')))
- .thenAnswer((_) => Future.value(process));
+ when(
+ processManager.start(
+ <Object>['adb', 'shell', 'dumpsys', 'power', '|', 'grep', 'mHoldingDisplaySuspendBlocker'],
+ workingDirectory: anyNamed('workingDirectory'),
+ ),
+ ).thenAnswer((_) => Future.value(process));
- HealthCheckResult healthCheckResult = await deviceDiscovery.screenOnCheck(processManager: processManager);
+ final HealthCheckResult healthCheckResult = await deviceDiscovery.screenOnCheck(processManager: processManager);
expect(healthCheckResult.succeeded, false);
expect(healthCheckResult.name, kScreenOnCheckKey);
expect(healthCheckResult.details, 'Executable adb failed with exit code 1.');
@@ -281,11 +318,15 @@
test('returns success when rotation is disabled', () async {
output = <List<int>>[utf8.encode('0')];
process = FakeProcess(0, out: output);
- when(processManager.start(<Object>['adb', 'shell', 'settings', 'get', 'system', 'accelerometer_rotation'],
- workingDirectory: anyNamed('workingDirectory')))
- .thenAnswer((_) => Future.value(process));
+ when(
+ processManager.start(
+ <Object>['adb', 'shell', 'settings', 'get', 'system', 'accelerometer_rotation'],
+ workingDirectory: anyNamed('workingDirectory'),
+ ),
+ ).thenAnswer((_) => Future.value(process));
- HealthCheckResult healthCheckResult = await deviceDiscovery.screenRotationCheck(processManager: processManager);
+ final HealthCheckResult healthCheckResult =
+ await deviceDiscovery.screenRotationCheck(processManager: processManager);
expect(healthCheckResult.succeeded, true);
expect(healthCheckResult.name, kScreenRotationCheckKey);
});
@@ -293,11 +334,15 @@
test('returns failure when screen rotation is enabled', () async {
output = <List<int>>[utf8.encode('1')];
process = FakeProcess(0, out: output);
- when(processManager.start(<Object>['adb', 'shell', 'settings', 'get', 'system', 'accelerometer_rotation'],
- workingDirectory: anyNamed('workingDirectory')))
- .thenAnswer((_) => Future.value(process));
+ when(
+ processManager.start(
+ <Object>['adb', 'shell', 'settings', 'get', 'system', 'accelerometer_rotation'],
+ workingDirectory: anyNamed('workingDirectory'),
+ ),
+ ).thenAnswer((_) => Future.value(process));
- HealthCheckResult healthCheckResult = await deviceDiscovery.screenRotationCheck(processManager: processManager);
+ final HealthCheckResult healthCheckResult =
+ await deviceDiscovery.screenRotationCheck(processManager: processManager);
expect(healthCheckResult.succeeded, false);
expect(healthCheckResult.name, kScreenRotationCheckKey);
expect(healthCheckResult.details, 'Screen rotation is enabled');
@@ -322,12 +367,18 @@
];
listProcess = FakeProcess(0, out: output);
killProcess = FakeProcess(0);
- when(processManager.start(<Object>['adb', 'shell', 'dumpsys', 'activity', '|', 'grep', 'top-activity'],
- workingDirectory: anyNamed('workingDirectory')))
- .thenAnswer((_) => Future.value(listProcess));
- when(processManager.start(<Object>['adb', 'shell', 'am', 'force-stop', 'com.google.android.apps.nexuslauncher'],
- workingDirectory: anyNamed('workingDirectory')))
- .thenAnswer((_) => Future.value(killProcess));
+ when(
+ processManager.start(
+ <Object>['adb', 'shell', 'dumpsys', 'activity', '|', 'grep', 'top-activity'],
+ workingDirectory: anyNamed('workingDirectory'),
+ ),
+ ).thenAnswer((_) => Future.value(listProcess));
+ when(
+ processManager.start(
+ <Object>['adb', 'shell', 'am', 'force-stop', 'com.google.android.apps.nexuslauncher'],
+ workingDirectory: anyNamed('workingDirectory'),
+ ),
+ ).thenAnswer((_) => Future.value(killProcess));
final bool result = await device.killProcesses(processManager: processManager);
expect(result, true);
@@ -337,12 +388,18 @@
output = <List<int>>[];
listProcess = FakeProcess(0, out: output);
killProcess = FakeProcess(0);
- when(processManager.start(<Object>['adb', 'shell', 'dumpsys', 'activity', '|', 'grep', 'top-activity'],
- workingDirectory: anyNamed('workingDirectory')))
- .thenAnswer((_) => Future.value(listProcess));
- when(processManager.start(<Object>['adb', 'shell', 'am', 'force-stop', 'com.google.android.apps.nexuslauncher'],
- workingDirectory: anyNamed('workingDirectory')))
- .thenAnswer((_) => Future.value(killProcess));
+ when(
+ processManager.start(
+ <Object>['adb', 'shell', 'dumpsys', 'activity', '|', 'grep', 'top-activity'],
+ workingDirectory: anyNamed('workingDirectory'),
+ ),
+ ).thenAnswer((_) => Future.value(listProcess));
+ when(
+ processManager.start(
+ <Object>['adb', 'shell', 'am', 'force-stop', 'com.google.android.apps.nexuslauncher'],
+ workingDirectory: anyNamed('workingDirectory'),
+ ),
+ ).thenAnswer((_) => Future.value(killProcess));
final bool result = await device.killProcesses(processManager: processManager);
expect(result, true);
@@ -354,12 +411,18 @@
];
listProcess = FakeProcess(0, out: output);
killProcess = FakeProcess(1);
- when(processManager.start(<Object>['adb', 'shell', 'dumpsys', 'activity', '|', 'grep', 'top-activity'],
- workingDirectory: anyNamed('workingDirectory')))
- .thenAnswer((_) => Future.value(listProcess));
- when(processManager.start(<Object>['adb', 'shell', 'am', 'force-stop', 'com.google.android.apps.nexuslauncher'],
- workingDirectory: anyNamed('workingDirectory')))
- .thenAnswer((_) => Future.value(killProcess));
+ when(
+ processManager.start(
+ <Object>['adb', 'shell', 'dumpsys', 'activity', '|', 'grep', 'top-activity'],
+ workingDirectory: anyNamed('workingDirectory'),
+ ),
+ ).thenAnswer((_) => Future.value(listProcess));
+ when(
+ processManager.start(
+ <Object>['adb', 'shell', 'am', 'force-stop', 'com.google.android.apps.nexuslauncher'],
+ workingDirectory: anyNamed('workingDirectory'),
+ ),
+ ).thenAnswer((_) => Future.value(killProcess));
final bool result = await device.killProcesses(processManager: processManager);
expect(result, false);
@@ -381,7 +444,8 @@
when(processManager.start(<Object>['adb', 'kill-server'], workingDirectory: anyNamed('workingDirectory')))
.thenAnswer((_) => Future.value(process));
- HealthCheckResult healthCheckResult = await deviceDiscovery.killAdbServerCheck(processManager: processManager);
+ final HealthCheckResult healthCheckResult =
+ await deviceDiscovery.killAdbServerCheck(processManager: processManager);
expect(healthCheckResult.succeeded, true);
expect(healthCheckResult.name, kKillAdbServerCheckKey);
});
@@ -391,7 +455,8 @@
when(processManager.start(<Object>['adb', 'kill-server'], workingDirectory: anyNamed('workingDirectory')))
.thenAnswer((_) => Future.value(process));
- HealthCheckResult healthCheckResult = await deviceDiscovery.killAdbServerCheck(processManager: processManager);
+ final HealthCheckResult healthCheckResult =
+ await deviceDiscovery.killAdbServerCheck(processManager: processManager);
expect(healthCheckResult.succeeded, false);
expect(healthCheckResult.name, kKillAdbServerCheckKey);
expect(healthCheckResult.details, 'Executable adb failed with exit code 1.');
@@ -416,11 +481,15 @@
''';
output = <List<int>>[utf8.encode(screenMessage)];
process = FakeProcess(0, out: output);
- when(processManager.start(<Object>['adb', 'shell', 'dumpsys', 'battery', '|', 'grep', 'level'],
- workingDirectory: anyNamed('workingDirectory')))
- .thenAnswer((_) => Future.value(process));
+ when(
+ processManager.start(
+ <Object>['adb', 'shell', 'dumpsys', 'battery', '|', 'grep', 'level'],
+ workingDirectory: anyNamed('workingDirectory'),
+ ),
+ ).thenAnswer((_) => Future.value(process));
- HealthCheckResult healthCheckResult = await deviceDiscovery.batteryLevelCheck(processManager: processManager);
+ final HealthCheckResult healthCheckResult =
+ await deviceDiscovery.batteryLevelCheck(processManager: processManager);
expect(healthCheckResult.succeeded, true);
expect(healthCheckResult.name, kBatteryLevelCheckKey);
});
@@ -432,11 +501,15 @@
''';
output = <List<int>>[utf8.encode(screenMessage)];
process = FakeProcess(0, out: output);
- when(processManager.start(<Object>['adb', 'shell', 'dumpsys', 'battery', '|', 'grep', 'level'],
- workingDirectory: anyNamed('workingDirectory')))
- .thenAnswer((_) => Future.value(process));
+ when(
+ processManager.start(
+ <Object>['adb', 'shell', 'dumpsys', 'battery', '|', 'grep', 'level'],
+ workingDirectory: anyNamed('workingDirectory'),
+ ),
+ ).thenAnswer((_) => Future.value(process));
- HealthCheckResult healthCheckResult = await deviceDiscovery.batteryLevelCheck(processManager: processManager);
+ final HealthCheckResult healthCheckResult =
+ await deviceDiscovery.batteryLevelCheck(processManager: processManager);
expect(healthCheckResult.succeeded, false);
expect(healthCheckResult.name, kBatteryLevelCheckKey);
expect(healthCheckResult.details, 'Battery level (10) is below 15');
@@ -460,11 +533,14 @@
''';
output = <List<int>>[utf8.encode(screenMessage)];
process = FakeProcess(0, out: output);
- when(processManager.start(<Object>['adb', 'shell', 'dumpsys', 'battery', '|', 'grep', 'temperature'],
- workingDirectory: anyNamed('workingDirectory')))
- .thenAnswer((_) => Future.value(process));
+ when(
+ processManager.start(
+ <Object>['adb', 'shell', 'dumpsys', 'battery', '|', 'grep', 'temperature'],
+ workingDirectory: anyNamed('workingDirectory'),
+ ),
+ ).thenAnswer((_) => Future.value(process));
- HealthCheckResult healthCheckResult =
+ final HealthCheckResult healthCheckResult =
await deviceDiscovery.batteryTemperatureCheck(processManager: processManager);
expect(healthCheckResult.succeeded, true);
expect(healthCheckResult.name, kBatteryTemperatureCheckKey);
@@ -476,11 +552,14 @@
''';
output = <List<int>>[utf8.encode(screenMessage)];
process = FakeProcess(0, out: output);
- when(processManager.start(<Object>['adb', 'shell', 'dumpsys', 'battery', '|', 'grep', 'temperature'],
- workingDirectory: anyNamed('workingDirectory')))
- .thenAnswer((_) => Future.value(process));
+ when(
+ processManager.start(
+ <Object>['adb', 'shell', 'dumpsys', 'battery', '|', 'grep', 'temperature'],
+ workingDirectory: anyNamed('workingDirectory'),
+ ),
+ ).thenAnswer((_) => Future.value(process));
- HealthCheckResult healthCheckResult =
+ final HealthCheckResult healthCheckResult =
await deviceDiscovery.batteryTemperatureCheck(processManager: processManager);
expect(healthCheckResult.succeeded, false);
expect(healthCheckResult.name, kBatteryTemperatureCheckKey);
diff --git a/device_doctor/test/src/health_test.dart b/device_doctor/test/src/health_test.dart
index ca0f835..1b9fa9e 100644
--- a/device_doctor/test/src/health_test.dart
+++ b/device_doctor/test/src/health_test.dart
@@ -22,30 +22,32 @@
});
test('succeeded', () async {
- Process proc = FakeProcess(0);
+ final Process proc = FakeProcess(0);
when(pm.start(any, workingDirectory: anyNamed('workingDirectory'))).thenAnswer((_) => Future.value(proc));
- HealthCheckResult res = await closeIosDialog(pm: pm);
+ final HealthCheckResult res = await closeIosDialog(pm: pm);
expect(res.succeeded, isTrue);
});
test('succeeded with code signing overwrite', () async {
- Process proc = FakeProcess(0);
+ final Process proc = FakeProcess(0);
when(pm.start(any, workingDirectory: anyNamed('workingDirectory'))).thenAnswer((_) => Future.value(proc));
- platform.Platform pl = platform.FakePlatform(environment: <String, String>{
- 'FLUTTER_XCODE_CODE_SIGN_STYLE': 'Manual',
- 'FLUTTER_XCODE_DEVELOPMENT_TEAM': 'S8QB4VV633',
- 'FLUTTER_XCODE_PROVISIONING_PROFILE_SPECIFIER': 'a name with space',
- });
+ final platform.Platform pl = platform.FakePlatform(
+ environment: <String, String>{
+ 'FLUTTER_XCODE_CODE_SIGN_STYLE': 'Manual',
+ 'FLUTTER_XCODE_DEVELOPMENT_TEAM': 'S8QB4VV633',
+ 'FLUTTER_XCODE_PROVISIONING_PROFILE_SPECIFIER': 'a name with space',
+ },
+ );
- HealthCheckResult res = await closeIosDialog(pm: pm, pl: pl);
+ final HealthCheckResult res = await closeIosDialog(pm: pm, pl: pl);
expect(res.succeeded, isTrue);
});
test('failed', () async {
- Process proc = FakeProcess(123);
+ final Process proc = FakeProcess(123);
when(pm.start(any, workingDirectory: anyNamed('workingDirectory'))).thenAnswer((_) => Future.value(proc));
expect(
@@ -55,7 +57,7 @@
});
test('tool is not found', () async {
- Process proc = FakeProcess(123);
+ final Process proc = FakeProcess(123);
when(pm.start(any, workingDirectory: anyNamed('workingDirectory'))).thenAnswer((_) => Future.value(proc));
expect(
diff --git a/device_doctor/test/src/host_utils_test.dart b/device_doctor/test/src/host_utils_test.dart
index b95118f..7e29d50 100644
--- a/device_doctor/test/src/host_utils_test.dart
+++ b/device_doctor/test/src/host_utils_test.dart
@@ -23,7 +23,7 @@
output = '123 abc';
when(processManager.runSync(<String>['powershell', 'Get-CimInstance', 'Win32_Process']))
.thenAnswer((_) => ProcessResult(1, 0, output, 'def'));
- List<String> processes = runningProcessesOnWindows('abc', processManager: processManager);
+ final List<String> processes = runningProcessesOnWindows('abc', processManager: processManager);
expect(processes, equals(<String>['123']));
});
@@ -31,7 +31,7 @@
output = '123 abc\n 456 abc\n 789 def';
when(processManager.runSync(<String>['powershell', 'Get-CimInstance', 'Win32_Process']))
.thenAnswer((_) => ProcessResult(1, 0, output, 'def'));
- List<String> processes = runningProcessesOnWindows('abc', processManager: processManager);
+ final List<String> processes = runningProcessesOnWindows('abc', processManager: processManager);
expect(processes, equals(<String>['123', '456']));
});
@@ -39,7 +39,7 @@
output = '123 def';
when(processManager.runSync(<String>['powershell', 'Get-CimInstance', 'Win32_Process']))
.thenAnswer((_) => ProcessResult(1, 0, output, 'def'));
- List<String> processes = runningProcessesOnWindows('abc', processManager: processManager);
+ final List<String> processes = runningProcessesOnWindows('abc', processManager: processManager);
expect(processes, equals(<String>[]));
});
});
diff --git a/device_doctor/test/src/ios_debug_symbol_doctor_test.dart b/device_doctor/test/src/ios_debug_symbol_doctor_test.dart
index e1ddfb2..b4567cb 100644
--- a/device_doctor/test/src/ios_debug_symbol_doctor_test.dart
+++ b/device_doctor/test/src/ios_debug_symbol_doctor_test.dart
@@ -110,12 +110,13 @@
});
expect(result, isTrue);
expect(
- logger.logs[Level.INFO],
- containsAllInOrder(<String>[
- 'Launching Xcode...',
- 'Waiting for 300 seconds',
- 'Waited for 300 seconds, now killing Xcode',
- ]));
+ logger.logs[Level.INFO],
+ containsAllInOrder(<String>[
+ 'Launching Xcode...',
+ 'Waiting for 300 seconds',
+ 'Waited for 300 seconds, now killing Xcode',
+ ]),
+ );
});
});
}
diff --git a/device_doctor/test/src/ios_device_test.dart b/device_doctor/test/src/ios_device_test.dart
index 9b041e5..675433c 100644
--- a/device_doctor/test/src/ios_device_test.dart
+++ b/device_doctor/test/src/ios_device_test.dart
@@ -31,17 +31,17 @@
test('deviceDiscovery', () async {
deviceDiscovery.outputs = <dynamic>[''];
expect(await deviceDiscovery.discoverDevices(), isEmpty);
- StringBuffer sb = StringBuffer();
+ final StringBuffer sb = StringBuffer();
sb.writeln('abcdefg');
deviceDiscovery.outputs = <dynamic>[sb.toString()];
- List<Device> devices = await deviceDiscovery.discoverDevices();
+ final List<Device> devices = await deviceDiscovery.discoverDevices();
expect(devices.length, equals(1));
expect(devices[0].deviceId, equals('abcdefg'));
});
test('checkDevices without device', () async {
deviceDiscovery.outputs = <dynamic>[''];
- Map<String, List<HealthCheckResult>> results = await deviceDiscovery.checkDevices();
+ final Map<String, List<HealthCheckResult>> results = await deviceDiscovery.checkDevices();
await expectLater(results.keys.length, 0);
});
@@ -89,7 +89,8 @@
process = FakeProcess(0);
when(processManager.start(any, workingDirectory: anyNamed('workingDirectory')))
.thenAnswer((_) => Future.value(process));
- HealthCheckResult healthCheckResult = await deviceDiscovery.keychainUnlockCheck(processManager: processManager);
+ final HealthCheckResult healthCheckResult =
+ await deviceDiscovery.keychainUnlockCheck(processManager: processManager);
expect(healthCheckResult.succeeded, true);
});
@@ -97,40 +98,41 @@
process = FakeProcess(1);
when(processManager.start(any, workingDirectory: anyNamed('workingDirectory')))
.thenAnswer((_) => Future.value(process));
- HealthCheckResult healthCheckResult = await deviceDiscovery.keychainUnlockCheck(processManager: processManager);
+ final HealthCheckResult healthCheckResult =
+ await deviceDiscovery.keychainUnlockCheck(processManager: processManager);
expect(healthCheckResult.succeeded, false);
expect(healthCheckResult.name, kKeychainUnlockCheckKey);
expect(healthCheckResult.details, 'Executable ${kUnlockLoginKeychain} failed with exit code 1.');
});
test('Cert check - success', () async {
- StringBuffer sb = StringBuffer();
+ final StringBuffer sb = StringBuffer();
sb.writeln('1) abcdefg "Apple Development: Flutter Devicelab (hijklmn)"');
sb.writeln('1 valid identities found');
output = <List<int>>[utf8.encode(sb.toString())];
process = FakeProcess(0, out: output);
when(processManager.start(any, workingDirectory: anyNamed('workingDirectory')))
.thenAnswer((_) => Future.value(process));
- HealthCheckResult healthCheckResult = await deviceDiscovery.certCheck(processManager: processManager);
+ final HealthCheckResult healthCheckResult = await deviceDiscovery.certCheck(processManager: processManager);
expect(healthCheckResult.succeeded, true);
});
test('Cert check - failure without target certificate', () async {
- StringBuffer sb = StringBuffer();
+ final StringBuffer sb = StringBuffer();
sb.writeln('abcdefg');
sb.writeln('hijklmn');
output = <List<int>>[utf8.encode(sb.toString())];
process = FakeProcess(0, out: output);
when(processManager.start(any, workingDirectory: anyNamed('workingDirectory')))
.thenAnswer((_) => Future.value(process));
- HealthCheckResult healthCheckResult = await deviceDiscovery.certCheck(processManager: processManager);
+ final HealthCheckResult healthCheckResult = await deviceDiscovery.certCheck(processManager: processManager);
expect(healthCheckResult.succeeded, false);
expect(healthCheckResult.name, kCertCheckKey);
expect(healthCheckResult.details, sb.toString().trim());
});
test('Cert check - failure with multiple certificates', () async {
- StringBuffer sb = StringBuffer();
+ final StringBuffer sb = StringBuffer();
sb.writeln('1) abcdefg "Apple Development: Flutter Devicelab (hijklmn)"');
sb.writeln('1) opqrst "uvwxyz"');
@@ -139,21 +141,21 @@
process = FakeProcess(0, out: output);
when(processManager.start(any, workingDirectory: anyNamed('workingDirectory')))
.thenAnswer((_) => Future.value(process));
- HealthCheckResult healthCheckResult = await deviceDiscovery.certCheck(processManager: processManager);
+ final HealthCheckResult healthCheckResult = await deviceDiscovery.certCheck(processManager: processManager);
expect(healthCheckResult.succeeded, false);
expect(healthCheckResult.name, kCertCheckKey);
expect(healthCheckResult.details, sb.toString().trim());
});
test('Cert check - failure with revoked certificates', () async {
- StringBuffer sb = StringBuffer();
+ final StringBuffer sb = StringBuffer();
sb.writeln('1) abcdefg "Apple Development: Flutter Devicelab (hijklmn)" (CSSMERR_TP_CERT_REVOKED)');
sb.writeln('1 valid identities found');
output = <List<int>>[utf8.encode(sb.toString())];
process = FakeProcess(0, out: output);
when(processManager.start(any, workingDirectory: anyNamed('workingDirectory')))
.thenAnswer((_) => Future.value(process));
- HealthCheckResult healthCheckResult = await deviceDiscovery.certCheck(processManager: processManager);
+ final HealthCheckResult healthCheckResult = await deviceDiscovery.certCheck(processManager: processManager);
expect(healthCheckResult.succeeded, false);
expect(healthCheckResult.name, kCertCheckKey);
expect(healthCheckResult.details, sb.toString().trim());
@@ -163,31 +165,31 @@
process = FakeProcess(1);
when(processManager.start(any, workingDirectory: anyNamed('workingDirectory')))
.thenAnswer((_) => Future.value(process));
- HealthCheckResult healthCheckResult = await deviceDiscovery.certCheck(processManager: processManager);
+ final HealthCheckResult healthCheckResult = await deviceDiscovery.certCheck(processManager: processManager);
expect(healthCheckResult.succeeded, false);
expect(healthCheckResult.name, kCertCheckKey);
expect(healthCheckResult.details, 'Executable security failed with exit code 1.');
});
test('Device pair check - success', () async {
- StringBuffer sb = StringBuffer();
+ final StringBuffer sb = StringBuffer();
sb.writeln('SUCCESS: Validated pairing with device abcdefg-hijklmn');
output = <List<int>>[utf8.encode(sb.toString())];
process = FakeProcess(0, out: output);
when(processManager.start(any, workingDirectory: anyNamed('workingDirectory')))
.thenAnswer((_) => Future.value(process));
- HealthCheckResult healthCheckResult = await deviceDiscovery.devicePairCheck(processManager: processManager);
+ final HealthCheckResult healthCheckResult = await deviceDiscovery.devicePairCheck(processManager: processManager);
expect(healthCheckResult.succeeded, true);
});
test('Device pair check - failure', () async {
- StringBuffer sb = StringBuffer();
+ final StringBuffer sb = StringBuffer();
sb.writeln('abcdefg');
output = <List<int>>[utf8.encode(sb.toString())];
process = FakeProcess(0, out: output);
when(processManager.start(any, workingDirectory: anyNamed('workingDirectory')))
.thenAnswer((_) => Future.value(process));
- HealthCheckResult healthCheckResult = await deviceDiscovery.devicePairCheck(processManager: processManager);
+ final HealthCheckResult healthCheckResult = await deviceDiscovery.devicePairCheck(processManager: processManager);
expect(healthCheckResult.succeeded, false);
expect(healthCheckResult.name, kDevicePairCheckKey);
expect(healthCheckResult.details, sb.toString().trim());
@@ -197,7 +199,7 @@
process = FakeProcess(1);
when(processManager.start(any, workingDirectory: anyNamed('workingDirectory')))
.thenAnswer((_) => Future.value(process));
- HealthCheckResult healthCheckResult = await deviceDiscovery.devicePairCheck(processManager: processManager);
+ final HealthCheckResult healthCheckResult = await deviceDiscovery.devicePairCheck(processManager: processManager);
expect(healthCheckResult.succeeded, false);
expect(healthCheckResult.name, kDevicePairCheckKey);
expect(healthCheckResult.details, 'Executable idevicepair failed with exit code 1.');
@@ -209,12 +211,12 @@
List<List<int>> lsOutput;
List<List<int>> securityOutput;
test('success', () async {
- String fileName = 'abcdefg';
+ const String fileName = 'abcdefg';
lsOutput = <List<int>>[utf8.encode(fileName)];
lsProcess = FakeProcess(0, out: lsOutput);
- String deviceID = 'deviceId';
- String profileContent = '''<array>
+ const String deviceID = 'deviceId';
+ const String profileContent = '''<array>
<string>test1</string>
<string>$deviceID</string>
<string>test2</string>
@@ -224,31 +226,32 @@
securityProcess = FakeProcess(0, out: securityOutput);
final String? homeDir = Platform.environment['HOME'];
- when(processManager.start(<Object>['ls', '$homeDir/Library/MobileDevice/Provisioning\ Profiles'],
- workingDirectory: anyNamed('workingDirectory')))
- .thenAnswer((_) => Future.value(lsProcess));
- when(processManager.start(<Object>[
- 'security',
- 'cms',
- '-D',
- '-i',
- '$homeDir/Library/MobileDevice/Provisioning\ Profiles/$fileName'
- ], workingDirectory: anyNamed('workingDirectory')))
- .thenAnswer((_) => Future.value(securityProcess));
+ when(
+ processManager.start(
+ <Object>['ls', '$homeDir/Library/MobileDevice/Provisioning\ Profiles'],
+ workingDirectory: anyNamed('workingDirectory'),
+ ),
+ ).thenAnswer((_) => Future.value(lsProcess));
+ when(
+ processManager.start(
+ <Object>['security', 'cms', '-D', '-i', '$homeDir/Library/MobileDevice/Provisioning\ Profiles/$fileName'],
+ workingDirectory: anyNamed('workingDirectory'),
+ ),
+ ).thenAnswer((_) => Future.value(securityProcess));
- HealthCheckResult healthCheckResult =
+ final HealthCheckResult healthCheckResult =
await deviceDiscovery.deviceProvisioningProfileCheck(deviceID, processManager: processManager);
expect(healthCheckResult.succeeded, true);
expect(healthCheckResult.name, kDeviceProvisioningProfileCheckKey);
});
test('deviceId does not exist', () async {
- String fileName = 'abcdefg';
+ const String fileName = 'abcdefg';
lsOutput = <List<int>>[utf8.encode(fileName)];
lsProcess = FakeProcess(0, out: lsOutput);
- String deviceID = 'deviceId';
- String profileContent = '''<array>
+ const String deviceID = 'deviceId';
+ const String profileContent = '''<array>
<string>test1</string>
<string>test2</string>
</array>
@@ -257,19 +260,20 @@
securityProcess = FakeProcess(0, out: securityOutput);
final String? homeDir = Platform.environment['HOME'];
- when(processManager.start(<Object>['ls', '$homeDir/Library/MobileDevice/Provisioning\ Profiles'],
- workingDirectory: anyNamed('workingDirectory')))
- .thenAnswer((_) => Future.value(lsProcess));
- when(processManager.start(<Object>[
- 'security',
- 'cms',
- '-D',
- '-i',
- '$homeDir/Library/MobileDevice/Provisioning\ Profiles/$fileName'
- ], workingDirectory: anyNamed('workingDirectory')))
- .thenAnswer((_) => Future.value(securityProcess));
+ when(
+ processManager.start(
+ <Object>['ls', '$homeDir/Library/MobileDevice/Provisioning\ Profiles'],
+ workingDirectory: anyNamed('workingDirectory'),
+ ),
+ ).thenAnswer((_) => Future.value(lsProcess));
+ when(
+ processManager.start(
+ <Object>['security', 'cms', '-D', '-i', '$homeDir/Library/MobileDevice/Provisioning\ Profiles/$fileName'],
+ workingDirectory: anyNamed('workingDirectory'),
+ ),
+ ).thenAnswer((_) => Future.value(securityProcess));
- HealthCheckResult healthCheckResult =
+ final HealthCheckResult healthCheckResult =
await deviceDiscovery.deviceProvisioningProfileCheck(deviceID, processManager: processManager);
expect(healthCheckResult.succeeded, false);
expect(healthCheckResult.name, kDeviceProvisioningProfileCheckKey);
@@ -281,31 +285,37 @@
Process process;
List<List<int>> output;
test('battery level is okay', () async {
- String batteryLevel = '100';
+ const String batteryLevel = '100';
output = <List<int>>[utf8.encode(batteryLevel)];
process = FakeProcess(0, out: output);
- when(processManager.start(
- <Object>['ideviceinfo', '-q', 'com.apple.mobile.battery', '-k', 'BatteryCurrentCapacity'],
- workingDirectory: anyNamed('workingDirectory')))
- .thenAnswer((_) => Future.value(process));
+ when(
+ processManager.start(
+ <Object>['ideviceinfo', '-q', 'com.apple.mobile.battery', '-k', 'BatteryCurrentCapacity'],
+ workingDirectory: anyNamed('workingDirectory'),
+ ),
+ ).thenAnswer((_) => Future.value(process));
- HealthCheckResult healthCheckResult = await deviceDiscovery.batteryLevelCheck(processManager: processManager);
+ final HealthCheckResult healthCheckResult =
+ await deviceDiscovery.batteryLevelCheck(processManager: processManager);
expect(healthCheckResult.succeeded, true);
expect(healthCheckResult.name, kBatteryLevelCheckKey);
});
test('battery level is below minLevel', () async {
- String batteryLevel = '10';
+ const String batteryLevel = '10';
output = <List<int>>[utf8.encode(batteryLevel)];
process = FakeProcess(0, out: output);
- when(processManager.start(
- <Object>['ideviceinfo', '-q', 'com.apple.mobile.battery', '-k', 'BatteryCurrentCapacity'],
- workingDirectory: anyNamed('workingDirectory')))
- .thenAnswer((_) => Future.value(process));
+ when(
+ processManager.start(
+ <Object>['ideviceinfo', '-q', 'com.apple.mobile.battery', '-k', 'BatteryCurrentCapacity'],
+ workingDirectory: anyNamed('workingDirectory'),
+ ),
+ ).thenAnswer((_) => Future.value(process));
- HealthCheckResult healthCheckResult = await deviceDiscovery.batteryLevelCheck(processManager: processManager);
+ final HealthCheckResult healthCheckResult =
+ await deviceDiscovery.batteryLevelCheck(processManager: processManager);
expect(healthCheckResult.succeeded, false);
expect(healthCheckResult.name, kBatteryLevelCheckKey);
expect(healthCheckResult.details, 'Battery level ($batteryLevel) is below 15');
@@ -328,14 +338,15 @@
test('device restart - success', () async {
idevicediagnosticsPath = '/abc/def/idevicediagnostics';
whichProcess = FakeProcess(0, out: <List<int>>[utf8.encode(idevicediagnosticsPath)]);
- when(processManager
- .start(<String>['which', 'idevicediagnostics'], workingDirectory: anyNamed('workingDirectory')))
- .thenAnswer((_) => Future.value(whichProcess));
+ when(
+ processManager.start(<String>['which', 'idevicediagnostics'], workingDirectory: anyNamed('workingDirectory')),
+ ).thenAnswer((_) => Future.value(whichProcess));
process = FakeProcess(0);
device = IosDevice(deviceId: 'abc');
- when(processManager
- .start(<Object>[idevicediagnosticsPath, 'restart'], workingDirectory: anyNamed('workingDirectory')))
- .thenAnswer((_) => Future.value(process));
+ when(
+ processManager
+ .start(<Object>[idevicediagnosticsPath, 'restart'], workingDirectory: anyNamed('workingDirectory')),
+ ).thenAnswer((_) => Future.value(process));
final bool result = await device.restart_device(processManager: processManager);
expect(result, isTrue);
});
@@ -343,14 +354,15 @@
test('device restart - failure', () async {
idevicediagnosticsPath = '/abc/def/idevicediagnostics';
whichProcess = FakeProcess(0, out: <List<int>>[utf8.encode(idevicediagnosticsPath)]);
- when(processManager
- .start(<String>['which', 'idevicediagnostics'], workingDirectory: anyNamed('workingDirectory')))
- .thenAnswer((_) => Future.value(whichProcess));
+ when(
+ processManager.start(<String>['which', 'idevicediagnostics'], workingDirectory: anyNamed('workingDirectory')),
+ ).thenAnswer((_) => Future.value(whichProcess));
process = FakeProcess(1);
device = IosDevice(deviceId: 'abc');
- when(processManager
- .start(<Object>[idevicediagnosticsPath, 'restart'], workingDirectory: anyNamed('workingDirectory')))
- .thenAnswer((_) => Future.value(process));
+ when(
+ processManager
+ .start(<Object>[idevicediagnosticsPath, 'restart'], workingDirectory: anyNamed('workingDirectory')),
+ ).thenAnswer((_) => Future.value(process));
final bool result = await device.restart_device(processManager: processManager);
expect(result, isFalse);
});
@@ -420,12 +432,14 @@
.thenAnswer((_) => Future.value(whichProcess));
when(processManager.start(<Object>[ideviceinstallerPath, '-l'], workingDirectory: anyNamed('workingDirectory')))
.thenAnswer((_) => Future.value(process));
- when(processManager
- .start(<Object>[ideviceinstallerPath, '-U', 'abc'], workingDirectory: anyNamed('workingDirectory')))
- .thenAnswer((_) => Future.value(process_uninstall));
- when(processManager
- .start(<Object>[ideviceinstallerPath, '-U', 'jkl'], workingDirectory: anyNamed('workingDirectory')))
- .thenAnswer((_) => Future.value(process_uninstall));
+ when(
+ processManager
+ .start(<Object>[ideviceinstallerPath, '-U', 'abc'], workingDirectory: anyNamed('workingDirectory')),
+ ).thenAnswer((_) => Future.value(process_uninstall));
+ when(
+ processManager
+ .start(<Object>[ideviceinstallerPath, '-U', 'jkl'], workingDirectory: anyNamed('workingDirectory')),
+ ).thenAnswer((_) => Future.value(process_uninstall));
output = '''CFBundleIdentifier, CFBundleVersion, CFBundleDisplayName
abc, def, ghi
@@ -447,17 +461,19 @@
jkl, mno, pqr
''';
process = FakeProcess(0, out: <List<int>>[utf8.encode(output)]);
- Process process_uninstall = FakeProcess(0);
+ final Process process_uninstall = FakeProcess(0);
when(processManager.start(<String>['which', 'ideviceinstaller'], workingDirectory: anyNamed('workingDirectory')))
.thenAnswer((_) => Future.value(whichProcess));
when(processManager.start(<Object>[ideviceinstallerPath, '-l'], workingDirectory: anyNamed('workingDirectory')))
.thenAnswer((_) => Future.value(process));
- when(processManager
- .start(<Object>[ideviceinstallerPath, '-U', 'abc'], workingDirectory: anyNamed('workingDirectory')))
- .thenAnswer((_) => Future.value(process_uninstall));
- when(processManager
- .start(<Object>[ideviceinstallerPath, '-U', 'jkl'], workingDirectory: anyNamed('workingDirectory')))
- .thenAnswer((_) => Future.value(process_uninstall));
+ when(
+ processManager
+ .start(<Object>[ideviceinstallerPath, '-U', 'abc'], workingDirectory: anyNamed('workingDirectory')),
+ ).thenAnswer((_) => Future.value(process_uninstall));
+ when(
+ processManager
+ .start(<Object>[ideviceinstallerPath, '-U', 'jkl'], workingDirectory: anyNamed('workingDirectory')),
+ ).thenAnswer((_) => Future.value(process_uninstall));
final bool result = await device.uninstall_applications(processManager: processManager);
expect(result, isTrue);
@@ -482,7 +498,7 @@
.thenAnswer((_) => Future.value(processWhichIdeviceID));
when(processManager.start(<String>['/test/idevice_id', '-l'], workingDirectory: anyNamed('workingDirectory')))
.thenAnswer((_) => Future.value(processIdeviceID));
- String deviceId = await deviceDiscovery.deviceListOutput(processManager: processManager);
+ final String deviceId = await deviceDiscovery.deviceListOutput(processManager: processManager);
expect(deviceId, 'abc');
});
});
diff --git a/device_doctor/test/src/mac_test.dart b/device_doctor/test/src/mac_test.dart
index f0b4c16..f004038 100644
--- a/device_doctor/test/src/mac_test.dart
+++ b/device_doctor/test/src/mac_test.dart
@@ -29,7 +29,7 @@
.thenAnswer((_) => Future.value(process));
output = <List<int>>[utf8.encode('swarming')];
process = FakeProcess(0, out: output);
- HealthCheckResult healthCheckResult = await userAutoLoginCheck(processManager: processManager);
+ final HealthCheckResult healthCheckResult = await userAutoLoginCheck(processManager: processManager);
expect(healthCheckResult.succeeded, true);
});
@@ -37,7 +37,7 @@
when(processManager.start(any, workingDirectory: anyNamed('workingDirectory')))
.thenAnswer((_) => Future.value(process));
process = FakeProcess(1);
- HealthCheckResult healthCheckResult = await userAutoLoginCheck(processManager: processManager);
+ final HealthCheckResult healthCheckResult = await userAutoLoginCheck(processManager: processManager);
expect(healthCheckResult.succeeded, false);
expect(healthCheckResult.name, kUserAutoLoginCheckKey);
expect(healthCheckResult.details, 'Executable defaults failed with exit code 1.');
@@ -48,7 +48,7 @@
.thenAnswer((_) => Future.value(process));
output = <List<int>>[utf8.encode('test')];
process = FakeProcess(0, out: output);
- HealthCheckResult healthCheckResult = await userAutoLoginCheck(processManager: processManager);
+ final HealthCheckResult healthCheckResult = await userAutoLoginCheck(processManager: processManager);
expect(healthCheckResult.succeeded, false);
expect(healthCheckResult.name, kUserAutoLoginCheckKey);
expect(healthCheckResult.details, 'swarming user is not setup for auto login');
diff --git a/device_doctor/test/src/utils.dart b/device_doctor/test/src/utils.dart
index dd1379c..6a6ccf8 100644
--- a/device_doctor/test/src/utils.dart
+++ b/device_doctor/test/src/utils.dart
@@ -22,8 +22,10 @@
bool runInShell = false,
ProcessStartMode mode = ProcessStartMode.normal,
}) {
- return super.noSuchMethod(Invocation.method(#start, [command], {#workingDirectory: workingDirectory}),
- returnValue: Future<Process>.value(FakeProcess(0)));
+ return super.noSuchMethod(
+ Invocation.method(#start, [command], {#workingDirectory: workingDirectory}),
+ returnValue: Future<Process>.value(FakeProcess(0)),
+ );
}
@override
@@ -55,14 +57,15 @@
}
class FakeProcess extends Fake implements Process {
- FakeProcess(int exitCode,
- {List<List<int>>? err = const [
- <int>[1, 2, 3]
- ],
- List<List<int>>? out = const [
- <int>[1, 2, 3]
- ]})
- : _exitCode = exitCode,
+ FakeProcess(
+ int exitCode, {
+ List<List<int>>? err = const [
+ <int>[1, 2, 3]
+ ],
+ List<List<int>>? out = const [
+ <int>[1, 2, 3]
+ ],
+ }) : _exitCode = exitCode,
_err = err,
_out = out;
diff --git a/device_doctor/test/src/utils_test.dart b/device_doctor/test/src/utils_test.dart
index f80f164..7114a6f 100644
--- a/device_doctor/test/src/utils_test.dart
+++ b/device_doctor/test/src/utils_test.dart
@@ -36,14 +36,14 @@
});
test('validate process', () async {
- StringBuffer sb = StringBuffer();
+ final StringBuffer sb = StringBuffer();
sb.writeln('abc');
output = <List<int>>[utf8.encode(sb.toString())];
- Process process = FakeProcess(123, out: output);
+ final Process process = FakeProcess(123, out: output);
when(processManager.start(any, workingDirectory: anyNamed('workingDirectory')))
.thenAnswer((_) => Future.value(process));
- Process proc = await startProcess('abc', <String>['a', 'b', 'c'], processManager: processManager);
+ final Process proc = await startProcess('abc', <String>['a', 'b', 'c'], processManager: processManager);
expect(proc, process);
});
});
@@ -58,7 +58,7 @@
});
test('exit code 0', () async {
- StringBuffer sb = StringBuffer();
+ final StringBuffer sb = StringBuffer();
sb.writeln('abc');
output = <List<int>>[utf8.encode(sb.toString())];
process = FakeProcess(0, out: output);
@@ -69,7 +69,7 @@
});
test('exit code not 0', () async {
- StringBuffer sb = StringBuffer();
+ final StringBuffer sb = StringBuffer();
sb.writeln('List of devices attached');
sb.writeln('ZY223JQNMR device');
output = <List<int>>[utf8.encode(sb.toString())];
@@ -90,24 +90,27 @@
});
test('returns path when binary does not exist by default but exists in M1 homebrew bin', () async {
- String path = '$kM1BrewBinPath/ideviceinstaller';
+ final String path = '$kM1BrewBinPath/ideviceinstaller';
output = <List<int>>[utf8.encode(path)];
- Process processM1 = FakeProcess(0, out: output);
- Process processDefault = FakeProcess(1, out: <List<int>>[]);
+ final Process processM1 = FakeProcess(0, out: output);
+ final Process processDefault = FakeProcess(1, out: <List<int>>[]);
when(processManager.start(<String>['which', 'ideviceinstaller'], workingDirectory: anyNamed('workingDirectory')))
.thenAnswer((_) => Future.value(processDefault));
- when(processManager.start(<String>['which', '$kM1BrewBinPath/ideviceinstaller'],
- workingDirectory: anyNamed('workingDirectory')))
- .thenAnswer((_) => Future.value(processM1));
+ when(
+ processManager.start(
+ <String>['which', '$kM1BrewBinPath/ideviceinstaller'],
+ workingDirectory: anyNamed('workingDirectory'),
+ ),
+ ).thenAnswer((_) => Future.value(processM1));
final String result = await getMacBinaryPath('ideviceinstaller', processManager: processManager);
expect(result, '$kM1BrewBinPath/ideviceinstaller');
});
test('returns path when binary exists by default', () async {
- String path = '/abc/def/ideviceinstaller';
+ const String path = '/abc/def/ideviceinstaller';
output = <List<int>>[utf8.encode(path)];
- Process process = FakeProcess(0, out: output);
+ final Process process = FakeProcess(0, out: output);
when(processManager.start(<String>['which', 'ideviceinstaller'], workingDirectory: anyNamed('workingDirectory')))
.thenAnswer((_) => Future.value(process));
@@ -116,13 +119,16 @@
});
test('throws exception when binary does not exist in any location', () async {
- Process processM1 = FakeProcess(1, out: <List<int>>[]);
- Process processDefault = FakeProcess(1, out: <List<int>>[]);
+ final Process processM1 = FakeProcess(1, out: <List<int>>[]);
+ final Process processDefault = FakeProcess(1, out: <List<int>>[]);
when(processManager.start(<String>['which', 'ideviceinstaller'], workingDirectory: anyNamed('workingDirectory')))
.thenAnswer((_) => Future.value(processDefault));
- when(processManager.start(<String>['which', '$kM1BrewBinPath/ideviceinstaller'],
- workingDirectory: anyNamed('workingDirectory')))
- .thenAnswer((_) => Future.value(processM1));
+ when(
+ processManager.start(
+ <String>['which', '$kM1BrewBinPath/ideviceinstaller'],
+ workingDirectory: anyNamed('workingDirectory'),
+ ),
+ ).thenAnswer((_) => Future.value(processM1));
expect(
getMacBinaryPath('ideviceinstaller', processManager: processManager),
diff --git a/licenses/check_licenses.dart b/licenses/check_licenses.dart
index eb7e02f..3a9ae9c 100644
--- a/licenses/check_licenses.dart
+++ b/licenses/check_licenses.dart
@@ -24,7 +24,7 @@
}
Future<void> run(List<String> arguments) async {
- String cocoonPath = path.join(path.dirname(Platform.script.path), '..');
+ final String cocoonPath = path.join(path.dirname(Platform.script.path), '..');
print('$clock Root path: $cocoonPath');
print('$clock Licenses...');
await verifyNoMissingLicense(cocoonPath);
@@ -40,37 +40,93 @@
Future<void> verifyNoMissingLicense(String workingDirectory, {bool checkMinimums = true}) async {
final int? overrideMinimumMatches = checkMinimums ? null : 0;
await _verifyNoMissingLicenseForExtension(
- workingDirectory, 'dart', overrideMinimumMatches ?? 2000, _generateLicense('// '));
+ workingDirectory,
+ 'dart',
+ overrideMinimumMatches ?? 2000,
+ _generateLicense('// '),
+ );
await _verifyNoMissingLicenseForExtension(
- workingDirectory, 'java', overrideMinimumMatches ?? 39, _generateLicense('// '));
+ workingDirectory,
+ 'java',
+ overrideMinimumMatches ?? 39,
+ _generateLicense('// '),
+ );
await _verifyNoMissingLicenseForExtension(
- workingDirectory, 'h', overrideMinimumMatches ?? 30, _generateLicense('// '));
+ workingDirectory,
+ 'h',
+ overrideMinimumMatches ?? 30,
+ _generateLicense('// '),
+ );
await _verifyNoMissingLicenseForExtension(
- workingDirectory, 'm', overrideMinimumMatches ?? 30, _generateLicense('// '));
+ workingDirectory,
+ 'm',
+ overrideMinimumMatches ?? 30,
+ _generateLicense('// '),
+ );
await _verifyNoMissingLicenseForExtension(
- workingDirectory, 'swift', overrideMinimumMatches ?? 10, _generateLicense('// '));
+ workingDirectory,
+ 'swift',
+ overrideMinimumMatches ?? 10,
+ _generateLicense('// '),
+ );
await _verifyNoMissingLicenseForExtension(
- workingDirectory, 'gradle', overrideMinimumMatches ?? 100, _generateLicense('// '));
+ workingDirectory,
+ 'gradle',
+ overrideMinimumMatches ?? 100,
+ _generateLicense('// '),
+ );
await _verifyNoMissingLicenseForExtension(
- workingDirectory, 'gn', overrideMinimumMatches ?? 0, _generateLicense('# '));
+ workingDirectory,
+ 'gn',
+ overrideMinimumMatches ?? 0,
+ _generateLicense('# '),
+ );
await _verifyNoMissingLicenseForExtension(
- workingDirectory, 'Dockerfile', overrideMinimumMatches ?? 1, _generateLicense('# '));
+ workingDirectory,
+ 'Dockerfile',
+ overrideMinimumMatches ?? 1,
+ _generateLicense('# '),
+ );
await _verifyNoMissingLicenseForExtension(
- workingDirectory, 'sh', overrideMinimumMatches ?? 1, '#!/bin/bash\n' + _generateLicense('# '));
+ workingDirectory,
+ 'sh',
+ overrideMinimumMatches ?? 1,
+ '#!/bin/bash\n' + _generateLicense('# '),
+ );
await _verifyNoMissingLicenseForExtension(
- workingDirectory, 'bat', overrideMinimumMatches ?? 1, _generateLicense(':: '));
+ workingDirectory,
+ 'bat',
+ overrideMinimumMatches ?? 1,
+ _generateLicense(':: '),
+ );
await _verifyNoMissingLicenseForExtension(
- workingDirectory, 'ps1', overrideMinimumMatches ?? 1, _generateLicense('# '));
+ workingDirectory,
+ 'ps1',
+ overrideMinimumMatches ?? 1,
+ _generateLicense('# '),
+ );
await _verifyNoMissingLicenseForExtension(
- workingDirectory, 'html', overrideMinimumMatches ?? 1, '<!-- ${_generateLicense('')} -->',
- trailingBlank: false);
+ workingDirectory,
+ 'html',
+ overrideMinimumMatches ?? 1,
+ '<!-- ${_generateLicense('')} -->',
+ trailingBlank: false,
+ );
await _verifyNoMissingLicenseForExtension(
- workingDirectory, 'xml', overrideMinimumMatches ?? 1, '<!-- ${_generateLicense('')} -->');
+ workingDirectory,
+ 'xml',
+ overrideMinimumMatches ?? 1,
+ '<!-- ${_generateLicense('')} -->',
+ );
}
Future<void> _verifyNoMissingLicenseForExtension(
- String workingDirectory, String extension, int minimumMatches, String license,
- {bool trailingBlank = true}) async {
+ String workingDirectory,
+ String extension,
+ int minimumMatches,
+ String license, {
+ bool trailingBlank = true,
+}) async {
assert(!license.endsWith('\n'));
final String licensePattern = license + '\n' + (trailingBlank ? '\n' : '');
final List<String> errors = <String>[];
@@ -129,8 +185,10 @@
pending.addAll(entity.listSync());
}
}
- assert(matches >= minimumMatches,
- 'Expected to find at least $minimumMatches files with extension ".$extension" in "$workingDirectory", but only found $matches.');
+ assert(
+ matches >= minimumMatches,
+ 'Expected to find at least $minimumMatches files with extension ".$extension" in "$workingDirectory", but only found $matches.',
+ );
}
bool _isPartOfAppTemplate(Directory directory) {
diff --git a/test_utilities/bin/global_test_runner.dart b/test_utilities/bin/global_test_runner.dart
index 30511b0..142ae14 100755
--- a/test_utilities/bin/global_test_runner.dart
+++ b/test_utilities/bin/global_test_runner.dart
@@ -2,6 +2,7 @@
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
+import 'dart:async';
import 'dart:io';
import 'package:args/args.dart';
import 'package:yaml/yaml.dart';
@@ -9,32 +10,34 @@
// Runs all the configured tests for cocoon repo.
Future<Null> main(List<String> rawArgs) async {
- ArgParser argParser = ArgParser()..addOption('tests-file', abbr: 't', defaultsTo: '../tests.yaml');
- ArgResults args = argParser.parse(rawArgs);
+ final ArgParser argParser = ArgParser()..addOption('tests-file', abbr: 't', defaultsTo: '../tests.yaml');
+ final ArgResults args = argParser.parse(rawArgs);
// Load tests yaml file.
- File file = File(args['tests-file']);
- var doc = loadYaml(file.readAsStringSync());
+ final File file = File(args['tests-file']);
+ final doc = loadYaml(file.readAsStringSync());
// Execute the tests
- String baseDir = normalize(join(dirname(Platform.script.toFilePath()), '..', '..'));
- String prepareScriptPath = join(baseDir, 'test_utilities', 'bin', 'prepare_environment.sh');
+ final String baseDir = normalize(join(dirname(Platform.script.toFilePath()), '..', '..'));
+ final String prepareScriptPath = join(baseDir, 'test_utilities', 'bin', 'prepare_environment.sh');
await runShellCommand(<String>[prepareScriptPath], 'prepare environment');
doc['tasks'].forEach((task) async {
- String scriptPath = join(baseDir, task['script']);
- String taskPath = join(baseDir, task['task']);
+ final String scriptPath = join(baseDir, task['script']);
+ final String taskPath = join(baseDir, task['task']);
await runShellCommand(<String>[scriptPath, taskPath], task['task']);
});
}
void runShellCommand(List<String> args, String taskName) async {
- Process.run('sh', args).then((result) {
- stdout.writeln('.. stdout ..');
- stdout.writeln(result.stdout);
- stdout.writeln('.. stderr ..');
- stderr.writeln(result.stderr);
- if (result.exitCode != 0) {
- stderr.writeln('There were failures running tests from $taskName');
- exit(result.exitCode);
- }
- });
+ unawaited(
+ Process.run('sh', args).then((result) {
+ stdout.writeln('.. stdout ..');
+ stdout.writeln(result.stdout);
+ stdout.writeln('.. stderr ..');
+ stderr.writeln(result.stderr);
+ if (result.exitCode != 0) {
+ stderr.writeln('There were failures running tests from $taskName');
+ exit(result.exitCode);
+ }
+ }),
+ );
}