Visitar URL original
[flutter_tools] Bundle data assets from hooks in flutter test (#193435) · suryaKommana2662/flutter@c31b315 · GitHub
Skip to content

Commit c31b315

Browse files
dcharkessuryaKommana2662
authored andcommitted
[flutter_tools] Bundle data assets from hooks in flutter test (flutter#193435)
Previously, `flutter test` ran native assets hooks via `TestCompilerNativeAssetsBuilder.build(buildInfo)`, which only returned the `NativeAssetsManifest.json` URI and discarded the `FlutterHookResult` containing hook-generated data assets. Bug: * flutter#146264 ### Changes - Add `buildWithHookResult` to `TestCompilerNativeAssetsBuilder` returning both `nativeAssetsManifest` and `flutterHookResult`. - Pass `flutterHookResult` to `_buildTestAsset` / `assetBundle.build` in `TestCommand`. - Update `TestCommand._needsRebuild` to check if bundled asset files exist on disk, guard `pub.existsSync()`, and check `flutterHookResult.dependencies` modification timestamps. - Add a hermetic test in `test_test.dart` verifying that `flutter test` bundles data assets from hooks into `build/unit_test_assets`. ### PR Stack | # | PR | Branch | Commit | | :-: | :--- | :--- | :--- | | 1 | flutter#193434 | `data-assets-empty-pubspec` | flutter@62199c4 | | **2** | **👉 flutter#193435 (this PR)** | `data-assets-flutter-test` | flutter@390c757 | | 3 | flutter#193436 | `data-assets-dev-dependencies-release-test` | flutter@cca04e9 | | 4 | flutter#193437 | `data-assets-widget-preview` | flutter@0a5a8e9 | > **Note:** This PR is stacked on flutter#193434. To review only this PR's diff before the base PR lands, view commit flutter@390c757. ## Pre-launch Checklist - [x] I read the [Contributor Guide] and followed the process outlined there for submitting PRs. - [x] I read the [AI contribution guidelines] and understand my responsibilities, or I am not using AI tools. - [x] I read the [Tree Hygiene] wiki page, which explains my responsibilities. - [x] I read and followed the [Flutter Style Guide], including [Features we expect every widget to implement]. - [x] I signed the [CLA]. - [x] I listed at least one issue that this PR fixes in the description above. - [x] I updated/added relevant in-code documentation (doc comments with `///`). - [x] If this PR introduces a new feature or capability, I created and linked a website documentation issue or PR in [flutter/website] (or verified none is needed). - [x] I added new tests to check the change I am making, or this PR is [test-exempt]. - [x] I followed the [breaking change policy] and added [Data Driven Fixes] where supported. - [x] All existing and new tests are passing.
1 parent 3b696e6 commit c31b315

7 files changed

Lines changed: 180 additions & 23 deletions

File tree

‎dev/bots/test.dart‎

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -252,7 +252,10 @@ Future<void> _runIntegrationToolTests() async {
252252

253253
await runFlutterTest(path.join(flutterRoot, 'dev', 'integration_tests', 'hook_user_defines'));
254254
await runFlutterTest(path.join(flutterRoot, 'dev', 'integration_tests', 'link_hook'));
255-
await runFlutterTest(path.join(flutterRoot, 'dev', 'integration_tests', 'data_asset_app'));
255+
await runFlutterTest(
256+
path.join(flutterRoot, 'dev', 'integration_tests', 'data_asset_app'),
257+
environment: <String, String>{'FLUTTER_DART_DATA_ASSETS': 'true'},
258+
);
256259
}
257260

258261
Future<void> _runWidgetPreviewScaffoldToolTests() async {

‎dev/integration_tests/data_asset_app/test/data_asset_app_test.dart‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,5 +9,11 @@ void main() {
99
testWidgets('Data Asset Demo smoke test', (WidgetTester tester) async {
1010
await tester.pumpWidget(const MyApp());
1111
expect(find.text('Data Asset Demo'), findsWidgets);
12+
await tester.pump(const Duration(milliseconds: 500));
13+
expect(
14+
find.textContaining('FOUND "packages/data_asset_app/data/id1.txt": "content1"'),
15+
findsOneWidget,
16+
);
17+
expect(find.textContaining('package_content1'), findsOneWidget);
1218
});
1319
}

‎packages/flutter_tools/lib/src/commands/test.dart‎

Lines changed: 42 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -524,28 +524,35 @@ class TestCommand extends FlutterCommand with DeviceBasedDevelopmentArtifacts {
524524
uninstallApp: boolArg('uninstall'),
525525
);
526526

527-
final Uri? nativeAssetsJson = _isIntegrationTest
528-
? null // Don't build for host when running integration tests.
529-
: await nativeAssetsBuilder?.build(buildInfo);
527+
final (:Uri? nativeAssetsManifest, :FlutterHookResult? flutterHookResult) = _isIntegrationTest
528+
? (
529+
nativeAssetsManifest: null,
530+
flutterHookResult: null,
531+
) // Don't build for host when running integration tests.
532+
: (await nativeAssetsBuilder?.buildWithHookResult(buildInfo) ??
533+
(nativeAssetsManifest: null, flutterHookResult: null));
530534
String? testAssetPath;
531535
if (buildTestAssets) {
532536
await _buildTestAsset(
533537
flavor: buildInfo.flavor,
534538
impellerStatus: debuggingOptions.enableImpeller,
535539
buildMode: debuggingOptions.buildInfo.mode,
536540
packageConfigPath: buildInfo.packageConfigPath,
541+
flutterHookResult: flutterHookResult,
537542
);
538543
}
539-
if (buildTestAssets || nativeAssetsJson != null) {
544+
if (buildTestAssets || nativeAssetsManifest != null) {
540545
testAssetPath = fs.path.join(flutterProject.directory.path, 'build', 'unit_test_assets');
541546
}
542-
if (nativeAssetsJson != null) {
547+
if (nativeAssetsManifest != null) {
543548
final Directory testAssetDirectory = fs.directory(testAssetPath);
544549
if (!testAssetDirectory.existsSync()) {
545550
await testAssetDirectory.create(recursive: true);
546551
}
547-
final File nativeAssetsManifest = testAssetDirectory.childFile('NativeAssetsManifest.json');
548-
await fs.file(nativeAssetsJson).copy(nativeAssetsManifest.path);
552+
final File copiedNativeAssetsManifest = testAssetDirectory.childFile(
553+
'NativeAssetsManifest.json',
554+
);
555+
await fs.file(nativeAssetsManifest).copy(copiedNativeAssetsManifest.path);
549556
}
550557

551558
final String? concurrencyString = stringArg('concurrency');
@@ -831,6 +838,7 @@ class TestCommand extends FlutterCommand with DeviceBasedDevelopmentArtifacts {
831838
required ImpellerStatus impellerStatus,
832839
required BuildMode buildMode,
833840
required String packageConfigPath,
841+
FlutterHookResult? flutterHookResult,
834842
}) async {
835843
final ToolContext(
836844
:Artifacts artifacts,
@@ -841,6 +849,7 @@ class TestCommand extends FlutterCommand with DeviceBasedDevelopmentArtifacts {
841849
) = _toolContext;
842850
final AssetBundle assetBundle = AssetBundleFactory.instance.createBundle();
843851
final int build = await assetBundle.build(
852+
flutterHookResult: flutterHookResult,
844853
packageConfigPath: packageConfigPath,
845854
flavor: flavor,
846855
includeAssetsFromDevDependencies: true,
@@ -849,7 +858,7 @@ class TestCommand extends FlutterCommand with DeviceBasedDevelopmentArtifacts {
849858
if (build != 0) {
850859
throwToolExit('Error: Failed to build asset bundle');
851860
}
852-
if (_needsRebuild(assetBundle.entries, flavor)) {
861+
if (_needsRebuild(assetBundle.entries, flavor, flutterHookResult)) {
853862
await writeBundle(
854863
fs.directory(fs.path.join(getBuildDirectory(config, fs), 'unit_test_assets')),
855864
assetBundle.entries,
@@ -876,29 +885,45 @@ class TestCommand extends FlutterCommand with DeviceBasedDevelopmentArtifacts {
876885
}
877886
}
878887

879-
bool _needsRebuild(Map<String, AssetBundleEntry> entries, String? flavor) {
888+
bool _needsRebuild(
889+
Map<String, AssetBundleEntry> entries,
890+
String? flavor,
891+
FlutterHookResult? flutterHookResult,
892+
) {
880893
// TODO(andrewkolos): This logic might fail in the future if we change the
881894
// schema of the contents of the asset manifest file and the user does not
882895
// perform a `flutter clean` after upgrading.
883896
// See https://github.com/flutter/flutter/issues/128563.
884897
final ToolContext(:Config config, :FileSystem fs) = _toolContext;
885-
final File manifest = fs.file(
886-
fs.path.join(getBuildDirectory(config, fs), 'unit_test_assets', 'AssetManifest.bin'),
898+
final String unitTestAssetsDir = fs.path.join(
899+
getBuildDirectory(config, fs),
900+
'unit_test_assets',
887901
);
902+
final File manifest = fs.file(fs.path.join(unitTestAssetsDir, 'AssetManifest.bin'));
888903
if (!manifest.existsSync()) {
889904
return true;
890905
}
891906
final DateTime lastModified = manifest.lastModifiedSync();
892907
final File pub = fs.file('pubspec.yaml');
893-
if (pub.lastModifiedSync().isAfter(lastModified)) {
908+
if (pub.existsSync() && pub.lastModifiedSync().isAfter(lastModified)) {
894909
return true;
895910
}
896911

897-
final Iterable<DevFSFileContent> files = entries.values
898-
.map((AssetBundleEntry asset) => asset.content)
899-
.whereType<DevFSFileContent>();
900-
for (final entry in files) {
901-
if (entry.isModifiedAfter(lastModified)) {
912+
for (final MapEntry<String, AssetBundleEntry> entry in entries.entries) {
913+
final DevFSContent content = entry.value.content;
914+
if (content is DevFSFileContent) {
915+
if (!fs.file(fs.path.join(unitTestAssetsDir, entry.key)).existsSync()) {
916+
return true;
917+
}
918+
if (content.isModifiedAfter(lastModified)) {
919+
return true;
920+
}
921+
}
922+
}
923+
924+
for (final Uri dependency in flutterHookResult?.dependencies ?? const <Uri>[]) {
925+
final FileStat stat = fs.statSync(dependency.toFilePath());
926+
if (stat.type == FileSystemEntityType.notFound || stat.modified.isAfter(lastModified)) {
902927
return true;
903928
}
904929
}

‎packages/flutter_tools/lib/src/isolated/native_assets/test/native_assets.dart‎

Lines changed: 15 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,12 @@ class TestCompilerNativeAssetsBuilderImpl implements TestCompilerNativeAssetsBui
1919
const TestCompilerNativeAssetsBuilderImpl();
2020

2121
@override
22-
Future<Uri?> build(BuildInfo buildInfo) => testCompilerBuildNativeAssets(buildInfo);
22+
Future<Uri?> build(BuildInfo buildInfo) async =>
23+
(await buildWithHookResult(buildInfo)).nativeAssetsManifest;
24+
25+
@override
26+
Future<TestCompilerNativeAssetsBuildResult> buildWithHookResult(BuildInfo buildInfo) =>
27+
testCompilerBuildNativeAssets(buildInfo);
2328

2429
@override
2530
String windowsBuildDirectory(FlutterProject project) {
@@ -28,9 +33,11 @@ class TestCompilerNativeAssetsBuilderImpl implements TestCompilerNativeAssetsBui
2833
}
2934
}
3035

31-
Future<Uri?> testCompilerBuildNativeAssets(BuildInfo buildInfo) async {
36+
Future<TestCompilerNativeAssetsBuildResult> testCompilerBuildNativeAssets(
37+
BuildInfo buildInfo,
38+
) async {
3239
if (!buildInfo.buildNativeAssets) {
33-
return null;
40+
return (nativeAssetsManifest: null, flutterHookResult: null);
3441
}
3542
final Uri projectUri = FlutterProject.current().directory.uri;
3643
final String runPackageName = buildInfo.packageConfig.packages
@@ -57,7 +64,7 @@ Future<Uri?> testCompilerBuildNativeAssets(BuildInfo buildInfo) async {
5764
globals.fs,
5865
buildRunner,
5966
);
60-
return null;
67+
return (nativeAssetsManifest: null, flutterHookResult: null);
6168
}
6269

6370
// Only `flutter test` uses the
@@ -98,5 +105,8 @@ Future<Uri?> testCompilerBuildNativeAssets(BuildInfo buildInfo) async {
98105
);
99106
assert(globals.fs.file(nativeAssetsFileUri).existsSync());
100107

101-
return nativeAssetsFileUri;
108+
return (
109+
nativeAssetsManifest: nativeAssetsFileUri,
110+
flutterHookResult: dartHookResult.asFlutterResult,
111+
);
102112
}

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

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,14 +2,23 @@
22
// Use of this source code is governed by a BSD-style license that can be
33
// found in the LICENSE file.
44

5+
import 'asset.dart';
56
import 'build_info.dart';
67
import 'project.dart';
78

9+
typedef TestCompilerNativeAssetsBuildResult = ({
10+
Uri? nativeAssetsManifest,
11+
FlutterHookResult? flutterHookResult,
12+
});
13+
814
/// An interface to enable overriding native assets build logic in other
915
/// build systems.
1016
abstract class TestCompilerNativeAssetsBuilder {
1117
Future<Uri?> build(BuildInfo buildInfo);
1218

19+
Future<TestCompilerNativeAssetsBuildResult> buildWithHookResult(BuildInfo buildInfo) async =>
20+
(nativeAssetsManifest: await build(buildInfo), flutterHookResult: null);
21+
1322
/// Returns the Windows native assets build directory.
1423
///
1524
/// By prepending the PATH environment variable for the flutter tester with the

‎packages/flutter_tools/test/commands.shard/hermetic/test_test.dart‎

Lines changed: 72 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@ import 'dart:convert';
88
import 'package:args/command_runner.dart';
99
import 'package:file/memory.dart';
1010
import 'package:file_testing/file_testing.dart';
11+
import 'package:flutter_tools/src/asset.dart';
1112
import 'package:flutter_tools/src/base/async_guard.dart';
1213
import 'package:flutter_tools/src/base/common.dart';
1314
import 'package:flutter_tools/src/base/file_system.dart';
@@ -1467,6 +1468,63 @@ dev_dependencies:
14671468
},
14681469
);
14691470

1471+
testUsingContext(
1472+
'builds asset bundle with data assets from hook',
1473+
() async {
1474+
final testRunner = FakeFlutterTestRunner(0);
1475+
final File dataAssetFile = fs.file(fs.path.join('data', 'hook_asset.txt'))
1476+
..createSync(recursive: true)
1477+
..writeAsStringSync('from_hook');
1478+
fs.file('pubspec.yaml').writeAsStringSync(_pubspecContents);
1479+
final nativeAssetsBuilder = _FakeNativeAssetsBuilderWithDataAssets(
1480+
FlutterHookResult(
1481+
buildStart: DateTime.now(),
1482+
buildEnd: DateTime.now(),
1483+
dataAssets: <HookAsset>[
1484+
HookAsset(file: dataAssetFile.uri, name: 'data/hook_asset.txt', package: 'my_app'),
1485+
],
1486+
dependencies: <Uri>[dataAssetFile.uri],
1487+
),
1488+
);
1489+
final testCommand = TestCommand(
1490+
toolContext: toolContext,
1491+
testRunner: testRunner,
1492+
nativeAssetsBuilder: nativeAssetsBuilder,
1493+
);
1494+
final CommandRunner<void> commandRunner = createTestCommandRunner(testCommand);
1495+
1496+
await commandRunner.run(const <String>['test', '--no-pub']);
1497+
1498+
final File bundledDataAsset = fs.file(
1499+
globals.fs.path.join('build', 'unit_test_assets', 'packages/my_app/data/hook_asset.txt'),
1500+
);
1501+
final File assetManifestBin = fs.file(
1502+
globals.fs.path.join('build', 'unit_test_assets', 'AssetManifest.bin'),
1503+
);
1504+
expect(bundledDataAsset, exists);
1505+
expect(bundledDataAsset.readAsStringSync(), 'from_hook');
1506+
final List<int> initialManifestBytes = assetManifestBin.readAsBytesSync();
1507+
1508+
// Delete the dependency file; hook now produces no data assets.
1509+
dataAssetFile.deleteSync();
1510+
nativeAssetsBuilder.hookResult = FlutterHookResult(
1511+
buildStart: DateTime.now(),
1512+
buildEnd: DateTime.now(),
1513+
dataAssets: const <HookAsset>[],
1514+
dependencies: <Uri>[dataAssetFile.uri],
1515+
);
1516+
1517+
await commandRunner.run(const <String>['test', '--no-pub']);
1518+
1519+
expect(assetManifestBin.readAsBytesSync(), isNot(equals(initialManifestBytes)));
1520+
},
1521+
overrides: <Type, Generator>{
1522+
FileSystem: () => fs,
1523+
ProcessManager: () => FakeProcessManager.empty(),
1524+
DeviceManager: () => _FakeDeviceManager(<Device>[]),
1525+
},
1526+
);
1527+
14701528
group('Fatal Logs', () {
14711529
testUsingContext(
14721530
"doesn't fail when --fatal-warnings is set and no warning output",
@@ -2046,3 +2104,17 @@ class _FakeDeviceManager extends DeviceManager {
20462104
return _connectedDevices;
20472105
}
20482106
}
2107+
2108+
class _FakeNativeAssetsBuilderWithDataAssets extends Fake
2109+
implements TestCompilerNativeAssetsBuilder {
2110+
_FakeNativeAssetsBuilderWithDataAssets(this.hookResult);
2111+
2112+
FlutterHookResult hookResult;
2113+
2114+
@override
2115+
Future<Uri?> build(BuildInfo buildInfo) async => null;
2116+
2117+
@override
2118+
Future<TestCompilerNativeAssetsBuildResult> buildWithHookResult(BuildInfo buildInfo) async =>
2119+
(nativeAssetsManifest: null, flutterHookResult: hookResult);
2120+
}
Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
// Copyright 2014 The Flutter Authors. All rights reserved.
2+
// Use of this source code is governed by a BSD-style license that can be
3+
// found in the LICENSE file.
4+
5+
import '../../src/common.dart';
6+
import '../test_utils.dart' show platform;
7+
import '../transition_test_utils.dart';
8+
import 'dart_data_asset_utils.dart';
9+
10+
void main() {
11+
if (!platform.isMacOS && !platform.isLinux && !platform.isWindows) {
12+
return;
13+
}
14+
setUpAll(setUpAllDataAssets);
15+
setUp(setUpDataAssets);
16+
tearDown(tearDownDataAssets);
17+
18+
group('dart data assets', () {
19+
testWithoutContext('flutter test', () async {
20+
final ProcessTestResult result = await runFlutter(
21+
<String>['test', '-v'],
22+
appRoot.path,
23+
<Transition>[Barrier(RegExp('.* All tests passed!'))],
24+
);
25+
if (result.exitCode != 0) {
26+
throw Exception(
27+
'flutter test failed: ${result.exitCode}\n${result.stderr}\n${result.stdout}',
28+
);
29+
}
30+
});
31+
});
32+
}

0 commit comments

Comments
 (0)