Skip to content

Commit e3efd66

Browse files
authored
[flutter_tools] Fix test separation between VersionFreshnessValidator and FlutterVersion.checkFlutterVersionFreshness (flutter#191593)
Several tests in `version_test.dart` were incorrectly asserting server ping behavior on `VersionFreshnessValidator.run()`, which performs presentation and warning logic without network execution. - Add unit tests for `FlutterVersion.checkFlutterVersionFreshness` verifying remote ping caching, git fetch invocation, and timestamp recording on failure. - Isolate `VersionFreshnessValidator` unit tests into a dedicated group verifying warning presentation and warning timestamp tracking. - Update `FakeCache.setStampFor` to retain updated stamp data for load verification. Fixes flutter#104065
1 parent edac39b commit e3efd66

2 files changed

Lines changed: 379 additions & 136 deletions

File tree

‎packages/flutter_tools/lib/src/version.dart‎

Lines changed: 104 additions & 37 deletions
Original file line numberDiff line numberDiff line change
@@ -75,6 +75,9 @@ abstract class FlutterVersion {
7575
required FileSystem fs,
7676
required Git git,
7777
required String flutterRoot,
78+
Platform? platform,
79+
Logger? logger,
80+
Cache? cache,
7881
@protected bool fetchTags = false,
7982
}) {
8083
final File versionFile = getVersionFile(fs, flutterRoot);
@@ -84,6 +87,9 @@ abstract class FlutterVersion {
8487
versionFile,
8588
git: git,
8689
flutterRoot: flutterRoot,
90+
logger: logger,
91+
platform: platform,
92+
cache: cache,
8793
);
8894
if (version != null) {
8995
final String gitPath = fs.path.join(flutterRoot, '.git');
@@ -123,8 +129,11 @@ abstract class FlutterVersion {
123129
frameworkRevision: frameworkRevision,
124130
fs: fs,
125131
flutterRoot: flutterRoot,
126-
fetchTags: fetchTags,
127132
git: git,
133+
platform: platform,
134+
logger: logger,
135+
cache: cache,
136+
fetchTags: fetchTags,
128137
);
129138
}
130139

@@ -133,23 +142,33 @@ abstract class FlutterVersion {
133142
required Git git,
134143
required this.flutterRoot,
135144
required this.fs,
145+
Platform? platform,
146+
Logger? logger,
147+
Cache? cache,
136148
}) : _clock = clock,
137-
_git = git;
149+
_git = git,
150+
_platform = platform,
151+
_logger = logger,
152+
_cache = cache;
138153

139154
factory FlutterVersion.fromRevision({
140155
SystemClock clock = const SystemClock(),
141156
required String flutterRoot,
142157
required String frameworkRevision,
143158
required FileSystem fs,
144159
required Git git,
160+
Platform? platform,
161+
Logger? logger,
162+
Cache? cache,
145163
bool fetchTags = false,
146164
}) {
147165
final GitTagVersion gitTagVersion = GitTagVersion.determine(
148-
globals.platform,
166+
platform ?? globals.platform,
149167
git: git,
150168
gitRef: frameworkRevision,
151169
workingDirectory: flutterRoot,
152170
fetchTags: fetchTags,
171+
logger: logger,
153172
);
154173
final String frameworkVersion = gitTagVersion.frameworkVersionFor(frameworkRevision);
155174
final result = _FlutterVersionGit._(
@@ -160,13 +179,20 @@ abstract class FlutterVersion {
160179
gitTagVersion: gitTagVersion,
161180
fs: fs,
162181
git: git,
182+
platform: platform,
183+
logger: logger,
184+
cache: cache,
163185
);
164186
if (fetchTags) {
165187
result.ensureVersionFile();
166188
}
167189
return result;
168190
}
169191

192+
final Platform? _platform;
193+
final Logger? _logger;
194+
final Cache? _cache;
195+
170196
/// Ensure the latest git tags are fetched and recalculate [FlutterVersion].
171197
///
172198
/// This is only required when not on beta or stable and we need to calculate
@@ -323,18 +349,22 @@ abstract class FlutterVersion {
323349
/// the date is omitted, and left `null`.
324350
String? get engineBuildDate;
325351

326-
/// Checks if the currently installed version of Flutter is up-to-date, and
352+
/// Checks if the current Flutter installation is up-to-date and
327353
/// warns the user if it isn't.
328354
///
329355
/// This function must run while [Cache.lock] is acquired because it reads and
330356
/// writes shared cache files.
331357
Future<void> checkFlutterVersionFreshness() async {
358+
final Cache effectiveCache = _cache ?? globals.cache;
359+
final Logger effectiveLogger = _logger ?? globals.logger;
360+
final Platform effectivePlatform = _platform ?? globals.platform;
361+
332362
// Don't perform update checks if we're not on an official channel.
333363
if (!kOfficialChannels.contains(channel)) {
334364
return;
335365
}
336366
// Don't perform the update check if the tracking remote is not standard.
337-
if (VersionUpstreamValidator(version: this, platform: globals.platform).run() != null) {
367+
if (VersionUpstreamValidator(version: this, platform: effectivePlatform).run() != null) {
338368
return;
339369
}
340370
DateTime localFrameworkCommitDate;
@@ -348,15 +378,18 @@ abstract class FlutterVersion {
348378
} on FormatException {
349379
return;
350380
}
351-
final DateTime? latestFlutterCommitDate = await _getLatestAvailableFlutterDate();
381+
final DateTime? latestFlutterCommitDate = await _getLatestAvailableFlutterDate(
382+
cache: effectiveCache,
383+
logger: effectiveLogger,
384+
);
352385

353386
return VersionFreshnessValidator(
354387
version: this,
355388
clock: _clock,
356389
localFrameworkCommitDate: localFrameworkCommitDate,
357390
latestFlutterCommitDate: latestFlutterCommitDate,
358-
logger: globals.logger,
359-
cache: globals.cache,
391+
logger: effectiveLogger,
392+
cache: effectiveCache,
360393
pauseTime: VersionFreshnessValidator.timeToPauseToLetUserReadTheMessage,
361394
).run();
362395
}
@@ -369,12 +402,12 @@ abstract class FlutterVersion {
369402
///
370403
/// Returns `null` if the cached version is out-of-date or missing, and we are
371404
/// unable to reach the server to get the latest version.
372-
Future<DateTime?> _getLatestAvailableFlutterDate() async {
373-
globals.cache.checkLockAcquired();
374-
final VersionCheckStamp versionCheckStamp = await VersionCheckStamp.load(
375-
globals.cache,
376-
globals.logger,
377-
);
405+
Future<DateTime?> _getLatestAvailableFlutterDate({
406+
required Cache cache,
407+
required Logger logger,
408+
}) async {
409+
cache.checkLockAcquired();
410+
final VersionCheckStamp versionCheckStamp = await VersionCheckStamp.load(cache, logger);
378411

379412
final DateTime now = _clock.now();
380413
if (versionCheckStamp.lastTimeVersionWasChecked != null) {
@@ -391,21 +424,22 @@ abstract class FlutterVersion {
391424
// Cache is empty or it's been a while since the last server ping. Ping the server.
392425
try {
393426
final DateTime remoteFrameworkCommitDate = DateTime.parse(
394-
await _fetchRemoteFrameworkCommitDate(),
427+
await _fetchRemoteFrameworkCommitDate(logger: logger),
395428
);
396429
await versionCheckStamp.store(
397430
newTimeVersionWasChecked: now,
398431
newKnownRemoteVersion: remoteFrameworkCommitDate,
432+
cache: cache,
399433
);
400434
return remoteFrameworkCommitDate;
401435
} on VersionCheckError catch (error) {
402436
// This happens when any of the git commands fails, which can happen when
403437
// there's no Internet connectivity. Remote version check is best effort
404438
// only. We do not prevent the command from running when it fails.
405-
globals.printTrace('Failed to check Flutter version in the remote repository: $error');
439+
logger.printTrace('Failed to check Flutter version in the remote repository: $error');
406440
// Still update the timestamp to avoid us hitting the server on every single
407441
// command if for some reason we cannot connect (eg. we may be offline).
408-
await versionCheckStamp.store(newTimeVersionWasChecked: now);
442+
await versionCheckStamp.store(newTimeVersionWasChecked: now, cache: cache);
409443
return null;
410444
}
411445
}
@@ -414,22 +448,17 @@ abstract class FlutterVersion {
414448
///
415449
/// Throws [VersionCheckError] if a git command fails, for example, when the
416450
/// remote git repository is not reachable due to a network issue.
417-
Future<String> _fetchRemoteFrameworkCommitDate() async {
451+
Future<String> _fetchRemoteFrameworkCommitDate({required Logger logger}) async {
418452
try {
419453
// Fetch upstream branch's commit and tags
420-
await _run(_git, ['fetch', '--tags']);
421-
return _gitCommitDate(
422-
git: _git,
423-
gitRef: kGitTrackingUpstream,
424-
workingDirectory: Cache.flutterRoot,
425-
);
454+
await _run(_git, ['fetch', '--tags'], workingDirectory: flutterRoot);
455+
return _gitCommitDate(git: _git, gitRef: kGitTrackingUpstream, workingDirectory: flutterRoot);
426456
} on VersionCheckError catch (error) {
427-
globals.printError(error.message);
457+
logger.printError(error.message);
428458
rethrow;
429459
}
430460
}
431461

432-
/// Return a short string for the version (e.g. `master/0.0.59-pre.92`, `scroll_refactor/a76bc8e22b`).
433462
String getVersionString({bool redactUnknownBranches = false}) {
434463
if (frameworkVersion != kUnknownFrameworkVersion) {
435464
return '${getBranchName(redactUnknownBranches: redactUnknownBranches)}/$frameworkVersion';
@@ -537,13 +566,19 @@ class _FlutterVersionFromFile extends FlutterVersion {
537566
required super.flutterRoot,
538567
required super.fs,
539568
required super.git,
569+
super.platform,
570+
super.logger,
571+
super.cache,
540572
}) : super._();
541573

542574
static _FlutterVersionFromFile? tryParseFromFile(
543575
File jsonFile, {
544576
required String flutterRoot,
545577
required Git git,
546578
SystemClock clock = const SystemClock(),
579+
Logger? logger,
580+
Platform? platform,
581+
Cache? cache,
547582
}) {
548583
try {
549584
final String jsonContents = jsonFile.readAsStringSync();
@@ -563,17 +598,24 @@ class _FlutterVersionFromFile extends FlutterVersion {
563598
engineBuildDate: manifest['engineBuildDate'] as String?,
564599
dartSdkVersion: manifest['dartSdkVersion']! as String,
565600
devToolsVersion: manifest['devToolsVersion']! as String,
566-
gitTagVersion: GitTagVersion.parse(manifest['flutterVersion']! as String),
601+
gitTagVersion: GitTagVersion.parse(manifest['flutterVersion']! as String, logger: logger),
567602
flutterRoot: flutterRoot,
568603
fs: jsonFile.fileSystem,
604+
platform: platform,
605+
logger: logger,
606+
cache: cache,
569607
);
570608
// ignore: avoid_catches_without_on_clauses
571609
} catch (err) {
572-
globals.printTrace('Failed to parse ${jsonFile.path} with $err');
610+
if (logger != null) {
611+
logger.printTrace('Failed to parse ${jsonFile.path} with $err');
612+
}
573613
try {
574614
jsonFile.deleteSync();
575615
} on FileSystemException {
576-
globals.printTrace('Failed to delete ${jsonFile.path}');
616+
if (logger != null) {
617+
logger.printTrace('Failed to delete ${jsonFile.path}');
618+
}
577619
}
578620
// Returning null means fallback to git implementation.
579621
return null;
@@ -634,6 +676,9 @@ class _FlutterVersionGit extends FlutterVersion {
634676
required this.gitTagVersion,
635677
required super.fs,
636678
required super.git,
679+
super.platform,
680+
super.logger,
681+
super.cache,
637682
}) : super._();
638683

639684
late final FlutterEngineStampFromFile? _engineStamp = FlutterEngineStampFromFile.tryParseFromFile(
@@ -972,9 +1017,12 @@ class VersionCheckError implements Exception {
9721017
/// standard output as a string.
9731018
///
9741019
/// If the command fails, throws a [ToolExit] exception.
975-
Future<String> _run(Git git, List<String> command) async {
1020+
Future<String> _run(Git git, List<String> command, {String? workingDirectory}) async {
9761021
// TODO(matanlurey): Inline this in the single place it's called in this file.
977-
final RunResult results = await git.run(command, workingDirectory: Cache.flutterRoot);
1022+
final RunResult results = await git.run(
1023+
command,
1024+
workingDirectory: workingDirectory ?? Cache.flutterRoot,
1025+
);
9781026

9791027
if (results.exitCode == 0) {
9801028
return results.stdout.trim();
@@ -1050,14 +1098,23 @@ class GitTagVersion {
10501098
String? workingDirectory,
10511099
bool fetchTags = false,
10521100
String gitRef = 'HEAD',
1101+
Logger? logger,
10531102
}) {
10541103
if (fetchTags) {
10551104
final String channel = git
10561105
.runSync(['symbolic-ref', '--short', 'HEAD'], workingDirectory: workingDirectory)
10571106
.stdout
10581107
.trim();
10591108
if (!kDevelopmentChannels.contains(channel) && kOfficialChannels.contains(channel)) {
1060-
globals.printTrace('Skipping request to fetchTags - on well known channel $channel.');
1109+
if (logger != null) {
1110+
logger.printTrace('Skipping request to fetchTags - on well known channel $channel.');
1111+
} else {
1112+
try {
1113+
globals.printTrace('Skipping request to fetchTags - on well known channel $channel.');
1114+
} on Exception {
1115+
// In testWithoutContext, globals is not available.
1116+
}
1117+
}
10611118
} else {
10621119
final String flutterGit =
10631120
platform.environment['FLUTTER_GIT_URL'] ?? 'https://github.com/flutter/flutter.git';
@@ -1078,14 +1135,14 @@ class GitTagVersion {
10781135
final stableTagPattern = RegExp(r'^\d+\.\d+\.\d+$');
10791136
for (final tag in tags) {
10801137
if (stableTagPattern.hasMatch(tag.trim())) {
1081-
return parse(tag);
1138+
return parse(tag, logger: logger);
10821139
}
10831140
}
10841141
// Next check for a dev tag
10851142
final devTagPattern = RegExp(r'^\d+\.\d+\.\d+-\d+\.\d+\.pre$');
10861143
for (final tag in tags) {
10871144
if (devTagPattern.hasMatch(tag.trim())) {
1088-
return parse(tag);
1145+
return parse(tag, logger: logger);
10891146
}
10901147
}
10911148

@@ -1094,13 +1151,15 @@ class GitTagVersion {
10941151
git: git,
10951152
workingDirectory: workingDirectory,
10961153
gitRef: gitRef,
1154+
logger: logger,
10971155
);
10981156
}
10991157

11001158
static GitTagVersion _useNewestTagAndCommitsPastFallback({
11011159
required Git git,
11021160
required String? workingDirectory,
11031161
required String gitRef,
1162+
Logger? logger,
11041163
}) {
11051164
final String latestTag = git
11061165
.runSync([
@@ -1127,7 +1186,7 @@ class GitTagVersion {
11271186
.stdout
11281187
.trim();
11291188

1130-
return parse('$latestTag-$commitCount');
1189+
return parse('$latestTag-$commitCount', logger: logger);
11311190
}
11321191

11331192
/// Parse a version string.
@@ -1174,14 +1233,22 @@ class GitTagVersion {
11741233
}
11751234

11761235
@visibleForTesting
1177-
static GitTagVersion parse(String version) {
1236+
static GitTagVersion parse(String version, {Logger? logger}) {
11781237
GitTagVersion gitTagVersion;
11791238

11801239
gitTagVersion = parseVersion(version);
11811240
if (gitTagVersion != const GitTagVersion.unknown()) {
11821241
return gitTagVersion;
11831242
}
1184-
globals.printTrace('Could not interpret results of "git describe": $version');
1243+
if (logger != null) {
1244+
logger.printTrace('Could not interpret results of "git describe": $version');
1245+
} else {
1246+
try {
1247+
globals.printTrace('Could not interpret results of "git describe": $version');
1248+
} on Exception {
1249+
// In testWithoutContext, globals is not available.
1250+
}
1251+
}
11851252
return const GitTagVersion.unknown();
11861253
}
11871254

0 commit comments

Comments
 (0)