Native assets support for MacOS and iOS (#130494)

Support for FFI calls with `@Native external` functions through Native assets on MacOS and iOS. This enables bundling native code without any build-system boilerplate code.

For more info see:

* https://github.com/flutter/flutter/issues/129757

### Implementation details for MacOS and iOS.

Dylibs are bundled by (1) making them fat binaries if multiple architectures are targeted, (2) code signing these, and (3) copying them to the frameworks folder. These steps are done manual rather than via CocoaPods. CocoaPods would have done the same steps, but (a) needs the dylibs to be there before the `xcodebuild` invocation (we could trick it, by having a minimal dylib in the place and replace it during the build process, that works), and (b) can't deal with having no dylibs to be bundled (we'd have to bundle a dummy dylib or include some dummy C code in the build file).

The dylibs are build as a new target inside flutter assemble, as that is the moment we know what build-mode and architecture to target.

The mapping from asset id to dylib-path is passed in to every kernel compilation path. The interesting case is hot-restart where the initial kernel file is compiled by the "inner" flutter assemble, while after hot restart the "outer" flutter run compiled kernel file is pushed to the device. Both kernel files need to contain the mapping. The "inner" flutter assemble gets its mapping from the NativeAssets target which builds the native assets. The "outer" flutter run get its mapping from a dry-run invocation. Since this hot restart can be used for multiple target devices (`flutter run -d all`) it contains the mapping for all known targets.

### Example vs template

The PR includes a new template that uses the new native assets in a package and has an app importing that. Separate discussion in: https://github.com/flutter/flutter/issues/131209.

### Tests

This PR adds new tests to cover the various use cases.

* dev/devicelab/bin/tasks/native_assets_ios.dart
  * Runs an example app with native assets in all build modes, doing hot reload and hot restart in debug mode.
* dev/devicelab/bin/tasks/native_assets_ios_simulator.dart
  * Runs an example app with native assets, doing hot reload and hot restart.
* packages/flutter_tools/test/integration.shard/native_assets_test.dart
  * Runs (incl hot reload/hot restart), builds, builds frameworks for iOS, MacOS and flutter-tester.
* packages/flutter_tools/test/general.shard/build_system/targets/native_assets_test.dart
  * Unit tests the new Target in the backend.
* packages/flutter_tools/test/general.shard/ios/native_assets_test.dart
* packages/flutter_tools/test/general.shard/macos/native_assets_test.dart
  * Unit tests the native assets being packaged on a iOS/MacOS build.

It also extends various existing tests:

* dev/devicelab/bin/tasks/module_test_ios.dart
   * Exercises the add2app scenario.
* packages/flutter_tools/test/general.shard/features_test.dart
   * Unit test the new feature flag.
This commit is contained in:
Daco Harkes
2023-09-10 10:07:13 +02:00
committed by GitHub
parent 690800bca3
commit aa36db1d29
74 changed files with 4132 additions and 412 deletions

View File

@@ -10,11 +10,14 @@ import 'package:flutter_tools/src/convert.dart';
import 'package:flutter_tools/src/dart/pub.dart';
import 'package:flutter_tools/src/doctor.dart';
import 'package:flutter_tools/src/doctor_validator.dart';
import 'package:flutter_tools/src/features.dart';
import 'package:flutter_tools/src/globals.dart' as globals;
import 'package:flutter_tools/src/project.dart';
import 'package:test/fake.dart';
import '../../src/common.dart';
import '../../src/context.dart';
import '../../src/fakes.dart';
import '../../src/test_flutter_command_runner.dart';
import '../../src/testbed.dart';
@@ -79,6 +82,7 @@ void main() {
globals.fs.path.join('flutter', 'packages', 'flutter_tools', 'templates', 'skeleton'),
globals.fs.path.join('flutter', 'packages', 'flutter_tools', 'templates', 'module', 'common'),
globals.fs.path.join('flutter', 'packages', 'flutter_tools', 'templates', 'package'),
globals.fs.path.join('flutter', 'packages', 'flutter_tools', 'templates', 'package_ffi'),
globals.fs.path.join('flutter', 'packages', 'flutter_tools', 'templates', 'plugin'),
globals.fs.path.join('flutter', 'packages', 'flutter_tools', 'templates', 'plugin_ffi'),
globals.fs.path.join('flutter', 'packages', 'flutter_tools', 'templates', 'plugin_shared'),
@@ -109,6 +113,7 @@ void main() {
flutterManifest.writeAsStringSync('{"files":[]}');
}, overrides: <Type, Generator>{
DoctorValidatorsProvider: () => FakeDoctorValidatorsProvider(),
FeatureFlags: () => TestFeatureFlags(isNativeAssetsEnabled: true),
});
});
@@ -133,6 +138,9 @@ void main() {
await runner.run(<String>['create', '--no-pub', '--template=plugin_ffi', 'testy5']);
expect((await command.usageValues).commandCreateProjectType, 'plugin_ffi');
await runner.run(<String>['create', '--no-pub', '--template=package_ffi', 'testy6']);
expect((await command.usageValues).commandCreateProjectType, 'package_ffi');
}));
testUsingContext('set iOS host language type as usage value', () => testbed.run(() async {
@@ -183,6 +191,29 @@ void main() {
}, overrides: <Type, Generator>{
Pub: () => fakePub,
}));
testUsingContext('package_ffi template not enabled', () async {
final CreateCommand command = CreateCommand();
final CommandRunner<void> runner = createTestCommandRunner(command);
expect(
runner.run(
<String>[
'create',
'--no-pub',
'--template=package_ffi',
'my_ffi_package',
],
),
throwsUsageException(
message: '"package_ffi" is not an allowed value for option "template"',
),
);
}, overrides: <Type, Generator>{
FeatureFlags: () => TestFeatureFlags(
isNativeAssetsEnabled: false, // ignore: avoid_redundant_argument_values, If we graduate the feature to true by default, don't break this test.
),
});
});
}

View File

@@ -856,6 +856,7 @@ class FakeBundleBuilder extends Fake implements BundleBuilder {
String? applicationKernelFilePath,
String? depfilePath,
String? assetDirPath,
Uri? nativeAssets,
@visibleForTesting BuildSystem? buildSystem,
}) async {}
}

View File

@@ -2610,6 +2610,18 @@ void main() {
, throwsToolExit(message: 'The "--platforms" argument is not supported', exitCode: 2));
});
testUsingContext('create an ffi package with --platforms throws error.', () async {
Cache.flutterRoot = '../..';
final CreateCommand command = CreateCommand();
final CommandRunner<void> runner = createTestCommandRunner(command);
await expectLater(
runner.run(<String>['create', '--no-pub', '--template=package_ffi', '--platform=ios', projectDir.path])
, throwsToolExit(message: 'The "--platforms" argument is not supported', exitCode: 2));
}, overrides: <Type, Generator>{
FeatureFlags: () => TestFeatureFlags(isNativeAssetsEnabled: true),
});
testUsingContext('create a plugin with android, delete then re-create folders', () async {
Cache.flutterRoot = '../..';
@@ -3315,43 +3327,49 @@ void main() {
FeatureFlags: () => TestFeatureFlags(isMacOSEnabled: true),
});
testUsingContext('FFI plugins error android language', () async {
final CreateCommand command = CreateCommand();
final CommandRunner<void> runner = createTestCommandRunner(command);
final List<String> args = <String>[
'create',
'--no-pub',
'--template=plugin_ffi',
'-a',
'kotlin',
'--platforms=android',
projectDir.path,
];
for (final String template in <String>['package_ffi', 'plugin_ffi']) {
testUsingContext('$template error android language', () async {
final CreateCommand command = CreateCommand();
final CommandRunner<void> runner = createTestCommandRunner(command);
final List<String> args = <String>[
'create',
'--no-pub',
'--template=$template',
'-a',
'kotlin',
if (template == 'plugin_ffi') '--platforms=android',
projectDir.path,
];
await expectLater(
runner.run(args),
throwsToolExit(message: 'The "android-language" option is not supported with the plugin_ffi template: the language will always be C or C++.'),
);
});
await expectLater(
runner.run(args),
throwsToolExit(message: 'The "android-language" option is not supported with the $template template: the language will always be C or C++.'),
);
}, overrides: <Type, Generator>{
FeatureFlags: () => TestFeatureFlags(isNativeAssetsEnabled: true),
});
testUsingContext('FFI plugins error ios language', () async {
final CreateCommand command = CreateCommand();
final CommandRunner<void> runner = createTestCommandRunner(command);
final List<String> args = <String>[
'create',
'--no-pub',
'--template=plugin_ffi',
'--ios-language',
'swift',
'--platforms=ios',
projectDir.path,
];
testUsingContext('$template error ios language', () async {
final CreateCommand command = CreateCommand();
final CommandRunner<void> runner = createTestCommandRunner(command);
final List<String> args = <String>[
'create',
'--no-pub',
'--template=$template',
'--ios-language',
'swift',
if (template == 'plugin_ffi') '--platforms=ios',
projectDir.path,
];
await expectLater(
runner.run(args),
throwsToolExit(message: 'The "ios-language" option is not supported with the plugin_ffi template: the language will always be C or C++.'),
);
});
await expectLater(
runner.run(args),
throwsToolExit(message: 'The "ios-language" option is not supported with the $template template: the language will always be C or C++.'),
);
}, overrides: <Type, Generator>{
FeatureFlags: () => TestFeatureFlags(isNativeAssetsEnabled: true),
});
}
testUsingContext('FFI plugins error web platform', () async {
final CreateCommand command = CreateCommand();

View File

@@ -71,10 +71,21 @@ void main() {
throwsA(isA<MissingDefineException>()));
});
const String emptyNativeAssets = '''
format-version:
- 1
- 0
- 0
native-assets: {}
''';
testWithoutContext('KernelSnapshot handles null result from kernel compilation', () async {
fileSystem.file('.dart_tool/package_config.json')
..createSync(recursive: true)
..writeAsStringSync('{"configVersion": 2, "packages":[]}');
androidEnvironment.buildDir.childFile('native_assets.yaml')
..createSync(recursive: true)
..writeAsStringSync(emptyNativeAssets);
final String build = androidEnvironment.buildDir.path;
final String flutterPatchedSdkPath = artifacts.getArtifactPath(
Artifact.flutterPatchedSdkPath,
@@ -102,6 +113,8 @@ void main() {
'$build/app.dill',
'--depfile',
'$build/kernel_snapshot.d',
'--native-assets',
'$build/native_assets.yaml',
'--verbosity=error',
'file:///lib/main.dart',
], exitCode: 1),
@@ -115,6 +128,9 @@ void main() {
fileSystem.file('.dart_tool/package_config.json')
..createSync(recursive: true)
..writeAsStringSync('{"configVersion": 2, "packages":[]}');
androidEnvironment.buildDir.childFile('native_assets.yaml')
..createSync(recursive: true)
..writeAsStringSync(emptyNativeAssets);
final String build = androidEnvironment.buildDir.path;
final String flutterPatchedSdkPath = artifacts.getArtifactPath(
Artifact.flutterPatchedSdkPath,
@@ -142,6 +158,8 @@ void main() {
'$build/app.dill',
'--depfile',
'$build/kernel_snapshot.d',
'--native-assets',
'$build/native_assets.yaml',
'--verbosity=error',
'file:///lib/main.dart',
], stdout: 'result $kBoundaryKey\n$kBoundaryKey\n$kBoundaryKey $build/app.dill 0\n'),
@@ -156,6 +174,9 @@ void main() {
fileSystem.file('.dart_tool/package_config.json')
..createSync(recursive: true)
..writeAsStringSync('{"configVersion": 2, "packages":[]}');
androidEnvironment.buildDir.childFile('native_assets.yaml')
..createSync(recursive: true)
..writeAsStringSync(emptyNativeAssets);
final String build = androidEnvironment.buildDir.path;
final String flutterPatchedSdkPath = artifacts.getArtifactPath(
Artifact.flutterPatchedSdkPath,
@@ -183,6 +204,8 @@ void main() {
'$build/app.dill',
'--depfile',
'$build/kernel_snapshot.d',
'--native-assets',
'$build/native_assets.yaml',
'--verbosity=error',
'file:///lib/main.dart',
], stdout: 'result $kBoundaryKey\n$kBoundaryKey\n$kBoundaryKey $build/app.dill 0\n'),
@@ -198,6 +221,9 @@ void main() {
fileSystem.file('.dart_tool/package_config.json')
..createSync(recursive: true)
..writeAsStringSync('{"configVersion": 2, "packages":[]}');
androidEnvironment.buildDir.childFile('native_assets.yaml')
..createSync(recursive: true)
..writeAsStringSync(emptyNativeAssets);
final String build = androidEnvironment.buildDir.path;
final String flutterPatchedSdkPath = artifacts.getArtifactPath(
Artifact.flutterPatchedSdkPath,
@@ -225,6 +251,8 @@ void main() {
'$build/app.dill',
'--depfile',
'$build/kernel_snapshot.d',
'--native-assets',
'$build/native_assets.yaml',
'--verbosity=error',
'foo',
'bar',
@@ -242,6 +270,9 @@ void main() {
fileSystem.file('.dart_tool/package_config.json')
..createSync(recursive: true)
..writeAsStringSync('{"configVersion": 2, "packages":[]}');
androidEnvironment.buildDir.childFile('native_assets.yaml')
..createSync(recursive: true)
..writeAsStringSync(emptyNativeAssets);
final String build = androidEnvironment.buildDir.path;
final String flutterPatchedSdkPath = artifacts.getArtifactPath(
Artifact.flutterPatchedSdkPath,
@@ -268,6 +299,8 @@ void main() {
'--incremental',
'--initialize-from-dill',
'$build/app.dill',
'--native-assets',
'$build/native_assets.yaml',
'--verbosity=error',
'file:///lib/main.dart',
], stdout: 'result $kBoundaryKey\n$kBoundaryKey\n$kBoundaryKey $build/app.dill 0\n'),
@@ -284,6 +317,9 @@ void main() {
fileSystem.file('.dart_tool/package_config.json')
..createSync(recursive: true)
..writeAsStringSync('{"configVersion": 2, "packages":[]}');
androidEnvironment.buildDir.childFile('native_assets.yaml')
..createSync(recursive: true)
..writeAsStringSync(emptyNativeAssets);
final String build = androidEnvironment.buildDir.path;
final String flutterPatchedSdkPath = artifacts.getArtifactPath(
Artifact.flutterPatchedSdkPath,
@@ -309,6 +345,8 @@ void main() {
'--incremental',
'--initialize-from-dill',
'$build/app.dill',
'--native-assets',
'$build/native_assets.yaml',
'--verbosity=error',
'file:///lib/main.dart',
], stdout: 'result $kBoundaryKey\n$kBoundaryKey\n$kBoundaryKey $build/app.dill 0\n'),
@@ -338,6 +376,9 @@ void main() {
fileSystem: fileSystem,
logger: logger,
);
testEnvironment.buildDir.childFile('native_assets.yaml')
..createSync(recursive: true)
..writeAsStringSync(emptyNativeAssets);
final String build = testEnvironment.buildDir.path;
final String flutterPatchedSdkPath = artifacts.getArtifactPath(
Artifact.flutterPatchedSdkPath,
@@ -365,6 +406,8 @@ void main() {
'--incremental',
'--initialize-from-dill',
'$build/app.dill',
'--native-assets',
'$build/native_assets.yaml',
'--verbosity=error',
'file:///lib/main.dart',
], stdout: 'result $kBoundaryKey\n$kBoundaryKey\n$kBoundaryKey /build/653e11a8e6908714056a57cd6b4f602a/app.dill 0\n'),

View File

@@ -0,0 +1,140 @@
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:file/memory.dart';
import 'package:file_testing/file_testing.dart';
import 'package:flutter_tools/src/artifacts.dart';
import 'package:flutter_tools/src/base/file_system.dart';
import 'package:flutter_tools/src/base/logger.dart';
import 'package:flutter_tools/src/build_info.dart';
import 'package:flutter_tools/src/build_system/build_system.dart';
import 'package:flutter_tools/src/build_system/exceptions.dart';
import 'package:flutter_tools/src/build_system/targets/native_assets.dart';
import 'package:flutter_tools/src/features.dart';
import 'package:flutter_tools/src/native_assets.dart';
import 'package:native_assets_cli/native_assets_cli.dart' as native_assets_cli;
import '../../../src/common.dart';
import '../../../src/context.dart';
import '../../../src/fakes.dart';
import '../../fake_native_assets_build_runner.dart';
void main() {
late FakeProcessManager processManager;
late Environment iosEnvironment;
late Artifacts artifacts;
late FileSystem fileSystem;
late Logger logger;
setUp(() {
processManager = FakeProcessManager.empty();
logger = BufferLogger.test();
artifacts = Artifacts.test();
fileSystem = MemoryFileSystem.test();
iosEnvironment = Environment.test(
fileSystem.currentDirectory,
defines: <String, String>{
kBuildMode: BuildMode.profile.cliName,
kTargetPlatform: getNameForTargetPlatform(TargetPlatform.ios),
kIosArchs: 'arm64',
kSdkRoot: 'path/to/iPhoneOS.sdk',
},
inputs: <String, String>{},
artifacts: artifacts,
processManager: processManager,
fileSystem: fileSystem,
logger: logger,
);
iosEnvironment.buildDir.createSync(recursive: true);
});
testWithoutContext('NativeAssets throws error if missing target platform', () async {
iosEnvironment.defines.remove(kTargetPlatform);
expect(const NativeAssets().build(iosEnvironment), throwsA(isA<MissingDefineException>()));
});
testUsingContext('NativeAssets throws error if missing ios archs', () async {
iosEnvironment.defines.remove(kIosArchs);
expect(const NativeAssets().build(iosEnvironment), throwsA(isA<MissingDefineException>()));
});
testUsingContext('NativeAssets throws error if missing sdk root', () async {
iosEnvironment.defines.remove(kSdkRoot);
expect(const NativeAssets().build(iosEnvironment), throwsA(isA<MissingDefineException>()));
});
// The NativeAssets Target should _always_ be creating a yaml an d file.
// The caching logic depends on this.
for (final bool isNativeAssetsEnabled in <bool>[true, false]) {
final String postFix = isNativeAssetsEnabled ? 'enabled' : 'disabled';
testUsingContext(
'Successfull native_assets.yaml and native_assets.d creation with feature $postFix',
overrides: <Type, Generator>{
FileSystem: () => fileSystem,
ProcessManager: () => processManager,
FeatureFlags: () => TestFeatureFlags(
isNativeAssetsEnabled: isNativeAssetsEnabled,
),
},
() async {
final NativeAssetsBuildRunner buildRunner = FakeNativeAssetsBuildRunner();
await NativeAssets(buildRunner: buildRunner).build(iosEnvironment);
expect(iosEnvironment.buildDir.childFile('native_assets.d'), exists);
expect(iosEnvironment.buildDir.childFile('native_assets.yaml'), exists);
},
);
}
testUsingContext(
'NativeAssets with an asset',
overrides: <Type, Generator>{
FileSystem: () => fileSystem,
ProcessManager: () => FakeProcessManager.any(),
FeatureFlags: () => TestFeatureFlags(isNativeAssetsEnabled: true),
},
() async {
final NativeAssetsBuildRunner buildRunner = FakeNativeAssetsBuildRunner(
buildResult: FakeNativeAssetsBuilderResult(assets: <native_assets_cli.Asset>[
native_assets_cli.Asset(
id: 'package:foo/foo.dart',
linkMode: native_assets_cli.LinkMode.dynamic,
target: native_assets_cli.Target.iOSArm64,
path: native_assets_cli.AssetAbsolutePath(
Uri.file('libfoo.dylib'),
),
)
], dependencies: <Uri>[
Uri.file('src/foo.c'),
]),
);
await NativeAssets(buildRunner: buildRunner).build(iosEnvironment);
final File nativeAssetsYaml = iosEnvironment.buildDir.childFile('native_assets.yaml');
final File depsFile = iosEnvironment.buildDir.childFile('native_assets.d');
expect(depsFile, exists);
// We don't care about the specific format, but it should contain the
// yaml as the file depending on the source files that went in to the
// build.
expect(
depsFile.readAsStringSync(),
stringContainsInOrder(<String>[
nativeAssetsYaml.path,
':',
'src/foo.c',
]),
);
expect(nativeAssetsYaml, exists);
// We don't care about the specific format, but it should contain the
// asset id and the path to the dylib.
expect(
nativeAssetsYaml.readAsStringSync(),
stringContainsInOrder(<String>[
'package:foo/foo.dart',
'libfoo.dylib',
]),
);
},
);
}

View File

@@ -435,4 +435,55 @@ void main() {
completer.complete();
await output;
});
testWithoutContext('KernelCompiler passes native assets', () async {
final BufferLogger logger = BufferLogger.test();
final StdoutHandler stdoutHandler = StdoutHandler(logger: logger, fileSystem: MemoryFileSystem.test());
final Completer<void> completer = Completer<void>();
final KernelCompiler kernelCompiler = KernelCompiler(
artifacts: Artifacts.test(),
fileSystem: MemoryFileSystem.test(),
fileSystemRoots: <String>[],
fileSystemScheme: '',
logger: logger,
processManager: FakeProcessManager.list(<FakeCommand>[
FakeCommand(command: const <String>[
'Artifact.engineDartBinary',
'--disable-dart-dev',
'Artifact.frontendServerSnapshotForEngineDartSdk',
'--sdk-root',
'/path/to/sdkroot/',
'--target=flutter',
'--no-print-incremental-dependencies',
'-Ddart.vm.profile=false',
'-Ddart.vm.product=false',
'--enable-asserts',
'--no-link-platform',
'--packages',
'.packages',
'--native-assets',
'path/to/native_assets.yaml',
'--verbosity=error',
'file:///path/to/main.dart',
], completer: completer),
]),
stdoutHandler: stdoutHandler,
);
final Future<CompilerOutput?> output = kernelCompiler.compile(
sdkRoot: '/path/to/sdkroot',
mainPath: '/path/to/main.dart',
buildMode: BuildMode.debug,
trackWidgetCreation: false,
dartDefines: const <String>[],
packageConfig: PackageConfig.empty,
packagesPath: '.packages',
nativeAssets: 'path/to/native_assets.yaml',
);
stdoutHandler.compilerOutput
?.complete(const CompilerOutput('', 0, <Uri>[]));
completer.complete();
expect((await output)?.outputFilename, '');
});
}

View File

@@ -644,6 +644,7 @@ class FakeBundleBuilder extends Fake implements BundleBuilder {
String? applicationKernelFilePath,
String? depfilePath,
String? assetDirPath,
Uri? nativeAssets,
@visibleForTesting BuildSystem? buildSystem
}) async {}
}

View File

@@ -702,7 +702,18 @@ class FakeResidentCompiler extends Fake implements ResidentCompiler {
Future<CompilerOutput> Function(Uri mainUri, List<Uri>? invalidatedFiles)? onRecompile;
@override
Future<CompilerOutput> recompile(Uri mainUri, List<Uri>? invalidatedFiles, {String? outputPath, PackageConfig? packageConfig, String? projectRootPath, FileSystem? fs, bool suppressErrors = false, bool checkDartPluginRegistry = false, File? dartPluginRegistrant}) {
Future<CompilerOutput> recompile(
Uri mainUri,
List<Uri>? invalidatedFiles, {
String? outputPath,
PackageConfig? packageConfig,
String? projectRootPath,
FileSystem? fs,
bool suppressErrors = false,
bool checkDartPluginRegistry = false,
File? dartPluginRegistrant,
Uri? nativeAssetsYaml,
}) {
return onRecompile?.call(mainUri, invalidatedFiles)
?? Future<CompilerOutput>.value(const CompilerOutput('', 1, <Uri>[]));
}

View File

@@ -0,0 +1,91 @@
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:flutter_tools/src/native_assets.dart';
import 'package:native_assets_builder/native_assets_builder.dart'
as native_assets_builder;
import 'package:native_assets_cli/native_assets_cli.dart';
import 'package:package_config/package_config_types.dart';
/// Mocks all logic instead of using `package:native_assets_builder`, which
/// relies on doing process calls to `pub` and the local file system.
class FakeNativeAssetsBuildRunner implements NativeAssetsBuildRunner {
FakeNativeAssetsBuildRunner({
this.hasPackageConfigResult = true,
this.packagesWithNativeAssetsResult = const <Package>[],
this.dryRunResult = const FakeNativeAssetsBuilderResult(),
this.buildResult = const FakeNativeAssetsBuilderResult(),
CCompilerConfig? cCompilerConfigResult,
}) : cCompilerConfigResult = cCompilerConfigResult ?? CCompilerConfig();
final native_assets_builder.BuildResult buildResult;
final native_assets_builder.DryRunResult dryRunResult;
final bool hasPackageConfigResult;
final List<Package> packagesWithNativeAssetsResult;
final CCompilerConfig cCompilerConfigResult;
int buildInvocations = 0;
int dryRunInvocations = 0;
int hasPackageConfigInvocations = 0;
int packagesWithNativeAssetsInvocations = 0;
@override
Future<native_assets_builder.BuildResult> build({
required bool includeParentEnvironment,
required BuildMode buildMode,
required LinkModePreference linkModePreference,
required Target target,
required Uri workingDirectory,
CCompilerConfig? cCompilerConfig,
int? targetAndroidNdkApi,
IOSSdk? targetIOSSdk,
}) async {
buildInvocations++;
return buildResult;
}
@override
Future<native_assets_builder.DryRunResult> dryRun({
required bool includeParentEnvironment,
required LinkModePreference linkModePreference,
required OS targetOs,
required Uri workingDirectory,
}) async {
dryRunInvocations++;
return dryRunResult;
}
@override
Future<bool> hasPackageConfig() async {
hasPackageConfigInvocations++;
return hasPackageConfigResult;
}
@override
Future<List<Package>> packagesWithNativeAssets() async {
packagesWithNativeAssetsInvocations++;
return packagesWithNativeAssetsResult;
}
@override
Future<CCompilerConfig> get cCompilerConfig async => cCompilerConfigResult;
}
final class FakeNativeAssetsBuilderResult
implements native_assets_builder.BuildResult {
const FakeNativeAssetsBuilderResult({
this.assets = const <Asset>[],
this.dependencies = const <Uri>[],
this.success = true,
});
@override
final List<Asset> assets;
@override
final List<Uri> dependencies;
@override
final bool success;
}

View File

@@ -400,5 +400,13 @@ void main() {
});
}
test('${nativeAssets.name} availability and default enabled', () {
expect(nativeAssets.master.enabledByDefault, false);
expect(nativeAssets.master.available, true);
expect(nativeAssets.beta.enabledByDefault, false);
expect(nativeAssets.beta.available, false);
expect(nativeAssets.stable.enabledByDefault, false);
expect(nativeAssets.stable.available, false);
});
});
}

View File

@@ -5,10 +5,13 @@
import 'package:file/memory.dart';
import 'package:flutter_tools/src/base/file_system.dart';
import 'package:flutter_tools/src/base/logger.dart';
import 'package:flutter_tools/src/features.dart';
import 'package:flutter_tools/src/flutter_project_metadata.dart';
import 'package:flutter_tools/src/project.dart';
import '../src/common.dart';
import '../src/context.dart';
import '../src/fakes.dart';
void main() {
late FileSystem fileSystem;
@@ -184,4 +187,16 @@ migration:
expect(logger.traceText, contains('The key `create_revision` was not found'));
});
testUsingContext('enabledValues does not contain packageFfi if native-assets not enabled', () {
expect(FlutterProjectType.enabledValues, isNot(contains(FlutterProjectType.packageFfi)));
expect(FlutterProjectType.enabledValues, contains(FlutterProjectType.plugin));
});
testUsingContext('enabledValues contains packageFfi if natives-assets enabled', () {
expect(FlutterProjectType.enabledValues, contains(FlutterProjectType.packageFfi));
expect(FlutterProjectType.enabledValues, contains(FlutterProjectType.plugin));
}, overrides: <Type, Generator>{
FeatureFlags: () => TestFeatureFlags(isNativeAssetsEnabled: true),
});
}

View File

@@ -2,8 +2,6 @@
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:file/memory.dart';
import 'package:flutter_tools/src/application_package.dart';
import 'package:flutter_tools/src/artifacts.dart';
@@ -16,12 +14,15 @@ import 'package:flutter_tools/src/build_system/targets/shader_compiler.dart';
import 'package:flutter_tools/src/compile.dart';
import 'package:flutter_tools/src/devfs.dart';
import 'package:flutter_tools/src/device.dart';
import 'package:flutter_tools/src/features.dart';
import 'package:flutter_tools/src/project.dart';
import 'package:flutter_tools/src/reporting/reporting.dart';
import 'package:flutter_tools/src/resident_devtools_handler.dart';
import 'package:flutter_tools/src/resident_runner.dart';
import 'package:flutter_tools/src/run_hot.dart';
import 'package:flutter_tools/src/vmservice.dart';
import 'package:native_assets_cli/native_assets_cli.dart' hide BuildMode, Target;
import 'package:native_assets_cli/native_assets_cli.dart' as native_assets_cli;
import 'package:package_config/package_config.dart';
import 'package:test/fake.dart';
import 'package:vm_service/vm_service.dart' as vm_service;
@@ -29,6 +30,7 @@ import 'package:vm_service/vm_service.dart' as vm_service;
import '../src/common.dart';
import '../src/context.dart';
import '../src/fakes.dart';
import 'fake_native_assets_build_runner.dart';
void main() {
group('validateReloadReport', () {
@@ -548,6 +550,134 @@ void main() {
expect(flutterDevice2.stoppedEchoingDeviceLog, true);
});
});
group('native assets', () {
late TestHotRunnerConfig testingConfig;
late FileSystem fileSystem;
setUp(() {
fileSystem = MemoryFileSystem.test();
testingConfig = TestHotRunnerConfig(
successfulHotRestartSetup: true,
);
});
testUsingContext('native assets restart', () async {
final FakeDevice device = FakeDevice();
final FakeFlutterDevice fakeFlutterDevice = FakeFlutterDevice(device);
final List<FlutterDevice> devices = <FlutterDevice>[
fakeFlutterDevice,
];
fakeFlutterDevice.updateDevFSReportCallback = () async => UpdateFSReport(
success: true,
invalidatedSourcesCount: 6,
syncedBytes: 8,
scannedSourcesCount: 16,
compileDuration: const Duration(seconds: 16),
transferDuration: const Duration(seconds: 32),
);
(fakeFlutterDevice.devFS! as FakeDevFs).baseUri = Uri.parse('file:///base_uri');
final FakeNativeAssetsBuildRunner buildRunner = FakeNativeAssetsBuildRunner(
packagesWithNativeAssetsResult: <Package>[
Package('bar', fileSystem.currentDirectory.uri),
],
dryRunResult: FakeNativeAssetsBuilderResult(
assets: <Asset>[
Asset(
id: 'package:bar/bar.dart',
linkMode: LinkMode.dynamic,
target: native_assets_cli.Target.macOSArm64,
path: AssetAbsolutePath(Uri.file('bar.dylib')),
),
],
),
);
final HotRunner hotRunner = HotRunner(
devices,
debuggingOptions: DebuggingOptions.disabled(BuildInfo.debug),
target: 'main.dart',
devtoolsHandler: createNoOpHandler,
buildRunner: buildRunner,
);
final OperationResult result = await hotRunner.restart(fullRestart: true);
expect(result.isOk, true);
// Hot restart does not require reruning anything for native assets.
// The previous native assets mapping should be used.
expect(buildRunner.buildInvocations, 0);
expect(buildRunner.dryRunInvocations, 0);
expect(buildRunner.hasPackageConfigInvocations, 0);
expect(buildRunner.packagesWithNativeAssetsInvocations, 0);
}, overrides: <Type, Generator>{
HotRunnerConfig: () => testingConfig,
Artifacts: () => Artifacts.test(),
FileSystem: () => fileSystem,
Platform: () => FakePlatform(),
ProcessManager: () => FakeProcessManager.empty(),
FeatureFlags: () => TestFeatureFlags(isNativeAssetsEnabled: true, isMacOSEnabled: true),
});
testUsingContext('native assets run unsupported', () async {
final FakeDevice device = FakeDevice(targetPlatform: TargetPlatform.android_arm64);
final FakeFlutterDevice fakeFlutterDevice = FakeFlutterDevice(device);
final List<FlutterDevice> devices = <FlutterDevice>[
fakeFlutterDevice,
];
fakeFlutterDevice.updateDevFSReportCallback = () async => UpdateFSReport(
success: true,
invalidatedSourcesCount: 6,
syncedBytes: 8,
scannedSourcesCount: 16,
compileDuration: const Duration(seconds: 16),
transferDuration: const Duration(seconds: 32),
);
(fakeFlutterDevice.devFS! as FakeDevFs).baseUri = Uri.parse('file:///base_uri');
final FakeNativeAssetsBuildRunner buildRunner = FakeNativeAssetsBuildRunner(
packagesWithNativeAssetsResult: <Package>[
Package('bar', fileSystem.currentDirectory.uri),
],
dryRunResult: FakeNativeAssetsBuilderResult(
assets: <Asset>[
Asset(
id: 'package:bar/bar.dart',
linkMode: LinkMode.dynamic,
target: native_assets_cli.Target.macOSArm64,
path: AssetAbsolutePath(Uri.file('bar.dylib')),
),
],
),
);
final HotRunner hotRunner = HotRunner(
devices,
debuggingOptions: DebuggingOptions.disabled(BuildInfo.debug),
target: 'main.dart',
devtoolsHandler: createNoOpHandler,
buildRunner: buildRunner,
);
expect(
() => hotRunner.run(),
throwsToolExit( message:
'Package(s) bar require the native assets feature. '
'This feature has not yet been implemented for `TargetPlatform.android_arm64`. '
'For more info see https://github.com/flutter/flutter/issues/129757.',
)
);
}, overrides: <Type, Generator>{
HotRunnerConfig: () => testingConfig,
Artifacts: () => Artifacts.test(),
FileSystem: () => fileSystem,
Platform: () => FakePlatform(),
ProcessManager: () => FakeProcessManager.empty(),
FeatureFlags: () => TestFeatureFlags(isNativeAssetsEnabled: true, isMacOSEnabled: true),
});
});
}
class FakeDevFs extends Fake implements DevFS {
@@ -580,6 +710,12 @@ class FakeDevFs extends Fake implements DevFS {
// Until we fix that, we have to also ignore related lints here.
// ignore: avoid_implementing_value_types
class FakeDevice extends Fake implements Device {
FakeDevice({
TargetPlatform targetPlatform = TargetPlatform.tester,
}) : _targetPlatform = targetPlatform;
final TargetPlatform _targetPlatform;
bool disposed = false;
@override
@@ -595,7 +731,7 @@ class FakeDevice extends Fake implements Device {
bool supportsFlutterExit = true;
@override
Future<TargetPlatform> get targetPlatform async => TargetPlatform.tester;
Future<TargetPlatform> get targetPlatform async => _targetPlatform;
@override
Future<String> get sdkNameAndVersion async => 'Tester';
@@ -658,6 +794,9 @@ class FakeFlutterDevice extends Fake implements FlutterDevice {
required List<Uri> invalidatedFiles,
required PackageConfig packageConfig,
}) => updateDevFSReportCallback();
@override
TargetPlatform? get targetPlatform => device._targetPlatform;
}
class TestFlutterDevice extends FlutterDevice {

View File

@@ -0,0 +1,274 @@
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:file/file.dart';
import 'package:file/memory.dart';
import 'package:file_testing/file_testing.dart';
import 'package:flutter_tools/src/artifacts.dart';
import 'package:flutter_tools/src/base/file_system.dart';
import 'package:flutter_tools/src/base/logger.dart';
import 'package:flutter_tools/src/base/platform.dart';
import 'package:flutter_tools/src/build_info.dart';
import 'package:flutter_tools/src/build_system/build_system.dart';
import 'package:flutter_tools/src/features.dart';
import 'package:flutter_tools/src/globals.dart' as globals;
import 'package:flutter_tools/src/ios/native_assets.dart';
import 'package:native_assets_cli/native_assets_cli.dart' hide BuildMode, Target;
import 'package:native_assets_cli/native_assets_cli.dart' as native_assets_cli;
import 'package:package_config/package_config_types.dart';
import '../../src/common.dart';
import '../../src/context.dart';
import '../../src/fakes.dart';
import '../fake_native_assets_build_runner.dart';
void main() {
late FakeProcessManager processManager;
late Environment environment;
late Artifacts artifacts;
late FileSystem fileSystem;
late BufferLogger logger;
late Uri projectUri;
setUp(() {
processManager = FakeProcessManager.empty();
logger = BufferLogger.test();
artifacts = Artifacts.test();
fileSystem = MemoryFileSystem.test();
environment = Environment.test(
fileSystem.currentDirectory,
inputs: <String, String>{},
artifacts: artifacts,
processManager: processManager,
fileSystem: fileSystem,
logger: logger,
);
environment.buildDir.createSync(recursive: true);
projectUri = environment.projectDir.uri;
});
testUsingContext('dry run with no package config', overrides: <Type, Generator>{
ProcessManager: () => FakeProcessManager.empty(),
}, () async {
expect(
await dryRunNativeAssetsIOS(
projectUri: projectUri,
fileSystem: fileSystem,
buildRunner: FakeNativeAssetsBuildRunner(
hasPackageConfigResult: false,
),
),
null,
);
expect(
(globals.logger as BufferLogger).traceText,
contains('No package config found. Skipping native assets compilation.'),
);
});
testUsingContext('build with no package config', overrides: <Type, Generator>{
ProcessManager: () => FakeProcessManager.empty(),
}, () async {
await buildNativeAssetsIOS(
darwinArchs: <DarwinArch>[DarwinArch.arm64],
environmentType: EnvironmentType.simulator,
projectUri: projectUri,
buildMode: BuildMode.debug,
fileSystem: fileSystem,
yamlParentDirectory: environment.buildDir.uri,
buildRunner: FakeNativeAssetsBuildRunner(
hasPackageConfigResult: false,
),
);
expect(
(globals.logger as BufferLogger).traceText,
contains('No package config found. Skipping native assets compilation.'),
);
});
testUsingContext('dry run with assets but not enabled', overrides: <Type, Generator>{
ProcessManager: () => FakeProcessManager.empty(),
}, () async {
final File packageConfig = environment.projectDir.childFile('.dart_tool/package_config.json');
await packageConfig.parent.create();
await packageConfig.create();
expect(
() => dryRunNativeAssetsIOS(
projectUri: projectUri,
fileSystem: fileSystem,
buildRunner: FakeNativeAssetsBuildRunner(
packagesWithNativeAssetsResult: <Package>[
Package('bar', projectUri),
],
),
),
throwsToolExit(
message: 'Package(s) bar require the native assets feature to be enabled. '
'Enable using `flutter config --enable-native-assets`.',
),
);
});
testUsingContext('dry run with assets', overrides: <Type, Generator>{
FeatureFlags: () => TestFeatureFlags(isNativeAssetsEnabled: true),
ProcessManager: () => FakeProcessManager.empty(),
}, () async {
final File packageConfig = environment.projectDir.childFile('.dart_tool/package_config.json');
await packageConfig.parent.create();
await packageConfig.create();
final Uri? nativeAssetsYaml = await dryRunNativeAssetsIOS(
projectUri: projectUri,
fileSystem: fileSystem,
buildRunner: FakeNativeAssetsBuildRunner(
packagesWithNativeAssetsResult: <Package>[
Package('bar', projectUri),
],
dryRunResult: FakeNativeAssetsBuilderResult(
assets: <Asset>[
Asset(
id: 'package:bar/bar.dart',
linkMode: LinkMode.dynamic,
target: native_assets_cli.Target.macOSArm64,
path: AssetAbsolutePath(Uri.file('bar.dylib')),
),
Asset(
id: 'package:bar/bar.dart',
linkMode: LinkMode.dynamic,
target: native_assets_cli.Target.macOSX64,
path: AssetAbsolutePath(Uri.file('bar.dylib')),
),
],
),
),
);
expect(
nativeAssetsYaml,
projectUri.resolve('build/native_assets/ios/native_assets.yaml'),
);
expect(
await fileSystem.file(nativeAssetsYaml).readAsString(),
contains('package:bar/bar.dart'),
);
});
testUsingContext('build with assets but not enabled', () async {
final File packageConfig = environment.projectDir.childFile('.dart_tool/package_config.json');
await packageConfig.parent.create();
await packageConfig.create();
expect(
() => buildNativeAssetsIOS(
darwinArchs: <DarwinArch>[DarwinArch.arm64],
environmentType: EnvironmentType.simulator,
projectUri: projectUri,
buildMode: BuildMode.debug,
fileSystem: fileSystem,
yamlParentDirectory: environment.buildDir.uri,
buildRunner: FakeNativeAssetsBuildRunner(
packagesWithNativeAssetsResult: <Package>[
Package('bar', projectUri),
],
),
),
throwsToolExit(
message: 'Package(s) bar require the native assets feature to be enabled. '
'Enable using `flutter config --enable-native-assets`.',
),
);
});
testUsingContext('build no assets', overrides: <Type, Generator>{
FeatureFlags: () => TestFeatureFlags(isNativeAssetsEnabled: true),
ProcessManager: () => FakeProcessManager.empty(),
}, () async {
final File packageConfig = environment.projectDir.childFile('.dart_tool/package_config.json');
await packageConfig.parent.create();
await packageConfig.create();
await buildNativeAssetsIOS(
darwinArchs: <DarwinArch>[DarwinArch.arm64],
environmentType: EnvironmentType.simulator,
projectUri: projectUri,
buildMode: BuildMode.debug,
fileSystem: fileSystem,
yamlParentDirectory: environment.buildDir.uri,
buildRunner: FakeNativeAssetsBuildRunner(
packagesWithNativeAssetsResult: <Package>[
Package('bar', projectUri),
],
),
);
expect(
environment.buildDir.childFile('native_assets.yaml'),
exists,
);
});
testUsingContext('build with assets', overrides: <Type, Generator>{
FeatureFlags: () => TestFeatureFlags(isNativeAssetsEnabled: true),
ProcessManager: () => FakeProcessManager.list(
<FakeCommand>[
const FakeCommand(
command: <Pattern>[
'lipo',
'-create',
'-output',
'/build/native_assets/ios/bar.dylib',
'bar.dylib',
],
),
const FakeCommand(
command: <Pattern>[
'install_name_tool',
'-id',
'@executable_path/Frameworks/bar.dylib',
'/build/native_assets/ios/bar.dylib',
],
),
const FakeCommand(
command: <Pattern>[
'codesign',
'--force',
'--sign',
'-',
'--timestamp=none',
'/build/native_assets/ios/bar.dylib',
],
),
],
),
}, () async {
if (const LocalPlatform().isWindows) {
return; // Backslashes in commands, but we will never run these commands on Windows.
}
final File packageConfig = environment.projectDir.childFile('.dart_tool/package_config.json');
await packageConfig.parent.create();
await packageConfig.create();
await buildNativeAssetsIOS(
darwinArchs: <DarwinArch>[DarwinArch.arm64],
environmentType: EnvironmentType.simulator,
projectUri: projectUri,
buildMode: BuildMode.debug,
fileSystem: fileSystem,
yamlParentDirectory: environment.buildDir.uri,
buildRunner: FakeNativeAssetsBuildRunner(
packagesWithNativeAssetsResult: <Package>[
Package('bar', projectUri),
],
buildResult: FakeNativeAssetsBuilderResult(
assets: <Asset>[
Asset(
id: 'package:bar/bar.dart',
linkMode: LinkMode.dynamic,
target: native_assets_cli.Target.macOSArm64,
path: AssetAbsolutePath(Uri.file('bar.dylib')),
),
],
),
),
);
expect(
environment.buildDir.childFile('native_assets.yaml'),
exists,
);
});
}

View File

@@ -0,0 +1,385 @@
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:file/file.dart';
import 'package:file/memory.dart';
import 'package:flutter_tools/src/artifacts.dart';
import 'package:flutter_tools/src/base/file_system.dart';
import 'package:flutter_tools/src/base/logger.dart';
import 'package:flutter_tools/src/base/platform.dart';
import 'package:flutter_tools/src/build_info.dart';
import 'package:flutter_tools/src/build_system/build_system.dart';
import 'package:flutter_tools/src/features.dart';
import 'package:flutter_tools/src/globals.dart' as globals;
import 'package:flutter_tools/src/macos/native_assets.dart';
import 'package:flutter_tools/src/native_assets.dart';
import 'package:native_assets_cli/native_assets_cli.dart' hide BuildMode, Target;
import 'package:native_assets_cli/native_assets_cli.dart' as native_assets_cli;
import 'package:package_config/package_config_types.dart';
import '../../src/common.dart';
import '../../src/context.dart';
import '../../src/fakes.dart';
import '../fake_native_assets_build_runner.dart';
void main() {
late FakeProcessManager processManager;
late Environment environment;
late Artifacts artifacts;
late FileSystem fileSystem;
late BufferLogger logger;
late Uri projectUri;
setUp(() {
processManager = FakeProcessManager.empty();
logger = BufferLogger.test();
artifacts = Artifacts.test();
fileSystem = MemoryFileSystem.test();
environment = Environment.test(
fileSystem.currentDirectory,
inputs: <String, String>{},
artifacts: artifacts,
processManager: processManager,
fileSystem: fileSystem,
logger: logger,
);
environment.buildDir.createSync(recursive: true);
projectUri = environment.projectDir.uri;
});
testUsingContext('dry run with no package config', overrides: <Type, Generator>{
ProcessManager: () => FakeProcessManager.empty(),
}, () async {
expect(
await dryRunNativeAssetsMacOS(
projectUri: projectUri,
fileSystem: fileSystem,
buildRunner: FakeNativeAssetsBuildRunner(
hasPackageConfigResult: false,
),
),
null,
);
expect(
(globals.logger as BufferLogger).traceText,
contains('No package config found. Skipping native assets compilation.'),
);
});
testUsingContext('build with no package config', overrides: <Type, Generator>{
ProcessManager: () => FakeProcessManager.empty(),
}, () async {
await buildNativeAssetsMacOS(
darwinArchs: <DarwinArch>[DarwinArch.arm64],
projectUri: projectUri,
buildMode: BuildMode.debug,
fileSystem: fileSystem,
buildRunner: FakeNativeAssetsBuildRunner(
hasPackageConfigResult: false,
),
);
expect(
(globals.logger as BufferLogger).traceText,
contains('No package config found. Skipping native assets compilation.'),
);
});
testUsingContext('dry run for multiple OSes with no package config', overrides: <Type, Generator>{
ProcessManager: () => FakeProcessManager.empty(),
}, () async {
await dryRunNativeAssetsMultipeOSes(
projectUri: projectUri,
fileSystem: fileSystem,
targetPlatforms: <TargetPlatform>[
TargetPlatform.darwin,
TargetPlatform.ios,
],
buildRunner: FakeNativeAssetsBuildRunner(
hasPackageConfigResult: false,
),
);
expect(
(globals.logger as BufferLogger).traceText,
contains('No package config found. Skipping native assets compilation.'),
);
});
testUsingContext('dry run with assets but not enabled', overrides: <Type, Generator>{
ProcessManager: () => FakeProcessManager.empty(),
}, () async {
final File packageConfig = environment.projectDir.childFile('.dart_tool/package_config.json');
await packageConfig.parent.create();
await packageConfig.create();
expect(
() => dryRunNativeAssetsMacOS(
projectUri: projectUri,
fileSystem: fileSystem,
buildRunner: FakeNativeAssetsBuildRunner(
packagesWithNativeAssetsResult: <Package>[
Package('bar', projectUri),
],
),
),
throwsToolExit(
message: 'Package(s) bar require the native assets feature to be enabled. '
'Enable using `flutter config --enable-native-assets`.',
),
);
});
testUsingContext('dry run with assets', overrides: <Type, Generator>{
FeatureFlags: () => TestFeatureFlags(isNativeAssetsEnabled: true),
ProcessManager: () => FakeProcessManager.empty(),
}, () async {
final File packageConfig = environment.projectDir.childFile('.dart_tool/package_config.json');
await packageConfig.parent.create();
await packageConfig.create();
final Uri? nativeAssetsYaml = await dryRunNativeAssetsMacOS(
projectUri: projectUri,
fileSystem: fileSystem,
buildRunner: FakeNativeAssetsBuildRunner(
packagesWithNativeAssetsResult: <Package>[
Package('bar', projectUri),
],
dryRunResult: FakeNativeAssetsBuilderResult(
assets: <Asset>[
Asset(
id: 'package:bar/bar.dart',
linkMode: LinkMode.dynamic,
target: native_assets_cli.Target.macOSArm64,
path: AssetAbsolutePath(Uri.file('bar.dylib')),
),
Asset(
id: 'package:bar/bar.dart',
linkMode: LinkMode.dynamic,
target: native_assets_cli.Target.macOSX64,
path: AssetAbsolutePath(Uri.file('bar.dylib')),
),
],
),
),
);
expect(
nativeAssetsYaml,
projectUri.resolve('build/native_assets/macos/native_assets.yaml'),
);
expect(
await fileSystem.file(nativeAssetsYaml).readAsString(),
contains('package:bar/bar.dart'),
);
});
testUsingContext('build with assets but not enabled', overrides: <Type, Generator>{
ProcessManager: () => FakeProcessManager.empty(),
}, () async {
final File packageConfig = environment.projectDir.childFile('.dart_tool/package_config.json');
await packageConfig.parent.create();
await packageConfig.create();
expect(
() => buildNativeAssetsMacOS(
darwinArchs: <DarwinArch>[DarwinArch.arm64],
projectUri: projectUri,
buildMode: BuildMode.debug,
fileSystem: fileSystem,
buildRunner: FakeNativeAssetsBuildRunner(
packagesWithNativeAssetsResult: <Package>[
Package('bar', projectUri),
],
),
),
throwsToolExit(
message: 'Package(s) bar require the native assets feature to be enabled. '
'Enable using `flutter config --enable-native-assets`.',
),
);
});
testUsingContext('build no assets', overrides: <Type, Generator>{
FeatureFlags: () => TestFeatureFlags(isNativeAssetsEnabled: true),
ProcessManager: () => FakeProcessManager.empty(),
}, () async {
final File packageConfig = environment.projectDir.childFile('.dart_tool/package_config.json');
await packageConfig.parent.create();
await packageConfig.create();
final (Uri? nativeAssetsYaml, _) = await buildNativeAssetsMacOS(
darwinArchs: <DarwinArch>[DarwinArch.arm64],
projectUri: projectUri,
buildMode: BuildMode.debug,
fileSystem: fileSystem,
buildRunner: FakeNativeAssetsBuildRunner(
packagesWithNativeAssetsResult: <Package>[
Package('bar', projectUri),
],
),
);
expect(
nativeAssetsYaml,
projectUri.resolve('build/native_assets/macos/native_assets.yaml'),
);
expect(
await fileSystem.file(nativeAssetsYaml).readAsString(),
isNot(contains('package:bar/bar.dart')),
);
});
for (final bool flutterTester in <bool>[false, true]) {
String testName = '';
if (flutterTester) {
testName += ' flutter tester';
}
testUsingContext('build with assets$testName', overrides: <Type, Generator>{
FeatureFlags: () => TestFeatureFlags(isNativeAssetsEnabled: true),
ProcessManager: () => FakeProcessManager.list(
<FakeCommand>[
const FakeCommand(
command: <Pattern>[
'lipo',
'-create',
'-output',
'/build/native_assets/macos/bar.dylib',
'bar.dylib',
],
),
const FakeCommand(
command: <Pattern>[
'install_name_tool',
'-id',
'@executable_path/Frameworks/bar.dylib',
'/build/native_assets/macos/bar.dylib',
],
),
const FakeCommand(
command: <Pattern>[
'codesign',
'--force',
'--sign',
'-',
'--timestamp=none',
'/build/native_assets/macos/bar.dylib',
],
),
],
),
}, () async {
if (const LocalPlatform().isWindows) {
return; // Backslashes in commands, but we will never run these commands on Windows.
}
final File packageConfig = environment.projectDir.childFile('.dart_tool/package_config.json');
await packageConfig.parent.create();
await packageConfig.create();
final (Uri? nativeAssetsYaml, _) = await buildNativeAssetsMacOS(
darwinArchs: <DarwinArch>[DarwinArch.arm64],
projectUri: projectUri,
buildMode: BuildMode.debug,
fileSystem: fileSystem,
flutterTester: flutterTester,
buildRunner: FakeNativeAssetsBuildRunner(
packagesWithNativeAssetsResult: <Package>[
Package('bar', projectUri),
],
buildResult: FakeNativeAssetsBuilderResult(
assets: <Asset>[
Asset(
id: 'package:bar/bar.dart',
linkMode: LinkMode.dynamic,
target: native_assets_cli.Target.macOSArm64,
path: AssetAbsolutePath(Uri.file('bar.dylib')),
),
],
),
),
);
expect(
nativeAssetsYaml,
projectUri.resolve('build/native_assets/macos/native_assets.yaml'),
);
expect(
await fileSystem.file(nativeAssetsYaml).readAsString(),
stringContainsInOrder(<String>[
'package:bar/bar.dart',
if (flutterTester)
// Tests run on host system, so the have the full path on the system.
'- ${projectUri.resolve('/build/native_assets/macos/bar.dylib').toFilePath()}'
else
// Apps are a bundle with the dylibs on their dlopen path.
'- bar.dylib',
]),
);
});
}
testUsingContext('static libs not supported', overrides: <Type, Generator>{
FeatureFlags: () => TestFeatureFlags(isNativeAssetsEnabled: true),
ProcessManager: () => FakeProcessManager.empty(),
}, () async {
final File packageConfig = environment.projectDir.childFile('.dart_tool/package_config.json');
await packageConfig.parent.create();
await packageConfig.create();
expect(
() => dryRunNativeAssetsMacOS(
projectUri: projectUri,
fileSystem: fileSystem,
buildRunner: FakeNativeAssetsBuildRunner(
packagesWithNativeAssetsResult: <Package>[
Package('bar', projectUri),
],
dryRunResult: FakeNativeAssetsBuilderResult(
assets: <Asset>[
Asset(
id: 'package:bar/bar.dart',
linkMode: LinkMode.static,
target: native_assets_cli.Target.macOSArm64,
path: AssetAbsolutePath(Uri.file('bar.a')),
),
Asset(
id: 'package:bar/bar.dart',
linkMode: LinkMode.static,
target: native_assets_cli.Target.macOSX64,
path: AssetAbsolutePath(Uri.file('bar.a')),
),
],
),
),
),
throwsToolExit(
message: 'Native asset(s) package:bar/bar.dart have their link mode set to '
'static, but this is not yet supported. '
'For more info see https://github.com/dart-lang/sdk/issues/49418.',
),
);
});
// This logic is mocked in the other tests to avoid having test order
// randomization causing issues with what processes are invoked.
// Exercise the parsing of the process output in this separate test.
testUsingContext('NativeAssetsBuildRunnerImpl.cCompilerConfig', overrides: <Type, Generator>{
FeatureFlags: () => TestFeatureFlags(isNativeAssetsEnabled: true),
ProcessManager: () => FakeProcessManager.list(
<FakeCommand>[
const FakeCommand(
command: <Pattern>['xcrun', 'clang', '--version'],
stdout: '''
Apple clang version 14.0.0 (clang-1400.0.29.202)
Target: arm64-apple-darwin22.6.0
Thread model: posix
InstalledDir: /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin''',
)
],
),
}, () async {
if (!const LocalPlatform().isMacOS) {
// TODO(dacoharkes): Implement other OSes. https://github.com/flutter/flutter/issues/129757
return;
}
final NativeAssetsBuildRunner runner = NativeAssetsBuildRunnerImpl(projectUri, fileSystem, logger);
final CCompilerConfig result = await runner.cCompilerConfig;
expect(
result.cc,
Uri.file(
'/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/clang',
),
);
});
}

View File

@@ -99,6 +99,7 @@ class FakeBundleBuilder extends Fake implements BundleBuilder {
String? applicationKernelFilePath,
String? depfilePath,
String? assetDirPath,
Uri? nativeAssets,
@visibleForTesting BuildSystem? buildSystem
}) async {
final Directory assetDirectory = fileSystem

View File

@@ -18,6 +18,7 @@ import 'package:flutter_tools/src/base/io.dart' as io;
import 'package:flutter_tools/src/base/logger.dart';
import 'package:flutter_tools/src/base/platform.dart';
import 'package:flutter_tools/src/build_info.dart';
import 'package:flutter_tools/src/build_system/build_system.dart';
import 'package:flutter_tools/src/build_system/targets/scene_importer.dart';
import 'package:flutter_tools/src/build_system/targets/shader_compiler.dart';
import 'package:flutter_tools/src/compile.dart';
@@ -25,6 +26,7 @@ import 'package:flutter_tools/src/convert.dart';
import 'package:flutter_tools/src/devfs.dart';
import 'package:flutter_tools/src/device.dart';
import 'package:flutter_tools/src/device_port_forwarder.dart';
import 'package:flutter_tools/src/features.dart';
import 'package:flutter_tools/src/globals.dart' as globals;
import 'package:flutter_tools/src/project.dart';
import 'package:flutter_tools/src/reporting/reporting.dart';
@@ -34,6 +36,9 @@ import 'package:flutter_tools/src/run_cold.dart';
import 'package:flutter_tools/src/run_hot.dart';
import 'package:flutter_tools/src/version.dart';
import 'package:flutter_tools/src/vmservice.dart';
import 'package:native_assets_cli/native_assets_cli.dart'
hide BuildMode, Target;
import 'package:native_assets_cli/native_assets_cli.dart' as native_assets_cli;
import 'package:package_config/package_config.dart';
import 'package:test/fake.dart';
import 'package:vm_service/vm_service.dart' as vm_service;
@@ -43,6 +48,7 @@ import '../src/context.dart';
import '../src/fake_vm_services.dart';
import '../src/fakes.dart';
import '../src/testbed.dart';
import 'fake_native_assets_build_runner.dart';
final vm_service.Event fakeUnpausedEvent = vm_service.Event(
kind: vm_service.EventKind.kResume,
@@ -2322,6 +2328,82 @@ flutter:
expect(flutterDevice.devFS!.hasSetAssetDirectory, true);
expect(fakeVmServiceHost!.hasRemainingExpectations, false);
}));
testUsingContext(
'native assets',
() => testbed.run(() async {
final FileSystem fileSystem = globals.fs;
final Environment environment = Environment.test(
fileSystem.currentDirectory,
inputs: <String, String>{},
artifacts: Artifacts.test(),
processManager: FakeProcessManager.empty(),
fileSystem: fileSystem,
logger: BufferLogger.test(),
);
final Uri projectUri = environment.projectDir.uri;
final FakeDevice device = FakeDevice(
targetPlatform: TargetPlatform.darwin,
sdkNameAndVersion: 'Macos',
);
final FakeFlutterDevice flutterDevice = FakeFlutterDevice()
..testUri = testUri
..vmServiceHost = (() => fakeVmServiceHost)
..device = device
.._devFS = devFS
..targetPlatform = TargetPlatform.darwin;
fakeVmServiceHost = FakeVmServiceHost(requests: <VmServiceExpectation>[
listViews,
listViews,
]);
globals.fs
.file(globals.fs.path.join('lib', 'main.dart'))
.createSync(recursive: true);
final FakeNativeAssetsBuildRunner buildRunner = FakeNativeAssetsBuildRunner(
packagesWithNativeAssetsResult: <Package>[
Package('bar', projectUri),
],
dryRunResult: FakeNativeAssetsBuilderResult(
assets: <Asset>[
Asset(
id: 'package:bar/bar.dart',
linkMode: LinkMode.dynamic,
target: native_assets_cli.Target.macOSArm64,
path: AssetAbsolutePath(Uri.file('bar.dylib')),
),
],
),
);
residentRunner = HotRunner(
<FlutterDevice>[
flutterDevice,
],
stayResident: false,
debuggingOptions: DebuggingOptions.enabled(const BuildInfo(
BuildMode.debug,
'',
treeShakeIcons: false,
trackWidgetCreation: true,
)),
target: 'main.dart',
devtoolsHandler: createNoOpHandler,
buildRunner: buildRunner,
);
final int? result = await residentRunner.run();
expect(result, 0);
expect(buildRunner.buildInvocations, 0);
expect(buildRunner.dryRunInvocations, 1);
expect(buildRunner.hasPackageConfigInvocations, 1);
expect(buildRunner.packagesWithNativeAssetsInvocations, 0);
}),
overrides: <Type, Generator>{
ProcessManager: () => FakeProcessManager.any(),
FeatureFlags: () => TestFeatureFlags(isNativeAssetsEnabled: true, isMacOSEnabled: true),
});
}
// This implements [dds.DartDevelopmentService], not the [DartDevelopmentService]
@@ -2386,7 +2468,7 @@ class FakeFlutterDevice extends Fake implements FlutterDevice {
DevelopmentShaderCompiler get developmentShaderCompiler => const FakeShaderCompiler();
@override
TargetPlatform get targetPlatform => TargetPlatform.android;
TargetPlatform targetPlatform = TargetPlatform.android;
@override
Stream<Uri?> get vmServiceUris => Stream<Uri?>.value(testUri);
@@ -2521,6 +2603,7 @@ class FakeResidentCompiler extends Fake implements ResidentCompiler {
bool suppressErrors = false,
bool checkDartPluginRegistry = false,
File? dartPluginRegistrant,
Uri? nativeAssetsYaml,
}) async {
didSuppressErrors = suppressErrors;
return nextOutput ?? const CompilerOutput('foo.dill', 0, <Uri>[]);

View File

@@ -1444,6 +1444,7 @@ class FakeResidentCompiler extends Fake implements ResidentCompiler {
bool suppressErrors = false,
bool checkDartPluginRegistry = false,
File? dartPluginRegistrant,
Uri? nativeAssetsYaml,
}) async {
return const CompilerOutput('foo.dill', 0, <Uri>[]);
}

View File

@@ -234,6 +234,7 @@ class FakeResidentCompiler extends Fake implements ResidentCompiler {
bool suppressErrors = false,
bool checkDartPluginRegistry = false,
File? dartPluginRegistrant,
Uri? nativeAssetsYaml,
}) async {
if (compilerOutput != null) {
fileSystem!.file(compilerOutput!.outputFilename).createSync(recursive: true);

View File

@@ -98,7 +98,6 @@ void main() {
artifacts: Artifacts.test(),
logger: BufferLogger.test(),
flutterVersion: FakeFlutterVersion(),
operatingSystemUtils: FakeOperatingSystemUtils(),
);
logLines = <String>[];
device.getLogReader().logLines.listen(logLines.add);
@@ -213,7 +212,6 @@ FlutterTesterDevices setUpFlutterTesterDevices() {
processManager: FakeProcessManager.any(),
fileSystem: MemoryFileSystem.test(),
flutterVersion: FakeFlutterVersion(),
operatingSystemUtils: FakeOperatingSystemUtils(),
);
}

View File

@@ -1190,6 +1190,7 @@ class FakeResidentCompiler extends Fake implements ResidentCompiler {
bool suppressErrors = false,
bool checkDartPluginRegistry = false,
File? dartPluginRegistrant,
Uri? nativeAssetsYaml,
}) async {
return output;
}

View File

@@ -254,6 +254,7 @@ void main() {
'VERBOSE_SCRIPT_LOGGING': '1',
'FLUTTER_BUILD_MODE': 'release',
'ACTION': 'install',
'FLUTTER_BUILD_DIR': 'build',
// Skip bitcode stripping since we just checked that above.
},
);

View File

@@ -0,0 +1,360 @@
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// This test exercises the embedding of the native assets mapping in dill files.
// An initial dill file is created by `flutter assemble` and used for running
// the application. This dill must contain the mapping.
// When doing hot reload, this mapping must stay in place.
// When doing a hot restart, a new dill file is pushed. This dill file must also
// contain the native assets mapping.
// When doing a hot reload, this mapping must stay in place.
@Timeout(Duration(minutes: 10))
library;
import 'dart:io';
import 'package:file/file.dart';
import 'package:file_testing/file_testing.dart';
import '../src/common.dart';
import 'test_utils.dart' show fileSystem, platform;
import 'transition_test_utils.dart';
final String hostOs = platform.operatingSystem;
final List<String> devices = <String>[
'flutter-tester',
hostOs,
];
final List<String> buildSubcommands = <String>[
hostOs,
if (hostOs == 'macos') 'ios',
];
final List<String> add2appBuildSubcommands = <String>[
if (hostOs == 'macos') ...<String>[
'macos-framework',
'ios-framework',
],
];
/// The build modes to target for each flutter command that supports passing
/// a build mode.
///
/// The flow of compiling kernel as well as bundling dylibs can differ based on
/// build mode, so we should cover this.
const List<String> buildModes = <String>[
'debug',
'profile',
'release',
];
const String packageName = 'package_with_native_assets';
const String exampleAppName = '${packageName}_example';
const String dylibName = 'lib$packageName.dylib';
void main() {
if (!platform.isMacOS) {
// TODO(dacoharkes): Implement other OSes. https://github.com/flutter/flutter/issues/129757
return;
}
setUpAll(() {
processManager.runSync(<String>[
flutterBin,
'config',
'--enable-native-assets',
]);
});
for (final String device in devices) {
for (final String buildMode in buildModes) {
if (device == 'flutter-tester' && buildMode != 'debug') {
continue;
}
final String hotReload = buildMode == 'debug' ? ' hot reload and hot restart' : '';
testWithoutContext('flutter run$hotReload with native assets $device $buildMode', () async {
await inTempDir((Directory tempDirectory) async {
final Directory packageDirectory = await createTestProject(packageName, tempDirectory);
final Directory exampleDirectory = packageDirectory.childDirectory('example');
final ProcessTestResult result = await runFlutter(
<String>[
'run',
'-d$device',
'--$buildMode',
],
exampleDirectory.path,
<Transition>[
Multiple(<Pattern>[
'Flutter run key commands.',
], handler: (String line) {
if (buildMode == 'debug') {
// Do a hot reload diff on the initial dill file.
return 'r';
} else {
// No hot reload and hot restart in release mode.
return 'q';
}
}),
if (buildMode == 'debug') ...<Transition>[
Barrier(
'Performing hot reload...'.padRight(progressMessageWidth),
logging: true,
),
Multiple(<Pattern>[
RegExp('Reloaded .*'),
], handler: (String line) {
// Do a hot restart, pushing a new complete dill file.
return 'R';
}),
Barrier('Performing hot restart...'.padRight(progressMessageWidth)),
Multiple(<Pattern>[
RegExp('Restarted application .*'),
], handler: (String line) {
// Do another hot reload, pushing a diff to the second dill file.
return 'r';
}),
Barrier(
'Performing hot reload...'.padRight(progressMessageWidth),
logging: true,
),
Multiple(<Pattern>[
RegExp('Reloaded .*'),
], handler: (String line) {
return 'q';
}),
],
const Barrier('Application finished.'),
],
logging: false,
);
if (result.exitCode != 0) {
throw Exception('flutter run failed: ${result.exitCode}\n${result.stderr}\n${result.stdout}');
}
final String stdout = result.stdout.join('\n');
// Check that we did not fail to resolve the native function in the
// dynamic library.
expect(stdout, isNot(contains("Invalid argument(s): Couldn't resolve native function 'sum'")));
// And also check that we did not have any other exceptions that might
// shadow the exception we would have gotten.
expect(stdout, isNot(contains('EXCEPTION CAUGHT BY WIDGETS LIBRARY')));
if (device == 'macos') {
expectDylibIsBundledMacOS(exampleDirectory, buildMode);
}
if (device == hostOs) {
expectCCompilerIsConfigured(exampleDirectory);
}
});
});
}
}
testWithoutContext('flutter test with native assets', () async {
await inTempDir((Directory tempDirectory) async {
final Directory packageDirectory = await createTestProject(packageName, tempDirectory);
final ProcessTestResult result = await runFlutter(
<String>[
'test',
],
packageDirectory.path,
<Transition>[
Barrier(RegExp('.* All tests passed!')),
],
logging: false,
);
if (result.exitCode != 0) {
throw Exception('flutter test failed: ${result.exitCode}\n${result.stderr}\n${result.stdout}');
}
});
});
for (final String buildSubcommand in buildSubcommands) {
for (final String buildMode in buildModes) {
testWithoutContext('flutter build $buildSubcommand with native assets $buildMode', () async {
await inTempDir((Directory tempDirectory) async {
final Directory packageDirectory = await createTestProject(packageName, tempDirectory);
final Directory exampleDirectory = packageDirectory.childDirectory('example');
final ProcessResult result = processManager.runSync(
<String>[
flutterBin,
'build',
buildSubcommand,
'--$buildMode',
if (buildSubcommand == 'ios') '--no-codesign',
],
workingDirectory: exampleDirectory.path,
);
if (result.exitCode != 0) {
throw Exception('flutter build failed: ${result.exitCode}\n${result.stderr}\n${result.stdout}');
}
if (buildSubcommand == 'macos') {
expectDylibIsBundledMacOS(exampleDirectory, buildMode);
} else if (buildSubcommand == 'ios') {
expectDylibIsBundledIos(exampleDirectory, buildMode);
}
expectCCompilerIsConfigured(exampleDirectory);
});
});
}
// This could be an hermetic unit test if the native_assets_builder
// could mock process runs and file system.
// https://github.com/dart-lang/native/issues/90.
testWithoutContext('flutter build $buildSubcommand error on static libraries', () async {
await inTempDir((Directory tempDirectory) async {
final Directory packageDirectory = await createTestProject(packageName, tempDirectory);
final File buildDotDart = packageDirectory.childFile('build.dart');
final String buildDotDartContents = await buildDotDart.readAsString();
// Overrides the build to output static libraries.
final String buildDotDartContentsNew = buildDotDartContents.replaceFirst(
'final buildConfig = await BuildConfig.fromArgs(args);',
r'''
final buildConfig = await BuildConfig.fromArgs([
'-D${LinkModePreference.configKey}=${LinkModePreference.static}',
...args,
]);
''',
);
expect(buildDotDartContentsNew, isNot(buildDotDartContents));
await buildDotDart.writeAsString(buildDotDartContentsNew);
final Directory exampleDirectory = packageDirectory.childDirectory('example');
final ProcessResult result = processManager.runSync(
<String>[
flutterBin,
'build',
buildSubcommand,
if (buildSubcommand == 'ios') '--no-codesign',
],
workingDirectory: exampleDirectory.path,
);
expect(result.exitCode, isNot(0));
expect(result.stderr, contains('link mode set to static, but this is not yet supported'));
});
});
}
for (final String add2appBuildSubcommand in add2appBuildSubcommands) {
testWithoutContext('flutter build $add2appBuildSubcommand with native assets', () async {
await inTempDir((Directory tempDirectory) async {
final Directory packageDirectory = await createTestProject(packageName, tempDirectory);
final Directory exampleDirectory = packageDirectory.childDirectory('example');
final ProcessResult result = processManager.runSync(
<String>[
flutterBin,
'build',
add2appBuildSubcommand,
],
workingDirectory: exampleDirectory.path,
);
if (result.exitCode != 0) {
throw Exception('flutter build failed: ${result.exitCode}\n${result.stderr}\n${result.stdout}');
}
for (final String buildMode in buildModes) {
expectDylibIsBundledWithFrameworks(exampleDirectory, buildMode, add2appBuildSubcommand.replaceAll('-framework', ''));
}
expectCCompilerIsConfigured(exampleDirectory);
});
});
}
}
/// For `flutter build` we can't easily test whether running the app works.
/// Check that we have the dylibs in the app.
void expectDylibIsBundledMacOS(Directory appDirectory, String buildMode) {
final Directory appBundle = appDirectory.childDirectory('build/$hostOs/Build/Products/${buildMode.upperCaseFirst()}/$exampleAppName.app');
expect(appBundle, exists);
final Directory dylibsFolder = appBundle.childDirectory('Contents/Frameworks');
expect(dylibsFolder, exists);
final File dylib = dylibsFolder.childFile(dylibName);
expect(dylib, exists);
}
void expectDylibIsBundledIos(Directory appDirectory, String buildMode) {
final Directory appBundle = appDirectory.childDirectory('build/ios/${buildMode.upperCaseFirst()}-iphoneos/Runner.app');
expect(appBundle, exists);
final Directory dylibsFolder = appBundle.childDirectory('Frameworks');
expect(dylibsFolder, exists);
final File dylib = dylibsFolder.childFile(dylibName);
expect(dylib, exists);
}
/// For `flutter build` we can't easily test whether running the app works.
/// Check that we have the dylibs in the app.
void expectDylibIsBundledWithFrameworks(Directory appDirectory, String buildMode, String os) {
final Directory frameworksFolder = appDirectory.childDirectory('build/$os/framework/${buildMode.upperCaseFirst()}');
expect(frameworksFolder, exists);
final File dylib = frameworksFolder.childFile(dylibName);
expect(dylib, exists);
}
/// Check that the native assets are built with the C Compiler that Flutter uses.
///
/// This inspects the build configuration to see if the C compiler was configured.
void expectCCompilerIsConfigured(Directory appDirectory) {
final Directory nativeAssetsBuilderDir = appDirectory.childDirectory('.dart_tool/native_assets_builder/');
for (final Directory subDir in nativeAssetsBuilderDir.listSync().whereType<Directory>()) {
final File config = subDir.childFile('config.yaml');
expect(config, exists);
final String contents = config.readAsStringSync();
// Dry run does not pass compiler info.
if (contents.contains('dry_run: true')) {
continue;
}
expect(contents, contains('cc: '));
}
}
extension on String {
String upperCaseFirst() {
return replaceFirst(this[0], this[0].toUpperCase());
}
}
Future<Directory> createTestProject(String packageName, Directory tempDirectory) async {
final ProcessResult result = processManager.runSync(
<String>[
flutterBin,
'create',
'--template=package_ffi',
packageName,
],
workingDirectory: tempDirectory.path,
);
if (result.exitCode != 0) {
throw Exception('flutter create failed: ${result.exitCode}\n${result.stderr}\n${result.stdout}');
}
final Directory packageDirectory = tempDirectory.childDirectory(packageName);
// No platform-specific boilerplate files.
expect(packageDirectory.childDirectory('android/'), isNot(exists));
expect(packageDirectory.childDirectory('ios/'), isNot(exists));
expect(packageDirectory.childDirectory('linux/'), isNot(exists));
expect(packageDirectory.childDirectory('macos/'), isNot(exists));
expect(packageDirectory.childDirectory('windows/'), isNot(exists));
return packageDirectory;
}
Future<void> inTempDir(Future<void> Function(Directory tempDirectory) fun) async {
final Directory tempDirectory = fileSystem.directory(fileSystem.systemTempDirectory.createTempSync().resolveSymbolicLinksSync());
try {
await fun(tempDirectory);
} finally {
tryToDelete(tempDirectory);
}
}

View File

@@ -26,310 +26,11 @@
@Tags(<String>['no-shuffle'])
library;
import 'dart:async';
import 'dart:convert';
import 'dart:io';
import 'package:meta/meta.dart';
import 'package:process/process.dart';
import '../src/common.dart';
import 'test_utils.dart' show fileSystem;
const ProcessManager processManager = LocalProcessManager();
final String flutterRoot = getFlutterRoot();
final String flutterBin = fileSystem.path.join(flutterRoot, 'bin', 'flutter');
void debugPrint(String message) {
// This is called to intentionally print debugging output when a test is
// either taking too long or has failed.
// ignore: avoid_print
print(message);
}
typedef LineHandler = String? Function(String line);
abstract class Transition {
const Transition({this.handler, this.logging});
/// Callback that is invoked when the transition matches.
///
/// This should not throw, even if the test is failing. (For example, don't use "expect"
/// in these callbacks.) Throwing here would prevent the [runFlutter] function from running
/// to completion, which would leave zombie `flutter` processes around.
final LineHandler? handler;
/// Whether to enable or disable logging when this transition is matched.
///
/// The default value, null, leaves the logging state unaffected.
final bool? logging;
bool matches(String line);
@protected
bool lineMatchesPattern(String line, Pattern pattern) {
if (pattern is String) {
return line == pattern;
}
return line.contains(pattern);
}
@protected
String describe(Pattern pattern) {
if (pattern is String) {
return '"$pattern"';
}
if (pattern is RegExp) {
return '/${pattern.pattern}/';
}
return '$pattern';
}
}
class Barrier extends Transition {
const Barrier(this.pattern, {super.handler, super.logging});
final Pattern pattern;
@override
bool matches(String line) => lineMatchesPattern(line, pattern);
@override
String toString() => describe(pattern);
}
class Multiple extends Transition {
Multiple(List<Pattern> patterns, {
super.handler,
super.logging,
}) : _originalPatterns = patterns,
patterns = patterns.toList();
final List<Pattern> _originalPatterns;
final List<Pattern> patterns;
@override
bool matches(String line) {
for (int index = 0; index < patterns.length; index += 1) {
if (lineMatchesPattern(line, patterns[index])) {
patterns.removeAt(index);
break;
}
}
return patterns.isEmpty;
}
@override
String toString() {
if (patterns.isEmpty) {
return '${_originalPatterns.map(describe).join(', ')} (all matched)';
}
return '${_originalPatterns.map(describe).join(', ')} (matched ${_originalPatterns.length - patterns.length} so far)';
}
}
class LogLine {
const LogLine(this.channel, this.stamp, this.message);
final String channel;
final String stamp;
final String message;
bool get couldBeCrash => message.contains('Oops; flutter has exited unexpectedly:');
@override
String toString() => '$stamp $channel: $message';
void printClearly() {
debugPrint('$stamp $channel: ${clarify(message)}');
}
static String clarify(String line) {
return line.runes.map<String>((int rune) {
if (rune >= 0x20 && rune <= 0x7F) {
return String.fromCharCode(rune);
}
switch (rune) {
case 0x00: return '<NUL>';
case 0x07: return '<BEL>';
case 0x08: return '<TAB>';
case 0x09: return '<BS>';
case 0x0A: return '<LF>';
case 0x0D: return '<CR>';
}
return '<${rune.toRadixString(16).padLeft(rune <= 0xFF ? 2 : rune <= 0xFFFF ? 4 : 5, '0')}>';
}).join();
}
}
class ProcessTestResult {
const ProcessTestResult(this.exitCode, this.logs);
final int exitCode;
final List<LogLine> logs;
List<String> get stdout {
return logs
.where((LogLine log) => log.channel == 'stdout')
.map<String>((LogLine log) => log.message)
.toList();
}
List<String> get stderr {
return logs
.where((LogLine log) => log.channel == 'stderr')
.map<String>((LogLine log) => log.message)
.toList();
}
@override
String toString() => 'exit code $exitCode\nlogs:\n ${logs.join('\n ')}\n';
}
Future<ProcessTestResult> runFlutter(
List<String> arguments,
String workingDirectory,
List<Transition> transitions, {
bool debug = false,
bool logging = true,
Duration expectedMaxDuration = const Duration(minutes: 10), // must be less than test timeout of 15 minutes! See ../../dart_test.yaml.
}) async {
final Stopwatch clock = Stopwatch()..start();
final Process process = await processManager.start(
<String>[flutterBin, ...arguments],
workingDirectory: workingDirectory,
);
final List<LogLine> logs = <LogLine>[];
int nextTransition = 0;
void describeStatus() {
if (transitions.isNotEmpty) {
debugPrint('Expected state transitions:');
for (int index = 0; index < transitions.length; index += 1) {
debugPrint(
'${index.toString().padLeft(5)} '
'${index < nextTransition ? 'ALREADY MATCHED ' :
index == nextTransition ? 'NOW WAITING FOR>' :
' '} ${transitions[index]}');
}
}
if (logs.isEmpty) {
debugPrint('So far nothing has been logged${ debug ? "" : "; use debug:true to print all output" }.');
} else {
debugPrint('Log${ debug ? "" : " (only contains logged lines; use debug:true to print all output)" }:');
for (final LogLine log in logs) {
log.printClearly();
}
}
}
bool streamingLogs = false;
Timer? timeout;
void processTimeout() {
if (!streamingLogs) {
streamingLogs = true;
if (!debug) {
debugPrint('Test is taking a long time (${clock.elapsed.inSeconds} seconds so far).');
}
describeStatus();
debugPrint('(streaming all logs from this point on...)');
} else {
debugPrint('(taking a long time...)');
}
}
String stamp() => '[${(clock.elapsed.inMilliseconds / 1000.0).toStringAsFixed(1).padLeft(5)}s]';
void processStdout(String line) {
final LogLine log = LogLine('stdout', stamp(), line);
if (logging) {
logs.add(log);
}
if (streamingLogs) {
log.printClearly();
}
if (nextTransition < transitions.length && transitions[nextTransition].matches(line)) {
if (streamingLogs) {
debugPrint('(matched ${transitions[nextTransition]})');
}
if (transitions[nextTransition].logging != null) {
if (!logging && transitions[nextTransition].logging!) {
logs.add(log);
}
logging = transitions[nextTransition].logging!;
if (streamingLogs) {
if (logging) {
debugPrint('(enabled logging)');
} else {
debugPrint('(disabled logging)');
}
}
}
if (transitions[nextTransition].handler != null) {
final String? command = transitions[nextTransition].handler!(line);
if (command != null) {
final LogLine inLog = LogLine('stdin', stamp(), command);
logs.add(inLog);
if (streamingLogs) {
inLog.printClearly();
}
process.stdin.write(command);
}
}
nextTransition += 1;
timeout?.cancel();
timeout = Timer(expectedMaxDuration ~/ 5, processTimeout); // This is not a failure timeout, just when to start logging verbosely to help debugging.
}
}
void processStderr(String line) {
final LogLine log = LogLine('stdout', stamp(), line);
logs.add(log);
if (streamingLogs) {
log.printClearly();
}
}
if (debug) {
processTimeout();
} else {
timeout = Timer(expectedMaxDuration ~/ 2, processTimeout); // This is not a failure timeout, just when to start logging verbosely to help debugging.
}
process.stdout.transform<String>(utf8.decoder).transform<String>(const LineSplitter()).listen(processStdout);
process.stderr.transform<String>(utf8.decoder).transform<String>(const LineSplitter()).listen(processStderr);
unawaited(process.exitCode.timeout(expectedMaxDuration, onTimeout: () { // This is a failure timeout, must not be short.
debugPrint('${stamp()} (process is not quitting, trying to send a "q" just in case that helps)');
debugPrint('(a functional test should never reach this point)');
final LogLine inLog = LogLine('stdin', stamp(), 'q');
logs.add(inLog);
if (streamingLogs) {
inLog.printClearly();
}
process.stdin.write('q');
return -1; // discarded
}).then(
(int i) => i,
onError: (Object error) {
// ignore errors here, they will be reported on the next line
return -1; // discarded
},
));
final int exitCode = await process.exitCode;
if (streamingLogs) {
debugPrint('${stamp()} (process terminated with exit code $exitCode)');
}
timeout?.cancel();
if (nextTransition < transitions.length) {
debugPrint('The subprocess terminated before all the expected transitions had been matched.');
if (logs.any((LogLine line) => line.couldBeCrash)) {
debugPrint('The subprocess may in fact have crashed. Check the stderr logs below.');
}
debugPrint('The transition that we were hoping to see next but that we never saw was:');
debugPrint('${nextTransition.toString().padLeft(5)} NOW WAITING FOR> ${transitions[nextTransition]}');
if (!streamingLogs) {
describeStatus();
debugPrint('(process terminated with exit code $exitCode)');
}
throw TestFailure('Missed some expected transitions.');
}
if (streamingLogs) {
debugPrint('${stamp()} (completed execution successfully!)');
}
return ProcessTestResult(exitCode, logs);
}
const int progressMessageWidth = 64;
import 'transition_test_utils.dart';
void main() {
testWithoutContext('flutter run writes and clears pidfile appropriately', () async {

View File

@@ -0,0 +1,338 @@
// Copyright 2014 The Flutter Authors. All rights reserved.
// 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';
import 'package:meta/meta.dart';
import 'package:process/process.dart';
import '../src/common.dart';
import 'test_utils.dart' show fileSystem;
const ProcessManager processManager = LocalProcessManager();
final String flutterRoot = getFlutterRoot();
final String flutterBin = fileSystem.path.join(flutterRoot, 'bin', 'flutter');
void debugPrint(String message) {
// This is called to intentionally print debugging output when a test is
// either taking too long or has failed.
// ignore: avoid_print
print(message);
}
typedef LineHandler = String? Function(String line);
abstract class Transition {
const Transition({this.handler, this.logging});
/// Callback that is invoked when the transition matches.
///
/// This should not throw, even if the test is failing. (For example, don't use "expect"
/// in these callbacks.) Throwing here would prevent the [runFlutter] function from running
/// to completion, which would leave zombie `flutter` processes around.
final LineHandler? handler;
/// Whether to enable or disable logging when this transition is matched.
///
/// The default value, null, leaves the logging state unaffected.
final bool? logging;
bool matches(String line);
@protected
bool lineMatchesPattern(String line, Pattern pattern) {
if (pattern is String) {
return line == pattern;
}
return line.contains(pattern);
}
@protected
String describe(Pattern pattern) {
if (pattern is String) {
return '"$pattern"';
}
if (pattern is RegExp) {
return '/${pattern.pattern}/';
}
return '$pattern';
}
}
class Barrier extends Transition {
const Barrier(this.pattern, {super.handler, super.logging});
final Pattern pattern;
@override
bool matches(String line) => lineMatchesPattern(line, pattern);
@override
String toString() => describe(pattern);
}
class Multiple extends Transition {
Multiple(
List<Pattern> patterns, {
super.handler,
super.logging,
}) : _originalPatterns = patterns,
patterns = patterns.toList();
final List<Pattern> _originalPatterns;
final List<Pattern> patterns;
@override
bool matches(String line) {
for (int index = 0; index < patterns.length; index += 1) {
if (lineMatchesPattern(line, patterns[index])) {
patterns.removeAt(index);
break;
}
}
return patterns.isEmpty;
}
@override
String toString() {
if (patterns.isEmpty) {
return '${_originalPatterns.map(describe).join(', ')} (all matched)';
}
return '${_originalPatterns.map(describe).join(', ')} (matched ${_originalPatterns.length - patterns.length} so far)';
}
}
class LogLine {
const LogLine(this.channel, this.stamp, this.message);
final String channel;
final String stamp;
final String message;
bool get couldBeCrash =>
message.contains('Oops; flutter has exited unexpectedly:');
@override
String toString() => '$stamp $channel: $message';
void printClearly() {
debugPrint('$stamp $channel: ${clarify(message)}');
}
static String clarify(String line) {
return line.runes.map<String>((int rune) {
if (rune >= 0x20 && rune <= 0x7F) {
return String.fromCharCode(rune);
}
switch (rune) {
case 0x00:
return '<NUL>';
case 0x07:
return '<BEL>';
case 0x08:
return '<TAB>';
case 0x09:
return '<BS>';
case 0x0A:
return '<LF>';
case 0x0D:
return '<CR>';
}
return '<${rune.toRadixString(16).padLeft(rune <= 0xFF ? 2 : rune <= 0xFFFF ? 4 : 5, '0')}>';
}).join();
}
}
class ProcessTestResult {
const ProcessTestResult(this.exitCode, this.logs);
final int exitCode;
final List<LogLine> logs;
List<String> get stdout {
return logs
.where((LogLine log) => log.channel == 'stdout')
.map<String>((LogLine log) => log.message)
.toList();
}
List<String> get stderr {
return logs
.where((LogLine log) => log.channel == 'stderr')
.map<String>((LogLine log) => log.message)
.toList();
}
@override
String toString() => 'exit code $exitCode\nlogs:\n ${logs.join('\n ')}\n';
}
Future<ProcessTestResult> runFlutter(
List<String> arguments,
String workingDirectory,
List<Transition> transitions, {
bool debug = false,
bool logging = true,
Duration expectedMaxDuration = const Duration(
minutes:
10), // must be less than test timeout of 15 minutes! See ../../dart_test.yaml.
}) async {
final Stopwatch clock = Stopwatch()..start();
final Process process = await processManager.start(
<String>[flutterBin, ...arguments],
workingDirectory: workingDirectory,
);
final List<LogLine> logs = <LogLine>[];
int nextTransition = 0;
void describeStatus() {
if (transitions.isNotEmpty) {
debugPrint('Expected state transitions:');
for (int index = 0; index < transitions.length; index += 1) {
debugPrint('${index.toString().padLeft(5)} '
'${index < nextTransition ? 'ALREADY MATCHED ' : index == nextTransition ? 'NOW WAITING FOR>' : ' '} ${transitions[index]}');
}
}
if (logs.isEmpty) {
debugPrint(
'So far nothing has been logged${debug ? "" : "; use debug:true to print all output"}.');
} else {
debugPrint(
'Log${debug ? "" : " (only contains logged lines; use debug:true to print all output)"}:');
for (final LogLine log in logs) {
log.printClearly();
}
}
}
bool streamingLogs = false;
Timer? timeout;
void processTimeout() {
if (!streamingLogs) {
streamingLogs = true;
if (!debug) {
debugPrint(
'Test is taking a long time (${clock.elapsed.inSeconds} seconds so far).');
}
describeStatus();
debugPrint('(streaming all logs from this point on...)');
} else {
debugPrint('(taking a long time...)');
}
}
String stamp() =>
'[${(clock.elapsed.inMilliseconds / 1000.0).toStringAsFixed(1).padLeft(5)}s]';
void processStdout(String line) {
final LogLine log = LogLine('stdout', stamp(), line);
if (logging) {
logs.add(log);
}
if (streamingLogs) {
log.printClearly();
}
if (nextTransition < transitions.length &&
transitions[nextTransition].matches(line)) {
if (streamingLogs) {
debugPrint('(matched ${transitions[nextTransition]})');
}
if (transitions[nextTransition].logging != null) {
if (!logging && transitions[nextTransition].logging!) {
logs.add(log);
}
logging = transitions[nextTransition].logging!;
if (streamingLogs) {
if (logging) {
debugPrint('(enabled logging)');
} else {
debugPrint('(disabled logging)');
}
}
}
if (transitions[nextTransition].handler != null) {
final String? command = transitions[nextTransition].handler!(line);
if (command != null) {
final LogLine inLog = LogLine('stdin', stamp(), command);
logs.add(inLog);
if (streamingLogs) {
inLog.printClearly();
}
process.stdin.write(command);
}
}
nextTransition += 1;
timeout?.cancel();
timeout = Timer(expectedMaxDuration ~/ 5,
processTimeout); // This is not a failure timeout, just when to start logging verbosely to help debugging.
}
}
void processStderr(String line) {
final LogLine log = LogLine('stdout', stamp(), line);
logs.add(log);
if (streamingLogs) {
log.printClearly();
}
}
if (debug) {
processTimeout();
} else {
timeout = Timer(expectedMaxDuration ~/ 2,
processTimeout); // This is not a failure timeout, just when to start logging verbosely to help debugging.
}
process.stdout
.transform<String>(utf8.decoder)
.transform<String>(const LineSplitter())
.listen(processStdout);
process.stderr
.transform<String>(utf8.decoder)
.transform<String>(const LineSplitter())
.listen(processStderr);
unawaited(process.exitCode.timeout(expectedMaxDuration, onTimeout: () {
// This is a failure timeout, must not be short.
debugPrint(
'${stamp()} (process is not quitting, trying to send a "q" just in case that helps)');
debugPrint('(a functional test should never reach this point)');
final LogLine inLog = LogLine('stdin', stamp(), 'q');
logs.add(inLog);
if (streamingLogs) {
inLog.printClearly();
}
process.stdin.write('q');
return -1; // discarded
}).then(
(int i) => i,
onError: (Object error) {
// ignore errors here, they will be reported on the next line
return -1; // discarded
},
));
final int exitCode = await process.exitCode;
if (streamingLogs) {
debugPrint('${stamp()} (process terminated with exit code $exitCode)');
}
timeout?.cancel();
if (nextTransition < transitions.length) {
debugPrint(
'The subprocess terminated before all the expected transitions had been matched.');
if (logs.any((LogLine line) => line.couldBeCrash)) {
debugPrint(
'The subprocess may in fact have crashed. Check the stderr logs below.');
}
debugPrint(
'The transition that we were hoping to see next but that we never saw was:');
debugPrint(
'${nextTransition.toString().padLeft(5)} NOW WAITING FOR> ${transitions[nextTransition]}');
if (!streamingLogs) {
describeStatus();
debugPrint('(process terminated with exit code $exitCode)');
}
throw TestFailure('Missed some expected transitions.');
}
if (streamingLogs) {
debugPrint('${stamp()} (completed execution successfully!)');
}
return ProcessTestResult(exitCode, logs);
}
const int progressMessageWidth = 64;

View File

@@ -449,6 +449,7 @@ class TestFeatureFlags implements FeatureFlags {
this.areCustomDevicesEnabled = false,
this.isFlutterWebWasmEnabled = false,
this.isCliAnimationEnabled = true,
this.isNativeAssetsEnabled = false,
});
@override
@@ -481,6 +482,9 @@ class TestFeatureFlags implements FeatureFlags {
@override
final bool isCliAnimationEnabled;
@override
final bool isNativeAssetsEnabled;
@override
bool isEnabled(Feature feature) {
switch (feature) {
@@ -502,6 +506,8 @@ class TestFeatureFlags implements FeatureFlags {
return areCustomDevicesEnabled;
case cliAnimation:
return isCliAnimationEnabled;
case nativeAssets:
return isNativeAssetsEnabled;
}
return false;
}