Add files using upload-large-folder tool
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
Files changed (50)
- .gitattributes+1
- NovelForge_Flutter_Development_Report.pdfAdded+3
- flutter/packages/flutter_localizations/README.mdAdded+134
- flutter/packages/flutter_test/analysis_options.yamlAdded+5
- flutter/packages/flutter_test/dart_test.yamlAdded+5
- flutter/packages/flutter_test/flutter_test.imlAdded+14
- flutter/packages/flutter_test/pubspec.lockAdded+191
- flutter/packages/flutter_test/pubspec.yamlAdded+56
- flutter/packages/flutter_tools/README.mdAdded+121
- flutter/packages/flutter_tools/analysis_options.yamlAdded+12
- flutter/packages/flutter_tools/dart_test.yamlAdded+18
- flutter/packages/flutter_tools/flutter_tools.imlAdded+21
- flutter/packages/flutter_tools/pubspec.lockAdded+741
- flutter/packages/flutter_tools/pubspec.yamlAdded+121
- flutter/packages/flutter_tools/test/general.shard/android/android_gradle_builder_test.dartAdded+1937
- flutter/packages/flutter_tools/test/general.shard/android/android_install_test.dartAdded+318
- flutter/packages/flutter_tools/test/general.shard/android/android_project_migration_test.dartAdded+474
- flutter/packages/flutter_tools/test/general.shard/devtools_launcher_test.dartAdded+152
- flutter/packages/flutter_tools/test/general.shard/emulator_test.dartAdded+405
- flutter/packages/flutter_tools/test/general.shard/fake_native_assets_build_runner.dartAdded+97
- flutter/packages/flutter_tools/test/general.shard/fake_process_manager_test.dartAdded+323
- flutter/packages/flutter_tools/test/general.shard/features_test.dartAdded+412
- flutter/packages/flutter_tools/test/general.shard/flutter_manifest_assets_test.dartAdded+163
- flutter/packages/flutter_tools/test/general.shard/flutter_manifest_assets_transformers_test.dartAdded+166
- flutter/packages/flutter_tools/test/general.shard/flutter_manifest_test.dartAdded+1558
- flutter/packages/flutter_tools/test/general.shard/flutter_platform_test.dartAdded+125
- flutter/packages/flutter_tools/test/general.shard/flutter_project_metadata_test.dartAdded+202
- flutter/packages/flutter_tools/test/general.shard/flutter_tester_device_test.dartAdded+300
- flutter/packages/flutter_tools/test/general.shard/flutter_validator_test.dartAdded+647
- flutter/packages/flutter_tools/test/general.shard/generate_localizations_test.dartAdded+2535
- flutter/packages/flutter_tools/test/general.shard/github_template_test.dartAdded+277
- flutter/packages/flutter_tools/test/general.shard/hot_shared.dartAdded+230
- flutter/packages/flutter_tools/test/general.shard/hot_test.dartAdded+977
- flutter/packages/flutter_tools/test/general.shard/html_utils_test.dartAdded+178
- flutter/packages/flutter_tools/test/general.shard/integration_test_device_test.dartAdded+256
- flutter/packages/flutter_tools/test/general.shard/license_collector_test.dartAdded+433
- flutter/packages/flutter_tools/test/general.shard/mdns_discovery_test.dartAdded+1058
- flutter/packages/flutter_tools/test/general.shard/message_parser_test.dartAdded+600
- flutter/packages/flutter_tools/test/general.shard/persistent_tool_state_test.dartAdded+58
- flutter/packages/flutter_tools/test/general.shard/plugin_parsing_test.dartAdded+423
- flutter/packages/flutter_tools/test/general.shard/plugins_test.dartAdded+1954
- flutter/packages/flutter_tools/test/general.shard/preview_device_test.dartAdded+208
- flutter/packages/flutter_tools/test/general.shard/project_file_invalidator_test.dartAdded+198
- flutter/packages/flutter_tools/test/general.shard/project_test.dartAdded+1727
- flutter/packages/flutter_tools/test/general.shard/project_validator_result_test.dartAdded+99
- flutter/packages/flutter_tools/test/general.shard/protocol_discovery_test.dartAdded+417
- flutter/packages/flutter_tools/test/general.shard/pub_dependencies_project_validator_test.dartAdded+77
- flutter/packages/flutter_tools/test/general.shard/resident_devtools_handler_test.dartAdded+501
- flutter/packages/flutter_tools/test/general.shard/resident_runner_helpers.dartAdded+545
- flutter/packages/flutter_tools/test/general.shard/resident_runner_test.dartAdded
3 unmodified lines4563 unmodified linesflutter/bin/cache/** filter=lfs diff=lfs merge=lfs -textnovelforge_enhancement_report.pdf filter=lfs diff=lfs merge=lfs -text001/NovelForge_Flutter_Development_Report.pdf filter=lfs diff=lfs merge=lfs -text3 unmodified lines45673 unmodified linesflutter/bin/cache/** filter=lfs diff=lfs merge=lfs -textnovelforge_enhancement_report.pdf filter=lfs diff=lfs merge=lfs -text001/NovelForge_Flutter_Development_Report.pdf filter=lfs diff=lfs merge=lfs -textNovelForge_Flutter_Development_Report.pdf filter=lfs diff=lfs merge=lfs -text
123version https://git-lfs.github.com/spec/v1oid sha256:ad0f73d3f651173322ce9271dcce70c29edb7da93893eccd5e16d932d129ed63size 512633123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134# Flutter Framework localizations
This package contains the localizations used by the Flutter frameworkitself.
See the [localization README](./lib/src/l10n/README.md) for more detailedinformation about the localizations themselves.
## Adding a new string to localizations
If you (someone contributing to the Flutter framework) want to add a newstring to the `MaterialLocalizations`, `WidgetsLocalizations` or the`CupertinoLocalizations` objects (e.g. because you've added a new widgetand it has a tooltip), follow these steps (these instructions are for`MaterialLocalizations`, but apply equally to `CupertinoLocalizations`and `WidgetsLocalizations`, with appropriate name substitutions):
1. ### For messages without parameters, add new getter ``` String get showMenuTooltip; ``` to the localizations class `MaterialLocalizations`, in [`packages/flutter/lib/src/material/material_localizations.dart`](https://github.com/flutter/flutter/blob/master/packages/flutter/lib/src/material/material_localizations.dart);
### For messages with parameters, add new function ``` String aboutListTileTitle(String applicationName); ``` to the same localization class.
2. Implement a default return value in `DefaultMaterialLocalizations` in the same file as in step 1.
### Messages without parameters: ``` @override String get showMenuTooltip => 'Show menu'; ``` ### Messages with parameters: ``` @override String aboutListTileTitle(String applicationName) => 'About $applicationName'; ``` For messages with parameters, do also add the function to `GlobalMaterialLocalizations` in [`packages/flutter_localizations/lib/src/material_localizations.dart`](https://github.com/flutter/flutter/blob/master/packages/flutter_localizations/lib/src/material_localizations.dart), and add a raw getter as demonstrated below:
``` /// The raw version of [aboutListTileTitle], with `$applicationName` verbatim /// in the string. @protected String get aboutListTileTitleRaw;
@override String aboutListTileTitle(String applicationName) { final String text = aboutListTileTitleRaw; return text.replaceFirst(r'$applicationName', applicationName); } ```
3. Add a test to `test/material/localizations_test.dart` that verifies that this new value is implemented.
4. Update the `flutter_localizations` package. To add a new string to the `flutter_localizations` package, you must first add it to the English translations (`lib/src/l10n/material_en.arb`), including a description.
### Messages without parameters: ``` "showMenuTooltip": "Show menu", "@showMenuTooltip": { "description": "The tooltip for the button that shows a popup menu." }, ```
### Messages with parameters: ``` "aboutListTileTitle": "About $applicationName", "@aboutListTileTitle": { "description": "The default title for the drawer item that shows an about page for the application. The value of $applicationName is the name of the application, like GMail or Chrome.", "parameters": "applicationName" }, ```
Then you need to add new entries for the string to all of the other language locale files by running: ``` dart dev/tools/localization/bin/gen_missing_localizations.dart ``` Which will copy the English strings into the other locales as placeholders until they can be translated.
Finally you need to re-generate lib/src/l10n/localizations.dart by running: ``` dart dev/tools/localization/bin/gen_localizations.dart --overwrite ```
If you got an error when running this command, [this issue](https://github.com/flutter/flutter/issues/104601) might be helpful.
TL;DR: If you got the same type of errors as discussed in the issue, run this instead: ``` dart dev/tools/localization/bin/gen_localizations.dart --overwrite --remove-undefined ```
There is a [localization README](./lib/src/l10n/README.md) file with further information in the `lib/src/l10n/` directory.
5. If you are a Google employee, you should then also follow the instructions at `go/flutter-l10n`. If you're not, don't worry about it.
## Updating an existing string
If you or someone contributing to the Flutter framework wants to modify anexisting string in the MaterialLocalizations objects, follow these steps:
1. Modify the default value of the relevant getter(s) in `DefaultMaterialLocalizations` below.
2. Update the `flutter_localizations` package. Modify the out-of-date English strings in `lib/src/l10n/material_en.arb`.
You also need to re-generate `lib/src/l10n/localizations.dart` by running: ``` dart dev/tools/localization/bin/gen_localizations.dart --overwrite ```
This script may result in your updated getters being created in newer locales and set to the old value of the strings. This is to be expected. Leave them as they were generated, and they will be picked up for translation.
There is a [localization README](./lib/src/l10n/README.md) file with further information in the `lib/src/l10n/` directory.
3. If you are a Google employee, you should then also follow the instructions at `go/flutter-l10n`. If you're not, don't worry about it.12345include: ../analysis_options.yaml
analyzer: exclude: - "test_fixes/**"12345tags: # This tag tells the test framework to not shuffle the test order according to # the --test-randomize-ordering-seed for the suites that have this tag. no-shuffle: allow_test_randomization: false1234567891011121314<?xml version="1.0" encoding="UTF-8"?><module type="WEB_MODULE" version="4"> <component name="NewModuleRootManager" inherit-compiler-output="true"> <exclude-output /> <content url="file://$MODULE_DIR$"> <excludeFolder url="file://$MODULE_DIR$/build" /> </content> <orderEntry type="inheritedJdk" /> <orderEntry type="sourceFolder" forTests="false" /> <orderEntry type="library" name="Dart SDK" level="project" /> <orderEntry type="library" name="Dart Packages" level="project" /> <orderEntry type="library" name="Flutter Plugins" level="project" /> </component></module>123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191# Generated by pub# See https://dart.dev/tools/pub/glossary#lockfilepackages: async: dependency: "direct main" description: name: async sha256: "947bfcf187f74dbc5e146c9eb9c0f10c9f8b30743e341481c1e2ed3ecc18c20c" url: "https://pub.dev" source: hosted version: "2.11.0" boolean_selector: dependency: "direct main" description: name: boolean_selector sha256: "6cfb5af12253eaf2b368f07bacc5a80d1301a071c73360d746b7f2e32d762c66" url: "https://pub.dev" source: hosted version: "2.1.1" characters: dependency: "direct main" description: name: characters sha256: "04a925763edad70e8443c99234dc3328f442e811f1d8fd1a72f1c8ad0f69a605" url: "https://pub.dev" source: hosted version: "1.3.0" clock: dependency: "direct main" description: name: clock sha256: cb6d7f03e1de671e34607e909a7213e31d7752be4fb66a86d29fe1eb14bfb5cf url: "https://pub.dev" source: hosted version: "1.1.1" collection: dependency: "direct main" description: name: collection sha256: ee67cb0715911d28db6bf4af1026078bd6f0128b07a5f66fb2ed94ec6783c09a url: "https://pub.dev" source: hosted version: "1.18.0" fake_async: dependency: "direct main" description: name: fake_async sha256: "511392330127add0b769b75a987850d136345d9227c6b94c96a04cf4a391bf78" url: "https://pub.dev" source: hosted version: "1.3.1" file: dependency: "direct dev" description: name: file sha256: "5fc22d7c25582e38ad9a8515372cd9a93834027aacf1801cf01164dac0ffa08c" url: "https://pub.dev" source: hosted version: "7.0.0" flutter: dependency: "direct main" description: flutter source: sdk version: "0.0.0" leak_tracker: dependency: "direct main" description: name: leak_tracker sha256: "78eb209deea09858f5269f5a5b02be4049535f568c07b275096836f01ea323fa" url: "https://pub.dev" source: hosted version: "10.0.0" leak_tracker_flutter_testing: dependency: "direct main" description: name: leak_tracker_flutter_testing sha256: b46c5e37c19120a8a01918cfaf293547f47269f7cb4b0058f21531c2465d6ef0 url: "https://pub.dev" source: hosted version: "2.0.1" leak_tracker_testing: dependency: "direct main" description: name: leak_tracker_testing sha256: a597f72a664dbd293f3bfc51f9ba69816f84dcd403cdac7066cb3f6003f3ab47 url: "https://pub.dev" source: hosted version: "2.0.1" matcher: dependency: "direct main" description: name: matcher sha256: d2323aa2060500f906aa31a895b4030b6da3ebdcc5619d14ce1aada65cd161cb url: "https://pub.dev" source: hosted version: "0.12.16+1" material_color_utilities: dependency: "direct main" description: name: material_color_utilities sha256: "0e0a020085b65b6083975e499759762399b4475f766c21668c4ecca34ea74e5a" url: "https://pub.dev" source: hosted version: "0.8.0" meta: dependency: "direct main" description: name: meta sha256: d584fa6707a52763a52446f02cc621b077888fb63b93bbcb1143a7be5a0c0c04 url: "https://pub.dev" source: hosted version: "1.11.0" path: dependency: "direct main" description: name: path sha256: "087ce49c3f0dc39180befefc60fdb4acd8f8620e5682fe2476afd0b3688bb4af" url: "https://pub.dev" source: hosted version: "1.9.0" sky_engine: dependency: transitive description: flutter source: sdk version: "0.0.99" source_span: dependency: "direct main" description: name: source_span sha256: "53e943d4206a5e30df338fd4c6e7a077e02254531b138a15aec3bd143c1a8b3c" url: "https://pub.dev" source: hosted version: "1.10.0" stack_trace: dependency: "direct main" description: name: stack_trace sha256: "73713990125a6d93122541237550ee3352a2d84baad52d375a4cad2eb9b7ce0b" url: "https://pub.dev" source: hosted version: "1.11.1" stream_channel: dependency: "direct main" description: name: stream_channel sha256: ba2aa5d8cc609d96bbb2899c28934f9e1af5cddbd60a827822ea467161eb54e7 url: "https://pub.dev" source: hosted version: "2.1.2" string_scanner: dependency: "direct main" description: name: string_scanner sha256: "556692adab6cfa87322a115640c11f13cb77b3f076ddcc5d6ae3c20242bedcde" url: "https://pub.dev" source: hosted version: "1.2.0" term_glyph: dependency: "direct main" description: name: term_glyph sha256: a29248a84fbb7c79282b40b8c72a1209db169a2e0542bce341da992fe1bc7e84 url: "https://pub.dev" source: hosted version: "1.2.1" test_api: dependency: "direct main" description: name: test_api sha256: "5c2f730018264d276c20e4f1503fd1308dfbbae39ec8ee63c5236311ac06954b" url: "https://pub.dev" source: hosted version: "0.6.1" vector_math: dependency: "direct main" description: name: vector_math sha256: "80b3257d1492ce4d091729e3a67a60407d227c27241d6927be0130c98e741803" url: "https://pub.dev" source: hosted version: "2.1.4" vm_service: dependency: "direct main" description: name: vm_service sha256: b3d56ff4341b8f182b96aceb2fa20e3dcb336b9f867bc0eafc0de10f1048e957 url: "https://pub.dev" source: hosted version: "13.0.0"sdks: dart: ">=3.2.0-0 <4.0.0"1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556name: flutter_test
environment: sdk: '>=3.2.0-0 <4.0.0'
dependencies: # To update these, use "flutter update-packages --force-upgrade". # # For detailed instructions, refer to: # https://github.com/flutter/flutter/wiki/Updating-dependencies-in-Flutter
flutter: sdk: flutter
# We depend on very specific internal implementation details of the # 'test' package, which change between versions, so when upgrading # this, make sure the tests are still running correctly. test_api: 0.6.1 matcher: 0.12.16+1
# Used by golden file comparator path: 1.9.0
# Testing utilities for dealing with async calls and time. fake_async: 1.3.1 clock: 1.1.1
# We import stack_trace because the test packages uses it and we # need to be able to unmangle the stack traces that it passed to # stack_trace. See https://github.com/dart-lang/test/issues/590 stack_trace: 1.11.1
# Used by globalToLocal et al. vector_math: 2.1.4
# Used to detect memory leaks with `testWidgets`. leak_tracker_flutter_testing: 2.0.1
async: 2.11.0 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" boolean_selector: 2.1.1 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" characters: 1.3.0 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" collection: 1.18.0 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" leak_tracker: 10.0.0 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" leak_tracker_testing: 2.0.1 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" material_color_utilities: 0.8.0 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" meta: 1.11.0 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" source_span: 1.10.0 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" stream_channel: 2.1.2 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" string_scanner: 1.2.0 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" term_glyph: 1.2.1 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" vm_service: 13.0.0 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade"
dev_dependencies: file: 7.0.0
# PUBSPEC CHECKSUM: 6913123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121# Flutter Tools
This section of the Flutter repository contains the command line developer toolsfor building Flutter applications.
## Working on Flutter Tools
Be sure to follow the instructions on [CONTRIBUTING.md](../../CONTRIBUTING.md)to set up your development environment. Further, familiarize yourself with the[style guide](https://github.com/flutter/flutter/wiki/Style-guide-for-Flutter-repo),which we follow.
### Setting up
First, ensure that the Dart SDK and other necessary artifacts are available byinvoking the Flutter Tools wrapper script. In this directory run:```shell$ flutter --version```
### Running the Tool
To run Flutter Tools from source, in this directory run:```shell$ dart bin/flutter_tools.dart```followed by command-line arguments, as usual.
### Running the analyzer
To run the analyzer on Flutter Tools, in this directory run:```shell$ flutter analyze```
### Writing tests
As with other parts of the Flutter repository, all changes in behavior [must betested](https://github.com/flutter/flutter/wiki/Style-guide-for-Flutter-repo#write-test-find-bug).Tests live under the `test/` subdirectory.
- Hermetic unit tests of tool internals go under `test/general.shard` and must run in significantly less than two seconds.
- Tests of tool commands go under `test/commands.shard`. Hermetic tests go under its `hermetic/` subdirectory. Non-hermetic tests go under its `permeable` sub-directory. Avoid adding tests here and prefer writing either a unit test or a full integration test.
- Integration tests (e.g. tests that run the tool in a subprocess) go under `test/integration.shard`.
- Slow web-related tests go in the `test/web.shard` directory.
In general, the tests for the code in a file called `file.dart` shouldgo in a file called `file_test.dart` in the subdirectory that matchesthe behavior of the test.
The `dart_test.yaml` file configures the timeout for these tests to be15 minutes. The `test.dart` script that is used in CI overrides thisto two seconds for the `test/general.shard` directory, to catchbehaviour that is unexpectedly slow.
Please avoid setting any other timeouts.
#### Using local engine builds in integration tests
The integration tests can be configured to use a specific local enginevariant by setting the `FLUTTER_LOCAL_ENGINE` and `FLUTTER_LOCAL_ENGINE_HOST`environment svariable to the name of the local engines (e.g. `android_debug_unopt`and `host_debug_unopt`). If the local engine build requires a source path, thiscan be provided by setting the `FLUTTER_LOCAL_ENGINE_SRC_PATH` environmentvariable. This second variable is not necessary if the `flutter` and `engine`checkouts are in adjacent directories.
```shellexport FLUTTER_LOCAL_ENGINE=android_debug_unoptexport FLUTTER_LOCAL_ENGINE_HOST=host_debug_unoptflutter test test/integration.shard/some_test_case```
### Running the tests
To run all of the unit tests:
```shell$ flutter test test/general.shard```
The tests in `test/integration.shard` are slower to run than the testsin `test/general.shard`. Depending on your development computer, youmight want to limit concurrency. Generally it is easier to run theseon CI, or to manually verify the behavior you are changing instead ofrunning the test.
The integration tests also require the `FLUTTER_ROOT` environmentvariable to be set. The full invocation to run everything mighttherefore look something like:
```shell$ export FLUTTER_ROOT=~/path/to/flutter-sdk$ flutter test --concurrency 1```
This may take some time (on the order of an hour). The unit testsalone take much less time (on the order of a minute).
You can run the tests in a specific file, e.g.:
```shell$ flutter test test/general.shard/utils_test.dart```
### Forcing snapshot regeneration
To force the Flutter Tools snapshot to be regenerated, delete the followingfiles:```shell$ rm ../../bin/cache/flutter_tools.stamp ../../bin/cache/flutter_tools.snapshot```123456789101112include: ../analysis_options.yaml
linter: rules: avoid_catches_without_on_clauses: true avoid_catching_errors: false # TODO(ianh): we should refactor the tool codebase to avoid relying on this so much library_private_types_in_public_api: false # Tool does not have any public API. no_runtimeType_toString: false # We use runtimeType for debugging in the tool. only_throw_errors: true prefer_relative_imports: true public_member_api_docs: false # Tool does not have any public API. unawaited_futures: true123456789101112131415161718# package:test configuration# https://github.com/dart-lang/test/blob/master/pkgs/test/doc/configuration.md
# Some of our tests take an absurdly long time to run, and on some# hosts they can take even longer due to the host suddenly being# overloaded. For this reason, we set the test timeout to# significantly more than it would be by default, and we never set the# timeouts in the tests themselves.## For the `test/general.shard` specifically, the `dev/bots/test.dart` script# overrides this, reducing it to only 2000ms. Unit tests must run fast!timeout: 15m
tags: # This tag tells the test framework to not shuffle the test order according to # the --test-randomize-ordering-seed for the suites that have this tag. no-shuffle: allow_test_randomization: false123456789101112131415161718192021<?xml version="1.0" encoding="UTF-8"?><module type="WEB_MODULE" version="4"> <component name="NewModuleRootManager" inherit-compiler-output="true"> <exclude-output /> <content url="file://$MODULE_DIR$"> <excludeFolder url="file://$MODULE_DIR$/build" /> <excludeFolder url="file://$MODULE_DIR$/test/data/dart_dependencies_test/asci_casing/build" /> <excludeFolder url="file://$MODULE_DIR$/test/data/dart_dependencies_test/bad_import/build" /> <excludeFolder url="file://$MODULE_DIR$/test/data/dart_dependencies_test/bad_package/build" /> <excludeFolder url="file://$MODULE_DIR$/test/data/dart_dependencies_test/bad_path/build" /> <excludeFolder url="file://$MODULE_DIR$/test/data/dart_dependencies_test/changed_sdk_location/build" /> <excludeFolder url="file://$MODULE_DIR$/test/data/dart_dependencies_test/good/build" /> <excludeFolder url="file://$MODULE_DIR$/test/data/dart_dependencies_test/syntax_error/build" /> </content> <orderEntry type="inheritedJdk" /> <orderEntry type="sourceFolder" forTests="false" /> <orderEntry type="library" name="Dart SDK" level="project" /> <orderEntry type="library" name="Dart Packages" level="project" /> <orderEntry type="library" name="Flutter Plugins" level="project" /> </component></module>123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741# Generated by pub# See https://dart.dev/tools/pub/glossary#lockfilepackages: _fe_analyzer_shared: dependency: "direct main" description: name: _fe_analyzer_shared sha256: "36a321c3d2cbe01cbcb3540a87b8843846e0206df3e691fa7b23e19e78de6d49" url: "https://pub.dev" source: hosted version: "65.0.0" analyzer: dependency: "direct main" description: name: analyzer sha256: dfe03b90ec022450e22513b5e5ca1f01c0c01de9c3fba2f7fd233cb57a6b9a07 url: "https://pub.dev" source: hosted version: "6.3.0" archive: dependency: "direct main" description: name: archive sha256: "80e5141fafcb3361653ce308776cfd7d45e6e9fbb429e14eec571382c0c5fecb" url: "https://pub.dev" source: hosted version: "3.3.2" args: dependency: "direct main" description: name: args sha256: eef6c46b622e0494a36c5a12d10d77fb4e855501a91c1b9ef9339326e58f0596 url: "https://pub.dev" source: hosted version: "2.4.2" async: dependency: "direct main" description: name: async sha256: "947bfcf187f74dbc5e146c9eb9c0f10c9f8b30743e341481c1e2ed3ecc18c20c" url: "https://pub.dev" source: hosted version: "2.11.0" boolean_selector: dependency: "direct main" description: name: boolean_selector sha256: "6cfb5af12253eaf2b368f07bacc5a80d1301a071c73360d746b7f2e32d762c66" url: "https://pub.dev" source: hosted version: "2.1.1" browser_launcher: dependency: "direct main" description: name: browser_launcher sha256: "6ee4c6b1f68a42e769ef6e663c4f56708522f7bce9d2ab6e308a37b612ffa4ec" url: "https://pub.dev" source: hosted version: "1.1.1" built_collection: dependency: "direct main" description: name: built_collection sha256: "376e3dd27b51ea877c28d525560790aee2e6fbb5f20e2f85d5081027d94e2100" url: "https://pub.dev" source: hosted version: "5.1.1" built_value: dependency: "direct main" description: name: built_value sha256: c9aabae0718ec394e5bc3c7272e6bb0dc0b32201a08fe185ec1d8401d3e39309 url: "https://pub.dev" source: hosted version: "8.8.1" checked_yaml: dependency: "direct dev" description: name: checked_yaml sha256: feb6bed21949061731a7a75fc5d2aa727cf160b91af9a3e464c5e3a32e28b5ff url: "https://pub.dev" source: hosted version: "2.0.3" cli_config: dependency: "direct main" description: name: cli_config sha256: "65c7830649e1f8247660f1b783effb460255d6e2c1ac94eb823cf1f84e59b288" url: "https://pub.dev" source: hosted version: "0.1.2" clock: dependency: "direct main" description: name: clock sha256: cb6d7f03e1de671e34607e909a7213e31d7752be4fb66a86d29fe1eb14bfb5cf url: "https://pub.dev" source: hosted version: "1.1.1" collection: dependency: "direct dev" description: name: collection sha256: ee67cb0715911d28db6bf4af1026078bd6f0128b07a5f66fb2ed94ec6783c09a url: "https://pub.dev" source: hosted version: "1.18.0" completion: dependency: "direct main" description: name: completion sha256: f11b7a628e6c42b9edc9b0bc3aa490e2d930397546d2f794e8e1325909d11c60 url: "https://pub.dev" source: hosted version: "1.0.1" convert: dependency: "direct main" description: name: convert sha256: "0f08b14755d163f6e2134cb58222dd25ea2a2ee8a195e53983d57c075324d592" url: "https://pub.dev" source: hosted version: "3.1.1" coverage: dependency: "direct main" description: name: coverage sha256: "8acabb8306b57a409bf4c83522065672ee13179297a6bb0cb9ead73948df7c76" url: "https://pub.dev" source: hosted version: "1.7.2" crypto: dependency: "direct main" description: name: crypto sha256: ff625774173754681d66daaf4a448684fb04b78f902da9cb3d308c19cc5e8bab url: "https://pub.dev" source: hosted version: "3.0.3" csslib: dependency: "direct main" description: name: csslib sha256: "706b5707578e0c1b4b7550f64078f0a0f19dec3f50a178ffae7006b0a9ca58fb" url: "https://pub.dev" source: hosted version: "1.0.0" dap: dependency: "direct main" description: name: dap sha256: "1dc9a11bc60836b151672d3edb6a56a18383ecf122e56eaf5837b32c81641aeb" url: "https://pub.dev" source: hosted version: "1.1.0" dds: dependency: "direct main" description: name: dds sha256: "436bf46d0bf15ec750098fbf4d43e90210873ea615aee14611bfd593ae52ddd8" url: "https://pub.dev" source: hosted version: "3.1.0+1" dds_service_extensions: dependency: "direct main" description: name: dds_service_extensions sha256: c41b86e0c7c496b39d10448f1e4bcd2dbabc29c4cce2bd6d864d57a837ab94b2 url: "https://pub.dev" source: hosted version: "1.6.2" devtools_shared: dependency: "direct main" description: name: devtools_shared sha256: "7f173edabb97ac7c7815ae6b08dc18733504e62651eb0ab4216559e173164df1" url: "https://pub.dev" source: hosted version: "6.0.3" dwds: dependency: "direct main" description: name: dwds sha256: "7ae2b39e73f959e572fa5efabf3606b0c9863a39067a869ac3ea593ace901280" url: "https://pub.dev" source: hosted version: "23.0.0+1" extension_discovery: dependency: "direct main" description: name: extension_discovery sha256: "20735622d0763865f9d94c3ecdce4441174530870760253e9d364fb4f3da8688" url: "https://pub.dev" source: hosted version: "2.0.0" fake_async: dependency: "direct main" description: name: fake_async sha256: "511392330127add0b769b75a987850d136345d9227c6b94c96a04cf4a391bf78" url: "https://pub.dev" source: hosted version: "1.3.1" file: dependency: "direct main" description: name: file sha256: "5fc22d7c25582e38ad9a8515372cd9a93834027aacf1801cf01164dac0ffa08c" url: "https://pub.dev" source: hosted version: "7.0.0" file_testing: dependency: "direct dev" description: name: file_testing sha256: "0aaadb4025bd350403f4308ad6c4cea953278d9407814b8342558e4946840fb5" url: "https://pub.dev" source: hosted version: "3.0.0" fixnum: dependency: "direct main" description: name: fixnum sha256: "25517a4deb0c03aa0f32fd12db525856438902d9c16536311e76cdc57b31d7d1" url: "https://pub.dev" source: hosted version: "1.1.0" flutter_template_images: dependency: "direct main" description: name: flutter_template_images sha256: fd3e55af73c577b9e3f88d4080d3e366cb5c8ef3fbd50b94dfeca56bb0235df6 url: "https://pub.dev" source: hosted version: "4.2.0" frontend_server_client: dependency: "direct main" description: name: frontend_server_client sha256: "408e3ca148b31c20282ad6f37ebfa6f4bdc8fede5b74bc2f08d9d92b55db3612" url: "https://pub.dev" source: hosted version: "3.2.0" glob: dependency: "direct main" description: name: glob sha256: "0e7014b3b7d4dac1ca4d6114f82bf1782ee86745b9b42a92c9289c23d8a0ab63" url: "https://pub.dev" source: hosted version: "2.1.2" graphs: dependency: "direct main" description: name: graphs sha256: aedc5a15e78fc65a6e23bcd927f24c64dd995062bcd1ca6eda65a3cff92a4d19 url: "https://pub.dev" source: hosted version: "2.3.1" html: dependency: "direct main" description: name: html sha256: "3a7812d5bcd2894edf53dfaf8cd640876cf6cef50a8f238745c8b8120ea74d3a" url: "https://pub.dev" source: hosted version: "0.15.4" http: dependency: "direct main" description: name: http sha256: "5895291c13fa8a3bd82e76d5627f69e0d85ca6a30dcac95c4ea19a5d555879c2" url: "https://pub.dev" source: hosted version: "0.13.6" http_multi_server: dependency: "direct main" description: name: http_multi_server sha256: "97486f20f9c2f7be8f514851703d0119c3596d14ea63227af6f7a481ef2b2f8b" url: "https://pub.dev" source: hosted version: "3.2.1" http_parser: dependency: "direct main" description: name: http_parser sha256: "2aa08ce0341cc9b354a498388e30986515406668dbcc4f7c950c3e715496693b" url: "https://pub.dev" source: hosted version: "4.0.2" intl: dependency: "direct main" description: name: intl sha256: "3bc132a9dbce73a7e4a21a17d06e1878839ffbf975568bc875c60537824b0c4d" url: "https://pub.dev" source: hosted version: "0.18.1" io: dependency: "direct main" description: name: io sha256: "2ec25704aba361659e10e3e5f5d672068d332fc8ac516421d483a11e5cbd061e" url: "https://pub.dev" source: hosted version: "1.0.4" js: dependency: "direct main" description: name: js sha256: f2c445dce49627136094980615a031419f7f3eb393237e4ecd97ac15dea343f3 url: "https://pub.dev" source: hosted version: "0.6.7" json_annotation: dependency: "direct dev" description: name: json_annotation sha256: b10a7b2ff83d83c777edba3c6a0f97045ddadd56c944e1a23a3fdf43a1bf4467 url: "https://pub.dev" source: hosted version: "4.8.1" json_rpc_2: dependency: "direct main" description: name: json_rpc_2 sha256: "5e469bffa23899edacb7b22787780068d650b106a21c76db3c49218ab7ca447e" url: "https://pub.dev" source: hosted version: "3.0.2" logging: dependency: "direct main" description: name: logging sha256: "623a88c9594aa774443aa3eb2d41807a48486b5613e67599fb4c41c0ad47c340" url: "https://pub.dev" source: hosted version: "1.2.0" matcher: dependency: "direct main" description: name: matcher sha256: d2323aa2060500f906aa31a895b4030b6da3ebdcc5619d14ce1aada65cd161cb url: "https://pub.dev" source: hosted version: "0.12.16+1" meta: dependency: "direct main" description: name: meta sha256: d584fa6707a52763a52446f02cc621b077888fb63b93bbcb1143a7be5a0c0c04 url: "https://pub.dev" source: hosted version: "1.11.0" mime: dependency: "direct main" description: name: mime sha256: e4ff8e8564c03f255408decd16e7899da1733852a9110a58fe6d1b817684a63e url: "https://pub.dev" source: hosted version: "1.0.4" multicast_dns: dependency: "direct main" description: name: multicast_dns sha256: "316cc47a958d4bd3c67bd238fe8b44fdfb6133bad89cb191c0c3bd3edb14e296" url: "https://pub.dev" source: hosted version: "0.3.2+6" mustache_template: dependency: "direct main" description: name: mustache_template sha256: a46e26f91445bfb0b60519be280555b06792460b27b19e2b19ad5b9740df5d1c url: "https://pub.dev" source: hosted version: "2.0.0" native_assets_builder: dependency: "direct main" description: name: native_assets_builder sha256: "15076b8010eb1ab2a01c1b4bee6abd0174f40f2151406466119b69b398071df4" url: "https://pub.dev" source: hosted version: "0.3.0" native_assets_cli: dependency: "direct main" description: name: native_assets_cli sha256: "3119600043214157fb54f4ef05717a82a7858f35625fe767799c60f3039361c8" url: "https://pub.dev" source: hosted version: "0.3.2" native_stack_traces: dependency: "direct main" description: name: native_stack_traces sha256: c797830b9910d13b0f4e70ddef15cde034214fe3bdb8092c4ea5ffad2f74013f url: "https://pub.dev" source: hosted version: "0.5.6" node_preamble: dependency: "direct dev" description: name: node_preamble sha256: "6e7eac89047ab8a8d26cf16127b5ed26de65209847630400f9aefd7cd5c730db" url: "https://pub.dev" source: hosted version: "2.0.2" package_config: dependency: "direct main" description: name: package_config sha256: "1c5b77ccc91e4823a5af61ee74e6b972db1ef98c2ff5a18d3161c982a55448bd" url: "https://pub.dev" source: hosted version: "2.1.0" path: dependency: "direct main" description: name: path sha256: "087ce49c3f0dc39180befefc60fdb4acd8f8620e5682fe2476afd0b3688bb4af" url: "https://pub.dev" source: hosted version: "1.9.0" petitparser: dependency: "direct main" description: name: petitparser sha256: c15605cd28af66339f8eb6fbe0e541bfe2d1b72d5825efc6598f3e0a31b9ad27 url: "https://pub.dev" source: hosted version: "6.0.2" platform: dependency: "direct main" description: name: platform sha256: "12220bb4b65720483f8fa9450b4332347737cf8213dd2840d8b2c823e47243ec" url: "https://pub.dev" source: hosted version: "3.1.4" pool: dependency: "direct main" description: name: pool sha256: "20fe868b6314b322ea036ba325e6fc0711a22948856475e2c2b6306e8ab39c2a" url: "https://pub.dev" source: hosted version: "1.5.1" process: dependency: "direct main" description: name: process sha256: "21e54fd2faf1b5bdd5102afd25012184a6793927648ea81eea80552ac9405b32" url: "https://pub.dev" source: hosted version: "5.0.2" pub_semver: dependency: "direct main" description: name: pub_semver sha256: "40d3ab1bbd474c4c2328c91e3a7df8c6dd629b79ece4c4bd04bee496a224fb0c" url: "https://pub.dev" source: hosted version: "2.1.4" pubspec_parse: dependency: "direct dev" description: name: pubspec_parse sha256: c63b2876e58e194e4b0828fcb080ad0e06d051cb607a6be51a9e084f47cb9367 url: "https://pub.dev" source: hosted version: "1.2.3" shelf: dependency: "direct main" description: name: shelf sha256: ad29c505aee705f41a4d8963641f91ac4cee3c8fad5947e033390a7bd8180fa4 url: "https://pub.dev" source: hosted version: "1.4.1" shelf_packages_handler: dependency: "direct main" description: name: shelf_packages_handler sha256: "89f967eca29607c933ba9571d838be31d67f53f6e4ee15147d5dc2934fee1b1e" url: "https://pub.dev" source: hosted version: "3.0.2" shelf_proxy: dependency: "direct main" description: name: shelf_proxy sha256: a71d2307f4393211930c590c3d2c00630f6c5a7a77edc1ef6436dfd85a6a7ee3 url: "https://pub.dev" source: hosted version: "1.0.4" shelf_static: dependency: "direct main" description: name: shelf_static sha256: a41d3f53c4adf0f57480578c1d61d90342cd617de7fc8077b1304643c2d85c1e url: "https://pub.dev" source: hosted version: "1.1.2" shelf_web_socket: dependency: "direct main" description: name: shelf_web_socket sha256: "9ca081be41c60190ebcb4766b2486a7d50261db7bd0f5d9615f2d653637a84c1" url: "https://pub.dev" source: hosted version: "1.0.4" source_map_stack_trace: dependency: "direct main" description: name: source_map_stack_trace sha256: "84cf769ad83aa6bb61e0aa5a18e53aea683395f196a6f39c4c881fb90ed4f7ae" url: "https://pub.dev" source: hosted version: "2.1.1" source_maps: dependency: "direct main" description: name: source_maps sha256: "708b3f6b97248e5781f493b765c3337db11c5d2c81c3094f10904bfa8004c703" url: "https://pub.dev" source: hosted version: "0.10.12" source_span: dependency: "direct main" description: name: source_span sha256: "53e943d4206a5e30df338fd4c6e7a077e02254531b138a15aec3bd143c1a8b3c" url: "https://pub.dev" source: hosted version: "1.10.0" sse: dependency: "direct main" description: name: sse sha256: "8168874cdbd42c36ea118ba9f88a656ad97f604f28c976c61cb6d5b281c5319c" url: "https://pub.dev" source: hosted version: "4.1.4" stack_trace: dependency: "direct main" description: name: stack_trace sha256: "73713990125a6d93122541237550ee3352a2d84baad52d375a4cad2eb9b7ce0b" url: "https://pub.dev" source: hosted version: "1.11.1" standard_message_codec: dependency: "direct main" description: name: standard_message_codec sha256: fc7dd712d191b7e33196a0ecf354c4573492bb95995e7166cb6f73b047f9cae0 url: "https://pub.dev" source: hosted version: "0.0.1+4" stream_channel: dependency: "direct main" description: name: stream_channel sha256: ba2aa5d8cc609d96bbb2899c28934f9e1af5cddbd60a827822ea467161eb54e7 url: "https://pub.dev" source: hosted version: "2.1.2" string_scanner: dependency: "direct main" description: name: string_scanner sha256: "556692adab6cfa87322a115640c11f13cb77b3f076ddcc5d6ae3c20242bedcde" url: "https://pub.dev" source: hosted version: "1.2.0" sync_http: dependency: "direct main" description: name: sync_http sha256: "7f0cd72eca000d2e026bcd6f990b81d0ca06022ef4e32fb257b30d3d1014a961" url: "https://pub.dev" source: hosted version: "0.3.1" term_glyph: dependency: "direct main" description: name: term_glyph sha256: a29248a84fbb7c79282b40b8c72a1209db169a2e0542bce341da992fe1bc7e84 url: "https://pub.dev" source: hosted version: "1.2.1" test: dependency: "direct dev" description: name: test sha256: a1f7595805820fcc05e5c52e3a231aedd0b72972cb333e8c738a8b1239448b6f url: "https://pub.dev" source: hosted version: "1.24.9" test_api: dependency: "direct main" description: name: test_api sha256: "5c2f730018264d276c20e4f1503fd1308dfbbae39ec8ee63c5236311ac06954b" url: "https://pub.dev" source: hosted version: "0.6.1" test_core: dependency: "direct main" description: name: test_core sha256: a757b14fc47507060a162cc2530d9a4a2f92f5100a952c7443b5cad5ef5b106a url: "https://pub.dev" source: hosted version: "0.5.9" typed_data: dependency: "direct main" description: name: typed_data sha256: facc8d6582f16042dd49f2463ff1bd6e2c9ef9f3d5da3d9b087e244a7b564b3c url: "https://pub.dev" source: hosted version: "1.3.2" unified_analytics: dependency: "direct main" description: name: unified_analytics sha256: "18204ce613142fc252b36f919d0f6dae4124df221812fe0b1bfb66251df280c1" url: "https://pub.dev" source: hosted version: "5.8.0+1" usage: dependency: "direct main" description: name: usage sha256: "0bdbde65a6e710343d02a56552eeaefd20b735e04bfb6b3ee025b6b22e8d0e15" url: "https://pub.dev" source: hosted version: "4.1.1" uuid: dependency: "direct main" description: name: uuid sha256: "648e103079f7c64a36dc7d39369cabb358d377078a051d6ae2ad3aa539519313" url: "https://pub.dev" source: hosted version: "3.0.7" vm_service: dependency: "direct main" description: name: vm_service sha256: b3d56ff4341b8f182b96aceb2fa20e3dcb336b9f867bc0eafc0de10f1048e957 url: "https://pub.dev" source: hosted version: "13.0.0" vm_service_interface: dependency: "direct main" description: name: vm_service_interface sha256: a1897b14842d58ca75de00ccaec6d0bdc9806b4c3560d781ef61dc6851a66f76 url: "https://pub.dev" source: hosted version: "1.0.0" vm_snapshot_analysis: dependency: "direct main" description: name: vm_snapshot_analysis sha256: "5a79b9fbb6be2555090f55b03b23907e75d44c3fd7bdd88da09848aa5a1914c8" url: "https://pub.dev" source: hosted version: "0.7.6" watcher: dependency: "direct main" description: name: watcher sha256: "3d2ad6751b3c16cf07c7fca317a1413b3f26530319181b37e3b9039b84fc01d8" url: "https://pub.dev" source: hosted version: "1.1.0" web: dependency: "direct main" description: name: web sha256: edc8a9573dd8c5a83a183dae1af2b6fd4131377404706ca4e5420474784906fa url: "https://pub.dev" source: hosted version: "0.4.0" web_socket_channel: dependency: "direct main" description: name: web_socket_channel sha256: "045ec2137c27bf1a32e6ffa0e734d532a6677bf9016a0d1a406c54e499ff945b" url: "https://pub.dev" source: hosted version: "2.4.1" webdriver: dependency: "direct main" description: name: webdriver sha256: "003d7da9519e1e5f329422b36c4dcdf18d7d2978d1ba099ea4e45ba490ed845e" url: "https://pub.dev" source: hosted version: "3.0.3" webkit_inspection_protocol: dependency: "direct main" description: name: webkit_inspection_protocol sha256: "87d3f2333bb240704cd3f1c6b5b7acd8a10e7f0bc28c28dcf14e782014f4a572" url: "https://pub.dev" source: hosted version: "1.2.1" xml: dependency: "direct main" description: name: xml sha256: b015a8ad1c488f66851d762d3090a21c600e479dc75e68328c52774040cf9226 url: "https://pub.dev" source: hosted version: "6.5.0" yaml: dependency: "direct main" description: name: yaml sha256: "75769501ea3489fca56601ff33454fe45507ea3bfb014161abc3b43ae25989d5" url: "https://pub.dev" source: hosted version: "3.1.2" yaml_edit: dependency: "direct main" description: name: yaml_edit sha256: "1579d4a0340a83cf9e4d580ea51a16329c916973bffd5bd4b45e911b25d46bfd" url: "https://pub.dev" source: hosted version: "2.1.1"sdks: dart: ">=3.3.0-91.0.dev <4.0.0"123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121name: flutter_toolsdescription: Tools for building Flutter applicationshomepage: https://flutter.dev
environment: sdk: '>=3.2.0-0 <4.0.0'
dependencies: # To update these, use "flutter update-packages --force-upgrade". # # For detailed instructions, refer to: # https://github.com/flutter/flutter/wiki/Updating-dependencies-in-Flutter archive: 3.3.2 args: 2.4.2 browser_launcher: 1.1.1 dds: 3.1.0+1 dwds: 23.0.0+1 completion: 1.0.1 coverage: 1.7.2 crypto: 3.0.3 file: 7.0.0 flutter_template_images: 4.2.0 html: 0.15.4 http: 0.13.6 intl: 0.18.1 meta: 1.11.0 multicast_dns: 0.3.2+6 mustache_template: 2.0.0 package_config: 2.1.0 process: 5.0.2 fake_async: 1.3.1 stack_trace: 1.11.1 usage: 4.1.1 webdriver: 3.0.3 webkit_inspection_protocol: 1.2.1 xml: 6.5.0 yaml: 3.1.2 native_stack_traces: 0.5.6 shelf: 1.4.1 vm_snapshot_analysis: 0.7.6 uuid: 3.0.7 web_socket_channel: 2.4.1 stream_channel: 2.1.2 shelf_web_socket: 1.0.4 shelf_static: 1.1.2 pub_semver: 2.1.4 pool: 1.5.1 path: 1.9.0 mime: 1.0.4 logging: 1.2.0 http_multi_server: 3.2.1 convert: 3.1.1 async: 2.11.0 unified_analytics: 5.8.0+1
cli_config: 0.1.2 graphs: 2.3.1 native_assets_builder: 0.3.0 native_assets_cli: 0.3.2
# We depend on very specific internal implementation details of the # 'test' package, which change between versions, so when upgrading # this, make sure the tests are still running correctly. test_api: 0.6.1 test_core: 0.5.9
vm_service: 13.0.0
standard_message_codec: 0.0.1+4
_fe_analyzer_shared: 65.0.0 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" analyzer: 6.3.0 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" boolean_selector: 2.1.1 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" built_collection: 5.1.1 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" built_value: 8.8.1 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" clock: 1.1.1 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" csslib: 1.0.0 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" dap: 1.1.0 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" dds_service_extensions: 1.6.2 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" devtools_shared: 6.0.3 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" extension_discovery: 2.0.0 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" fixnum: 1.1.0 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" frontend_server_client: 3.2.0 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" glob: 2.1.2 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" http_parser: 4.0.2 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" io: 1.0.4 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" js: 0.6.7 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" json_rpc_2: 3.0.2 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" matcher: 0.12.16+1 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" petitparser: 6.0.2 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" platform: 3.1.4 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" shelf_packages_handler: 3.0.2 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" shelf_proxy: 1.0.4 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" source_map_stack_trace: 2.1.1 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" source_maps: 0.10.12 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" source_span: 1.10.0 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" sse: 4.1.4 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" string_scanner: 1.2.0 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" sync_http: 0.3.1 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" term_glyph: 1.2.1 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" typed_data: 1.3.2 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" vm_service_interface: 1.0.0 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" watcher: 1.1.0 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" web: 0.4.0 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" yaml_edit: 2.1.1 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade"
dev_dependencies: collection: 1.18.0 file_testing: 3.0.0 pubspec_parse: 1.2.3
checked_yaml: 2.0.3 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" json_annotation: 4.8.1 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" node_preamble: 2.0.2 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" test: 1.24.9 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade"
dartdoc: # Exclude this package from the hosted API docs. nodoc: true
# PUBSPEC CHECKSUM: a81b12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937// 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:archive/archive.dart';import 'package:file/memory.dart';import 'package:file_testing/file_testing.dart';import 'package:flutter_tools/src/android/android_sdk.dart';import 'package:flutter_tools/src/android/android_studio.dart';import 'package:flutter_tools/src/android/application_package.dart';import 'package:flutter_tools/src/android/gradle.dart';import 'package:flutter_tools/src/android/gradle_errors.dart';import 'package:flutter_tools/src/android/gradle_utils.dart';import 'package:flutter_tools/src/artifacts.dart';import 'package:flutter_tools/src/base/file_system.dart';import 'package:flutter_tools/src/base/io.dart';import 'package:flutter_tools/src/base/logger.dart';import 'package:flutter_tools/src/base/platform.dart';import 'package:flutter_tools/src/base/process.dart';import 'package:flutter_tools/src/base/user_messages.dart';import 'package:flutter_tools/src/build_info.dart';import 'package:flutter_tools/src/cache.dart';import 'package:flutter_tools/src/project.dart';import 'package:flutter_tools/src/reporting/reporting.dart';import 'package:test/fake.dart';import 'package:unified_analytics/unified_analytics.dart';
import '../../src/common.dart';import '../../src/context.dart';import '../../src/fake_process_manager.dart';import '../../src/fakes.dart';
void main() { group('gradle build', () { late BufferLogger logger; late TestUsage testUsage; late FakeAnalytics fakeAnalytics; late FileSystem fileSystem; late FakeProcessManager processManager;
setUp(() { processManager = FakeProcessManager.empty(); logger = BufferLogger.test(); testUsage = TestUsage(); fileSystem = MemoryFileSystem.test(); Cache.flutterRoot = '';
fakeAnalytics = getInitializedFakeAnalyticsInstance( fs: fileSystem, fakeFlutterVersion: FakeFlutterVersion(), ); });
testUsingContext('Can immediately tool exit on recognized exit code/stderr', () async { final AndroidGradleBuilder builder = AndroidGradleBuilder( java: FakeJava(), logger: logger, processManager: processManager, fileSystem: fileSystem, artifacts: Artifacts.test(), usage: testUsage, analytics: fakeAnalytics, gradleUtils: FakeGradleUtils(), platform: FakePlatform(), androidStudio: FakeAndroidStudio(), ); processManager.addCommand(const FakeCommand( command: <String>[ 'gradlew', '-q', '-Ptarget-platform=android-arm,android-arm64,android-x64', '-Ptarget=lib/main.dart', '-Pbase-application-name=io.flutter.app.FlutterApplication', '-Pdart-obfuscation=false', '-Ptrack-widget-creation=false', '-Ptree-shake-icons=false', 'assembleRelease', ], exitCode: 1, stderr: '\nSome gradle message\n', ));
fileSystem.directory('android') .childFile('build.gradle') .createSync(recursive: true);
fileSystem.directory('android') .childFile('gradle.properties') .createSync(recursive: true);
fileSystem.directory('android') .childDirectory('app') .childFile('build.gradle') ..createSync(recursive: true) ..writeAsStringSync('apply from: irrelevant/flutter.gradle');
bool handlerCalled = false; await expectLater(() async { await builder.buildGradleApp( project: FlutterProject.fromDirectoryTest(fileSystem.currentDirectory), androidBuildInfo: const AndroidBuildInfo( BuildInfo( BuildMode.release, null, treeShakeIcons: false, ), ), target: 'lib/main.dart', isBuildingBundle: false, configOnly: false, localGradleErrors: <GradleHandledError>[ GradleHandledError( test: (String line) { return line.contains('Some gradle message'); }, handler: ({ String? line, FlutterProject? project, bool? usesAndroidX, bool? multidexEnabled }) async { handlerCalled = true; return GradleBuildStatus.exit; }, eventLabel: 'random-event-label', ), ], ); }, throwsToolExit( message: 'Gradle task assembleRelease failed with exit code 1' ));
expect(handlerCalled, isTrue);
expect(testUsage.events, contains( const TestUsageEvent( 'build', 'gradle', label: 'gradle-random-event-label-failure', parameters: CustomDimensions(), ), )); expect(testUsage.events, hasLength(2));
expect( fakeAnalytics.sentEvents, containsAll(<Event>[ Event.flutterBuildInfo(label: 'app-not-using-android-x', buildType: 'gradle'), Event.flutterBuildInfo(label: 'gradle-random-event-label-failure', buildType: 'gradle'), ]), );
expect( analyticsTimingEventExists( sentEvents: fakeAnalytics.sentEvents, workflow: 'build', variableName: 'gradle', ), true, );
}, overrides: <Type, Generator>{ AndroidStudio: () => FakeAndroidStudio(), });
testUsingContext('Verbose mode for APKs includes Gradle stacktrace and sets debug log level', () async { final AndroidGradleBuilder builder = AndroidGradleBuilder( java: FakeJava(), logger: BufferLogger.test(verbose: true), processManager: processManager, fileSystem: fileSystem, artifacts: Artifacts.test(), usage: testUsage, analytics: fakeAnalytics, gradleUtils: FakeGradleUtils(), platform: FakePlatform(), androidStudio: FakeAndroidStudio(), ); processManager.addCommand(const FakeCommand( command: <String>[ 'gradlew', '--full-stacktrace', '--info', '-Pverbose=true', '-Ptarget-platform=android-arm,android-arm64,android-x64', '-Ptarget=lib/main.dart', '-Pbase-application-name=io.flutter.app.FlutterApplication', '-Pdart-obfuscation=false', '-Ptrack-widget-creation=false', '-Ptree-shake-icons=false', 'assembleRelease', ], ));
fileSystem.directory('android') .childFile('build.gradle') .createSync(recursive: true);
fileSystem.directory('android') .childFile('gradle.properties') .createSync(recursive: true);
fileSystem.directory('android') .childDirectory('app') .childFile('build.gradle') ..createSync(recursive: true) ..writeAsStringSync('apply from: irrelevant/flutter.gradle');
fileSystem.directory('build') .childDirectory('app') .childDirectory('outputs') .childDirectory('flutter-apk') .childFile('app-release.apk') .createSync(recursive: true);
await builder.buildGradleApp( project: FlutterProject.fromDirectoryTest(fileSystem.currentDirectory), androidBuildInfo: const AndroidBuildInfo( BuildInfo( BuildMode.release, null, treeShakeIcons: false, ), ), target: 'lib/main.dart', isBuildingBundle: false, configOnly: false, localGradleErrors: <GradleHandledError>[], ); expect(processManager, hasNoRemainingExpectations); }, overrides: <Type, Generator>{ AndroidStudio: () => FakeAndroidStudio(), });
testUsingContext('Can retry build on recognized exit code/stderr', () async { final AndroidGradleBuilder builder = AndroidGradleBuilder( java: FakeJava(), logger: logger, processManager: processManager, fileSystem: fileSystem, artifacts: Artifacts.test(), usage: testUsage, analytics: fakeAnalytics, gradleUtils: FakeGradleUtils(), platform: FakePlatform(), androidStudio: FakeAndroidStudio(), );
const FakeCommand fakeCmd = FakeCommand( command: <String>[ 'gradlew', '-q', '-Ptarget-platform=android-arm,android-arm64,android-x64', '-Ptarget=lib/main.dart', '-Pbase-application-name=io.flutter.app.FlutterApplication', '-Pdart-obfuscation=false', '-Ptrack-widget-creation=false', '-Ptree-shake-icons=false', 'assembleRelease', ], exitCode: 1, stderr: '\nSome gradle message\n', );
processManager.addCommand(fakeCmd);
const int maxRetries = 2; for (int i = 0; i < maxRetries; i++) { processManager.addCommand(fakeCmd); }
fileSystem.directory('android') .childFile('build.gradle') .createSync(recursive: true);
fileSystem.directory('android') .childFile('gradle.properties') .createSync(recursive: true);
fileSystem.directory('android') .childDirectory('app') .childFile('build.gradle') ..createSync(recursive: true) ..writeAsStringSync('apply from: irrelevant/flutter.gradle');
int testFnCalled = 0; await expectLater(() async { await builder.buildGradleApp( maxRetries: maxRetries, project: FlutterProject.fromDirectoryTest(fileSystem.currentDirectory), androidBuildInfo: const AndroidBuildInfo( BuildInfo( BuildMode.release, null, treeShakeIcons: false, ), ), target: 'lib/main.dart', isBuildingBundle: false, configOnly: false, localGradleErrors: <GradleHandledError>[ GradleHandledError( test: (String line) { if (line.contains('Some gradle message')) { testFnCalled++; return true; } return false; }, handler: ({ String? line, FlutterProject? project, bool? usesAndroidX, bool? multidexEnabled }) async { return GradleBuildStatus.retry; }, eventLabel: 'random-event-label', ), ], ); }, throwsToolExit( message: 'Gradle task assembleRelease failed with exit code 1' ));
expect(logger.statusText, contains('Retrying Gradle Build: #1, wait time: 100ms')); expect(logger.statusText, contains('Retrying Gradle Build: #2, wait time: 200ms'));
expect(testFnCalled, equals(maxRetries + 1)); expect(testUsage.events, contains( const TestUsageEvent( 'build', 'gradle', label: 'gradle-random-event-label-failure', parameters: CustomDimensions(), ), )); expect(testUsage.events, hasLength(4));
expect(fakeAnalytics.sentEvents, hasLength(7)); expect(fakeAnalytics.sentEvents, contains( Event.flutterBuildInfo( label: 'gradle-random-event-label-failure', buildType: 'gradle', ), )); }, overrides: <Type, Generator>{ AndroidStudio: () => FakeAndroidStudio(), });
testUsingContext('Converts recognized ProcessExceptions into tools exits', () async { final AndroidGradleBuilder builder = AndroidGradleBuilder( java: FakeJava(), logger: logger, processManager: processManager, fileSystem: fileSystem, artifacts: Artifacts.test(), usage: testUsage, analytics: fakeAnalytics, gradleUtils: FakeGradleUtils(), platform: FakePlatform(), androidStudio: FakeAndroidStudio(), ); processManager.addCommand(const FakeCommand( command: <String>[ 'gradlew', '-q', '-Ptarget-platform=android-arm,android-arm64,android-x64', '-Ptarget=lib/main.dart', '-Pbase-application-name=io.flutter.app.FlutterApplication', '-Pdart-obfuscation=false', '-Ptrack-widget-creation=false', '-Ptree-shake-icons=false', 'assembleRelease', ], exitCode: 1, stderr: '\nSome gradle message\n', ));
fileSystem.directory('android') .childFile('build.gradle') .createSync(recursive: true);
fileSystem.directory('android') .childFile('gradle.properties') .createSync(recursive: true);
fileSystem.directory('android') .childDirectory('app') .childFile('build.gradle') ..createSync(recursive: true) ..writeAsStringSync('apply from: irrelevant/flutter.gradle');
bool handlerCalled = false; await expectLater(() async { await builder.buildGradleApp( project: FlutterProject.fromDirectoryTest(fileSystem.currentDirectory), androidBuildInfo: const AndroidBuildInfo( BuildInfo( BuildMode.release, null, treeShakeIcons: false, ), ), target: 'lib/main.dart', isBuildingBundle: false, configOnly: false, localGradleErrors: <GradleHandledError>[ GradleHandledError( test: (String line) { return line.contains('Some gradle message'); }, handler: ({ String? line, FlutterProject? project, bool? usesAndroidX, bool? multidexEnabled }) async { handlerCalled = true; return GradleBuildStatus.exit; }, eventLabel: 'random-event-label', ), ], ); }, throwsToolExit( message: 'Gradle task assembleRelease failed with exit code 1' ));
expect(handlerCalled, isTrue);
expect(testUsage.events, contains( const TestUsageEvent( 'build', 'gradle', label: 'gradle-random-event-label-failure', parameters: CustomDimensions(), ), )); expect(testUsage.events, hasLength(2));
expect(fakeAnalytics.sentEvents, hasLength(3)); expect(fakeAnalytics.sentEvents, contains( Event.flutterBuildInfo( label: 'gradle-random-event-label-failure', buildType: 'gradle', ), ));
}, overrides: <Type, Generator>{ AndroidStudio: () => FakeAndroidStudio(), });
testUsingContext('rethrows unrecognized ProcessException', () async { final AndroidGradleBuilder builder = AndroidGradleBuilder( java: FakeJava(), logger: logger, processManager: processManager, fileSystem: fileSystem, artifacts: Artifacts.test(), usage: testUsage, analytics: fakeAnalytics, gradleUtils: FakeGradleUtils(), platform: FakePlatform(), androidStudio: FakeAndroidStudio(), ); processManager.addCommand(FakeCommand( command: const <String>[ 'gradlew', '-q', '-Ptarget-platform=android-arm,android-arm64,android-x64', '-Ptarget=lib/main.dart', '-Pbase-application-name=io.flutter.app.FlutterApplication', '-Pdart-obfuscation=false', '-Ptrack-widget-creation=false', '-Ptree-shake-icons=false', 'assembleRelease', ], exitCode: 1, onRun: () { throw const ProcessException('', <String>[], 'Unrecognized'); } ));
fileSystem.directory('android') .childFile('build.gradle') .createSync(recursive: true);
fileSystem.directory('android') .childFile('gradle.properties') .createSync(recursive: true);
fileSystem.directory('android') .childDirectory('app') .childFile('build.gradle') ..createSync(recursive: true) ..writeAsStringSync('apply from: irrelevant/flutter.gradle');
await expectLater(() async { await builder.buildGradleApp( project: FlutterProject.fromDirectoryTest(fileSystem.currentDirectory), androidBuildInfo: const AndroidBuildInfo( BuildInfo( BuildMode.release, null, treeShakeIcons: false, ), ), target: 'lib/main.dart', isBuildingBundle: false, configOnly: false, localGradleErrors: const <GradleHandledError>[], ); }, throwsProcessException()); expect(processManager, hasNoRemainingExpectations); }, overrides: <Type, Generator>{ AndroidStudio: () => FakeAndroidStudio(), });
testUsingContext('logs success event after a successful retry', () async { final AndroidGradleBuilder builder = AndroidGradleBuilder( java: FakeJava(), logger: logger, processManager: processManager, fileSystem: fileSystem, artifacts: Artifacts.test(), usage: testUsage, analytics: fakeAnalytics, gradleUtils: FakeGradleUtils(), platform: FakePlatform(), androidStudio: FakeAndroidStudio(), ); processManager.addCommand(const FakeCommand( command: <String>[ 'gradlew', '-q', '-Ptarget-platform=android-arm,android-arm64,android-x64', '-Ptarget=lib/main.dart', '-Pbase-application-name=io.flutter.app.FlutterApplication', '-Pdart-obfuscation=false', '-Ptrack-widget-creation=false', '-Ptree-shake-icons=false', 'assembleRelease', ], exitCode: 1, stderr: '\nnSome gradle message\n', )); processManager.addCommand(const FakeCommand( command: <String>[ 'gradlew', '-q', '-Ptarget-platform=android-arm,android-arm64,android-x64', '-Ptarget=lib/main.dart', '-Pbase-application-name=io.flutter.app.FlutterApplication', '-Pdart-obfuscation=false', '-Ptrack-widget-creation=false', '-Ptree-shake-icons=false', 'assembleRelease', ], ));
fileSystem.directory('android') .childFile('build.gradle') .createSync(recursive: true);
fileSystem.directory('android') .childFile('gradle.properties') .createSync(recursive: true);
fileSystem.directory('android') .childDirectory('app') .childFile('build.gradle') ..createSync(recursive: true) ..writeAsStringSync('apply from: irrelevant/flutter.gradle');
fileSystem.directory('build') .childDirectory('app') .childDirectory('outputs') .childDirectory('flutter-apk') .childFile('app-release.apk') .createSync(recursive: true);
await builder.buildGradleApp( project: FlutterProject.fromDirectoryTest(fileSystem.currentDirectory), androidBuildInfo: const AndroidBuildInfo( BuildInfo( BuildMode.release, null, treeShakeIcons: false, ), ), target: 'lib/main.dart', isBuildingBundle: false, configOnly: false, localGradleErrors: <GradleHandledError>[ GradleHandledError( test: (String line) { return line.contains('Some gradle message'); }, handler: ({ String? line, FlutterProject? project, bool? usesAndroidX, bool? multidexEnabled }) async { return GradleBuildStatus.retry; }, eventLabel: 'random-event-label', ), ], ); expect(testUsage.events, contains( const TestUsageEvent( 'build', 'gradle', label: 'gradle-random-event-label-success', parameters: CustomDimensions(), ), )); expect(processManager, hasNoRemainingExpectations); }, overrides: <Type, Generator>{ AndroidStudio: () => FakeAndroidStudio(), });
testUsingContext('performs code size analysis and sends analytics', () async { final AndroidGradleBuilder builder = AndroidGradleBuilder( java: FakeJava(), logger: logger, processManager: processManager, fileSystem: fileSystem, artifacts: Artifacts.test(), usage: testUsage, analytics: fakeAnalytics, gradleUtils: FakeGradleUtils(), platform: FakePlatform( environment: <String, String>{ 'HOME': '/home', }, ), androidStudio: FakeAndroidStudio(), ); processManager.addCommand(const FakeCommand( command: <String>[ 'gradlew', '-q', '-Ptarget-platform=android-arm64', '-Ptarget=lib/main.dart', '-Pbase-application-name=io.flutter.app.FlutterApplication', '-Pdart-obfuscation=false', '-Ptrack-widget-creation=false', '-Ptree-shake-icons=false', '-Pcode-size-directory=foo', 'assembleRelease', ], ));
fileSystem.directory('android') .childFile('build.gradle') .createSync(recursive: true);
fileSystem.directory('android') .childFile('gradle.properties') .createSync(recursive: true);
fileSystem.directory('android') .childDirectory('app') .childFile('build.gradle') ..createSync(recursive: true) ..writeAsStringSync('apply from: irrelevant/flutter.gradle');
final Archive archive = Archive() ..addFile(ArchiveFile('AndroidManifest.xml', 100, List<int>.filled(100, 0))) ..addFile(ArchiveFile('META-INF/CERT.RSA', 10, List<int>.filled(10, 0))) ..addFile(ArchiveFile('META-INF/CERT.SF', 10, List<int>.filled(10, 0))) ..addFile(ArchiveFile('lib/arm64-v8a/libapp.so', 50, List<int>.filled(50, 0))) ..addFile(ArchiveFile('lib/arm64-v8a/libflutter.so', 50, List<int>.filled(50, 0)));
fileSystem.directory('build') .childDirectory('app') .childDirectory('outputs') .childDirectory('flutter-apk') .childFile('app-release.apk') ..createSync(recursive: true) ..writeAsBytesSync(ZipEncoder().encode(archive)!);
fileSystem.file('foo/snapshot.arm64-v8a.json') ..createSync(recursive: true) ..writeAsStringSync(r'''[ { "l": "dart:_internal", "c": "SubListIterable", "n": "[Optimized] skip", "s": 2400 }]'''); fileSystem.file('foo/trace.arm64-v8a.json') ..createSync(recursive: true) ..writeAsStringSync('{}');
await builder.buildGradleApp( project: FlutterProject.fromDirectoryTest(fileSystem.currentDirectory), androidBuildInfo: const AndroidBuildInfo( BuildInfo( BuildMode.release, null, treeShakeIcons: false, codeSizeDirectory: 'foo', ), targetArchs: <AndroidArch>[AndroidArch.arm64_v8a], ), target: 'lib/main.dart', isBuildingBundle: false, configOnly: false, localGradleErrors: <GradleHandledError>[], );
expect(testUsage.events, contains( const TestUsageEvent( 'code-size-analysis', 'apk', ), )); }, overrides: <Type, Generator>{ AndroidStudio: () => FakeAndroidStudio(), });
testUsingContext('indicates that an APK has been built successfully', () async { final AndroidGradleBuilder builder = AndroidGradleBuilder( java: FakeJava(), logger: logger, processManager: processManager, fileSystem: fileSystem, artifacts: Artifacts.test(), usage: testUsage, analytics: fakeAnalytics, gradleUtils: FakeGradleUtils(), platform: FakePlatform(), androidStudio: FakeAndroidStudio(), ); processManager.addCommand(const FakeCommand( command: <String>[ 'gradlew', '-q', '-Ptarget-platform=android-arm,android-arm64,android-x64', '-Ptarget=lib/main.dart', '-Pbase-application-name=io.flutter.app.FlutterApplication', '-Pdart-obfuscation=false', '-Ptrack-widget-creation=false', '-Ptree-shake-icons=false', 'assembleRelease', ], )); fileSystem.directory('android') .childFile('build.gradle') .createSync(recursive: true);
fileSystem.directory('android') .childFile('gradle.properties') .createSync(recursive: true);
fileSystem.directory('android') .childDirectory('app') .childFile('build.gradle') ..createSync(recursive: true) ..writeAsStringSync('apply from: irrelevant/flutter.gradle');
fileSystem.directory('build') .childDirectory('app') .childDirectory('outputs') .childDirectory('flutter-apk') .childFile('app-release.apk') .createSync(recursive: true);
await builder.buildGradleApp( project: FlutterProject.fromDirectoryTest(fileSystem.currentDirectory), androidBuildInfo: const AndroidBuildInfo( BuildInfo( BuildMode.release, null, treeShakeIcons: false, ), ), target: 'lib/main.dart', isBuildingBundle: false, configOnly: false, localGradleErrors: const <GradleHandledError>[], );
expect( logger.statusText, contains('Built build/app/outputs/flutter-apk/app-release.apk (0.0MB)'), ); expect(processManager, hasNoRemainingExpectations); }, overrides: <Type, Generator>{ AndroidStudio: () => FakeAndroidStudio(), });
testUsingContext('Uses namespace attribute if manifest lacks a package attribute', () async { final FlutterProject project = FlutterProject.fromDirectoryTest(fileSystem.currentDirectory); final AndroidSdk sdk = FakeAndroidSdk();
fileSystem.directory(project.android.hostAppGradleRoot) .childFile('build.gradle') .createSync(recursive: true);
fileSystem.directory(project.android.hostAppGradleRoot) .childDirectory('app') .childFile('build.gradle') ..createSync(recursive: true) ..writeAsStringSync('''apply from: irrelevant/flutter.gradle
android { namespace 'com.example.foo'}''');
fileSystem.directory(project.android.hostAppGradleRoot) .childDirectory('app') .childDirectory('src') .childDirectory('main') .childFile('AndroidManifest.xml') ..createSync(recursive: true) ..writeAsStringSync(r'''<manifest xmlns:android="http://schemas.android.com/apk/res/android"> <application android:label="namespacetest" android:name="${applicationName}" android:icon="@mipmap/ic_launcher"> <activity android:name=".MainActivity"> <intent-filter> <action android:name="android.intent.action.MAIN"/> <category android:name="android.intent.category.LAUNCHER"/> </intent-filter> </activity> </application></manifest>''');
final AndroidApk? androidApk = await AndroidApk.fromAndroidProject( project.android, androidSdk: sdk, fileSystem: fileSystem, logger: logger, processManager: processManager, processUtils: ProcessUtils(processManager: processManager, logger: logger), userMessages: UserMessages(), buildInfo: const BuildInfo(BuildMode.debug, null, treeShakeIcons: false), );
expect(androidApk?.id, 'com.example.foo'); });
testUsingContext('can call custom gradle task getBuildOptions and parse the result', () async { final AndroidGradleBuilder builder = AndroidGradleBuilder( java: FakeJava(), logger: logger, processManager: processManager, fileSystem: fileSystem, artifacts: Artifacts.test(), usage: testUsage, analytics: fakeAnalytics, gradleUtils: FakeGradleUtils(), platform: FakePlatform(), androidStudio: FakeAndroidStudio(), ); processManager.addCommand(const FakeCommand( command: <String>[ 'gradlew', '-q', 'printBuildVariants', ], stdout: '''BuildVariant: freeDebugBuildVariant: paidDebugBuildVariant: freeReleaseBuildVariant: paidReleaseBuildVariant: freeProfileBuildVariant: paidProfile ''', )); final List<String> actual = await builder.getBuildVariants( project: FlutterProject.fromDirectoryTest(fileSystem.currentDirectory), ); expect(actual, <String>['freeDebug', 'paidDebug', 'freeRelease', 'paidRelease', 'freeProfile', 'paidProfile']);
expect( analyticsTimingEventExists( sentEvents: fakeAnalytics.sentEvents, workflow: 'print', variableName: 'android build variants', ), true, ); }, overrides: <Type, Generator>{ AndroidStudio: () => FakeAndroidStudio(), Analytics: () => fakeAnalytics, });
testUsingContext('getBuildOptions returns empty list if gradle returns error', () async { final AndroidGradleBuilder builder = AndroidGradleBuilder( java: FakeJava(), logger: logger, processManager: processManager, fileSystem: fileSystem, artifacts: Artifacts.test(), usage: testUsage, analytics: fakeAnalytics, gradleUtils: FakeGradleUtils(), platform: FakePlatform(), androidStudio: FakeAndroidStudio(), ); processManager.addCommand(const FakeCommand( command: <String>[ 'gradlew', '-q', 'printBuildVariants', ], stderr: '''Gradle Crashed ''', exitCode: 1, )); final List<String> actual = await builder.getBuildVariants( project: FlutterProject.fromDirectoryTest(fileSystem.currentDirectory), ); expect(actual, const <String>[]); }, overrides: <Type, Generator>{ AndroidStudio: () => FakeAndroidStudio(), });
testUsingContext('can call custom gradle task outputFreeDebugAppLinkSettings and parse the result', () async { final String expectedOutputPath; expectedOutputPath = fileSystem.path.join('/build/deeplink_data', 'app-link-settings-freeDebug.json'); final AndroidGradleBuilder builder = AndroidGradleBuilder( java: FakeJava(), logger: logger, processManager: processManager, fileSystem: fileSystem, artifacts: Artifacts.test(), usage: testUsage, analytics: fakeAnalytics, gradleUtils: FakeGradleUtils(), platform: FakePlatform(), androidStudio: FakeAndroidStudio(), ); processManager.addCommand(FakeCommand( command: <String>[ 'gradlew', '-q', '-PoutputPath=$expectedOutputPath', 'outputFreeDebugAppLinkSettings', ], )); await builder.outputsAppLinkSettings( 'freeDebug', project: FlutterProject.fromDirectoryTest(fileSystem.currentDirectory), );
expect( analyticsTimingEventExists( sentEvents: fakeAnalytics.sentEvents, workflow: 'outputs', variableName: 'app link settings', ), true, ); }, overrides: <Type, Generator>{ AndroidStudio: () => FakeAndroidStudio(), FileSystem: () => fileSystem, ProcessManager: () => processManager, Analytics: () => fakeAnalytics, });
testUsingContext("doesn't indicate how to consume an AAR when printHowToConsumeAar is false", () async { final AndroidGradleBuilder builder = AndroidGradleBuilder( java: FakeJava(), logger: logger, processManager: processManager, fileSystem: fileSystem, artifacts: Artifacts.test(), usage: testUsage, analytics: fakeAnalytics, gradleUtils: FakeGradleUtils(), platform: FakePlatform(), androidStudio: FakeAndroidStudio(), ); processManager.addCommand(const FakeCommand( command: <String>[ 'gradlew', '-I=/packages/flutter_tools/gradle/aar_init_script.gradle', '-Pflutter-root=/', '-Poutput-dir=build/', '-Pis-plugin=false', '-PbuildNumber=1.0', '-q', '-Pdart-obfuscation=false', '-Ptrack-widget-creation=false', '-Ptree-shake-icons=false', '-Ptarget-platform=android-arm,android-arm64,android-x64', 'assembleAarRelease', ], ));
final File manifestFile = fileSystem.file('pubspec.yaml'); manifestFile.createSync(recursive: true); manifestFile.writeAsStringSync(''' flutter: module: androidPackage: com.example.test ''' );
fileSystem.file('.android/gradlew').createSync(recursive: true); fileSystem.file('.android/gradle.properties') .writeAsStringSync('irrelevant'); fileSystem.file('.android/build.gradle') .createSync(recursive: true); fileSystem.directory('build/outputs/repo').createSync(recursive: true);
await builder.buildGradleAar( androidBuildInfo: const AndroidBuildInfo(BuildInfo(BuildMode.release, null, treeShakeIcons: false)), project: FlutterProject.fromDirectoryTest(fileSystem.currentDirectory), outputDirectory: fileSystem.directory('build/'), target: '', buildNumber: '1.0', );
expect( logger.statusText, contains('Built build/outputs/repo'), ); expect( logger.statusText.contains('Consuming the Module'), isFalse, ); expect(processManager, hasNoRemainingExpectations);
expect( analyticsTimingEventExists( sentEvents: fakeAnalytics.sentEvents, workflow: 'build', variableName: 'gradle-aar', ), true, ); }, overrides: <Type, Generator>{ AndroidStudio: () => FakeAndroidStudio(), Analytics: () => fakeAnalytics, });
testUsingContext('Verbose mode for AARs includes Gradle stacktrace and sets debug log level', () async { final AndroidGradleBuilder builder = AndroidGradleBuilder( java: FakeJava(), logger: BufferLogger.test(verbose: true), processManager: processManager, fileSystem: fileSystem, artifacts: Artifacts.test(), usage: testUsage, analytics: fakeAnalytics, gradleUtils: FakeGradleUtils(), platform: FakePlatform(), androidStudio: FakeAndroidStudio(), ); processManager.addCommand(const FakeCommand( command: <String>[ 'gradlew', '-I=/packages/flutter_tools/gradle/aar_init_script.gradle', '-Pflutter-root=/', '-Poutput-dir=build/', '-Pis-plugin=false', '-PbuildNumber=1.0', '--full-stacktrace', '--info', '-Pverbose=true', '-Pdart-obfuscation=false', '-Ptrack-widget-creation=false', '-Ptree-shake-icons=false', '-Ptarget-platform=android-arm,android-arm64,android-x64', 'assembleAarRelease', ], ));
final File manifestFile = fileSystem.file('pubspec.yaml'); manifestFile.createSync(recursive: true); manifestFile.writeAsStringSync(''' flutter: module: androidPackage: com.example.test ''' );
fileSystem.file('.android/gradlew').createSync(recursive: true); fileSystem.file('.android/gradle.properties') .writeAsStringSync('irrelevant'); fileSystem.file('.android/build.gradle') .createSync(recursive: true); fileSystem.directory('build/outputs/repo').createSync(recursive: true);
await builder.buildGradleAar( androidBuildInfo: const AndroidBuildInfo(BuildInfo(BuildMode.release, null, treeShakeIcons: false)), project: FlutterProject.fromDirectoryTest(fileSystem.currentDirectory), outputDirectory: fileSystem.directory('build/'), target: '', buildNumber: '1.0', ); expect(processManager, hasNoRemainingExpectations); }, overrides: <Type, Generator>{ AndroidStudio: () => FakeAndroidStudio(), });
testUsingContext('gradle exit code and stderr is forwarded to tool exit', () async { final AndroidGradleBuilder builder = AndroidGradleBuilder( java: FakeJava(), logger: logger, processManager: processManager, fileSystem: fileSystem, artifacts: Artifacts.test(), usage: testUsage, analytics: fakeAnalytics, gradleUtils: FakeGradleUtils(), platform: FakePlatform(), androidStudio: FakeAndroidStudio(), ); processManager.addCommand(const FakeCommand( command: <String>[ 'gradlew', '-I=/packages/flutter_tools/gradle/aar_init_script.gradle', '-Pflutter-root=/', '-Poutput-dir=build/', '-Pis-plugin=false', '-PbuildNumber=1.0', '-q', '-Pdart-obfuscation=false', '-Ptrack-widget-creation=false', '-Ptree-shake-icons=false', '-Ptarget-platform=android-arm,android-arm64,android-x64', 'assembleAarRelease', ], exitCode: 108, stderr: 'Gradle task assembleAarRelease failed with exit code 108.', ));
final File manifestFile = fileSystem.file('pubspec.yaml'); manifestFile.createSync(recursive: true); manifestFile.writeAsStringSync(''' flutter: module: androidPackage: com.example.test ''' );
fileSystem.file('.android/gradlew').createSync(recursive: true); fileSystem.file('.android/gradle.properties') .writeAsStringSync('irrelevant'); fileSystem.file('.android/build.gradle') .createSync(recursive: true); fileSystem.directory('build/outputs/repo').createSync(recursive: true);
await expectLater(() async => builder.buildGradleAar( androidBuildInfo: const AndroidBuildInfo(BuildInfo(BuildMode.release, null, treeShakeIcons: false)), project: FlutterProject.fromDirectoryTest(fileSystem.currentDirectory), outputDirectory: fileSystem.directory('build/'), target: '', buildNumber: '1.0', ), throwsToolExit(exitCode: 108, message: 'Gradle task assembleAarRelease failed with exit code 108.')); expect(processManager, hasNoRemainingExpectations); }, overrides: <Type, Generator>{ AndroidStudio: () => FakeAndroidStudio(), });
testUsingContext('build apk uses selected local engine with arm32 ABI', () async { final AndroidGradleBuilder builder = AndroidGradleBuilder( java: FakeJava(), logger: logger, processManager: processManager, fileSystem: fileSystem, artifacts: Artifacts.testLocalEngine(localEngine: 'out/android_arm', localEngineHost: 'out/host_release'), usage: testUsage, analytics: fakeAnalytics, gradleUtils: FakeGradleUtils(), platform: FakePlatform(), androidStudio: FakeAndroidStudio(), ); processManager.addCommand(const FakeCommand( command: <String>[ 'gradlew', '-q', '-Plocal-engine-repo=/.tmp_rand0/flutter_tool_local_engine_repo.rand0', '-Plocal-engine-build-mode=release', '-Plocal-engine-out=out/android_arm', '-Plocal-engine-host-out=out/host_release', '-Ptarget-platform=android-arm', '-Ptarget=lib/main.dart', '-Pbase-application-name=io.flutter.app.FlutterApplication', '-Pdart-obfuscation=false', '-Ptrack-widget-creation=false', '-Ptree-shake-icons=false', 'assembleRelease', ], ));
fileSystem.file('out/android_arm/flutter_embedding_release.pom') ..createSync(recursive: true) ..writeAsStringSync('''<?xml version="1.0" encoding="UTF-8"?><project> <version>1.0.0-73fd6b049a80bcea2db1f26c7cee434907cd188b</version> <dependencies> </dependencies></project>'''); fileSystem.file('out/android_arm/armeabi_v7a_release.pom').createSync(recursive: true); fileSystem.file('out/android_arm/armeabi_v7a_release.jar').createSync(recursive: true); fileSystem.file('out/android_arm/armeabi_v7a_release.maven-metadata.xml').createSync(recursive: true); fileSystem.file('out/android_arm/flutter_embedding_release.jar').createSync(recursive: true); fileSystem.file('out/android_arm/flutter_embedding_release.pom').createSync(recursive: true); fileSystem.file('out/android_arm/flutter_embedding_release.maven-metadata.xml').createSync(recursive: true);
fileSystem.file('android/gradlew').createSync(recursive: true); fileSystem.directory('android') .childFile('gradle.properties') .createSync(recursive: true); fileSystem.file('android/build.gradle') .createSync(recursive: true); fileSystem.directory('android') .childDirectory('app') .childFile('build.gradle') ..createSync(recursive: true) ..writeAsStringSync('apply from: irrelevant/flutter.gradle');
await expectLater(() async { await builder.buildGradleApp( project: FlutterProject.fromDirectoryTest(fileSystem.currentDirectory), androidBuildInfo: const AndroidBuildInfo( BuildInfo( BuildMode.release, null, treeShakeIcons: false, ), ), target: 'lib/main.dart', isBuildingBundle: false, configOnly: false, localGradleErrors: const <GradleHandledError>[], ); }, throwsToolExit()); expect(processManager, hasNoRemainingExpectations); }, overrides: <Type, Generator>{ AndroidStudio: () => FakeAndroidStudio(), });
testUsingContext('build apk uses selected local engine with arm64 ABI', () async { final AndroidGradleBuilder builder = AndroidGradleBuilder( java: FakeJava(), logger: logger, processManager: processManager, fileSystem: fileSystem, artifacts: Artifacts.testLocalEngine(localEngine: 'out/android_arm64', localEngineHost: 'out/host_release'), usage: testUsage, analytics: fakeAnalytics, gradleUtils: FakeGradleUtils(), platform: FakePlatform(), androidStudio: FakeAndroidStudio(), ); processManager.addCommand(const FakeCommand( command: <String>[ 'gradlew', '-q', '-Plocal-engine-repo=/.tmp_rand0/flutter_tool_local_engine_repo.rand0', '-Plocal-engine-build-mode=release', '-Plocal-engine-out=out/android_arm64', '-Plocal-engine-host-out=out/host_release', '-Ptarget-platform=android-arm64', '-Ptarget=lib/main.dart', '-Pbase-application-name=io.flutter.app.FlutterApplication', '-Pdart-obfuscation=false', '-Ptrack-widget-creation=false', '-Ptree-shake-icons=false', 'assembleRelease', ], ));
fileSystem.file('out/android_arm64/flutter_embedding_release.pom') ..createSync(recursive: true) ..writeAsStringSync('''<?xml version="1.0" encoding="UTF-8"?><project> <version>1.0.0-73fd6b049a80bcea2db1f26c7cee434907cd188b</version> <dependencies> </dependencies></project>'''); fileSystem.file('out/android_arm64/arm64_v8a_release.pom').createSync(recursive: true); fileSystem.file('out/android_arm64/arm64_v8a_release.jar').createSync(recursive: true); fileSystem.file('out/android_arm64/arm64_v8a_release.maven-metadata.xml').createSync(recursive: true); fileSystem.file('out/android_arm64/flutter_embedding_release.jar').createSync(recursive: true); fileSystem.file('out/android_arm64/flutter_embedding_release.pom').createSync(recursive: true); fileSystem.file('out/android_arm64/flutter_embedding_release.maven-metadata.xml').createSync(recursive: true);
fileSystem.file('android/gradlew').createSync(recursive: true); fileSystem.directory('android') .childFile('gradle.properties') .createSync(recursive: true); fileSystem.file('android/build.gradle') .createSync(recursive: true); fileSystem.directory('android') .childDirectory('app') .childFile('build.gradle') ..createSync(recursive: true) ..writeAsStringSync('apply from: irrelevant/flutter.gradle');
await expectLater(() async { await builder.buildGradleApp( project: FlutterProject.fromDirectoryTest(fileSystem.currentDirectory), androidBuildInfo: const AndroidBuildInfo( BuildInfo( BuildMode.release, null, treeShakeIcons: false, ), ), target: 'lib/main.dart', isBuildingBundle: false, configOnly: false, localGradleErrors: const <GradleHandledError>[], ); }, throwsToolExit()); expect(processManager, hasNoRemainingExpectations); }, overrides: <Type, Generator>{ AndroidStudio: () => FakeAndroidStudio(), });
testUsingContext('build apk uses selected local engine with x86 ABI', () async { final AndroidGradleBuilder builder = AndroidGradleBuilder( java: FakeJava(), logger: logger, processManager: processManager, fileSystem: fileSystem, artifacts: Artifacts.testLocalEngine(localEngine: 'out/android_x86', localEngineHost: 'out/host_release'), usage: testUsage, analytics: fakeAnalytics, gradleUtils: FakeGradleUtils(), platform: FakePlatform(), androidStudio: FakeAndroidStudio(), ); processManager.addCommand(const FakeCommand( command: <String>[ 'gradlew', '-q', '-Plocal-engine-repo=/.tmp_rand0/flutter_tool_local_engine_repo.rand0', '-Plocal-engine-build-mode=release', '-Plocal-engine-out=out/android_x86', '-Plocal-engine-host-out=out/host_release', '-Ptarget-platform=android-x86', '-Ptarget=lib/main.dart', '-Pbase-application-name=io.flutter.app.FlutterApplication', '-Pdart-obfuscation=false', '-Ptrack-widget-creation=false', '-Ptree-shake-icons=false', 'assembleRelease', ], ));
fileSystem.file('out/android_x86/flutter_embedding_release.pom') ..createSync(recursive: true) ..writeAsStringSync('''<?xml version="1.0" encoding="UTF-8"?><project> <version>1.0.0-73fd6b049a80bcea2db1f26c7cee434907cd188b</version> <dependencies> </dependencies></project>'''); fileSystem.file('out/android_x86/x86_release.pom').createSync(recursive: true); fileSystem.file('out/android_x86/x86_release.jar').createSync(recursive: true); fileSystem.file('out/android_x86/x86_release.maven-metadata.xml').createSync(recursive: true); fileSystem.file('out/android_x86/flutter_embedding_release.jar').createSync(recursive: true); fileSystem.file('out/android_x86/flutter_embedding_release.pom').createSync(recursive: true); fileSystem.file('out/android_x86/flutter_embedding_release.maven-metadata.xml').createSync(recursive: true);
fileSystem.file('android/gradlew').createSync(recursive: true); fileSystem.directory('android') .childFile('gradle.properties') .createSync(recursive: true); fileSystem.file('android/build.gradle') .createSync(recursive: true); fileSystem.directory('android') .childDirectory('app') .childFile('build.gradle') ..createSync(recursive: true) ..writeAsStringSync('apply from: irrelevant/flutter.gradle');
await expectLater(() async { await builder.buildGradleApp( project: FlutterProject.fromDirectoryTest(fileSystem.currentDirectory), androidBuildInfo: const AndroidBuildInfo( BuildInfo( BuildMode.release, null, treeShakeIcons: false, ), ), target: 'lib/main.dart', isBuildingBundle: false, configOnly: false, localGradleErrors: const <GradleHandledError>[], ); }, throwsToolExit()); expect(processManager, hasNoRemainingExpectations); }, overrides: <Type, Generator>{ AndroidStudio: () => FakeAndroidStudio(), });
testUsingContext('build apk uses selected local engine with x64 ABI', () async { final AndroidGradleBuilder builder = AndroidGradleBuilder( java: FakeJava(), logger: logger, processManager: processManager, fileSystem: fileSystem, artifacts: Artifacts.testLocalEngine(localEngine: 'out/android_x64', localEngineHost: 'out/host_release'), usage: testUsage, analytics: fakeAnalytics, gradleUtils: FakeGradleUtils(), platform: FakePlatform(), androidStudio: FakeAndroidStudio(), ); processManager.addCommand(const FakeCommand( command: <String>[ 'gradlew', '-q', '-Plocal-engine-repo=/.tmp_rand0/flutter_tool_local_engine_repo.rand0', '-Plocal-engine-build-mode=release', '-Plocal-engine-out=out/android_x64', '-Plocal-engine-host-out=out/host_release', '-Ptarget-platform=android-x64', '-Ptarget=lib/main.dart', '-Pbase-application-name=io.flutter.app.FlutterApplication', '-Pdart-obfuscation=false', '-Ptrack-widget-creation=false', '-Ptree-shake-icons=false', 'assembleRelease', ], exitCode: 1, ));
fileSystem.file('out/android_x64/flutter_embedding_release.pom') ..createSync(recursive: true) ..writeAsStringSync('''<?xml version="1.0" encoding="UTF-8"?><project> <version>1.0.0-73fd6b049a80bcea2db1f26c7cee434907cd188b</version> <dependencies> </dependencies></project>'''); fileSystem.file('out/android_x64/x86_64_release.pom').createSync(recursive: true); fileSystem.file('out/android_x64/x86_64_release.jar').createSync(recursive: true); fileSystem.file('out/android_x64/x86_64_release.maven-metadata.xml').createSync(recursive: true); fileSystem.file('out/android_x64/flutter_embedding_release.jar').createSync(recursive: true); fileSystem.file('out/android_x64/flutter_embedding_release.pom').createSync(recursive: true); fileSystem.file('out/android_x64/flutter_embedding_release.maven-metadata.xml').createSync(recursive: true);
fileSystem.file('android/gradlew').createSync(recursive: true); fileSystem.directory('android') .childFile('gradle.properties') .createSync(recursive: true); fileSystem.file('android/build.gradle') .createSync(recursive: true); fileSystem.directory('android') .childDirectory('app') .childFile('build.gradle') ..createSync(recursive: true) ..writeAsStringSync('apply from: irrelevant/flutter.gradle');
await expectLater(() async { await builder.buildGradleApp( project: FlutterProject.fromDirectoryTest(fileSystem.currentDirectory), androidBuildInfo: const AndroidBuildInfo( BuildInfo( BuildMode.release, null, treeShakeIcons: false, ), ), target: 'lib/main.dart', isBuildingBundle: false, configOnly: false, localGradleErrors: const <GradleHandledError>[], ); }, throwsToolExit()); expect(processManager, hasNoRemainingExpectations); }, overrides: <Type, Generator>{ AndroidStudio: () => FakeAndroidStudio(), });
testUsingContext('honors --no-android-gradle-daemon setting', () async { final AndroidGradleBuilder builder = AndroidGradleBuilder( java: FakeJava(), logger: logger, processManager: processManager, fileSystem: fileSystem, artifacts: Artifacts.test(), usage: testUsage, analytics: fakeAnalytics, gradleUtils: FakeGradleUtils(), platform: FakePlatform(), androidStudio: FakeAndroidStudio(), ); processManager.addCommand( const FakeCommand(command: <String>[ 'gradlew', '-q', '--no-daemon', '-Ptarget-platform=android-arm,android-arm64,android-x64', '-Ptarget=lib/main.dart', '-Pbase-application-name=io.flutter.app.FlutterApplication', '-Pdart-obfuscation=false', '-Ptrack-widget-creation=false', '-Ptree-shake-icons=false', 'assembleRelease', ], )); fileSystem.file('android/gradlew').createSync(recursive: true);
fileSystem.directory('android') .childFile('gradle.properties') .createSync(recursive: true); fileSystem.file('android/build.gradle') .createSync(recursive: true); fileSystem.directory('android') .childDirectory('app') .childFile('build.gradle') ..createSync(recursive: true) ..writeAsStringSync('apply from: irrelevant/flutter.gradle');
await expectLater(() async { await builder.buildGradleApp( project: FlutterProject.fromDirectoryTest(fileSystem.currentDirectory), androidBuildInfo: const AndroidBuildInfo( BuildInfo( BuildMode.release, null, treeShakeIcons: false, androidGradleDaemon: false, ), ), target: 'lib/main.dart', isBuildingBundle: false, configOnly: false, localGradleErrors: const <GradleHandledError>[], ); }, throwsToolExit()); expect(processManager, hasNoRemainingExpectations); }, overrides: <Type, Generator>{ AndroidStudio: () => FakeAndroidStudio(), });
testUsingContext('build aar uses selected local engine with arm32 ABI', () async { final AndroidGradleBuilder builder = AndroidGradleBuilder( java: FakeJava(), logger: logger, processManager: processManager, fileSystem: fileSystem, artifacts: Artifacts.testLocalEngine(localEngine: 'out/android_arm', localEngineHost: 'out/host_release'), usage: testUsage, analytics: fakeAnalytics, gradleUtils: FakeGradleUtils(), platform: FakePlatform(), androidStudio: FakeAndroidStudio(), ); processManager.addCommand(const FakeCommand( command: <String>[ 'gradlew', '-I=/packages/flutter_tools/gradle/aar_init_script.gradle', '-Pflutter-root=/', '-Poutput-dir=build/', '-Pis-plugin=false', '-PbuildNumber=2.0', '-q', '-Pdart-obfuscation=false', '-Ptrack-widget-creation=false', '-Ptree-shake-icons=false', '-Plocal-engine-repo=/.tmp_rand0/flutter_tool_local_engine_repo.rand0', '-Plocal-engine-build-mode=release', '-Plocal-engine-out=out/android_arm', '-Plocal-engine-host-out=out/host_release', '-Ptarget-platform=android-arm', 'assembleAarRelease', ], ));
fileSystem.file('out/android_arm/flutter_embedding_release.pom') ..createSync(recursive: true) ..writeAsStringSync('''<?xml version="1.0" encoding="UTF-8"?><project> <version>1.0.0-73fd6b049a80bcea2db1f26c7cee434907cd188b</version> <dependencies> </dependencies></project>'''); fileSystem.file('out/android_arm/armeabi_v7a_release.pom').createSync(recursive: true); fileSystem.file('out/android_arm/armeabi_v7a_release.jar').createSync(recursive: true); fileSystem.file('out/android_arm/armeabi_v7a_release.maven-metadata.xml').createSync(recursive: true); fileSystem.file('out/android_arm/flutter_embedding_release.jar').createSync(recursive: true); fileSystem.file('out/android_arm/flutter_embedding_release.pom').createSync(recursive: true); fileSystem.file('out/android_arm/flutter_embedding_release.maven-metadata.xml').createSync(recursive: true);
final File manifestFile = fileSystem.file('pubspec.yaml'); manifestFile.createSync(recursive: true); manifestFile.writeAsStringSync(''' flutter: module: androidPackage: com.example.test ''' );
fileSystem.directory('.android/gradle') .createSync(recursive: true); fileSystem.directory('.android/gradle/wrapper') .createSync(recursive: true); fileSystem.file('.android/gradlew').createSync(recursive: true); fileSystem.file('.android/gradle.properties') .writeAsStringSync('irrelevant'); fileSystem.file('.android/build.gradle') .createSync(recursive: true);
fileSystem.directory('build/outputs/repo').createSync(recursive: true);
await builder.buildGradleAar( androidBuildInfo: const AndroidBuildInfo(BuildInfo(BuildMode.release, null, treeShakeIcons: false)), project: FlutterProject.fromDirectoryTest(fileSystem.currentDirectory), outputDirectory: fileSystem.directory('build/'), target: '', buildNumber: '2.0', );
expect(fileSystem.link( 'build/outputs/repo/io/flutter/flutter_embedding_release/' '1.0.0-73fd6b049a80bcea2db1f26c7cee434907cd188b/' 'flutter_embedding_release-1.0.0-73fd6b049a80bcea2db1f26c7cee434907cd188b.pom' ), exists); expect(processManager, hasNoRemainingExpectations); }, overrides: <Type, Generator>{ AndroidStudio: () => FakeAndroidStudio(), });
testUsingContext('build aar uses selected local engine with x64 ABI', () async { final AndroidGradleBuilder builder = AndroidGradleBuilder( java: FakeJava(), logger: logger, processManager: processManager, fileSystem: fileSystem, artifacts: Artifacts.testLocalEngine(localEngine: 'out/android_arm64', localEngineHost: 'out/host_release'), usage: testUsage, analytics: fakeAnalytics, gradleUtils: FakeGradleUtils(), platform: FakePlatform(), androidStudio: FakeAndroidStudio(), ); processManager.addCommand(const FakeCommand( command: <String>[ 'gradlew', '-I=/packages/flutter_tools/gradle/aar_init_script.gradle', '-Pflutter-root=/', '-Poutput-dir=build/', '-Pis-plugin=false', '-PbuildNumber=2.0', '-q', '-Pdart-obfuscation=false', '-Ptrack-widget-creation=false', '-Ptree-shake-icons=false', '-Plocal-engine-repo=/.tmp_rand0/flutter_tool_local_engine_repo.rand0', '-Plocal-engine-build-mode=release', '-Plocal-engine-out=out/android_arm64', '-Plocal-engine-host-out=out/host_release', '-Ptarget-platform=android-arm64', 'assembleAarRelease', ], ));
fileSystem.file('out/android_arm64/flutter_embedding_release.pom') ..createSync(recursive: true) ..writeAsStringSync('''<?xml version="1.0" encoding="UTF-8"?><project> <version>1.0.0-73fd6b049a80bcea2db1f26c7cee434907cd188b</version> <dependencies> </dependencies></project>'''); fileSystem.file('out/android_arm64/arm64_v8a_release.pom').createSync(recursive: true); fileSystem.file('out/android_arm64/arm64_v8a_release.jar').createSync(recursive: true); fileSystem.file('out/android_arm64/arm64_v8a_release.maven-metadata.xml').createSync(recursive: true); fileSystem.file('out/android_arm64/flutter_embedding_release.jar').createSync(recursive: true); fileSystem.file('out/android_arm64/flutter_embedding_release.pom').createSync(recursive: true); fileSystem.file('out/android_arm64/flutter_embedding_release.maven-metadata.xml').createSync(recursive: true);
final File manifestFile = fileSystem.file('pubspec.yaml'); manifestFile.createSync(recursive: true); manifestFile.writeAsStringSync(''' flutter: module: androidPackage: com.example.test ''' );
fileSystem.directory('.android/gradle') .createSync(recursive: true); fileSystem.directory('.android/gradle/wrapper') .createSync(recursive: true); fileSystem.file('.android/gradlew').createSync(recursive: true); fileSystem.file('.android/gradle.properties') .writeAsStringSync('irrelevant'); fileSystem.file('.android/build.gradle') .createSync(recursive: true); fileSystem.directory('build/outputs/repo').createSync(recursive: true);
await builder.buildGradleAar( androidBuildInfo: const AndroidBuildInfo( BuildInfo(BuildMode.release, null, treeShakeIcons: false)), project: FlutterProject.fromDirectoryTest(fileSystem.currentDirectory), outputDirectory: fileSystem.directory('build/'), target: '', buildNumber: '2.0', );
expect(fileSystem.link( 'build/outputs/repo/io/flutter/flutter_embedding_release/' '1.0.0-73fd6b049a80bcea2db1f26c7cee434907cd188b/' 'flutter_embedding_release-1.0.0-73fd6b049a80bcea2db1f26c7cee434907cd188b.pom' ), exists); expect(processManager, hasNoRemainingExpectations); }, overrides: <Type, Generator>{ AndroidStudio: () => FakeAndroidStudio(), });
testUsingContext('build aar uses selected local engine with x86 ABI', () async { final AndroidGradleBuilder builder = AndroidGradleBuilder( java: FakeJava(), logger: logger, processManager: processManager, fileSystem: fileSystem, artifacts: Artifacts.testLocalEngine(localEngine: 'out/android_x86', localEngineHost: 'out/host_release'), usage: testUsage, analytics: fakeAnalytics, gradleUtils: FakeGradleUtils(), platform: FakePlatform(), androidStudio: FakeAndroidStudio(), ); processManager.addCommand(const FakeCommand( command: <String>[ 'gradlew', '-I=/packages/flutter_tools/gradle/aar_init_script.gradle', '-Pflutter-root=/', '-Poutput-dir=build/', '-Pis-plugin=false', '-PbuildNumber=2.0', '-q', '-Pdart-obfuscation=false', '-Ptrack-widget-creation=false', '-Ptree-shake-icons=false', '-Plocal-engine-repo=/.tmp_rand0/flutter_tool_local_engine_repo.rand0', '-Plocal-engine-build-mode=release', '-Plocal-engine-out=out/android_x86', '-Plocal-engine-host-out=out/host_release', '-Ptarget-platform=android-x86', 'assembleAarRelease', ], ));
fileSystem.file('out/android_x86/flutter_embedding_release.pom') ..createSync(recursive: true) ..writeAsStringSync('''<?xml version="1.0" encoding="UTF-8"?><project> <version>1.0.0-73fd6b049a80bcea2db1f26c7cee434907cd188b</version> <dependencies> </dependencies></project>'''); fileSystem.file('out/android_x86/x86_release.pom').createSync(recursive: true); fileSystem.file('out/android_x86/x86_release.jar').createSync(recursive: true); fileSystem.file('out/android_x86/x86_release.maven-metadata.xml').createSync(recursive: true); fileSystem.file('out/android_x86/flutter_embedding_release.jar').createSync(recursive: true); fileSystem.file('out/android_x86/flutter_embedding_release.pom').createSync(recursive: true); fileSystem.file('out/android_x86/flutter_embedding_release.maven-metadata.xml').createSync(recursive: true);
final File manifestFile = fileSystem.file('pubspec.yaml'); manifestFile.createSync(recursive: true); manifestFile.writeAsStringSync(''' flutter: module: androidPackage: com.example.test ''' );
fileSystem.directory('.android/gradle') .createSync(recursive: true); fileSystem.directory('.android/gradle/wrapper') .createSync(recursive: true); fileSystem.file('.android/gradlew').createSync(recursive: true); fileSystem.file('.android/gradle.properties') .writeAsStringSync('irrelevant'); fileSystem.file('.android/build.gradle') .createSync(recursive: true); fileSystem.directory('build/outputs/repo').createSync(recursive: true);
await builder.buildGradleAar( androidBuildInfo: const AndroidBuildInfo( BuildInfo(BuildMode.release, null, treeShakeIcons: false)), project: FlutterProject.fromDirectoryTest(fileSystem.currentDirectory), outputDirectory: fileSystem.directory('build/'), target: '', buildNumber: '2.0', );
expect(fileSystem.link( 'build/outputs/repo/io/flutter/flutter_embedding_release/' '1.0.0-73fd6b049a80bcea2db1f26c7cee434907cd188b/' 'flutter_embedding_release-1.0.0-73fd6b049a80bcea2db1f26c7cee434907cd188b.pom' ), exists); expect(processManager, hasNoRemainingExpectations); }, overrides: <Type, Generator>{ AndroidStudio: () => FakeAndroidStudio(), });
testUsingContext('build aar uses selected local engine on x64 ABI', () async { final AndroidGradleBuilder builder = AndroidGradleBuilder( java: FakeJava(), logger: logger, processManager: processManager, fileSystem: fileSystem, artifacts: Artifacts.testLocalEngine(localEngine: 'out/android_x64', localEngineHost: 'out/host_release'), usage: testUsage, analytics: fakeAnalytics, gradleUtils: FakeGradleUtils(), platform: FakePlatform(), androidStudio: FakeAndroidStudio(), ); processManager.addCommand(const FakeCommand( command: <String>[ 'gradlew', '-I=/packages/flutter_tools/gradle/aar_init_script.gradle', '-Pflutter-root=/', '-Poutput-dir=build/', '-Pis-plugin=false', '-PbuildNumber=2.0', '-q', '-Pdart-obfuscation=false', '-Ptrack-widget-creation=false', '-Ptree-shake-icons=false', '-Plocal-engine-repo=/.tmp_rand0/flutter_tool_local_engine_repo.rand0', '-Plocal-engine-build-mode=release', '-Plocal-engine-out=out/android_x64', '-Plocal-engine-host-out=out/host_release', '-Ptarget-platform=android-x64', 'assembleAarRelease', ], ));
fileSystem.file('out/android_x64/flutter_embedding_release.pom') ..createSync(recursive: true) ..writeAsStringSync('''<?xml version="1.0" encoding="UTF-8"?><project> <version>1.0.0-73fd6b049a80bcea2db1f26c7cee434907cd188b</version> <dependencies> </dependencies></project>'''); fileSystem.file('out/android_x64/x86_64_release.pom').createSync(recursive: true); fileSystem.file('out/android_x64/x86_64_release.jar').createSync(recursive: true); fileSystem.file('out/android_x64/x86_64_release.maven-metadata.xml').createSync(recursive: true); fileSystem.file('out/android_x64/flutter_embedding_release.jar').createSync(recursive: true); fileSystem.file('out/android_x64/flutter_embedding_release.pom').createSync(recursive: true); fileSystem.file('out/android_x64/flutter_embedding_release.maven-metadata.xml').createSync(recursive: true);
final File manifestFile = fileSystem.file('pubspec.yaml'); manifestFile.createSync(recursive: true); manifestFile.writeAsStringSync(''' flutter: module: androidPackage: com.example.test ''' );
fileSystem.directory('.android/gradle') .createSync(recursive: true); fileSystem.directory('.android/gradle/wrapper') .createSync(recursive: true); fileSystem.file('.android/gradlew').createSync(recursive: true); fileSystem.file('.android/gradle.properties') .writeAsStringSync('irrelevant'); fileSystem.file('.android/build.gradle') .createSync(recursive: true); fileSystem.directory('build/outputs/repo').createSync(recursive: true);
await builder.buildGradleAar( androidBuildInfo: const AndroidBuildInfo( BuildInfo(BuildMode.release, null, treeShakeIcons: false)), project: FlutterProject.fromDirectoryTest(fileSystem.currentDirectory), outputDirectory: fileSystem.directory('build/'), target: '', buildNumber: '2.0', );
expect(fileSystem.link( 'build/outputs/repo/io/flutter/flutter_embedding_release/' '1.0.0-73fd6b049a80bcea2db1f26c7cee434907cd188b/' 'flutter_embedding_release-1.0.0-73fd6b049a80bcea2db1f26c7cee434907cd188b.pom' ), exists); expect(processManager, hasNoRemainingExpectations); }, overrides: <Type, Generator>{ AndroidStudio: () => FakeAndroidStudio(), }); });}
class FakeGradleUtils extends Fake implements GradleUtils { @override String getExecutable(FlutterProject project) { return 'gradlew'; }}
class FakeAndroidStudio extends Fake implements AndroidStudio { @override String get javaPath => '/android-studio/jbr';}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318// 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:flutter_tools/src/android/android_device.dart';import 'package:flutter_tools/src/android/android_sdk.dart';import 'package:flutter_tools/src/android/application_package.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:test/fake.dart';
import '../../src/common.dart';import '../../src/fake_process_manager.dart';
const FakeCommand kAdbVersionCommand = FakeCommand( command: <String>['adb', 'version'], stdout: 'Android Debug Bridge version 1.0.39',);const FakeCommand kAdbStartServerCommand = FakeCommand( command: <String>['adb', 'start-server']);const FakeCommand kInstallCommand = FakeCommand( command: <String>[ 'adb', '-s', '1234', 'install', '-t', '-r', '--user', '10', 'app-debug.apk', ],);const FakeCommand kStoreShaCommand = FakeCommand( command: <String>['adb', '-s', '1234', 'shell', 'echo', '-n', '', '>', '/data/local/tmp/sky.app.sha1']);
void main() { late FileSystem fileSystem; late BufferLogger logger;
setUp(() { fileSystem = MemoryFileSystem.test(); logger = BufferLogger.test(); });
AndroidDevice setUpAndroidDevice({ AndroidSdk? androidSdk, ProcessManager? processManager, }) { androidSdk ??= FakeAndroidSdk(); return AndroidDevice('1234', modelID: 'TestModel', logger: logger, platform: FakePlatform(), androidSdk: androidSdk, fileSystem: fileSystem, processManager: processManager ?? FakeProcessManager.any(), ); }
testWithoutContext('Cannot install app on API level below 16', () async { final FakeProcessManager processManager = FakeProcessManager.list(<FakeCommand>[ kAdbVersionCommand, kAdbStartServerCommand, const FakeCommand( command: <String>['adb', '-s', '1234', 'shell', 'getprop'], stdout: '[ro.build.version.sdk]: [11]', ), ]); final File apk = fileSystem.file('app-debug.apk')..createSync(); final AndroidApk androidApk = AndroidApk( applicationPackage: apk, id: 'app', versionCode: 22, launchActivity: 'Main', ); final AndroidDevice androidDevice = setUpAndroidDevice( processManager: processManager, );
expect(await androidDevice.installApp(androidApk), false); expect(processManager, hasNoRemainingExpectations); });
testWithoutContext('Cannot install app if APK file is missing', () async { final File apk = fileSystem.file('app-debug.apk'); final AndroidApk androidApk = AndroidApk( applicationPackage: apk, id: 'app', versionCode: 22, launchActivity: 'Main', ); final AndroidDevice androidDevice = setUpAndroidDevice( );
expect(await androidDevice.installApp(androidApk), false); });
testWithoutContext('Can install app on API level 16 or greater', () async { final FakeProcessManager processManager = FakeProcessManager.list(<FakeCommand>[ kAdbVersionCommand, kAdbStartServerCommand, const FakeCommand( command: <String>['adb', '-s', '1234', 'shell', 'getprop'], stdout: '[ro.build.version.sdk]: [16]', ), const FakeCommand( command: <String>['adb', '-s', '1234', 'shell', 'pm', 'list', 'packages', '--user', '10', 'app'], stdout: '\n' ), kInstallCommand, kStoreShaCommand, ]); final File apk = fileSystem.file('app-debug.apk')..createSync(); final AndroidApk androidApk = AndroidApk( applicationPackage: apk, id: 'app', versionCode: 22, launchActivity: 'Main', ); final AndroidDevice androidDevice = setUpAndroidDevice( processManager: processManager, );
expect(await androidDevice.installApp(androidApk, userIdentifier: '10'), true); expect(processManager, hasNoRemainingExpectations); });
testWithoutContext('Defaults to API level 16 if adb returns a null response', () async { final FakeProcessManager processManager = FakeProcessManager.list(<FakeCommand>[ kAdbVersionCommand, kAdbStartServerCommand, const FakeCommand( command: <String>['adb', '-s', '1234', 'shell', 'getprop'], ), const FakeCommand( command: <String>['adb', '-s', '1234', 'shell', 'pm', 'list', 'packages', '--user', '10', 'app'], stdout: '\n' ), kInstallCommand, kStoreShaCommand, ]); final File apk = fileSystem.file('app-debug.apk')..createSync(); final AndroidApk androidApk = AndroidApk( applicationPackage: apk, id: 'app', versionCode: 22, launchActivity: 'Main', ); final AndroidDevice androidDevice = setUpAndroidDevice( processManager: processManager, );
expect(await androidDevice.installApp(androidApk, userIdentifier: '10'), true); expect(processManager, hasNoRemainingExpectations); });
testWithoutContext('displays error if user not found', () async { final FakeProcessManager processManager = FakeProcessManager.list(<FakeCommand>[ kAdbVersionCommand, kAdbStartServerCommand, const FakeCommand( command: <String>['adb', '-s', '1234', 'shell', 'getprop'], ), // This command is run before the user is checked and is allowed to fail. const FakeCommand( command: <String>['adb', '-s', '1234', 'shell', 'pm', 'list', 'packages', '--user', 'jane', 'app'], stderr: 'Blah blah', exitCode: 1, ), const FakeCommand( command: <String>[ 'adb', '-s', '1234', 'install', '-t', '-r', '--user', 'jane', 'app-debug.apk', ], exitCode: 1, stderr: 'Exception occurred while executing: java.lang.IllegalArgumentException: Bad user number: jane', ), ]); final File apk = fileSystem.file('app-debug.apk')..createSync(); final AndroidApk androidApk = AndroidApk( applicationPackage: apk, id: 'app', versionCode: 22, launchActivity: 'Main', ); final AndroidDevice androidDevice = setUpAndroidDevice( processManager: processManager, );
expect(await androidDevice.installApp(androidApk, userIdentifier: 'jane'), false); expect(logger.errorText, contains('Error: User "jane" not found. Run "adb shell pm list users" to see list of available identifiers.')); expect(processManager, hasNoRemainingExpectations); });
testWithoutContext('Will skip install if the correct version is up to date', () async { final FakeProcessManager processManager = FakeProcessManager.list(<FakeCommand>[ kAdbVersionCommand, kAdbStartServerCommand, const FakeCommand( command: <String>['adb', '-s', '1234', 'shell', 'getprop'], stdout: '[ro.build.version.sdk]: [16]', ), const FakeCommand( command: <String>['adb', '-s', '1234', 'shell', 'pm', 'list', 'packages', '--user', '10', 'app'], stdout: 'package:app\n' ), const FakeCommand( command: <String>['adb', '-s', '1234', 'shell', 'cat', '/data/local/tmp/sky.app.sha1'], stdout: 'example_sha', ), ]); final File apk = fileSystem.file('app-debug.apk')..createSync(); fileSystem.file('app-debug.apk.sha1').writeAsStringSync('example_sha'); final AndroidApk androidApk = AndroidApk( applicationPackage: apk, id: 'app', versionCode: 22, launchActivity: 'Main', ); final AndroidDevice androidDevice = setUpAndroidDevice( processManager: processManager, );
expect(await androidDevice.installApp(androidApk, userIdentifier: '10'), true); expect(processManager, hasNoRemainingExpectations); });
testWithoutContext('Will uninstall if the correct version is not up to date and install fails', () async { final FakeProcessManager processManager = FakeProcessManager.list(<FakeCommand>[ kAdbVersionCommand, kAdbStartServerCommand, const FakeCommand( command: <String>['adb', '-s', '1234', 'shell', 'getprop'], stdout: '[ro.build.version.sdk]: [16]', ), const FakeCommand( command: <String>['adb', '-s', '1234', 'shell', 'pm', 'list', 'packages', '--user', '10', 'app'], stdout: 'package:app\n' ), const FakeCommand( command: <String>['adb', '-s', '1234', 'shell', 'cat', '/data/local/tmp/sky.app.sha1'], stdout: 'different_example_sha', ), const FakeCommand( command: <String>['adb', '-s', '1234', 'install', '-t', '-r', '--user', '10', 'app-debug.apk'], exitCode: 1, stderr: '[INSTALL_FAILED_INSUFFICIENT_STORAGE]', ), const FakeCommand(command: <String>['adb', '-s', '1234', 'uninstall', '--user', '10', 'app']), kInstallCommand, const FakeCommand(command: <String>['adb', '-s', '1234', 'shell', 'echo', '-n', 'example_sha', '>', '/data/local/tmp/sky.app.sha1']), ]); final File apk = fileSystem.file('app-debug.apk')..createSync(); fileSystem.file('app-debug.apk.sha1').writeAsStringSync('example_sha'); final AndroidApk androidApk = AndroidApk( applicationPackage: apk, id: 'app', versionCode: 22, launchActivity: 'Main', ); final AndroidDevice androidDevice = setUpAndroidDevice( processManager: processManager, );
expect(await androidDevice.installApp(androidApk, userIdentifier: '10'), true); expect(processManager, hasNoRemainingExpectations); });
testWithoutContext('Will fail to install if the apk was never installed and it fails the first time', () async { final FakeProcessManager processManager = FakeProcessManager.list(<FakeCommand>[ kAdbVersionCommand, kAdbStartServerCommand, const FakeCommand( command: <String>['adb', '-s', '1234', 'shell', 'getprop'], stdout: '[ro.build.version.sdk]: [16]', ), const FakeCommand( command: <String>['adb', '-s', '1234', 'shell', 'pm', 'list', 'packages', '--user', '10', 'app'], stdout: '\n' ), const FakeCommand( command: <String>['adb', '-s', '1234', 'install', '-t', '-r', '--user', '10', 'app-debug.apk'], exitCode: 1, stderr: '[INSTALL_FAILED_INSUFFICIENT_STORAGE]', ), ]); final File apk = fileSystem.file('app-debug.apk')..createSync(); final AndroidApk androidApk = AndroidApk( applicationPackage: apk, id: 'app', versionCode: 22, launchActivity: 'Main', ); final AndroidDevice androidDevice = setUpAndroidDevice( processManager: processManager, );
expect(await androidDevice.installApp(androidApk, userIdentifier: '10'), false); expect(processManager, hasNoRemainingExpectations); });}
class FakeAndroidSdk extends Fake implements AndroidSdk { @override String get adbPath => 'adb';}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474// 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/android/android_studio.dart';import 'package:flutter_tools/src/android/gradle_utils.dart';import 'package:flutter_tools/src/android/migrations/android_studio_java_gradle_conflict_migration.dart';import 'package:flutter_tools/src/android/migrations/min_sdk_version_migration.dart';import 'package:flutter_tools/src/android/migrations/top_level_gradle_build_file_migration.dart';import 'package:flutter_tools/src/base/logger.dart';import 'package:flutter_tools/src/base/version.dart';import 'package:flutter_tools/src/project.dart';import 'package:test/fake.dart';
import '../../src/common.dart';import '../../src/context.dart';import '../../src/fakes.dart';
const String otherGradleVersionWrapper = r'''distributionBase=GRADLE_USER_HOMEdistributionPath=wrapper/distsdistributionUrl=https\://services.gradle.org/distributions/gradle-6.6-all.zipzipStoreBase=GRADLE_USER_HOMEzipStorePath=wrapper/dists''';
const String gradleWrapperToMigrate = r'''distributionBase=GRADLE_USER_HOMEdistributionPath=wrapper/distsdistributionUrl=https\://services.gradle.org/distributions/gradle-6.7-all.zipzipStoreBase=GRADLE_USER_HOMEzipStorePath=wrapper/dists''';
const String gradleWrapperToMigrateTo = r'''distributionBase=GRADLE_USER_HOMEdistributionPath=wrapper/distsdistributionUrl=https\://services.gradle.org/distributions/gradle-7.6.1-all.zipzipStoreBase=GRADLE_USER_HOMEzipStorePath=wrapper/dists''';
String sampleModuleGradleBuildFile(String minSdkVersionString) { return r'''plugins { id "com.android.application" id "kotlin-android" id "dev.flutter.flutter-gradle-plugin"}
def localProperties = new Properties()def localPropertiesFile = rootProject.file('local.properties')if (localPropertiesFile.exists()) { localPropertiesFile.withReader('UTF-8') { reader -> localProperties.load(reader) }}
def flutterVersionCode = localProperties.getProperty('flutter.versionCode')if (flutterVersionCode == null) { flutterVersionCode = '1'}
def flutterVersionName = localProperties.getProperty('flutter.versionName')if (flutterVersionName == null) { flutterVersionName = '1.0'}
android { namespace "com.example.asset_sample" compileSdk flutter.compileSdkVersion ndkVersion flutter.ndkVersion
compileOptions { sourceCompatibility JavaVersion.VERSION_1_8 targetCompatibility JavaVersion.VERSION_1_8 }
kotlinOptions { jvmTarget = '1.8' }
sourceSets { main.java.srcDirs += 'src/main/kotlin' }
defaultConfig { // TODO: Specify your own unique Application ID (https://developer.android.com/studio/build/application-id.html). applicationId "com.example.asset_sample" // You can update the following values to match your application needs. // For more information, see: https://docs.flutter.dev/deployment/android#reviewing-the-gradle-build-configuration. ''' + minSdkVersionString + r'''
targetSdkVersion flutter.targetSdkVersion versionCode flutterVersionCode.toInteger() versionName flutterVersionName }
buildTypes { release { // TODO: Add your own signing config for the release build. // Signing with the debug keys for now, so `flutter run --release` works. signingConfig signingConfigs.debug } }}
flutter { source '../..'}
dependencies {}''';}
final Version androidStudioDolphin = Version(2021, 3, 1);
const Version _javaVersion17 = Version.withText(17, 0, 2, 'openjdk 17.0.2');const Version _javaVersion16 = Version.withText(16, 0, 2, 'openjdk 16.0.2');
void main() { group('Android migration', () { group('migrate the Gradle "clean" task to lazy declaration', () { late MemoryFileSystem memoryFileSystem; late BufferLogger bufferLogger; late FakeAndroidProject project; late File topLevelGradleBuildFile;
setUp(() { memoryFileSystem = MemoryFileSystem.test(); bufferLogger = BufferLogger.test(); project = FakeAndroidProject( root: memoryFileSystem.currentDirectory.childDirectory('android')..createSync(), ); topLevelGradleBuildFile = project.hostAppGradleRoot.childFile('build.gradle'); });
testUsingContext('skipped if files are missing', () { final TopLevelGradleBuildFileMigration androidProjectMigration = TopLevelGradleBuildFileMigration( project, bufferLogger, ); androidProjectMigration.migrate(); expect(topLevelGradleBuildFile.existsSync(), isFalse); expect(bufferLogger.traceText, contains('Top-level Gradle build file not found, skipping migration of task "clean".')); });
testUsingContext('skipped if nothing to upgrade', () { topLevelGradleBuildFile.writeAsStringSync('''tasks.register("clean", Delete) { delete rootProject.buildDir} ''');
final TopLevelGradleBuildFileMigration androidProjectMigration = TopLevelGradleBuildFileMigration( project, bufferLogger, ); final DateTime previousLastModified = topLevelGradleBuildFile.lastModifiedSync(); androidProjectMigration.migrate();
expect(topLevelGradleBuildFile.lastModifiedSync(), previousLastModified); });
testUsingContext('top-level build.gradle is migrated', () { topLevelGradleBuildFile.writeAsStringSync('''task clean(type: Delete) { delete rootProject.buildDir}''');
final TopLevelGradleBuildFileMigration androidProjectMigration = TopLevelGradleBuildFileMigration( project, bufferLogger, ); androidProjectMigration.migrate();
expect(bufferLogger.traceText, contains('Migrating "clean" Gradle task to lazy declaration style.')); expect(topLevelGradleBuildFile.readAsStringSync(), equals('''tasks.register("clean", Delete) { delete rootProject.buildDir}''')); }); });
group('migrate the gradle version to one that does not conflict with the ' 'Android Studio-provided java version', () { late MemoryFileSystem memoryFileSystem; late BufferLogger bufferLogger; late FakeAndroidProject project; late File gradleWrapperPropertiesFile;
setUp(() { memoryFileSystem = MemoryFileSystem.test(); bufferLogger = BufferLogger.test(); project = FakeAndroidProject( root: memoryFileSystem.currentDirectory.childDirectory('android')..createSync(), ); project.hostAppGradleRoot.childDirectory(gradleDirectoryName) .childDirectory(gradleWrapperDirectoryName) .createSync(recursive: true); gradleWrapperPropertiesFile = project.hostAppGradleRoot .childDirectory(gradleDirectoryName) .childDirectory(gradleWrapperDirectoryName) .childFile(gradleWrapperPropertiesFilename); });
testWithoutContext('skipped if files are missing', () { final AndroidStudioJavaGradleConflictMigration migration = AndroidStudioJavaGradleConflictMigration( java: FakeJava(version: _javaVersion17), bufferLogger, project: project, androidStudio: FakeAndroidStudio(version: androidStudioDolphin), ); migration.migrate(); expect(gradleWrapperPropertiesFile.existsSync(), isFalse); expect(bufferLogger.traceText, contains(gradleWrapperNotFound)); });
testWithoutContext('skipped if android studio is null', () { final AndroidStudioJavaGradleConflictMigration migration = AndroidStudioJavaGradleConflictMigration( java: FakeJava(version: _javaVersion17), bufferLogger, project: project, ); gradleWrapperPropertiesFile.writeAsStringSync(gradleWrapperToMigrate); migration.migrate(); expect(bufferLogger.traceText, contains(androidStudioNotFound)); expect(gradleWrapperPropertiesFile.readAsStringSync(), gradleWrapperToMigrate); });
testWithoutContext('skipped if android studio version is null', () { final AndroidStudioJavaGradleConflictMigration migration = AndroidStudioJavaGradleConflictMigration( java: FakeJava(version: _javaVersion17), bufferLogger, project: project, androidStudio: FakeAndroidStudio(version: null), ); gradleWrapperPropertiesFile.writeAsStringSync(gradleWrapperToMigrate); migration.migrate(); expect(bufferLogger.traceText, contains(androidStudioNotFound)); expect(gradleWrapperPropertiesFile.readAsStringSync(), gradleWrapperToMigrate); });
testWithoutContext('skipped if error is encountered in migrate()', () { final AndroidStudioJavaGradleConflictMigration migration = AndroidStudioJavaGradleConflictMigration( java: FakeErroringJava(), bufferLogger, project: project, androidStudio: FakeAndroidStudio(version: androidStudioFlamingo), ); gradleWrapperPropertiesFile.writeAsStringSync(gradleWrapperToMigrate); migration.migrate(); expect(bufferLogger.traceText, contains(errorWhileMigrating)); expect(gradleWrapperPropertiesFile.readAsStringSync(), gradleWrapperToMigrate); });
testWithoutContext('skipped if android studio version is less than flamingo', () { final AndroidStudioJavaGradleConflictMigration migration = AndroidStudioJavaGradleConflictMigration( java: FakeJava(), bufferLogger, project: project, androidStudio: FakeAndroidStudio(version: androidStudioDolphin), ); gradleWrapperPropertiesFile.writeAsStringSync(gradleWrapperToMigrate); migration.migrate(); expect(gradleWrapperPropertiesFile.readAsStringSync(), gradleWrapperToMigrate); expect(bufferLogger.traceText, contains(androidStudioVersionBelowFlamingo)); });
testWithoutContext('skipped if bundled java version is less than 17', () { final AndroidStudioJavaGradleConflictMigration migration = AndroidStudioJavaGradleConflictMigration( java: FakeJava(version: _javaVersion16), bufferLogger, project: project, androidStudio: FakeAndroidStudio(version: androidStudioFlamingo), ); gradleWrapperPropertiesFile.writeAsStringSync(gradleWrapperToMigrate); migration.migrate(); expect(gradleWrapperPropertiesFile.readAsStringSync(), gradleWrapperToMigrate); expect(bufferLogger.traceText, contains(javaVersionNot17)); });
testWithoutContext('nothing is changed if gradle version not one that was ' 'used by flutter create', () { final AndroidStudioJavaGradleConflictMigration migration = AndroidStudioJavaGradleConflictMigration( java: FakeJava(version: _javaVersion17), bufferLogger, project: project, androidStudio: FakeAndroidStudio(version: androidStudioFlamingo), ); gradleWrapperPropertiesFile.writeAsStringSync(otherGradleVersionWrapper); migration.migrate(); expect(gradleWrapperPropertiesFile.readAsStringSync(), otherGradleVersionWrapper); expect(bufferLogger.traceText, isEmpty); });
testWithoutContext('change is made with one of the specific gradle versions' ' we migrate for', () { final AndroidStudioJavaGradleConflictMigration migration = AndroidStudioJavaGradleConflictMigration( java: FakeJava(version: _javaVersion17), bufferLogger, project: project, androidStudio: FakeAndroidStudio(version: androidStudioFlamingo), ); gradleWrapperPropertiesFile.writeAsStringSync(gradleWrapperToMigrate); migration.migrate(); expect(gradleWrapperPropertiesFile.readAsStringSync(), gradleWrapperToMigrateTo); expect(bufferLogger.statusText, contains('Conflict detected between ' 'Android Studio Java version and Gradle version, upgrading Gradle ' 'version from 6.7 to $gradleVersion7_6_1.')); });
testWithoutContext('change is not made when opt out flag is set', () { final AndroidStudioJavaGradleConflictMigration migration = AndroidStudioJavaGradleConflictMigration( java: FakeJava(version: _javaVersion17), bufferLogger, project: project, androidStudio: FakeAndroidStudio(version: androidStudioFlamingo), ); gradleWrapperPropertiesFile.writeAsStringSync(gradleWrapperToMigrate + optOutFlag); migration.migrate(); expect(gradleWrapperPropertiesFile.readAsStringSync(), gradleWrapperToMigrate + optOutFlag); expect(bufferLogger.traceText, contains(optOutFlagEnabled)); }); });
group('migrate min sdk versions less than 19 to flutter.minSdkVersion ' 'when in a FlutterProject that is an app', () { late MemoryFileSystem memoryFileSystem; late BufferLogger bufferLogger; late FakeAndroidProject project; late MinSdkVersionMigration migration;
setUp(() { memoryFileSystem = MemoryFileSystem.test(); memoryFileSystem.currentDirectory.childDirectory('android').createSync(); bufferLogger = BufferLogger.test(); project = FakeAndroidProject( root: memoryFileSystem.currentDirectory.childDirectory('android'), ); project.appGradleFile.parent.createSync(recursive: true); migration = MinSdkVersionMigration( project, bufferLogger ); });
testWithoutContext('do nothing when files missing', () { migration.migrate(); expect(bufferLogger.traceText, contains(appGradleNotFoundWarning)); });
testWithoutContext('replace when api 16', () { const String minSdkVersion16 = 'minSdkVersion 16'; project.appGradleFile.writeAsStringSync(sampleModuleGradleBuildFile(minSdkVersion16)); migration.migrate(); expect(project.appGradleFile.readAsStringSync(), sampleModuleGradleBuildFile(replacementMinSdkText)); });
testWithoutContext('replace when api 17', () { const String minSdkVersion17 = 'minSdkVersion 17'; project.appGradleFile.writeAsStringSync(sampleModuleGradleBuildFile(minSdkVersion17)); migration.migrate(); expect(project.appGradleFile.readAsStringSync(), sampleModuleGradleBuildFile(replacementMinSdkText)); });
testWithoutContext('replace when api 18', () { const String minSdkVersion18 = 'minSdkVersion 18'; project.appGradleFile.writeAsStringSync(sampleModuleGradleBuildFile(minSdkVersion18)); migration.migrate(); expect(project.appGradleFile.readAsStringSync(), sampleModuleGradleBuildFile(replacementMinSdkText)); });
testWithoutContext('do nothing when >=api 19', () { const String minSdkVersion19 = 'minSdkVersion 19'; project.appGradleFile.writeAsStringSync(sampleModuleGradleBuildFile(minSdkVersion19)); migration.migrate(); expect(project.appGradleFile.readAsStringSync(), sampleModuleGradleBuildFile(minSdkVersion19)); });
testWithoutContext('do nothing when already using ' 'flutter.minSdkVersion', () { project.appGradleFile.writeAsStringSync(sampleModuleGradleBuildFile(replacementMinSdkText)); migration.migrate(); expect(project.appGradleFile.readAsStringSync(), sampleModuleGradleBuildFile(replacementMinSdkText)); });
testWithoutContext('avoid rewriting comments', () { const String code = '// minSdkVersion 16 // old default\n' ' minSdkVersion 23 // new version'; project.appGradleFile.writeAsStringSync(sampleModuleGradleBuildFile(code)); migration.migrate(); expect(project.appGradleFile.readAsStringSync(), sampleModuleGradleBuildFile(code)); });
testWithoutContext('do nothing when project is a module', () { project = FakeAndroidProject( root: memoryFileSystem.currentDirectory.childDirectory('android'), module: true, ); migration = MinSdkVersionMigration( project, bufferLogger ); const String minSdkVersion16 = 'minSdkVersion 16'; project.appGradleFile.writeAsStringSync(sampleModuleGradleBuildFile(minSdkVersion16)); migration.migrate(); expect(project.appGradleFile.readAsStringSync(), sampleModuleGradleBuildFile(minSdkVersion16)); });
testWithoutContext('do nothing when minSdkVersion is set ' 'to a constant', () { const String minSdkVersionConstant = 'minSdkVersion kMinSdkversion'; project.appGradleFile.writeAsStringSync(sampleModuleGradleBuildFile(minSdkVersionConstant)); migration.migrate(); expect(project.appGradleFile.readAsStringSync(), sampleModuleGradleBuildFile(minSdkVersionConstant)); });
testWithoutContext('do nothing when minSdkVersion is set ' 'using = syntax', () { const String equalsSyntaxMinSdkVersion16 = 'minSdkVersion = 16'; project.appGradleFile.writeAsStringSync(sampleModuleGradleBuildFile(equalsSyntaxMinSdkVersion16)); migration.migrate(); expect(project.appGradleFile.readAsStringSync(), sampleModuleGradleBuildFile(equalsSyntaxMinSdkVersion16)); }); }); });}
class FakeAndroidProject extends Fake implements AndroidProject { FakeAndroidProject({required Directory root, this.module, this.plugin}) : hostAppGradleRoot = root;
@override Directory hostAppGradleRoot;
final bool? module; final bool? plugin;
@override bool get isPlugin => plugin ?? false;
@override bool get isModule => module ?? false;
@override File get appGradleFile => hostAppGradleRoot.childDirectory('app').childFile('build.gradle');}
class FakeAndroidStudio extends Fake implements AndroidStudio { FakeAndroidStudio({required Version? version}) { _version = version; }
late Version? _version;
@override Version? get version => _version;}
class FakeErroringJava extends FakeJava { @override Version get version { throw Exception('How did this happen?'); }}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152// 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 'package:flutter_tools/src/base/io.dart';import 'package:flutter_tools/src/base/logger.dart';import 'package:flutter_tools/src/cache.dart';import 'package:flutter_tools/src/devtools_launcher.dart';import 'package:flutter_tools/src/resident_runner.dart';
import '../src/common.dart';import '../src/fake_process_manager.dart';import '../src/fakes.dart';
void main() { late BufferLogger logger;
Cache.flutterRoot = '';
setUp(() { logger = BufferLogger.test(); });
testWithoutContext('DevtoolsLauncher launches DevTools from the SDK and saves the URI', () async { final Completer<void> completer = Completer<void>(); final DevtoolsLauncher launcher = DevtoolsServerLauncher( dartExecutable: 'dart', logger: logger, botDetector: const FakeBotDetector(false), processManager: FakeProcessManager.list(<FakeCommand>[ FakeCommand( command: const <String>[ 'dart', 'devtools', '--no-launch-browser', ], stdout: 'Serving DevTools at http://127.0.0.1:9100\n', completer: completer, ), ]), );
final DevToolsServerAddress? address = await launcher.serve(); expect(address?.host, '127.0.0.1'); expect(address?.port, 9100); });
testWithoutContext('DevtoolsLauncher does not launch a new DevTools instance if one is already active', () async { final Completer<void> completer = Completer<void>(); final DevtoolsLauncher launcher = DevtoolsServerLauncher( dartExecutable: 'dart', logger: logger, botDetector: const FakeBotDetector(false), processManager: FakeProcessManager.list(<FakeCommand>[ FakeCommand( command: const <String>[ 'dart', 'devtools', '--no-launch-browser', ], stdout: 'Serving DevTools at http://127.0.0.1:9100\n', completer: completer, ), ]), );
DevToolsServerAddress? address = await launcher.serve(); expect(address?.host, '127.0.0.1'); expect(address?.port, 9100);
// Call `serve` again and verify that the already running server is returned. address = await launcher.serve(); expect(address?.host, '127.0.0.1'); expect(address?.port, 9100); });
testWithoutContext('DevtoolsLauncher can launch devtools with a memory profile', () async { final FakeProcessManager processManager = FakeProcessManager.list(<FakeCommand>[ const FakeCommand( command: <String>[ 'dart', 'devtools', '--no-launch-browser', '--vm-uri=localhost:8181/abcdefg', '--profile-memory=foo', ], stdout: 'Serving DevTools at http://127.0.0.1:9100\n', ), ]); final DevtoolsLauncher launcher = DevtoolsServerLauncher( dartExecutable: 'dart', logger: logger, botDetector: const FakeBotDetector(false), processManager: processManager, );
await launcher.launch(Uri.parse('localhost:8181/abcdefg'), additionalArguments: <String>['--profile-memory=foo']);
expect(launcher.processStart, completes); expect(processManager, hasNoRemainingExpectations); });
testWithoutContext('DevtoolsLauncher prints error if exception is thrown during launch', () async { final DevtoolsLauncher launcher = DevtoolsServerLauncher( dartExecutable: 'dart', logger: logger, botDetector: const FakeBotDetector(false), processManager: FakeProcessManager.list(<FakeCommand>[ const FakeCommand( command: <String>[ 'dart', 'devtools', '--no-launch-browser', '--vm-uri=http://127.0.0.1:1234/abcdefg', ], exception: ProcessException('pub', <String>[]), ), ]), );
await launcher.launch(Uri.parse('http://127.0.0.1:1234/abcdefg'));
expect(logger.errorText, contains('Failed to launch DevTools: ProcessException')); });
testWithoutContext('DevtoolsLauncher handles failure of DevTools process on a bot', () async { final Completer<void> completer = Completer<void>(); final DevtoolsServerLauncher launcher = DevtoolsServerLauncher( dartExecutable: 'dart', logger: logger, botDetector: const FakeBotDetector(true), processManager: FakeProcessManager.list(<FakeCommand>[ FakeCommand( command: const <String>[ 'dart', 'devtools', '--no-launch-browser', ], stdout: 'Serving DevTools at http://127.0.0.1:9100\n', completer: completer, exitCode: 255, ), ]), );
await launcher.launch(null); completer.complete(); expect(launcher.devToolsProcessExit, throwsToolExit()); });}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405// 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/android/android_sdk.dart';import 'package:flutter_tools/src/android/android_workflow.dart';import 'package:flutter_tools/src/base/logger.dart';import 'package:flutter_tools/src/device.dart';import 'package:flutter_tools/src/emulator.dart';import 'package:flutter_tools/src/ios/ios_emulators.dart';import 'package:flutter_tools/src/macos/xcode.dart';import 'package:test/fake.dart';
import '../src/common.dart';import '../src/context.dart';import '../src/fake_process_manager.dart';import '../src/fakes.dart';
const FakeEmulator emulator1 = FakeEmulator('Nexus_5', 'Nexus 5', 'Google');const FakeEmulator emulator2 = FakeEmulator('Nexus_5X_API_27_x86', 'Nexus 5X', 'Google');const FakeEmulator emulator3 = FakeEmulator('iOS Simulator', 'iOS Simulator', 'Apple');const List<Emulator> emulators = <Emulator>[ emulator1, emulator2, emulator3,];
// We have to send a command that fails in order to get the list of valid// system images paths. This is an example of the output to use in the fake.const String fakeCreateFailureOutput = 'Error: Package path (-k) not specified. Valid system image paths are:\n' 'system-images;android-27;google_apis;x86\n' 'system-images;android-P;google_apis;x86\n' 'system-images;android-27;google_apis_playstore;x86\n' 'null\n'; // Yep, these really end with null (on dantup's machine at least)
const FakeCommand kListEmulatorsCommand = FakeCommand( command: <String>['avdmanager', 'create', 'avd', '-n', 'temp'], stderr: fakeCreateFailureOutput, exitCode: 1,);
void main() { late FakeProcessManager fakeProcessManager; late FakeAndroidSdk sdk; late FileSystem fileSystem; late Xcode xcode;
setUp(() { fileSystem = MemoryFileSystem.test(); fakeProcessManager = FakeProcessManager.empty(); sdk = FakeAndroidSdk(); xcode = Xcode.test(processManager: fakeProcessManager, fileSystem: fileSystem);
sdk ..avdManagerPath = 'avdmanager' ..emulatorPath = 'emulator' ..adbPath = 'adb'; });
group('EmulatorManager', () { // iOS discovery uses context. testUsingContext('getEmulators', () async { // Test that EmulatorManager.getEmulators() doesn't throw. final EmulatorManager emulatorManager = EmulatorManager( java: FakeJava(), fileSystem: MemoryFileSystem.test(), logger: BufferLogger.test(), processManager: FakeProcessManager.list(<FakeCommand>[ const FakeCommand( command: <String>['emulator', '-list-avds'], stdout: 'existing-avd-1', ), ]), androidSdk: sdk, androidWorkflow: AndroidWorkflow( androidSdk: sdk, featureFlags: TestFeatureFlags(), ), );
await expectLater(() async => emulatorManager.getAllAvailableEmulators(), returnsNormally); });
testUsingContext('getEmulators with no Android SDK', () async { // Test that EmulatorManager.getEmulators() doesn't throw when there's no Android SDK. final EmulatorManager emulatorManager = EmulatorManager( java: FakeJava(), fileSystem: MemoryFileSystem.test(), logger: BufferLogger.test(), processManager: FakeProcessManager.list(<FakeCommand>[ const FakeCommand( command: <String>['emulator', '-list-avds'], stdout: 'existing-avd-1', ), ]), androidWorkflow: AndroidWorkflow( androidSdk: sdk, featureFlags: TestFeatureFlags(), ), );
await expectLater(() async => emulatorManager.getAllAvailableEmulators(), returnsNormally); });
testWithoutContext('getEmulatorsById', () async { final TestEmulatorManager testEmulatorManager = TestEmulatorManager(emulators, java: FakeJava(), logger: BufferLogger.test(), processManager: fakeProcessManager, androidWorkflow: AndroidWorkflow( androidSdk: sdk, featureFlags: TestFeatureFlags(), ), fileSystem: fileSystem, );
expect(await testEmulatorManager.getEmulatorsMatching('Nexus_5'), <Emulator>[emulator1]); expect(await testEmulatorManager.getEmulatorsMatching('Nexus_5X'), <Emulator>[emulator2]); expect(await testEmulatorManager.getEmulatorsMatching('Nexus_5X_API_27_x86'), <Emulator>[emulator2]); expect(await testEmulatorManager.getEmulatorsMatching('Nexus'), <Emulator>[emulator1, emulator2]); expect(await testEmulatorManager.getEmulatorsMatching('iOS Simulator'), <Emulator>[emulator3]); expect(await testEmulatorManager.getEmulatorsMatching('ios'), <Emulator>[emulator3]); });
testUsingContext('create emulator with a missing avdmanager does not crash.', () async { sdk.avdManagerPath = null; final EmulatorManager emulatorManager = EmulatorManager( java: FakeJava(), fileSystem: MemoryFileSystem.test(), logger: BufferLogger.test(), processManager: FakeProcessManager.list(<FakeCommand>[ const FakeCommand( command: <String>['emulator', '-list-avds'], stdout: 'existing-avd-1', ), ]), androidSdk: sdk, androidWorkflow: AndroidWorkflow( androidSdk: sdk, featureFlags: TestFeatureFlags(), ), ); final CreateEmulatorResult result = await emulatorManager.createEmulator();
expect(result.success, false); expect(result.error, contains('avdmanager is missing from the Android SDK')); });
// iOS discovery uses context. testUsingContext('create emulator with an empty name does not fail', () async { final EmulatorManager emulatorManager = EmulatorManager( java: FakeJava(), fileSystem: MemoryFileSystem.test(), logger: BufferLogger.test(), processManager: FakeProcessManager.list(<FakeCommand>[ const FakeCommand( command: <String>['emulator', '-list-avds'], stdout: 'existing-avd-1', ), const FakeCommand( command: <String>['avdmanager', 'list', 'device', '-c'], stdout: 'test\ntest2\npixel\npixel-xl\n', ), kListEmulatorsCommand, const FakeCommand( command: <String>[ 'avdmanager', 'create', 'avd', '-n', 'flutter_emulator', '-k', 'system-images;android-27;google_apis_playstore;x86', '-d', 'pixel', ], ), ]), androidSdk: sdk, androidWorkflow: AndroidWorkflow( androidSdk: sdk, featureFlags: TestFeatureFlags(), ), ); final CreateEmulatorResult result = await emulatorManager.createEmulator();
expect(result.success, true); });
testWithoutContext('create emulator with a unique name does not throw', () async { final EmulatorManager emulatorManager = EmulatorManager( java: FakeJava(), fileSystem: MemoryFileSystem.test(), logger: BufferLogger.test(), processManager: FakeProcessManager.list(<FakeCommand>[ const FakeCommand( command: <String>['avdmanager', 'list', 'device', '-c'], stdout: 'test\ntest2\npixel\npixel-xl\n', ), kListEmulatorsCommand, const FakeCommand( command: <String>[ 'avdmanager', 'create', 'avd', // The specified name is given with the -n flag. '-n', 'test', '-k', 'system-images;android-27;google_apis_playstore;x86', '-d', 'pixel', ], ), ]), androidSdk: sdk, androidWorkflow: AndroidWorkflow( androidSdk: sdk, featureFlags: TestFeatureFlags(), ), ); final CreateEmulatorResult result = await emulatorManager.createEmulator(name: 'test');
expect(result.success, true); });
testWithoutContext('create emulator with an existing name errors', () async { final EmulatorManager emulatorManager = EmulatorManager( java: FakeJava(), fileSystem: MemoryFileSystem.test(), logger: BufferLogger.test(), processManager: FakeProcessManager.list(<FakeCommand>[ const FakeCommand( command: <String>['avdmanager', 'list', 'device', '-c'], stdout: 'test\ntest2\npixel\npixel-xl\n', ), kListEmulatorsCommand, const FakeCommand( command: <String>[ 'avdmanager', 'create', 'avd', '-n', 'existing-avd-1', '-k', 'system-images;android-27;google_apis_playstore;x86', '-d', 'pixel', ], exitCode: 1, stderr: "Error: Android Virtual Device 'existing-avd-1' already exists.\n" 'Use --force if you want to replace it.', ), ]), androidSdk: sdk, androidWorkflow: AndroidWorkflow( androidSdk: sdk, featureFlags: TestFeatureFlags(), ), ); final CreateEmulatorResult result = await emulatorManager.createEmulator(name: 'existing-avd-1');
expect(result.success, false); });
// iOS discovery uses context. testUsingContext('create emulator without a name but when default exists adds a suffix', () async { final EmulatorManager emulatorManager = EmulatorManager( java: FakeJava(), fileSystem: MemoryFileSystem.test(), logger: BufferLogger.test(), processManager: FakeProcessManager.list(<FakeCommand>[ const FakeCommand( command: <String>['emulator', '-list-avds'], stdout: 'existing-avd-1\nflutter_emulator', ), const FakeCommand( command: <String>['avdmanager', 'list', 'device', '-c'], stdout: 'test\ntest2\npixel\npixel-xl\n', ), kListEmulatorsCommand, const FakeCommand( command: <String>[ 'avdmanager', 'create', 'avd', // a "_2" suffix is added to disambiguate from the existing emulator. '-n', 'flutter_emulator_2', '-k', 'system-images;android-27;google_apis_playstore;x86', '-d', 'pixel', ], ), ]), androidSdk: sdk, androidWorkflow: AndroidWorkflow( androidSdk: sdk, featureFlags: TestFeatureFlags(), ), ); final CreateEmulatorResult result = await emulatorManager.createEmulator();
expect(result.success, true); expect(result.emulatorName, 'flutter_emulator_2'); }); });
group('ios_emulators', () { testUsingContext('runs correct launch commands', () async { fileSystem.directory('/fake/Xcode.app/Contents/Developer/Applications/Simulator.app').createSync(recursive: true); fakeProcessManager.addCommands( <FakeCommand>[ const FakeCommand( command: <String>['/usr/bin/xcode-select', '--print-path'], stdout: '/fake/Xcode.app/Contents/Developer', ), const FakeCommand(command: <String>[ 'open', '-n', '-a', '/fake/Xcode.app/Contents/Developer/Applications/Simulator.app', ]), const FakeCommand(command: <String>[ 'open', '-a', '/fake/Xcode.app/Contents/Developer/Applications/Simulator.app', ]), ], );
const Emulator emulator = IOSEmulator('ios'); await emulator.launch(); expect(fakeProcessManager, hasNoRemainingExpectations); }, overrides: <Type, Generator>{ ProcessManager: () => fakeProcessManager, Xcode: () => xcode, FileSystem: () => fileSystem, }); });}
class TestEmulatorManager extends EmulatorManager { TestEmulatorManager(this.allEmulators, { required super.java, required super.logger, required super.processManager, required super.androidWorkflow, required super.fileSystem, });
final List<Emulator> allEmulators;
@override Future<List<Emulator>> getAllAvailableEmulators() { return Future<List<Emulator>>.value(allEmulators); }}
class FakeEmulator extends Emulator { const FakeEmulator(String id, this.name, this.manufacturer) : super(id, true);
@override final String name;
@override final String manufacturer;
@override Category get category => Category.mobile;
@override PlatformType get platformType => PlatformType.android;
@override Future<void> launch({bool coldBoot = false}) { throw UnimplementedError('Not implemented in Mock'); }}
class FakeAndroidSdk extends Fake implements AndroidSdk { @override String? avdManagerPath;
@override String? emulatorPath;
@override String? adbPath;
@override String? getAvdManagerPath() => avdManagerPath;
@override String getAvdPath() => 'avd';}12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697// 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, CCompilerConfig? ndkCCompilerConfigResult, }) : cCompilerConfigResult = cCompilerConfigResult ?? CCompilerConfig(), ndkCCompilerConfigResult = ndkCCompilerConfigResult ?? CCompilerConfig();
final native_assets_builder.BuildResult buildResult; final native_assets_builder.DryRunResult dryRunResult; final bool hasPackageConfigResult; final List<Package> packagesWithNativeAssetsResult; final CCompilerConfig cCompilerConfigResult; final CCompilerConfig ndkCCompilerConfigResult;
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;
@override Future<CCompilerConfig> get ndkCCompilerConfig 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;}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323// 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 'package:fake_async/fake_async.dart';import 'package:flutter_tools/src/base/io.dart';import 'package:flutter_tools/src/convert.dart' show utf8;
import '../src/common.dart';import '../src/fake_process_manager.dart';
void main() { group(FakeProcess, () { testWithoutContext('exits with specified exit code', () async { final FakeProcess process = FakeProcess(exitCode: 42); expect(await process.exitCode, 42); });
testWithoutContext('exits with specified stderr, stdout', () async { final FakeProcess process = FakeProcess( stderr: 'stderr\u{FFFD}'.codeUnits, stdout: 'stdout\u{FFFD}'.codeUnits, ); await process.exitCode;
// Verify that no encoding changes have been applied to output. // // In the past, we had hardcoded UTF-8 encoding for these streams in // FakeProcess. When a specific encoding is desired, it can be specified // on FakeCommand or in the encoding parameter of FakeProcessManager.run // or FakeProcessManager.runAsync. expect((await process.stderr.toList()).expand((List<int> x) => x), 'stderr\u{FFFD}'.codeUnits); expect((await process.stdout.toList()).expand((List<int> x) => x), 'stdout\u{FFFD}'.codeUnits); });
testWithoutContext('exits after specified delay (if no completer specified)', () { final bool done = FakeAsync().run<bool>((FakeAsync time) { final FakeProcess process = FakeProcess( duration: const Duration(seconds: 30), );
bool hasExited = false; unawaited(process.exitCode.then((int _) { hasExited = true; }));
// Verify process hasn't exited before specified delay. time.elapse(const Duration(seconds: 15)); expect(hasExited, isFalse);
// Verify process has exited after specified delay. time.elapse(const Duration(seconds: 20)); expect(hasExited, isTrue);
return true; }); expect(done, isTrue); });
testWithoutContext('exits when completer completes (if no duration specified)', () { final bool done = FakeAsync().run<bool>((FakeAsync time) { final Completer<void> completer = Completer<void>(); final FakeProcess process = FakeProcess( completer: completer, );
bool hasExited = false; unawaited(process.exitCode.then((int _) { hasExited = true; }));
// Verify process hasn't exited when all async tasks flushed. time.elapse(Duration.zero); expect(hasExited, isFalse);
// Verify process has exited after completer completes. completer.complete(); time.flushMicrotasks(); expect(hasExited, isTrue);
return true; }); expect(done, isTrue); });
testWithoutContext('when completer and duration are specified, does not exit until completer is completed', () { final bool done = FakeAsync().run<bool>((FakeAsync time) { final Completer<void> completer = Completer<void>(); final FakeProcess process = FakeProcess( duration: const Duration(seconds: 30), completer: completer, );
bool hasExited = false; unawaited(process.exitCode.then((int _) { hasExited = true; }));
// Verify process hasn't exited before specified delay. time.elapse(const Duration(seconds: 15)); expect(hasExited, isFalse);
// Verify process hasn't exited until the completer completes. time.elapse(const Duration(seconds: 20)); expect(hasExited, isFalse);
// Verify process exits after the completer completes. completer.complete(); time.flushMicrotasks(); expect(hasExited, isTrue);
return true; }); expect(done, isTrue); });
testWithoutContext('when completer and duration are specified, does not exit until duration has elapsed', () { final bool done = FakeAsync().run<bool>((FakeAsync time) { final Completer<void> completer = Completer<void>(); final FakeProcess process = FakeProcess( duration: const Duration(seconds: 30), completer: completer, );
bool hasExited = false; unawaited(process.exitCode.then((int _) { hasExited = true; }));
// Verify process hasn't exited before specified delay. time.elapse(const Duration(seconds: 15)); expect(hasExited, isFalse);
// Verify process does not exit until duration has elapsed. completer.complete(); expect(hasExited, isFalse);
// Verify process exits after the duration elapses. time.elapse(const Duration(seconds: 20)); expect(hasExited, isTrue);
return true; }); expect(done, isTrue); });
testWithoutContext('process exit is asynchronous', () async { final FakeProcess process = FakeProcess();
bool hasExited = false; unawaited(process.exitCode.then((int _) { hasExited = true; }));
// Verify process hasn't completed. expect(hasExited, isFalse);
// Flush async tasks. Verify process completes. await Future<void>.delayed(Duration.zero); expect(hasExited, isTrue); });
testWithoutContext('stderr, stdout stream data after exit when outputFollowsExit is true', () async { final FakeProcess process = FakeProcess( stderr: 'stderr'.codeUnits, stdout: 'stdout'.codeUnits, outputFollowsExit: true, );
final List<int> stderr = <int>[]; final List<int> stdout = <int>[]; process.stderr.listen(stderr.addAll); process.stdout.listen(stdout.addAll);
// Ensure that no bytes have been received at process exit. await process.exitCode; expect(stderr, isEmpty); expect(stdout, isEmpty);
// Flush all remaining async work. Ensure stderr, stdout is received. await Future<void>.delayed(Duration.zero); expect(stderr, 'stderr'.codeUnits); expect(stdout, 'stdout'.codeUnits); }); });
group(FakeProcessManager, () { late FakeProcessManager manager;
setUp(() { manager = FakeProcessManager.empty(); });
group('start', () { testWithoutContext('can run a fake command', () async { manager.addCommand(const FakeCommand(command: <String>['faketool']));
final Process process = await manager.start(<String>['faketool']); expect(await process.exitCode, 0); expect(await utf8.decodeStream(process.stdout), isEmpty); expect(await utf8.decodeStream(process.stderr), isEmpty); });
testWithoutContext('outputFollowsExit delays stderr, stdout until after process exit', () async { manager.addCommand(const FakeCommand( command: <String>['faketool'], stderr: 'hello', stdout: 'world', outputFollowsExit: true, ));
final List<int> stderrBytes = <int>[]; final List<int> stdoutBytes = <int>[];
// Start the process. final Process process = await manager.start(<String>['faketool']); final StreamSubscription<List<int>> stderrSubscription = process.stderr.listen((List<int> chunk) { stderrBytes.addAll(chunk); }); final StreamSubscription<List<int>> stdoutSubscription = process.stdout.listen((List<int> chunk) { stdoutBytes.addAll(chunk); });
// Immediately after exit, no output is emitted. await process.exitCode; expect(utf8.decode(stderrBytes), isEmpty); expect(utf8.decode(stdoutBytes), isEmpty);
// Output is emitted asynchronously after process exit. await Future.wait(<Future<void>>[ stderrSubscription.asFuture(), stdoutSubscription.asFuture(), ]); expect(utf8.decode(stderrBytes), 'hello'); expect(utf8.decode(stdoutBytes), 'world');
// Clean up stream subscriptions. await stderrSubscription.cancel(); await stdoutSubscription.cancel(); }); });
group('run', () { testWithoutContext('can run a fake command', () async { manager.addCommand(const FakeCommand(command: <String>['faketool']));
final ProcessResult result = await manager.run(<String>['faketool']); expect(result.exitCode, 0); expect(result.stdout, isEmpty); expect(result.stderr, isEmpty); });
testWithoutContext('stderr, stdout are String if encoding is unspecified', () async { manager.addCommand(const FakeCommand(command: <String>['faketool']));
final ProcessResult result = await manager.run(<String>['faketool']); expect(result.exitCode, 0); expect(result.stdout, isA<String>()); expect(result.stderr, isA<String>()); });
testWithoutContext('stderr, stdout are List<int> if encoding is null', () async { manager.addCommand(const FakeCommand(command: <String>['faketool']));
final ProcessResult result = await manager.run( <String>['faketool'], stderrEncoding: null, stdoutEncoding: null, ); expect(result.exitCode, 0); expect(result.stdout, isA<List<int>>()); expect(result.stderr, isA<List<int>>()); });
testWithoutContext('stderr, stdout are String if encoding is specified', () async { manager.addCommand(const FakeCommand(command: <String>['faketool']));
final ProcessResult result = await manager.run( <String>['faketool'], stderrEncoding: utf8, stdoutEncoding: utf8, ); expect(result.exitCode, 0); expect(result.stdout, isA<String>()); expect(result.stderr, isA<String>()); }); });
group('runSync', () { testWithoutContext('can run a fake command', () { manager.addCommand(const FakeCommand(command: <String>['faketool']));
final ProcessResult result = manager.runSync(<String>['faketool']); expect(result.exitCode, 0); expect(result.stdout, isEmpty); expect(result.stderr, isEmpty); });
testWithoutContext('stderr, stdout are String if encoding is unspecified', () { manager.addCommand(const FakeCommand(command: <String>['faketool']));
final ProcessResult result = manager.runSync(<String>['faketool']); expect(result.exitCode, 0); expect(result.stdout, isA<String>()); expect(result.stderr, isA<String>()); });
testWithoutContext('stderr, stdout are List<int> if encoding is null', () { manager.addCommand(const FakeCommand(command: <String>['faketool']));
final ProcessResult result = manager.runSync( <String>['faketool'], stderrEncoding: null, stdoutEncoding: null, ); expect(result.exitCode, 0); expect(result.stdout, isA<List<int>>()); expect(result.stderr, isA<List<int>>()); });
testWithoutContext('stderr, stdout are String if encoding is specified', () { manager.addCommand(const FakeCommand(command: <String>['faketool']));
final ProcessResult result = manager.runSync( <String>['faketool'], stderrEncoding: utf8, stdoutEncoding: utf8, ); expect(result.exitCode, 0); expect(result.stdout, isA<String>()); expect(result.stderr, isA<String>()); }); }); });}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412// 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/base/config.dart';import 'package:flutter_tools/src/base/platform.dart';import 'package:flutter_tools/src/features.dart';import 'package:flutter_tools/src/flutter_features.dart';
import '../src/common.dart';import '../src/fakes.dart';
void main() { group('Features', () { late Config testConfig; late FakePlatform platform; late FlutterFeatureFlags featureFlags;
setUp(() { testConfig = Config.test(); platform = FakePlatform(environment: <String, String>{});
for (final Feature feature in allConfigurableFeatures) { testConfig.setValue(feature.configSetting!, false); }
featureFlags = FlutterFeatureFlags( flutterVersion: FakeFlutterVersion(), config: testConfig, platform: platform, ); });
FeatureFlags createFlags(String channel) { return FlutterFeatureFlags( flutterVersion: FakeFlutterVersion(branch: channel), config: testConfig, platform: platform, ); }
testWithoutContext('setting has safe defaults', () { const FeatureChannelSetting featureSetting = FeatureChannelSetting();
expect(featureSetting.available, false); expect(featureSetting.enabledByDefault, false); });
testWithoutContext('has safe defaults', () { const Feature feature = Feature(name: 'example');
expect(feature.name, 'example'); expect(feature.environmentOverride, null); expect(feature.configSetting, null); });
testWithoutContext('retrieves the correct setting for each branch', () { const FeatureChannelSetting masterSetting = FeatureChannelSetting(available: true); const FeatureChannelSetting betaSetting = FeatureChannelSetting(available: true); const FeatureChannelSetting stableSetting = FeatureChannelSetting(available: true); const Feature feature = Feature( name: 'example', master: masterSetting, beta: betaSetting, stable: stableSetting, );
expect(feature.getSettingForChannel('master'), masterSetting); expect(feature.getSettingForChannel('beta'), betaSetting); expect(feature.getSettingForChannel('stable'), stableSetting); expect(feature.getSettingForChannel('unknown'), masterSetting); });
testWithoutContext('env variables are only enabled with "true" string', () { platform.environment = <String, String>{'FLUTTER_WEB': 'hello'};
expect(featureFlags.isWebEnabled, false);
platform.environment = <String, String>{'FLUTTER_WEB': 'true'};
expect(featureFlags.isWebEnabled, true); });
testWithoutContext('Flutter web wasm only enable on master', () { expect(flutterWebWasm.getSettingForChannel('master').enabledByDefault, isTrue); expect(flutterWebWasm.getSettingForChannel('beta').enabledByDefault, isFalse); expect(flutterWebWasm.getSettingForChannel('stable').enabledByDefault, isFalse); });
testWithoutContext('Flutter web help string', () { expect(flutterWebFeature.generateHelpMessage(), 'Enable or disable Flutter for web.'); });
testWithoutContext('Flutter macOS desktop help string', () { expect(flutterMacOSDesktopFeature.generateHelpMessage(), 'Enable or disable support for desktop on macOS.'); });
testWithoutContext('Flutter Linux desktop help string', () { expect(flutterLinuxDesktopFeature.generateHelpMessage(), 'Enable or disable support for desktop on Linux.'); });
testWithoutContext('Flutter Windows desktop help string', () { expect(flutterWindowsDesktopFeature.generateHelpMessage(), 'Enable or disable support for desktop on Windows.'); });
testWithoutContext('help string on multiple channels', () { const Feature testWithoutContextFeature = Feature( name: 'example', master: FeatureChannelSetting(available: true), beta: FeatureChannelSetting(available: true), stable: FeatureChannelSetting(available: true), configSetting: 'foo', );
expect(testWithoutContextFeature.generateHelpMessage(), 'Enable or disable example.'); });
/// Flutter Web
testWithoutContext('Flutter web off by default on master', () { final FeatureFlags featureFlags = createFlags('master');
expect(featureFlags.isWebEnabled, false); });
testWithoutContext('Flutter web enabled with config on master', () { final FeatureFlags featureFlags = createFlags('master'); testConfig.setValue('enable-web', true);
expect(featureFlags.isWebEnabled, true); });
testWithoutContext('Flutter web enabled with environment variable on master', () { final FeatureFlags featureFlags = createFlags('master'); platform.environment = <String, String>{'FLUTTER_WEB': 'true'};
expect(featureFlags.isWebEnabled, true); });
testWithoutContext('Flutter web off by default on beta', () { final FeatureFlags featureFlags = createFlags('beta');
expect(featureFlags.isWebEnabled, false); });
testWithoutContext('Flutter web enabled with config on beta', () { final FeatureFlags featureFlags = createFlags('beta'); testConfig.setValue('enable-web', true);
expect(featureFlags.isWebEnabled, true); });
testWithoutContext('Flutter web not enabled with environment variable on beta', () { final FeatureFlags featureFlags = createFlags('beta'); platform.environment = <String, String>{'FLUTTER_WEB': 'true'};
expect(featureFlags.isWebEnabled, true); });
testWithoutContext('Flutter web on by default on stable', () { final FeatureFlags featureFlags = createFlags('stable'); testConfig.removeValue('enable-web');
expect(featureFlags.isWebEnabled, true); });
testWithoutContext('Flutter web enabled with config on stable', () { final FeatureFlags featureFlags = createFlags('stable'); testConfig.setValue('enable-web', true);
expect(featureFlags.isWebEnabled, true); });
testWithoutContext('Flutter web not enabled with environment variable on stable', () { final FeatureFlags featureFlags = createFlags('stable'); platform.environment = <String, String>{'FLUTTER_WEB': 'enabled'};
expect(featureFlags.isWebEnabled, false); });
/// Flutter macOS desktop.
testWithoutContext('Flutter macos desktop off by default on master', () { final FeatureFlags featureFlags = createFlags('master');
expect(featureFlags.isMacOSEnabled, false); });
testWithoutContext('Flutter macos desktop enabled with config on master', () { final FeatureFlags featureFlags = createFlags('master'); testConfig.setValue('enable-macos-desktop', true);
expect(featureFlags.isMacOSEnabled, true); });
testWithoutContext('Flutter macos desktop enabled with environment variable on master', () { final FeatureFlags featureFlags = createFlags('master'); platform.environment = <String, String>{'FLUTTER_MACOS': 'true'};
expect(featureFlags.isMacOSEnabled, true); });
testWithoutContext('Flutter macos desktop off by default on beta', () { final FeatureFlags featureFlags = createFlags('beta');
expect(featureFlags.isMacOSEnabled, false); });
testWithoutContext('Flutter macos desktop enabled with config on beta', () { final FeatureFlags featureFlags = createFlags('beta'); testConfig.setValue('enable-macos-desktop', true);
expect(featureFlags.isMacOSEnabled, true); });
testWithoutContext('Flutter macos desktop enabled with environment variable on beta', () { final FeatureFlags featureFlags = createFlags('beta'); platform.environment = <String, String>{'FLUTTER_MACOS': 'true'};
expect(featureFlags.isMacOSEnabled, true); });
testWithoutContext('Flutter macos desktop off by default on stable', () { final FeatureFlags featureFlags = createFlags('stable');
expect(featureFlags.isMacOSEnabled, false); });
testWithoutContext('Flutter macos desktop enabled with config on stable', () { final FeatureFlags featureFlags = createFlags('stable'); testConfig.setValue('enable-macos-desktop', true);
expect(featureFlags.isMacOSEnabled, true); });
testWithoutContext('Flutter macos desktop enabled with environment variable on stable', () { final FeatureFlags featureFlags = createFlags('stable'); platform.environment = <String, String>{'FLUTTER_MACOS': 'true'};
expect(featureFlags.isMacOSEnabled, true); });
/// Flutter Linux Desktop testWithoutContext('Flutter linux desktop off by default on master', () { final FeatureFlags featureFlags = createFlags('stable');
expect(featureFlags.isLinuxEnabled, false); });
testWithoutContext('Flutter linux desktop enabled with config on master', () { final FeatureFlags featureFlags = createFlags('master'); testConfig.setValue('enable-linux-desktop', true);
expect(featureFlags.isLinuxEnabled, true); });
testWithoutContext('Flutter linux desktop enabled with environment variable on master', () { final FeatureFlags featureFlags = createFlags('master'); platform.environment = <String, String>{'FLUTTER_LINUX': 'true'};
expect(featureFlags.isLinuxEnabled, true); });
testWithoutContext('Flutter linux desktop off by default on beta', () { final FeatureFlags featureFlags = createFlags('beta');
expect(featureFlags.isLinuxEnabled, false); });
testWithoutContext('Flutter linux desktop enabled with config on beta', () { final FeatureFlags featureFlags = createFlags('beta'); testConfig.setValue('enable-linux-desktop', true);
expect(featureFlags.isLinuxEnabled, true); });
testWithoutContext('Flutter linux desktop enabled with environment variable on beta', () { final FeatureFlags featureFlags = createFlags('beta'); platform.environment = <String, String>{'FLUTTER_LINUX': 'true'};
expect(featureFlags.isLinuxEnabled, true); });
testWithoutContext('Flutter linux desktop off by default on stable', () { final FeatureFlags featureFlags = createFlags('stable');
expect(featureFlags.isLinuxEnabled, false); });
testWithoutContext('Flutter linux desktop enabled with config on stable', () { final FeatureFlags featureFlags = createFlags('stable'); testConfig.setValue('enable-linux-desktop', true);
expect(featureFlags.isLinuxEnabled, true); });
testWithoutContext('Flutter linux desktop enabled with environment variable on stable', () { final FeatureFlags featureFlags = createFlags('stable'); platform.environment = <String, String>{'FLUTTER_LINUX': 'true'};
expect(featureFlags.isLinuxEnabled, true); });
/// Flutter Windows desktop. testWithoutContext('Flutter Windows desktop off by default on master', () { final FeatureFlags featureFlags = createFlags('master');
expect(featureFlags.isWindowsEnabled, false); });
testWithoutContext('Flutter Windows desktop enabled with config on master', () { final FeatureFlags featureFlags = createFlags('master'); testConfig.setValue('enable-windows-desktop', true);
expect(featureFlags.isWindowsEnabled, true); });
testWithoutContext('Flutter Windows desktop enabled with environment variable on master', () { final FeatureFlags featureFlags = createFlags('master'); platform.environment = <String, String>{'FLUTTER_WINDOWS': 'true'};
expect(featureFlags.isWindowsEnabled, true); });
testWithoutContext('Flutter Windows desktop off by default on beta', () { final FeatureFlags featureFlags = createFlags('beta');
expect(featureFlags.isWindowsEnabled, false); });
testWithoutContext('Flutter Windows desktop enabled with config on beta', () { final FeatureFlags featureFlags = createFlags('beta'); testConfig.setValue('enable-windows-desktop', true);
expect(featureFlags.isWindowsEnabled, true); });
testWithoutContext('Flutter Windows desktop enabled with environment variable on beta', () { final FeatureFlags featureFlags = createFlags('beta'); platform.environment = <String, String>{'FLUTTER_WINDOWS': 'true'};
expect(featureFlags.isWindowsEnabled, true); });
testWithoutContext('Flutter Windows desktop off by default on stable', () { final FeatureFlags featureFlags = createFlags('stable');
expect(featureFlags.isWindowsEnabled, false); });
testWithoutContext('Flutter Windows desktop enabled with config on stable', () { final FeatureFlags featureFlags = createFlags('stable'); testConfig.setValue('enable-windows-desktop', true);
expect(featureFlags.isWindowsEnabled, true); });
testWithoutContext('Flutter Windows desktop enabled with environment variable on stable', () { final FeatureFlags featureFlags = createFlags('stable'); platform.environment = <String, String>{'FLUTTER_WINDOWS': 'true'};
expect(featureFlags.isWindowsEnabled, true); });
for (final Feature feature in <Feature>[ flutterWindowsDesktopFeature, flutterMacOSDesktopFeature, flutterLinuxDesktopFeature, ]) { test('${feature.name} available and enabled by default on master', () { expect(feature.master.enabledByDefault, true); expect(feature.master.available, true); }); test('${feature.name} available and enabled by default on beta', () { expect(feature.beta.enabledByDefault, true); expect(feature.beta.available, true); }); test('${feature.name} available and enabled by default on stable', () { expect(feature.stable.enabledByDefault, true); expect(feature.stable.available, true); }); }
// Custom devices on all channels for (final String channel in <String>['master', 'beta', 'stable']) { testWithoutContext('Custom devices are enabled with flag on $channel', () { final FeatureFlags featureFlags = createFlags(channel); testConfig.setValue('enable-custom-devices', true); expect(featureFlags.areCustomDevicesEnabled, true); });
testWithoutContext('Custom devices are enabled with environment variable on $channel', () { final FeatureFlags featureFlags = createFlags(channel); platform.environment = <String, String>{'FLUTTER_CUSTOM_DEVICES': 'true'}; expect(featureFlags.areCustomDevicesEnabled, true); }); }
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); }); });}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163// 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/base/logger.dart';import 'package:flutter_tools/src/flutter_manifest.dart';
import '../src/common.dart';
void main() { group('parsing of assets section in flutter manifests', () { testWithoutContext('ignores empty list of assets', () { final BufferLogger logger = BufferLogger.test();
const String manifest = '''name: testdependencies: flutter: sdk: flutterflutter: assets: []''';
final FlutterManifest? flutterManifest = FlutterManifest.createFromString( manifest, logger: logger, );
expect(flutterManifest, isNotNull); expect(flutterManifest!.assets, isEmpty); });
testWithoutContext('parses two simple asset declarations', () async { final BufferLogger logger = BufferLogger.test(); const String manifest = '''name: testdependencies: flutter: sdk: flutterflutter: uses-material-design: true assets: - a/foo - a/bar''';
final FlutterManifest flutterManifest = FlutterManifest.createFromString( manifest, logger: logger, )!;
expect(flutterManifest.assets, <AssetsEntry>[ AssetsEntry(uri: Uri.parse('a/foo')), AssetsEntry(uri: Uri.parse('a/bar')), ]); });
testWithoutContext('does not crash on empty entry', () { final BufferLogger logger = BufferLogger.test(); const String manifest = '''name: testdependencies: flutter: sdk: flutterflutter: uses-material-design: true assets: - lib/gallery/example_code.dart -''';
FlutterManifest.createFromString( manifest, logger: logger, );
expect(logger.errorText, contains('Asset manifest contains a null or empty uri.')); });
testWithoutContext('handles special characters in asset URIs', () { final BufferLogger logger = BufferLogger.test();
const String manifest = '''name: testdependencies: flutter: sdk: flutterflutter: uses-material-design: true assets: - lib/gallery/abc#xyz - lib/gallery/abc?xyz - lib/gallery/aaa bbb''';
final FlutterManifest flutterManifest = FlutterManifest.createFromString( manifest, logger: logger, )!; final List<AssetsEntry> assets = flutterManifest.assets;
expect(assets, <AssetsEntry>[ AssetsEntry(uri: Uri.parse('lib/gallery/abc%23xyz')), AssetsEntry(uri: Uri.parse('lib/gallery/abc%3Fxyz')), AssetsEntry(uri: Uri.parse('lib/gallery/aaa%20bbb')), ]); });
testWithoutContext('parses an asset with flavors', () async { final BufferLogger logger = BufferLogger.test(); const String manifest = '''name: testdependencies: flutter: sdk: flutterflutter: uses-material-design: true assets: - path: a/foo flavors: - apple - strawberry''';
final FlutterManifest flutterManifest = FlutterManifest.createFromString( manifest, logger: logger, )!;
expect(flutterManifest.assets, <AssetsEntry>[ AssetsEntry( uri: Uri.parse('a/foo'), flavors: const <String>{'apple', 'strawberry'}, ), ]); });
testWithoutContext("prints an error when an asset entry's flavor is not a string", () async { final BufferLogger logger = BufferLogger.test();
const String manifest = '''name: testdependencies: flutter: sdk: flutterflutter: uses-material-design: true assets: - assets/folder/ - path: assets/vanilla/ flavors: - key1: value1 key2: value2'''; FlutterManifest.createFromString(manifest, logger: logger); expect(logger.errorText, contains( 'Unable to parse assets section.\n' 'In flavors section of asset "assets/vanilla/": Expected flavors ' 'to be a list of String, but element at index 0 was a YamlMap.\n' )); }); });}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166// 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/base/logger.dart';import 'package:flutter_tools/src/flutter_manifest.dart';
import '../src/common.dart';
void main() { group('parsing of assets section in flutter manifests with asset transformers', () { testWithoutContext('parses an asset with a simple transformation', () async { final BufferLogger logger = BufferLogger.test(); const String manifest = '''name: testdependencies: flutter: sdk: flutterflutter: uses-material-design: true assets: - path: asset/hello.txt transformers: - package: my_package '''; final FlutterManifest? parsedManifest = FlutterManifest.createFromString(manifest, logger: logger);
expect(parsedManifest!.assets, <AssetsEntry>[ AssetsEntry( uri: Uri.parse('asset/hello.txt'), transformers: const <AssetTransformerEntry>[ AssetTransformerEntry(package: 'my_package', args: <String>[]) ], ), ]);
expect(logger.errorText, isEmpty); });
testWithoutContext('parses an asset with a transformation that has args', () async { final BufferLogger logger = BufferLogger.test(); const String manifest = '''name: testdependencies: flutter: sdk: flutterflutter: uses-material-design: true assets: - path: asset/hello.txt transformers: - package: my_package args: ["-e", "--color", "purple"]'''; final FlutterManifest? parsedManifest = FlutterManifest.createFromString(manifest, logger: logger);
expect(parsedManifest!.assets, <AssetsEntry>[ AssetsEntry( uri: Uri.parse('asset/hello.txt'), transformers: const <AssetTransformerEntry>[ AssetTransformerEntry( package: 'my_package', args: <String>['-e', '--color', 'purple'], ) ], ), ]); expect(logger.errorText, isEmpty); });
testWithoutContext('fails when a transformers section is not a list', () async { final BufferLogger logger = BufferLogger.test(); const String manifest = '''name: testdependencies: flutter: sdk: flutterflutter: uses-material-design: true assets: - path: asset/hello.txt transformers: - my_transformer '''; FlutterManifest.createFromString(manifest, logger: logger); expect( logger.errorText, 'Unable to parse assets section.\n' 'In transformers section of asset "asset/hello.txt": Expected ' 'transformers list to be a list of Map, but element at index 0 was a String.\n', ); }); testWithoutContext('fails when a transformers section package is not a string', () async { final BufferLogger logger = BufferLogger.test();
const String manifest = '''name: testdependencies: flutter: sdk: flutterflutter: uses-material-design: true assets: - path: asset/hello.txt transformers: - package: i am a key: i am a value '''; FlutterManifest.createFromString(manifest, logger: logger); expect( logger.errorText, 'Unable to parse assets section.\n' 'In transformers section of asset "asset/hello.txt": ' 'Expected "package" to be a String. Found YamlMap instead.\n', ); });
testWithoutContext('fails when a transformer is missing the package field', () async { final BufferLogger logger = BufferLogger.test(); const String manifest = '''name: testdependencies: flutter: sdk: flutterflutter: uses-material-design: true assets: - path: asset/hello.txt transformers: - args: ["-e"] '''; FlutterManifest.createFromString(manifest, logger: logger); expect( logger.errorText, 'Unable to parse assets section.\n' 'In transformers section of asset "asset/hello.txt": Expected "package" to be a ' 'String. Found Null instead.\n', ); });
testWithoutContext('fails when a transformer has args field that is not a list of strings', () async { final BufferLogger logger = BufferLogger.test(); const String manifest = '''name: testdependencies: flutter: sdk: flutterflutter: uses-material-design: true assets: - path: asset/hello.txt transformers: - package: my_transformer args: hello '''; FlutterManifest.createFromString(manifest, logger: logger); expect( logger.errorText, 'Unable to parse assets section.\n' 'In transformers section of asset "asset/hello.txt": In args section ' 'of transformer using package "my_transformer": Expected args to be a ' 'list of String, but got hello (String).\n', ); }); });}1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558// 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/base/deferred_component.dart';import 'package:flutter_tools/src/base/file_system.dart';import 'package:flutter_tools/src/base/logger.dart';import 'package:flutter_tools/src/cache.dart';import 'package:flutter_tools/src/flutter_manifest.dart';
import '../src/common.dart';
void main() { late BufferLogger logger;
setUpAll(() { Cache.flutterRoot = getFlutterRoot(); });
setUp(() { logger = BufferLogger.test(); });
testWithoutContext('FlutterManifest is empty when the pubspec.yaml file is empty', () async { final FlutterManifest flutterManifest = FlutterManifest.createFromString( '', logger: logger, )!;
expect(flutterManifest.isEmpty, true); expect(flutterManifest.appName, ''); expect(flutterManifest.usesMaterialDesign, false); expect(flutterManifest.fontsDescriptor, isEmpty); expect(flutterManifest.fonts, isEmpty); expect(flutterManifest.assets, isEmpty); expect(flutterManifest.additionalLicenses, isEmpty); });
testWithoutContext('FlutterManifest is null when the pubspec.yaml file is not a map', () async { expect(FlutterManifest.createFromString( 'Not a map', logger: logger, ), isNull);
expect(logger.errorText, contains('Expected YAML map')); });
testWithoutContext('FlutterManifest has no fonts or assets when the "flutter" section is empty', () async { const String manifest = '''name: testdependencies: flutter: sdk: flutter'''; final FlutterManifest flutterManifest = FlutterManifest.createFromString( manifest, logger: logger, )!;
expect(flutterManifest, isNotNull); expect(flutterManifest.isEmpty, false); expect(flutterManifest.appName, 'test'); expect(flutterManifest.usesMaterialDesign, false); expect(flutterManifest.fontsDescriptor, isEmpty); expect(flutterManifest.fonts, isEmpty); expect(flutterManifest.assets, isEmpty); });
testWithoutContext('FlutterManifest knows if Material Design is used', () async { const String manifest = '''name: testdependencies: flutter: sdk: flutterflutter: uses-material-design: true'''; final FlutterManifest flutterManifest = FlutterManifest.createFromString( manifest, logger: logger, )!;
expect(flutterManifest.usesMaterialDesign, true); });
testWithoutContext('FlutterManifest knows if generate is provided', () async { const String manifest = '''name: testdependencies: flutter: sdk: flutterflutter: generate: true'''; final FlutterManifest flutterManifest = FlutterManifest.createFromString( manifest, logger: logger, )!;
expect(flutterManifest.generateSyntheticPackage, true); });
testWithoutContext('FlutterManifest can parse invalid generate key', () async { const String manifest = '''name: testdependencies: flutter: sdk: flutterflutter: generate: "invalid"'''; final FlutterManifest flutterManifest = FlutterManifest.createFromString( manifest, logger: logger, )!;
expect(flutterManifest.generateSyntheticPackage, false); });
testWithoutContext('FlutterManifest knows if generate is disabled', () async { const String manifest = '''name: testdependencies: flutter: sdk: flutterflutter: generate: false'''; final FlutterManifest flutterManifest = FlutterManifest.createFromString( manifest, logger: logger, )!;
expect(flutterManifest.generateSyntheticPackage, false); });
testWithoutContext('FlutterManifest has two assets', () async { const String manifest = '''name: testdependencies: flutter: sdk: flutterflutter: uses-material-design: true assets: - a/foo - a/bar''';
final FlutterManifest flutterManifest = FlutterManifest.createFromString( manifest, logger: logger, )!;
expect(flutterManifest.assets, <AssetsEntry>[ AssetsEntry(uri: Uri.parse('a/foo')), AssetsEntry(uri: Uri.parse('a/bar')), ]); });
testWithoutContext('FlutterManifest assets entry flavor is not a string', () async { const String manifest = '''name: testdependencies: flutter: sdk: flutterflutter: uses-material-design: true assets: - assets/folder/ - path: assets/vanilla/ flavors: - key1: value1 key2: value2'''; FlutterManifest.createFromString(manifest, logger: logger); expect(logger.errorText, contains('Asset manifest entry is malformed. ' 'Expected "flavors" entry to be a list of strings.')); });
testWithoutContext('FlutterManifest has one font family with one asset', () async { const String manifest = '''name: testdependencies: flutter: sdk: flutterflutter: uses-material-design: true fonts: - family: foo fonts: - asset: a/bar''';
final FlutterManifest flutterManifest = FlutterManifest.createFromString( manifest, logger: logger, )!;
expect(flutterManifest.fonts, hasLength(1)); expect(flutterManifest.fonts.single, matchesFont( familyName: 'foo', descriptor: <String, Object>{ 'family': 'foo', 'fonts': <Object>[ <String, Object>{'asset': 'a/bar'}, ], }, fontAssets: <Matcher>[ matchesFontAsset(assetUri: Uri.parse('a/bar')), ], )); });
testWithoutContext('FlutterManifest has one font family with a simple asset ' 'and one with weight', () async { const String manifest = '''name: testdependencies: flutter: sdk: flutterflutter: uses-material-design: true fonts: - family: foo fonts: - asset: a/bar - asset: a/bar weight: 400''';
final FlutterManifest flutterManifest = FlutterManifest.createFromString( manifest, logger: logger, )!;
expect(flutterManifest.fonts, hasLength(1)); expect(flutterManifest.fonts.single, matchesFont( familyName: 'foo', descriptor: <String, Object>{ 'family': 'foo', 'fonts': <Object>[ <String, Object>{'asset': 'a/bar'}, <String, Object>{'weight': 400, 'asset': 'a/bar'}, ], }, fontAssets: <Matcher>[ matchesFontAsset(assetUri: Uri.parse('a/bar')), matchesFontAsset(assetUri: Uri.parse('a/bar'), weight: 400), ]) ); });
testWithoutContext('FlutterManifest has one font family with a simple asset ' 'and one with weight and style', () { const String manifest = '''name: testdependencies: flutter: sdk: flutterflutter: uses-material-design: true fonts: - family: foo fonts: - asset: a/bar - asset: a/bar weight: 400 style: italic''';
final FlutterManifest flutterManifest = FlutterManifest.createFromString( manifest, logger: logger, )!;
expect(flutterManifest.fonts, hasLength(1)); expect(flutterManifest.fonts.single, matchesFont( familyName: 'foo', descriptor: <String, Object>{ 'family': 'foo', 'fonts': <Object>[ <String, Object>{'asset': 'a/bar'}, <String, Object>{'weight': 400, 'style': 'italic', 'asset': 'a/bar'}, ], }, fontAssets: <Matcher>[ matchesFontAsset(assetUri: Uri.parse('a/bar')), matchesFontAsset(assetUri: Uri.parse('a/bar'), weight: 400, style: 'italic'), ], )); });
testWithoutContext('FlutterManifest has two font families, each with one ' 'simple asset and one with weight and style', () { const String manifest = '''name: testdependencies: flutter: sdk: flutterflutter: uses-material-design: true fonts: - family: foo fonts: - asset: a/bar - asset: a/bar weight: 400 style: italic - family: bar fonts: - asset: a/baz - weight: 400 asset: a/baz style: italic''';
final FlutterManifest flutterManifest = FlutterManifest.createFromString( manifest, logger: logger, )!;
expect(flutterManifest.fonts, hasLength(2)); expect(flutterManifest.fonts, containsAll(<Matcher>[ matchesFont( familyName: 'foo', descriptor: <String, Object>{ 'family': 'foo', 'fonts': <Object>[ <String, Object>{'asset': 'a/bar'}, <String, Object>{'weight': 400, 'style': 'italic', 'asset': 'a/bar'}, ], }, fontAssets: <Matcher>[ matchesFontAsset(assetUri: Uri.parse('a/bar')), matchesFontAsset(assetUri: Uri.parse('a/bar'), weight: 400, style: 'italic'), ], ), matchesFont( familyName: 'bar', descriptor: <String, Object>{ 'family': 'bar', 'fonts': <Object>[ <String, Object>{'asset': 'a/baz'}, <String, Object>{'weight': 400, 'style': 'italic', 'asset': 'a/baz'}, ], }, fontAssets: <Matcher>[ matchesFontAsset(assetUri: Uri.parse('a/baz')), matchesFontAsset(assetUri: Uri.parse('a/baz'), weight: 400, style: 'italic'), ], ), ])); });
testWithoutContext('FlutterManifest.fontsDescriptor combines descriptors from ' 'individual fonts', () { const String manifest = '''name: testdependencies: flutter: sdk: flutterflutter: uses-material-design: true fonts: - family: foo fonts: - asset: a/bar - asset: a/bar weight: 400 style: italic - family: bar fonts: - asset: a/baz - weight: 400 asset: a/baz style: italic''';
final FlutterManifest flutterManifest = FlutterManifest.createFromString( manifest, logger: logger, )!;
expect(flutterManifest.fontsDescriptor, <Object>[ <String, Object>{ 'family': 'foo', 'fonts': <Object>[ <String, Object>{'asset': 'a/bar'}, <String, Object>{'weight': 400, 'style': 'italic', 'asset': 'a/bar'}, ], }, <String, Object>{ 'family': 'bar', 'fonts': <Object>[ <String, Object>{'asset': 'a/baz'}, <String, Object>{'weight': 400, 'style': 'italic', 'asset': 'a/baz'}, ], }, ]); });
testWithoutContext('FlutterManifest has only one of two font families when ' 'one declaration is missing the "family" option', () async { const String manifest = '''name: testdependencies: flutter: sdk: flutterflutter: uses-material-design: true fonts: - family: foo fonts: - asset: a/bar - asset: a/bar weight: 400 style: italic - fonts: - asset: a/baz - asset: a/baz weight: 400 style: italic''';
final FlutterManifest flutterManifest = FlutterManifest.createFromString( manifest, logger: logger, )!;
expect(flutterManifest.fonts, hasLength(1)); expect(flutterManifest.fonts, containsAll(<Matcher>[ matchesFont( familyName: 'foo', descriptor: <String, Object>{ 'family': 'foo', 'fonts': <Object>[ <String, Object>{'asset': 'a/bar'}, <String, Object>{'weight': 400, 'style': 'italic', 'asset': 'a/bar'}, ], }, fontAssets: <Matcher>[ matchesFontAsset(assetUri: Uri.parse('a/bar')), matchesFontAsset(assetUri: Uri.parse('a/bar'), weight: 400, style: 'italic'), ], ), ])); });
testWithoutContext('FlutterManifest has only one of two font families when ' 'one declaration is missing the "fonts" option', () async { const String manifest = '''name: testdependencies: flutter: sdk: flutterflutter: uses-material-design: true fonts: - family: foo fonts: - asset: a/bar - asset: a/bar weight: 400 style: italic - family: bar''';
final FlutterManifest flutterManifest = FlutterManifest.createFromString( manifest, logger: logger, )!;
expect(flutterManifest.fonts, hasLength(1)); expect(flutterManifest.fonts, containsAll(<Matcher>[ matchesFont( familyName: 'foo', descriptor: <String, Object>{ 'family': 'foo', 'fonts': <Object>[ <String, Object>{'asset': 'a/bar'}, <String, Object>{'weight': 400, 'style': 'italic', 'asset': 'a/bar'}, ], }, fontAssets: <Matcher>[ matchesFontAsset(assetUri: Uri.parse('a/bar')), matchesFontAsset(assetUri: Uri.parse('a/bar'), weight: 400, style: 'italic'), ], ), ])); });
testWithoutContext('FlutterManifest has no font family when declaration is ' 'missing the "asset" option', () async { const String manifest = '''name: testdependencies: flutter: sdk: flutterflutter: uses-material-design: true fonts: - family: foo fonts: - weight: 400''';
final FlutterManifest flutterManifest = FlutterManifest.createFromString( manifest, logger: logger, )!;
expect(flutterManifest.fontsDescriptor, isEmpty); expect(flutterManifest.fonts, isEmpty); });
testWithoutContext('FlutterManifest allows a blank flutter section', () { const String manifest = '''name: testdependencies: flutter: sdk: flutterflutter:''';
final FlutterManifest flutterManifest = FlutterManifest.createFromString( manifest, logger: logger, )!;
expect(flutterManifest.isEmpty, false); expect(flutterManifest.isModule, false); expect(flutterManifest.isPlugin, false); expect(flutterManifest.androidPackage, null); expect(flutterManifest.usesAndroidX, false); });
testWithoutContext('FlutterManifest allows a module declaration', () { const String manifest = '''name: testflutter: module: androidPackage: com.example androidX: true''';
final FlutterManifest flutterManifest = FlutterManifest.createFromString( manifest, logger: logger, )!;
expect(flutterManifest.isModule, true); expect(flutterManifest.androidPackage, 'com.example'); expect(flutterManifest.usesAndroidX, true); });
testWithoutContext('FlutterManifest allows a legacy plugin declaration', () { const String manifest = '''name: testflutter: plugin: androidPackage: com.example''';
final FlutterManifest flutterManifest = FlutterManifest.createFromString( manifest, logger: logger, )!;
expect(flutterManifest.isPlugin, true); expect(flutterManifest.androidPackage, 'com.example'); });
testWithoutContext('FlutterManifest allows a multi-plat plugin declaration ' 'with android only', () { const String manifest = '''name: testflutter: plugin: platforms: android: package: com.example pluginClass: TestPlugin''';
final FlutterManifest flutterManifest = FlutterManifest.createFromString( manifest, logger: logger, )!;
expect(flutterManifest.isPlugin, true); expect(flutterManifest.androidPackage, 'com.example'); });
testWithoutContext('FlutterManifest allows a multi-plat plugin declaration ' 'with ios only', () { const String manifest = '''name: testflutter: plugin: platforms: ios: pluginClass: HelloPlugin''';
final FlutterManifest flutterManifest = FlutterManifest.createFromString( manifest, logger: logger, )!;
expect(flutterManifest.isPlugin, true); expect(flutterManifest.androidPackage, isNull); });
testWithoutContext('FlutterManifest handles an invalid plugin declaration', () { const String manifest = '''name: testflutter: plugin:''';
final FlutterManifest? flutterManifest = FlutterManifest.createFromString( manifest, logger: logger, );
expect(flutterManifest, null); expect(logger.errorText, contains('Expected "plugin" to be an object, but got null')); });
testWithoutContext('FlutterManifest parses major.minor.patch+build version clause 1', () { const String manifest = '''name: testversion: 1.0.0+2dependencies: flutter: sdk: flutterflutter:''';
final FlutterManifest? flutterManifest = FlutterManifest.createFromString( manifest, logger: logger, );
expect(flutterManifest, matchesManifest( appVersion: '1.0.0+2', buildName: '1.0.0', buildNumber: '2', )); });
testWithoutContext('FlutterManifest parses major.minor.patch with no build version', () { const String manifest = '''name: testversion: 0.0.1dependencies: flutter: sdk: flutterflutter:''';
final FlutterManifest? flutterManifest = FlutterManifest.createFromString( manifest, logger: logger, );
expect(flutterManifest, matchesManifest( appVersion: '0.0.1', buildName: '0.0.1', )); });
testWithoutContext('FlutterManifest parses major.minor.patch+build version clause 2', () { const String manifest = '''name: testversion: 1.0.0-beta+exp.sha.5114f85dependencies: flutter: sdk: flutterflutter:''';
final FlutterManifest? flutterManifest = FlutterManifest.createFromString( manifest, logger: logger, );
expect(flutterManifest, matchesManifest( appVersion: '1.0.0-beta+exp.sha.5114f85', buildName: '1.0.0-beta', buildNumber: 'exp.sha.5114f85', )); });
testWithoutContext('FlutterManifest parses major.minor+build version clause', () { const String manifest = '''name: testversion: 1.0.0+2dependencies: flutter: sdk: flutterflutter:''';
final FlutterManifest? flutterManifest = FlutterManifest.createFromString( manifest, logger: logger, );
expect(flutterManifest, matchesManifest( appVersion: '1.0.0+2', buildName: '1.0.0', buildNumber: '2', )); });
testWithoutContext('FlutterManifest parses empty version clause', () { const String manifest = '''name: testversion:dependencies: flutter: sdk: flutterflutter:''';
final FlutterManifest? flutterManifest = FlutterManifest.createFromString( manifest, logger: logger, );
expect(flutterManifest, matchesManifest()); });
testWithoutContext('FlutterManifest parses no version clause', () { const String manifest = '''name: testdependencies: flutter: sdk: flutterflutter:''';
final FlutterManifest? flutterManifest = FlutterManifest.createFromString( manifest, logger: logger, );
expect(flutterManifest, matchesManifest()); });
// Regression test for https://github.com/flutter/flutter/issues/31764 testWithoutContext('FlutterManifest returns proper error when font detail is malformed', () { const String manifest = '''name: testdependencies: flutter: sdk: flutterflutter: fonts: - family: foo fonts: -asset: a/bar''';
final FlutterManifest? flutterManifest = FlutterManifest.createFromString( manifest, logger: logger, );
expect(flutterManifest, null); expect(logger.errorText, contains('Expected "fonts" to either be null or a list.')); });
testWithoutContext('FlutterManifest ignores empty list of fonts', () { const String manifest = '''name: testdependencies: flutter: sdk: flutterflutter: fonts: []''';
final FlutterManifest? flutterManifest = FlutterManifest.createFromString( manifest, logger: logger, );
expect(flutterManifest, isNotNull); expect(flutterManifest!.fonts.length, 0); });
testWithoutContext('FlutterManifest ignores empty list of assets', () { const String manifest = '''name: testdependencies: flutter: sdk: flutterflutter: assets: []''';
final FlutterManifest? flutterManifest = FlutterManifest.createFromString( manifest, logger: logger, );
expect(flutterManifest, isNotNull); expect(flutterManifest!.assets.length, 0); });
testWithoutContext('FlutterManifest returns proper error when font detail is ' 'not a list of maps', () { const String manifest = '''name: testdependencies: flutter: sdk: flutterflutter: fonts: - family: foo fonts: - asset''';
final FlutterManifest? flutterManifest = FlutterManifest.createFromString( manifest, logger: logger, );
expect(flutterManifest, null); expect(logger.errorText, contains('Expected "fonts" to be a list of maps.')); });
testWithoutContext('FlutterManifest returns proper error when font is a map ' 'instead of a list', () { const String manifest = '''name: testdependencies: flutter: sdk: flutterflutter: fonts: family: foo fonts: -asset: a/bar''';
final FlutterManifest? flutterManifest = FlutterManifest.createFromString( manifest, logger: logger, );
expect(flutterManifest, null); expect(logger.errorText, contains('Expected "fonts" to be a list')); });
testWithoutContext('FlutterManifest returns proper error when second font ' 'family is invalid', () { const String manifest = '''name: testdependencies: flutter: sdk: flutterflutter: uses-material-design: true fonts: - family: foo fonts: - asset: a/bar - string''';
final FlutterManifest? flutterManifest = FlutterManifest.createFromString( manifest, logger: logger, );
expect(flutterManifest, null); expect(logger.errorText, contains('Expected a map.')); });
testWithoutContext('FlutterManifest does not crash on empty entry', () { const String manifest = '''name: testdependencies: flutter: sdk: flutterflutter: uses-material-design: true assets: - lib/gallery/example_code.dart -''';
FlutterManifest.createFromString( manifest, logger: logger, );
expect(logger.errorText, contains('Asset manifest contains a null or empty uri.')); });
testWithoutContext('FlutterManifest handles special characters in asset URIs', () { const String manifest = '''name: testdependencies: flutter: sdk: flutterflutter: uses-material-design: true assets: - lib/gallery/abc#xyz - lib/gallery/abc?xyz - lib/gallery/aaa bbb''';
final FlutterManifest flutterManifest = FlutterManifest.createFromString( manifest, logger: logger, )!; final List<AssetsEntry> assets = flutterManifest.assets;
expect(assets, hasLength(3)); expect(assets, <AssetsEntry>[ AssetsEntry(uri: Uri.parse('lib/gallery/abc%23xyz')), AssetsEntry(uri: Uri.parse('lib/gallery/abc%3Fxyz')), AssetsEntry(uri: Uri.parse('lib/gallery/aaa%20bbb')), ]); });
testWithoutContext('FlutterManifest returns proper error when flutter is a ' 'list instead of a map', () { const String manifest = '''name: testdependencies: flutter: sdk: flutterflutter: - uses-material-design: true''';
final FlutterManifest? flutterManifest = FlutterManifest.createFromString( manifest, logger: logger, );
expect(flutterManifest, null); expect(logger.errorText, contains( 'Expected "flutter" section to be an object or null, but got ' '[{uses-material-design: true}].', ), ); });
testWithoutContext('FlutterManifest can parse manifest on posix filesystem', () { const String manifest = '''name: testdependencies: flutter: sdk: flutterflutter:'''; final FileSystem fileSystem = MemoryFileSystem.test(); fileSystem.file('pubspec.yaml').writeAsStringSync(manifest);
final FlutterManifest flutterManifest = FlutterManifest.createFromPath( 'pubspec.yaml', fileSystem: fileSystem, logger: logger, )!;
expect(flutterManifest.isEmpty, false); });
testWithoutContext('FlutterManifest can parse manifest on windows filesystem', () { const String manifest = '''name: testdependencies: flutter: sdk: flutterflutter:''';
final FileSystem fileSystem = MemoryFileSystem.test(style: FileSystemStyle.windows); fileSystem.file('pubspec.yaml').writeAsStringSync(manifest);
final FlutterManifest flutterManifest = FlutterManifest.createFromPath( 'pubspec.yaml', fileSystem: fileSystem, logger: logger, )!;
expect(flutterManifest.isEmpty, false); });
testWithoutContext('FlutterManifest getSupportedPlatforms return null if runs on legacy format', () { const String manifest = '''name: testflutter: plugin: androidPackage: com.example''';
final FlutterManifest flutterManifest = FlutterManifest.createFromString( manifest, logger: logger, )!;
expect(flutterManifest.isPlugin, true); expect(flutterManifest.supportedPlatforms, null); });
testWithoutContext('FlutterManifest validSupportedPlatforms return null if the platform keys are not valid', () { const String manifest = '''name: testflutter: plugin: platforms: some_platform: pluginClass: SomeClass''';
final FlutterManifest flutterManifest = FlutterManifest.createFromString( manifest, logger: logger, )!;
expect(flutterManifest.isPlugin, true); expect(flutterManifest.validSupportedPlatforms, null); });
testWithoutContext('FlutterManifest validSupportedPlatforms only returns valid platforms', () { const String manifest = '''name: testflutter: plugin: platforms: some_platform: pluginClass: SomeClass ios: pluginClass: SomeClass''';
final FlutterManifest flutterManifest = FlutterManifest.createFromString( manifest, logger: logger, )!;
expect(flutterManifest.isPlugin, true); final Map<String, dynamic> validSupportedPlatforms = flutterManifest.validSupportedPlatforms!; expect(validSupportedPlatforms['ios'], <String, dynamic>{'pluginClass': 'SomeClass'}); expect(validSupportedPlatforms['some_platform'], isNull); });
testWithoutContext('FlutterManifest getSupportedPlatforms returns valid platforms.', () { const String manifest = '''name: testflutter: plugin: platforms: android: package: com.example pluginClass: SomeClass ios: pluginClass: SomeClass''';
final FlutterManifest flutterManifest = FlutterManifest.createFromString( manifest, logger: logger, )!;
expect(flutterManifest.isPlugin, true); final Map<String, dynamic> validSupportedPlatforms = flutterManifest.validSupportedPlatforms!; expect(validSupportedPlatforms['ios'], <String, dynamic>{'pluginClass': 'SomeClass'}); expect(validSupportedPlatforms['android'], <String, dynamic>{ 'pluginClass': 'SomeClass', 'package': 'com.example', }); });
testWithoutContext('FlutterManifest validates a platform section that is a list ' 'instead of a map', () { const String manifest = '''name: testflutter: plugin: platforms: - android''';
final FlutterManifest? flutterManifest = FlutterManifest.createFromString( manifest, logger: logger, );
expect(flutterManifest, null); expect(logger.errorText, contains('flutter.plugin.platforms should be a map with the platform name as the key')); });
testWithoutContext('FlutterManifest validates plugin format not support.', () { const String manifest = '''name: testflutter: plugin: android: package: com.example pluginClass: SomeClass ios: pluginClass: SomeClass''';
final FlutterManifest? flutterManifest = FlutterManifest.createFromString( manifest, logger: logger, );
expect(flutterManifest, null); expect(logger.errorText, contains('Cannot find the `flutter.plugin.platforms` key in the `pubspec.yaml` file. ')); });
testWithoutContext('FlutterManifest handles empty licenses list', () async { const String manifest = '''name: testdependencies: flutter: sdk: flutterflutter: licenses: []''';
final FlutterManifest? flutterManifest = FlutterManifest.createFromString( manifest, logger: logger, );
expect(flutterManifest, isNotNull); expect(flutterManifest!.additionalLicenses.length, 0); });
testWithoutContext('FlutterManifest can specify additional LICENSE files', () async { const String manifest = '''name: testdependencies: flutter: sdk: flutterflutter: licenses: - foo.txt''';
final FlutterManifest flutterManifest = FlutterManifest.createFromString( manifest, logger: logger, )!;
expect(flutterManifest.additionalLicenses, <String>['foo.txt']); });
testWithoutContext('FlutterManifest can validate incorrect licenses key', () async { const String manifest = '''name: testdependencies: flutter: sdk: flutterflutter: licenses: foo.txt''';
final FlutterManifest? flutterManifest = FlutterManifest.createFromString( manifest, logger: logger, );
expect(flutterManifest, null); expect(logger.errorText, 'Expected "licenses" to be a list of files, but got foo.txt (String)\n'); });
testWithoutContext('FlutterManifest validates individual list items', () async { const String manifest = '''name: testdependencies: flutter: sdk: flutterflutter: licenses: - foo.txt - bar: fizz''';
final FlutterManifest? flutterManifest = FlutterManifest.createFromString( manifest, logger: logger, );
expect(flutterManifest, null); expect(logger.errorText, 'Expected "licenses" to be a list of files, but element 1 was a YamlMap\n'); });
testWithoutContext('FlutterManifest parses single deferred components', () async { const String manifest = '''name: testdependencies: flutter: sdk: flutterflutter: deferred-components: - name: component1 libraries: - lib1 assets: - path/to/asset.jpg''';
final FlutterManifest flutterManifest = FlutterManifest.createFromString( manifest, logger: logger, )!;
expect(flutterManifest, isNotNull); final List<DeferredComponent> deferredComponents = flutterManifest.deferredComponents!; expect(deferredComponents.length, 1); expect(deferredComponents[0].name, 'component1'); expect(deferredComponents[0].libraries.length, 1); expect(deferredComponents[0].libraries[0], 'lib1'); expect(deferredComponents[0].assets.length, 1); expect(deferredComponents[0].assets[0].uri.path, 'path/to/asset.jpg'); });
testWithoutContext('FlutterManifest parses multiple deferred components', () async { const String manifest = '''name: testdependencies: flutter: sdk: flutterflutter: deferred-components: - name: component1 libraries: - lib1 assets: - path/to/asset.jpg - name: component2 libraries: - lib2 - lib3 assets: - path/to/asset2.jpg''';
final FlutterManifest flutterManifest = FlutterManifest.createFromString( manifest, logger: logger, )!;
expect(flutterManifest, isNotNull); final List<DeferredComponent> deferredComponents = flutterManifest.deferredComponents!; expect(deferredComponents.length, 2); expect(deferredComponents[0].name, 'component1'); expect(deferredComponents[0].libraries.length, 1); expect(deferredComponents[0].libraries[0], 'lib1'); expect(deferredComponents[0].assets.length, 1); expect(deferredComponents[0].assets[0].uri.path, 'path/to/asset.jpg');
expect(deferredComponents[1].name, 'component2'); expect(deferredComponents[1].libraries.length, 2); expect(deferredComponents[1].libraries[0], 'lib2'); expect(deferredComponents[1].libraries[1], 'lib3'); expect(deferredComponents[1].assets.length, 1); expect(deferredComponents[1].assets[0].uri.path, 'path/to/asset2.jpg'); });
testWithoutContext('FlutterManifest parses empty deferred components', () async { const String manifest = '''name: testdependencies: flutter: sdk: flutterflutter: deferred-components:''';
final FlutterManifest flutterManifest = FlutterManifest.createFromString( manifest, logger: logger, )!;
expect(flutterManifest, isNotNull); expect(flutterManifest.deferredComponents!.length, 0); });
testWithoutContext('FlutterManifest deferred component requires name', () async { const String manifest = '''name: testdependencies: flutter: sdk: flutterflutter: deferred-components: - libraries: - lib1''';
final FlutterManifest? flutterManifest = FlutterManifest.createFromString( manifest, logger: logger, );
expect(flutterManifest, null); expect(logger.errorText, 'Expected the 0 element in "deferred-components" to have required key "name" of type String\n'); });
testWithoutContext('FlutterManifest deferred component is list', () async { const String manifest = '''name: testdependencies: flutter: sdk: flutterflutter: deferred-components: blah''';
final FlutterManifest? flutterManifest = FlutterManifest.createFromString( manifest, logger: logger, );
expect(flutterManifest, null); expect(logger.errorText, 'Expected "deferred-components" to be a list, but got blah (String).\n'); });
testWithoutContext('FlutterManifest deferred component libraries is list', () async { const String manifest = '''name: testdependencies: flutter: sdk: flutterflutter: deferred-components: - name: blah libraries: blah''';
final FlutterManifest? flutterManifest = FlutterManifest.createFromString( manifest, logger: logger, );
expect(flutterManifest, null); expect(logger.errorText, 'Expected "libraries" key in the 0 element of "deferred-components" to be a list, but got blah (String).\n'); });
testWithoutContext('FlutterManifest deferred component libraries is string', () async { const String manifest = '''name: testdependencies: flutter: sdk: flutterflutter: deferred-components: - name: blah libraries: - not-a-string:''';
final FlutterManifest? flutterManifest = FlutterManifest.createFromString( manifest, logger: logger, );
expect(flutterManifest, null); expect(logger.errorText, 'Expected "libraries" key in the 0 element of "deferred-components" to be a list of dart library Strings, but element 0 was a YamlMap\n'); });
testWithoutContext('FlutterManifest deferred component assets is string', () async { const String manifest = '''name: testdependencies: flutter: sdk: flutterflutter: deferred-components: - name: blah assets: - not-a-string:''';
final FlutterManifest? flutterManifest = FlutterManifest.createFromString( manifest, logger: logger, );
expect(flutterManifest, null); expect(logger.errorText, 'Asset manifest entry is malformed. Expected asset entry to be either a string or a map containing a "path" entry. Got Null instead.\n'); });
testWithoutContext('FlutterManifest deferred component multiple assets is string', () async { const String manifest = '''name: testdependencies: flutter: sdk: flutterflutter: deferred-components: - name: blah assets: - path/to/file.so - also-not-a-string: - woo''';
final FlutterManifest? flutterManifest = FlutterManifest.createFromString( manifest, logger: logger, );
expect(flutterManifest, null); expect(logger.errorText, 'Asset manifest entry is malformed. Expected asset entry to be either a string or a map containing a "path" entry. Got Null instead.\n'); });
testWithoutContext('FlutterManifest multiple deferred components assets is string', () async { const String manifest = '''name: testdependencies: flutter: sdk: flutterflutter: deferred-components: - name: blah assets: - path/to/file.so - name: blah2 assets: - path/to/other/file.so - not-a-string: - woo''';
final FlutterManifest? flutterManifest = FlutterManifest.createFromString( manifest, logger: logger, );
expect(flutterManifest, null); expect(logger.errorText, 'Asset manifest entry is malformed. Expected asset entry to be either a string or a map containing a "path" entry. Got Null instead.\n'); });
testWithoutContext('FlutterManifest deferred component assets is list', () async { const String manifest = '''name: testdependencies: flutter: sdk: flutterflutter: deferred-components: - name: blah assets: blah''';
final FlutterManifest? flutterManifest = FlutterManifest.createFromString( manifest, logger: logger, );
expect(flutterManifest, null); expect(logger.errorText, 'Expected "assets" to be a list, but got blah (String).\n'); });
testWithoutContext('FlutterManifest parses asset-only deferred components', () async { const String manifest = '''name: testdependencies: flutter: sdk: flutterflutter: deferred-components: - name: component1 assets: - path/to/asset1.jpg - path/to/asset2.jpg - path/to/asset3.jpg''';
final FlutterManifest flutterManifest = FlutterManifest.createFromString( manifest, logger: logger, )!;
expect(flutterManifest, isNotNull); final List<DeferredComponent> deferredComponents = flutterManifest.deferredComponents!; expect(deferredComponents.length, 1); expect(deferredComponents[0].name, 'component1'); expect(deferredComponents[0].libraries.length, 0); expect(deferredComponents[0].assets.length, 3); expect(deferredComponents[0].assets[0].uri.path, 'path/to/asset1.jpg'); expect(deferredComponents[0].assets[1].uri.path, 'path/to/asset2.jpg'); expect(deferredComponents[0].assets[2].uri.path, 'path/to/asset3.jpg'); });
testWithoutContext('FlutterManifest can parse empty dependencies', () async { const String manifest = '''name: test'''; final FlutterManifest? flutterManifest = FlutterManifest.createFromString( manifest, logger: BufferLogger.test(), );
expect(flutterManifest, isNotNull); expect(flutterManifest!.dependencies, isEmpty); });}
Matcher matchesManifest({ String? appVersion, String? buildName, String? buildNumber,}) { return isA<FlutterManifest>() .having((FlutterManifest manifest) => manifest.appVersion, 'appVersion', appVersion) .having((FlutterManifest manifest) => manifest.buildName, 'buildName', buildName) .having((FlutterManifest manifest) => manifest.buildNumber, 'buildNumber', buildNumber);}
Matcher matchesFontAsset({ required Uri assetUri, int? weight, String? style,}) { return isA<FontAsset>() .having((FontAsset fontAsset) => fontAsset.assetUri, 'assetUri', assetUri) .having((FontAsset fontAsset) => fontAsset.weight, 'weight', weight) .having((FontAsset fontAsset) => fontAsset.style, 'style', style);}
Matcher matchesFont({ required Map<String, Object> descriptor, required String familyName, required List<Matcher> fontAssets,}) { return isA<Font>() .having((Font font) => font.descriptor, 'descriptor', descriptor) .having((Font font) => font.familyName, 'familyName', familyName) .having((Font font) => font.fontAssets, 'fontAssets', containsAll(fontAssets));}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125// 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:flutter_tools/src/base/file_system.dart';import 'package:flutter_tools/src/base/io.dart';import 'package:flutter_tools/src/build_info.dart';import 'package:flutter_tools/src/device.dart';import 'package:flutter_tools/src/test/flutter_platform.dart';import 'package:test_core/backend.dart'; // ignore: deprecated_member_use
import '../src/common.dart';import '../src/context.dart';
void main() { late FileSystem fileSystem;
setUp(() { fileSystem = MemoryFileSystem.test(); fileSystem.file('.dart_tool/package_config.json') ..createSync(recursive: true) ..writeAsStringSync('{"configVersion":2,"packages":[]}'); });
group('FlutterPlatform', () { late SuitePlatform fakeSuitePlatform; setUp(() { fakeSuitePlatform = SuitePlatform(Runtime.vm); });
testUsingContext('ensureConfiguration throws an error if an ' 'explicitVmServicePort is specified and more than one test file', () async { final FlutterPlatform flutterPlatform = FlutterPlatform( shellPath: '/', debuggingOptions: DebuggingOptions.enabled( BuildInfo.debug, hostVmServicePort: 1234, ), enableVmService: false, ); flutterPlatform.loadChannel('test1.dart', fakeSuitePlatform);
expect(() => flutterPlatform.loadChannel('test2.dart', fakeSuitePlatform), throwsToolExit()); }, overrides: <Type, Generator>{ FileSystem: () => fileSystem, ProcessManager: () => FakeProcessManager.any(), });
testUsingContext('ensureConfiguration throws an error if a precompiled ' 'entrypoint is specified and more that one test file', () { final FlutterPlatform flutterPlatform = FlutterPlatform( debuggingOptions: DebuggingOptions.enabled(BuildInfo.debug), shellPath: '/', precompiledDillPath: 'example.dill', enableVmService: false, ); flutterPlatform.loadChannel('test1.dart', fakeSuitePlatform);
expect(() => flutterPlatform.loadChannel('test2.dart', fakeSuitePlatform), throwsToolExit()); }, overrides: <Type, Generator>{ FileSystem: () => fileSystem, ProcessManager: () => FakeProcessManager.any(), });
testUsingContext('installHook creates a FlutterPlatform', () { expect(() => installHook( shellPath: 'abc', debuggingOptions: DebuggingOptions.enabled( BuildInfo.debug, startPaused: true, ), ), throwsAssertionError);
expect(() => installHook( shellPath: 'abc', debuggingOptions: DebuggingOptions.enabled( BuildInfo.debug, startPaused: true, hostVmServicePort: 123, ), ), throwsAssertionError);
FlutterPlatform? capturedPlatform; final Map<String, String> expectedPrecompiledDillFiles = <String, String>{'Key': 'Value'}; final FlutterPlatform flutterPlatform = installHook( shellPath: 'abc', debuggingOptions: DebuggingOptions.enabled( BuildInfo.debug, startPaused: true, disableServiceAuthCodes: true, hostVmServicePort: 200, ), enableVmService: true, machine: true, precompiledDillPath: 'def', precompiledDillFiles: expectedPrecompiledDillFiles, updateGoldens: true, testAssetDirectory: '/build/test', serverType: InternetAddressType.IPv6, icudtlPath: 'ghi', platformPluginRegistration: (FlutterPlatform platform) { capturedPlatform = platform; }, uriConverter: (String input) => '$input/test', );
expect(identical(capturedPlatform, flutterPlatform), equals(true)); expect(flutterPlatform.shellPath, equals('abc')); expect(flutterPlatform.debuggingOptions.buildInfo, equals(BuildInfo.debug)); expect(flutterPlatform.debuggingOptions.startPaused, equals(true)); expect(flutterPlatform.debuggingOptions.disableServiceAuthCodes, equals(true)); expect(flutterPlatform.debuggingOptions.hostVmServicePort, equals(200)); expect(flutterPlatform.enableVmService, equals(true)); expect(flutterPlatform.machine, equals(true)); expect(flutterPlatform.host, InternetAddress.loopbackIPv6); expect(flutterPlatform.precompiledDillPath, equals('def')); expect(flutterPlatform.precompiledDillFiles, expectedPrecompiledDillFiles); expect(flutterPlatform.updateGoldens, equals(true)); expect(flutterPlatform.testAssetDirectory, '/build/test'); expect(flutterPlatform.icudtlPath, equals('ghi')); expect(flutterPlatform.uriConverter?.call('hello'), 'hello/test'); }); });}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202// 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: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; late BufferLogger logger; late File metadataFile;
setUp(() { fileSystem = MemoryFileSystem.test(); logger = BufferLogger.test(); metadataFile = fileSystem.file('.metadata'); });
testWithoutContext('project metadata fields are empty when file does not exist', () { final FlutterProjectMetadata projectMetadata = FlutterProjectMetadata(metadataFile, logger); expect(projectMetadata.projectType, isNull); expect(projectMetadata.versionChannel, isNull); expect(projectMetadata.versionRevision, isNull);
expect(logger.traceText, contains('No .metadata file found at .metadata')); });
testWithoutContext('project metadata fields are empty when file is empty', () { metadataFile.createSync(); final FlutterProjectMetadata projectMetadata = FlutterProjectMetadata(metadataFile, logger); expect(projectMetadata.projectType, isNull); expect(projectMetadata.versionChannel, isNull); expect(projectMetadata.versionRevision, isNull);
expect(logger.traceText, contains('.metadata file at .metadata was empty or malformed.')); });
testWithoutContext('project metadata fields are empty when file is not valid yaml', () { metadataFile.writeAsStringSync(' channel: @something'); final FlutterProjectMetadata projectMetadata = FlutterProjectMetadata(metadataFile, logger); expect(projectMetadata.projectType, isNull); expect(projectMetadata.versionChannel, isNull); expect(projectMetadata.versionRevision, isNull);
expect(logger.traceText, contains('.metadata file at .metadata was empty or malformed.')); });
testWithoutContext('projectType is populated when version is null', () { metadataFile ..createSync() ..writeAsStringSync('''version:project_type: plugin '''); final FlutterProjectMetadata projectMetadata = FlutterProjectMetadata(metadataFile, logger); expect(projectMetadata.projectType, FlutterProjectType.plugin); expect(projectMetadata.versionChannel, isNull); expect(projectMetadata.versionRevision, isNull);
expect(logger.traceText, contains('The value of key `version` in .metadata was expected to be YamlMap but was Null')); });
testWithoutContext('projectType is populated when version is malformed', () { metadataFile ..createSync() ..writeAsStringSync('''version: STRING INSTEAD OF MAPproject_type: plugin '''); final FlutterProjectMetadata projectMetadata = FlutterProjectMetadata(metadataFile, logger); expect(projectMetadata.projectType, FlutterProjectType.plugin); expect(projectMetadata.versionChannel, isNull); expect(projectMetadata.versionRevision, isNull);
expect(logger.traceText, contains('The value of key `version` in .metadata was expected to be YamlMap but was String')); });
testWithoutContext('version is populated when projectType is malformed', () { metadataFile ..createSync() ..writeAsStringSync('''version: revision: b59b226a49391949247e3d6122e34bb001049ae4 channel: stableproject_type: {} '''); final FlutterProjectMetadata projectMetadata = FlutterProjectMetadata(metadataFile, logger); expect(projectMetadata.projectType, isNull); expect(projectMetadata.versionChannel, 'stable'); expect(projectMetadata.versionRevision, 'b59b226a49391949247e3d6122e34bb001049ae4');
expect(logger.traceText, contains('The value of key `project_type` in .metadata was expected to be String but was YamlMap')); });
testWithoutContext('migrate config is populated when version is malformed', () { metadataFile ..createSync() ..writeAsStringSync('''version: STRING INSTEAD OF MAPproject_type: {}
migration: platforms: - platform: root create_revision: abcdefg base_revision: baserevision
unmanaged_files: - 'file1' '''); final FlutterProjectMetadata projectMetadata = FlutterProjectMetadata(metadataFile, logger); expect(projectMetadata.projectType, isNull); expect(projectMetadata.migrateConfig.platformConfigs[SupportedPlatform.root]?.createRevision, 'abcdefg'); expect(projectMetadata.migrateConfig.platformConfigs[SupportedPlatform.root]?.baseRevision, 'baserevision'); expect(projectMetadata.migrateConfig.unmanagedFiles[0], 'file1');
expect(logger.traceText, contains('The value of key `version` in .metadata was expected to be YamlMap but was String')); expect(logger.traceText, contains('The value of key `project_type` in .metadata was expected to be String but was YamlMap')); });
testWithoutContext('migrate config is populated when unmanaged_files is malformed', () { metadataFile ..createSync() ..writeAsStringSync('''version: revision: b59b226a49391949247e3d6122e34bb001049ae4 channel: stableproject_type: app
migration: platforms: - platform: root create_revision: abcdefg base_revision: baserevision
unmanaged_files: {} '''); final FlutterProjectMetadata projectMetadata = FlutterProjectMetadata(metadataFile, logger); expect(projectMetadata.projectType, FlutterProjectType.app); expect(projectMetadata.migrateConfig.platformConfigs[SupportedPlatform.root]?.createRevision, 'abcdefg'); expect(projectMetadata.migrateConfig.platformConfigs[SupportedPlatform.root]?.baseRevision, 'baserevision'); // Tool uses default unmanaged files list when malformed. expect(projectMetadata.migrateConfig.unmanagedFiles[0], 'lib/main.dart');
expect(logger.traceText, contains('The value of key `unmanaged_files` in .metadata was expected to be YamlList but was YamlMap')); });
testWithoutContext('platforms is populated with a malformed entry', () { metadataFile ..createSync() ..writeAsStringSync('''version: revision: b59b226a49391949247e3d6122e34bb001049ae4 channel: stableproject_type: app
migration: platforms: - platform: root create_revision: abcdefg base_revision: baserevision - platform: android base_revision: baserevision - platform: ios create_revision: abcdefg base_revision: baserevision
unmanaged_files: - 'file1' '''); final FlutterProjectMetadata projectMetadata = FlutterProjectMetadata(metadataFile, logger); expect(projectMetadata.projectType, FlutterProjectType.app); expect(projectMetadata.migrateConfig.platformConfigs[SupportedPlatform.root]?.createRevision, 'abcdefg'); expect(projectMetadata.migrateConfig.platformConfigs[SupportedPlatform.root]?.baseRevision, 'baserevision'); expect(projectMetadata.migrateConfig.platformConfigs[SupportedPlatform.ios]?.createRevision, 'abcdefg'); expect(projectMetadata.migrateConfig.platformConfigs[SupportedPlatform.ios]?.baseRevision, 'baserevision'); expect(projectMetadata.migrateConfig.platformConfigs.containsKey(SupportedPlatform.android), false); expect(projectMetadata.migrateConfig.unmanagedFiles[0], 'file1');
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), });}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300// 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 'package:dds/dds.dart';import 'package:file/memory.dart';import 'package:flutter_tools/src/base/file_system.dart';import 'package:flutter_tools/src/base/io.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/device.dart';import 'package:flutter_tools/src/test/flutter_tester_device.dart';import 'package:flutter_tools/src/test/font_config_manager.dart';import 'package:flutter_tools/src/vmservice.dart';import 'package:stream_channel/stream_channel.dart';import 'package:test/fake.dart';
import '../src/context.dart';import '../src/fake_process_manager.dart';import '../src/fake_vm_services.dart';
void main() { late FakePlatform platform; late FileSystem fileSystem; late FakeProcessManager processManager; late FlutterTesterTestDevice device;
setUp(() { fileSystem = MemoryFileSystem.test(); // Not Windows. platform = FakePlatform( environment: <String, String>{}, ); processManager = FakeProcessManager.any(); });
FlutterTesterTestDevice createDevice({ List<String> dartEntrypointArgs = const <String>[], bool enableVmService = false, }) => TestFlutterTesterDevice( platform: platform, fileSystem: fileSystem, processManager: processManager, enableVmService: enableVmService, dartEntrypointArgs: dartEntrypointArgs, uriConverter: (String input) => '$input/converted', );
testUsingContext('Missing dir error caught for FontConfigManger.dispose', () async { final FontConfigManager fontConfigManager = FontConfigManager();
final Directory fontsDirectory = fileSystem.file(fontConfigManager.fontConfigFile).parent; fontsDirectory.deleteSync(recursive: true);
await fontConfigManager.dispose(); }, overrides: <Type, Generator>{ FileSystem: () => fileSystem, ProcessManager: () => processManager, });
group('The FLUTTER_TEST environment variable is passed to the test process', () { setUp(() { processManager = FakeProcessManager.list(<FakeCommand>[]); device = createDevice();
fileSystem .file('.dart_tool/package_config.json') ..createSync(recursive: true) ..writeAsStringSync('{"configVersion":2,"packages":[]}'); });
FakeCommand flutterTestCommand(String expectedFlutterTestValue) { return FakeCommand(command: const <String>[ '/', '--disable-vm-service', '--ipv6', '--enable-checked-mode', '--verify-entry-points', '--enable-software-rendering', '--skia-deterministic-rendering', '--enable-dart-profiling', '--non-interactive', '--use-test-fonts', '--disable-asset-fonts', '--packages=.dart_tool/package_config.json', 'example.dill', ], environment: <String, String>{ 'FLUTTER_TEST': expectedFlutterTestValue, 'FONTCONFIG_FILE': device.fontConfigManager.fontConfigFile.path, 'SERVER_PORT': '0', 'APP_NAME': '', }); }
testUsingContext('as true when not originally set', () async { processManager.addCommand(flutterTestCommand('true'));
await device.start('example.dill'); expect(processManager, hasNoRemainingExpectations); });
testUsingContext('as true when set to true', () async { platform.environment = <String, String>{'FLUTTER_TEST': 'true'}; processManager.addCommand(flutterTestCommand('true'));
await device.start('example.dill'); expect(processManager, hasNoRemainingExpectations); });
testUsingContext('as false when set to false', () async { platform.environment = <String, String>{'FLUTTER_TEST': 'false'}; processManager.addCommand(flutterTestCommand('false'));
await device.start('example.dill'); expect(processManager, hasNoRemainingExpectations); });
testUsingContext('unchanged when set', () async { platform.environment = <String, String>{'FLUTTER_TEST': 'neither true nor false'}; processManager.addCommand(flutterTestCommand('neither true nor false'));
await device.start('example.dill'); expect(processManager, hasNoRemainingExpectations); }); });
group('Dart Entrypoint Args', () { setUp(() { processManager = FakeProcessManager.list(<FakeCommand>[ const FakeCommand( command: <String>[ '/', '--disable-vm-service', '--ipv6', '--enable-checked-mode', '--verify-entry-points', '--enable-software-rendering', '--skia-deterministic-rendering', '--enable-dart-profiling', '--non-interactive', '--use-test-fonts', '--disable-asset-fonts', '--packages=.dart_tool/package_config.json', '--foo', '--bar', 'example.dill', ], stdout: 'success', stderr: 'failure', ), ]); device = createDevice(dartEntrypointArgs: <String>['--foo', '--bar']); });
testUsingContext('Can pass additional arguments to tester binary', () async { await device.start('example.dill');
expect(processManager, hasNoRemainingExpectations); }); });
group('DDS', () { setUp(() { processManager = FakeProcessManager.list(<FakeCommand>[ const FakeCommand( command: <String>[ '/', '--vm-service-port=0', '--ipv6', '--enable-checked-mode', '--verify-entry-points', '--enable-software-rendering', '--skia-deterministic-rendering', '--enable-dart-profiling', '--non-interactive', '--use-test-fonts', '--disable-asset-fonts', '--packages=.dart_tool/package_config.json', 'example.dill', ], stdout: 'The Dart VM service is listening on http://localhost:1234', stderr: 'failure', ), ]); device = createDevice(enableVmService: true); });
testUsingContext('skips setting VM Service port and uses the input port for DDS instead', () async { await device.start('example.dill'); await device.vmServiceUri;
final Uri uri = await (device as TestFlutterTesterDevice).ddsServiceUriFuture(); expect(uri.port, 1234); });
testUsingContext('sets up UriConverter from context', () async { await device.start('example.dill'); await device.vmServiceUri;
final FakeDartDevelopmentService dds = (device as TestFlutterTesterDevice).dds as FakeDartDevelopmentService; final String? result = dds .uriConverter ?.call('test'); expect(result, 'test/converted'); }); });}
/// A Flutter Tester device.////// Uses a mock HttpServer. We don't want to bind random ports in our CI hosts.class TestFlutterTesterDevice extends FlutterTesterTestDevice { TestFlutterTesterDevice({ required super.platform, required super.fileSystem, required super.processManager, required super.enableVmService, required List<String> dartEntrypointArgs, required UriConverter uriConverter, }) : super( id: 999, shellPath: '/', logger: BufferLogger.test(), debuggingOptions: DebuggingOptions.enabled( const BuildInfo( BuildMode.debug, '', treeShakeIcons: false, ), hostVmServicePort: 1234, dartEntrypointArgs: dartEntrypointArgs, ), machine: false, host: InternetAddress.loopbackIPv6, testAssetDirectory: null, flutterProject: null, icudtlPath: null, compileExpression: null, fontConfigManager: FontConfigManager(), uriConverter: uriConverter, ); late DartDevelopmentService dds;
final Completer<Uri> _ddsServiceUriCompleter = Completer<Uri>();
Future<Uri> ddsServiceUriFuture() => _ddsServiceUriCompleter.future;
@override Future<DartDevelopmentService> startDds( Uri uri, { UriConverter? uriConverter, }) async { _ddsServiceUriCompleter.complete(uri); dds = FakeDartDevelopmentService( Uri.parse('http://localhost:${debuggingOptions.hostVmServicePort}'), Uri.parse('http://localhost:8080'), uriConverter: uriConverter, ); return dds; }
@override Future<FlutterVmService> connectToVmServiceImpl( Uri httpUri, { CompileExpression? compileExpression, required Logger logger, }) async { return FakeVmServiceHost(requests: <VmServiceExpectation>[ const FakeVmServiceRequest(method: '_serveObservatory'), ]).vmService; }
@override Future<HttpServer> bind(InternetAddress? host, int port) async => FakeHttpServer();
@override Future<StreamChannel<String>> get remoteChannel async => StreamChannelController<String>().foreign;}
class FakeDartDevelopmentService extends Fake implements DartDevelopmentService { FakeDartDevelopmentService(this.uri, this.original, {this.uriConverter});
final Uri original; final UriConverter? uriConverter;
@override final Uri uri;
@override Uri get remoteVmServiceUri => original;}class FakeHttpServer extends Fake implements HttpServer { @override int get port => 0;}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647// 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/os.dart';import 'package:flutter_tools/src/base/platform.dart';import 'package:flutter_tools/src/base/user_messages.dart';import 'package:flutter_tools/src/doctor.dart';import 'package:flutter_tools/src/doctor_validator.dart';import 'package:flutter_tools/src/version.dart';import 'package:test/fake.dart';
import '../src/common.dart';import '../src/fake_process_manager.dart';import '../src/fakes.dart';
/// Matches a doctor validation result.Matcher _matchDoctorValidation({ required ValidationType validationType, required String statusInfo, required Object messages}) { return const TypeMatcher<ValidationResult>() .having((ValidationResult result) => result.type, 'type', validationType) .having((ValidationResult result) => result.statusInfo, 'statusInfo', statusInfo) .having((ValidationResult result) => result.messages, 'messages', messages);}
void main() { testWithoutContext('FlutterValidator shows an error message if gen_snapshot is ' 'downloaded and exits with code 1', () async { final FakeFlutterVersion flutterVersion = FakeFlutterVersion( frameworkVersion: '1.0.0', branch: 'beta', ); final MemoryFileSystem fileSystem = MemoryFileSystem.test(); final Artifacts artifacts = Artifacts.test(); final FlutterValidator flutterValidator = FlutterValidator( platform: FakePlatform( localeName: 'en_US.UTF-8', environment: <String, String>{}, ), flutterVersion: () => flutterVersion, devToolsVersion: () => '2.8.0', userMessages: UserMessages(), artifacts: artifacts, fileSystem: fileSystem, flutterRoot: () => '/sdk/flutter', operatingSystemUtils: FakeOperatingSystemUtils(name: 'Linux'), processManager: FakeProcessManager.list(<FakeCommand>[ const FakeCommand( command: <String>['Artifact.genSnapshot'], exitCode: 1, ), ]) ); fileSystem.file(artifacts.getArtifactPath(Artifact.genSnapshot)).createSync(recursive: true);
expect(await flutterValidator.validate(), _matchDoctorValidation( validationType: ValidationType.partial, statusInfo: 'Channel beta, 1.0.0, on Linux, locale en_US.UTF-8', messages: containsAll(const <ValidationMessage>[ ValidationMessage.error( 'Downloaded executables cannot execute on host.\n' 'See https://github.com/flutter/flutter/issues/6207 for more information.\n' 'On Debian/Ubuntu/Mint: sudo apt-get install lib32stdc++6\n' 'On Fedora: dnf install libstdc++.i686\n' 'On Arch: pacman -S lib32-gcc-libs\n', ), ])), ); });
testWithoutContext('FlutterValidator shows an error message if Rosetta is needed', () async { final FakeFlutterVersion flutterVersion = FakeFlutterVersion( frameworkVersion: '1.0.0', branch: 'beta', ); final MemoryFileSystem fileSystem = MemoryFileSystem.test(); final Artifacts artifacts = Artifacts.test(); final FlutterValidator flutterValidator = FlutterValidator( platform: FakePlatform( operatingSystem: 'macos', localeName: 'en_US.UTF-8', environment: <String, String>{}, ), flutterVersion: () => flutterVersion, devToolsVersion: () => '2.8.0', userMessages: UserMessages(), artifacts: artifacts, fileSystem: fileSystem, flutterRoot: () => 'sdk/flutter', operatingSystemUtils: FakeOperatingSystemUtils(name: 'macOS', hostPlatform: HostPlatform.darwin_arm64), processManager: FakeProcessManager.list(<FakeCommand>[ const FakeCommand( command: <String>['Artifact.genSnapshot'], exitCode: 1, ), ]) ); fileSystem.file(artifacts.getArtifactPath(Artifact.genSnapshot)).createSync(recursive: true);
expect(await flutterValidator.validate(), _matchDoctorValidation( validationType: ValidationType.partial, statusInfo: 'Channel beta, 1.0.0, on macOS, locale en_US.UTF-8', messages: containsAll(const <ValidationMessage>[ ValidationMessage.error( 'Downloaded executables cannot execute on host.\n' 'See https://github.com/flutter/flutter/issues/6207 for more information.\n' 'Flutter requires the Rosetta translation environment on ARM Macs. Try running:\n' ' sudo softwareupdate --install-rosetta --agree-to-license\n' ), ])), ); });
testWithoutContext('FlutterValidator does not run gen_snapshot binary check if it is not already downloaded', () async { final FakeFlutterVersion flutterVersion = FakeFlutterVersion( frameworkVersion: '1.0.0', branch: 'beta', ); final FlutterValidator flutterValidator = FlutterValidator( platform: FakePlatform( operatingSystem: 'windows', localeName: 'en_US.UTF-8', environment: <String, String>{}, ), flutterVersion: () => flutterVersion, devToolsVersion: () => '2.8.0', userMessages: UserMessages(), artifacts: Artifacts.test(), fileSystem: MemoryFileSystem.test(), operatingSystemUtils: FakeOperatingSystemUtils(name: 'Windows'), processManager: FakeProcessManager.empty(), flutterRoot: () => '/sdk/flutter', );
// gen_snapshot is downloaded on demand, and the doctor should not // fail if the gen_snapshot binary is not present. expect(await flutterValidator.validate(), _matchDoctorValidation( validationType: ValidationType.success, statusInfo: 'Channel beta, 1.0.0, on Windows, locale en_US.UTF-8', messages: anything, )); });
testWithoutContext('FlutterValidator handles exception thrown by version checking', () async { final FlutterValidator flutterValidator = FlutterValidator( platform: FakePlatform(operatingSystem: 'windows', localeName: 'en_US.UTF-8'), flutterVersion: () => FakeThrowingFlutterVersion(), devToolsVersion: () => '2.8.0', userMessages: UserMessages(), artifacts: Artifacts.test(), fileSystem: MemoryFileSystem.test(), operatingSystemUtils: FakeOperatingSystemUtils(name: 'Windows'), processManager: FakeProcessManager.empty(), flutterRoot: () => '/sdk/flutter', );
expect(await flutterValidator.validate(), _matchDoctorValidation( validationType: ValidationType.partial, statusInfo: 'Channel beta, 0.0.0, on Windows, locale en_US.UTF-8', messages: containsAll(const <ValidationMessage>[ ValidationMessage('Flutter version 0.0.0 on channel beta at /sdk/flutter'), ValidationMessage.error('version error'), ]), )); });
testWithoutContext('FlutterValidator shows mirrors on pub and flutter cloud storage', () async { final FakeFlutterVersion flutterVersion = FakeFlutterVersion( frameworkVersion: '1.0.0', branch: 'beta', ); final Platform platform = FakePlatform( operatingSystem: 'windows', localeName: 'en_US.UTF-8', environment: <String, String>{ 'PUB_HOSTED_URL': 'https://example.com/pub', 'FLUTTER_STORAGE_BASE_URL': 'https://example.com/flutter', }, ); final MemoryFileSystem fileSystem = MemoryFileSystem.test(); final Artifacts artifacts = Artifacts.test(); final FlutterValidator flutterValidator = FlutterValidator( platform: platform, flutterVersion: () => flutterVersion, devToolsVersion: () => '2.8.0', userMessages: UserMessages(), artifacts: artifacts, fileSystem: fileSystem, processManager: FakeProcessManager.any(), operatingSystemUtils: FakeOperatingSystemUtils(name: 'Windows'), flutterRoot: () => '/sdk/flutter' );
expect(await flutterValidator.validate(), _matchDoctorValidation( validationType: ValidationType.success, statusInfo: 'Channel beta, 1.0.0, on Windows, locale en_US.UTF-8', messages: containsAll(const <ValidationMessage>[ ValidationMessage('Pub download mirror https://example.com/pub'), ValidationMessage('Flutter download mirror https://example.com/flutter'), ]) )); });
testWithoutContext('FlutterValidator shows FLUTTER_GIT_URL when set and fails if upstream is not the same', () async { final FlutterValidator flutterValidator = FlutterValidator( platform: FakePlatform( localeName: 'en_US.UTF-8', environment: <String, String> { 'FLUTTER_GIT_URL': 'https://githubmirror.com/flutter.git', }, ), flutterVersion: () => FakeFlutterVersion( frameworkVersion: '1.0.0', branch: 'beta' ), devToolsVersion: () => '2.8.0', userMessages: UserMessages(), artifacts: Artifacts.test(), fileSystem: MemoryFileSystem.test(), processManager: FakeProcessManager.any(), operatingSystemUtils: FakeOperatingSystemUtils(name: 'Linux'), flutterRoot: () => '/sdk/flutter', );
expect(await flutterValidator.validate(), _matchDoctorValidation( validationType: ValidationType.partial, statusInfo: 'Channel beta, 1.0.0, on Linux, locale en_US.UTF-8', messages: containsAll(const <ValidationMessage>[ ValidationMessage.hint('Upstream repository https://github.com/flutter/flutter.git is not the same as FLUTTER_GIT_URL'), ValidationMessage('FLUTTER_GIT_URL = https://githubmirror.com/flutter.git'), ValidationMessage( 'If those were intentional, you can disregard the above warnings; however it is ' 'recommended to use "git" directly to perform update checks and upgrades.' ), ]), )); });
testWithoutContext('FlutterValidator fails when channel is unknown', () async { final FlutterValidator flutterValidator = FlutterValidator( platform: FakePlatform(localeName: 'en_US.UTF-8'), flutterVersion: () => FakeFlutterVersion( branch: 'unknown', frameworkVersion: '1.0.0', ), devToolsVersion: () => '2.8.0', userMessages: UserMessages(), artifacts: Artifacts.test(), fileSystem: MemoryFileSystem.test(), processManager: FakeProcessManager.any(), operatingSystemUtils: FakeOperatingSystemUtils(name: 'Linux'), flutterRoot: () => '/sdk/flutter', );
expect(await flutterValidator.validate(), _matchDoctorValidation( validationType: ValidationType.partial, statusInfo: 'Channel [user-branch], 1.0.0, on Linux, locale en_US.UTF-8', messages: containsAll(<ValidationMessage>[ const ValidationMessage.hint( 'Flutter version 1.0.0 on channel [user-branch] at /sdk/flutter\n' 'Currently on an unknown channel. Run `flutter channel` to switch to an official channel.\n' "If that doesn't fix the issue, reinstall Flutter by following instructions at https://flutter.dev/docs/get-started/install." ), const ValidationMessage( 'If those were intentional, you can disregard the above warnings; however it is ' 'recommended to use "git" directly to perform update checks and upgrades.' ), ]), )); });
testWithoutContext('FlutterValidator fails when framework version is unknown', () async { final FlutterValidator flutterValidator = FlutterValidator( platform: FakePlatform(localeName: 'en_US.UTF-8'), flutterVersion: () => FakeFlutterVersion( frameworkVersion: '0.0.0-unknown', branch: 'beta', ), devToolsVersion: () => '2.8.0', userMessages: UserMessages(), artifacts: Artifacts.test(), fileSystem: MemoryFileSystem.test(), processManager: FakeProcessManager.any(), operatingSystemUtils: FakeOperatingSystemUtils(name: 'Linux'), flutterRoot: () => '/sdk/flutter', );
expect(await flutterValidator.validate(), _matchDoctorValidation( validationType: ValidationType.partial, statusInfo: 'Channel beta, 0.0.0-unknown, on Linux, locale en_US.UTF-8', messages: containsAll(<ValidationMessage>[ const ValidationMessage.hint( 'Flutter version 0.0.0-unknown on channel beta at /sdk/flutter\n' 'Cannot resolve current version, possibly due to local changes.\n' 'Reinstall Flutter by following instructions at https://flutter.dev/docs/get-started/install.' ), const ValidationMessage( 'If those were intentional, you can disregard the above warnings; however it is ' 'recommended to use "git" directly to perform update checks and upgrades.' ), ]), )); });
group('FlutterValidator shows flutter upstream remote', () { testWithoutContext('standard url', () async { final FlutterValidator flutterValidator = FlutterValidator( platform: FakePlatform(localeName: 'en_US.UTF-8'), flutterVersion: () => FakeFlutterVersion( frameworkVersion: '1.0.0', branch: 'beta' ), devToolsVersion: () => '2.8.0', userMessages: UserMessages(), artifacts: Artifacts.test(), fileSystem: MemoryFileSystem.test(), processManager: FakeProcessManager.any(), operatingSystemUtils: FakeOperatingSystemUtils(name: 'Linux'), flutterRoot: () => '/sdk/flutter', );
expect(await flutterValidator.validate(), _matchDoctorValidation( validationType: ValidationType.success, statusInfo: 'Channel beta, 1.0.0, on Linux, locale en_US.UTF-8', messages: contains(const ValidationMessage('Upstream repository https://github.com/flutter/flutter.git')), )); });
testWithoutContext('non-standard url', () async { final FlutterValidator flutterValidator = FlutterValidator( platform: FakePlatform(localeName: 'en_US.UTF-8'), flutterVersion: () => FakeFlutterVersion( frameworkVersion: '1.0.0', branch: 'beta', repositoryUrl: 'https://githubmirror.com/flutter.git' ), devToolsVersion: () => '2.8.0', userMessages: UserMessages(), artifacts: Artifacts.test(), fileSystem: MemoryFileSystem.test(), processManager: FakeProcessManager.any(), operatingSystemUtils: FakeOperatingSystemUtils(name: 'Linux'), flutterRoot: () => 'sdk/flutter', );
expect(await flutterValidator.validate(), _matchDoctorValidation( validationType: ValidationType.partial, statusInfo: 'Channel beta, 1.0.0, on Linux, locale en_US.UTF-8', messages: containsAll(<ValidationMessage>[ const ValidationMessage.hint( 'Upstream repository https://githubmirror.com/flutter.git is not a standard remote.\n' 'Set environment variable "FLUTTER_GIT_URL" to ' 'https://githubmirror.com/flutter.git to dismiss this error.' ), const ValidationMessage( 'If those were intentional, you can disregard the above warnings; however it is ' 'recommended to use "git" directly to perform update checks and upgrades.' ), ]), )); });
testWithoutContext('as unknown if upstream is null', () async { final FlutterValidator flutterValidator = FlutterValidator( platform: FakePlatform(localeName: 'en_US.UTF-8'), flutterVersion: () => FakeFlutterVersion( frameworkVersion: '1.0.0', branch: 'beta', repositoryUrl: null, ), devToolsVersion: () => '2.8.0', userMessages: UserMessages(), artifacts: Artifacts.test(), fileSystem: MemoryFileSystem.test(), processManager: FakeProcessManager.any(), operatingSystemUtils: FakeOperatingSystemUtils(name: 'Linux'), flutterRoot: () => 'sdk/flutter', );
expect(await flutterValidator.validate(), _matchDoctorValidation( validationType: ValidationType.partial, statusInfo: 'Channel beta, 1.0.0, on Linux, locale en_US.UTF-8', messages: containsAll(<ValidationMessage>[ const ValidationMessage.hint( 'Unknown upstream repository.\n' 'Reinstall Flutter by following instructions at https://flutter.dev/docs/get-started/install.' ), const ValidationMessage( 'If those were intentional, you can disregard the above warnings; however it is ' 'recommended to use "git" directly to perform update checks and upgrades.' ), ]), )); }); });
testWithoutContext('Do not show the message for intentional errors if FlutterValidator passes', () async { final FlutterValidator flutterValidator = FlutterValidator( platform: FakePlatform(localeName: 'en_US.UTF-8'), flutterVersion: () => FakeFlutterVersion( frameworkVersion: '1.0.0', branch: 'beta' ), devToolsVersion: () => '2.8.0', userMessages: UserMessages(), artifacts: Artifacts.test(), fileSystem: MemoryFileSystem.test(), processManager: FakeProcessManager.any(), operatingSystemUtils: FakeOperatingSystemUtils(name: 'Linux'), flutterRoot: () => '/sdk/flutter', );
expect(await flutterValidator.validate(), _matchDoctorValidation( validationType: ValidationType.success, statusInfo: 'Channel beta, 1.0.0, on Linux, locale en_US.UTF-8', messages: isNot( contains(const ValidationMessage( 'If those were intentional, you can disregard the above warnings; however it is ' 'recommended to use "git" directly to perform update checks and upgrades.' )), ), )); });
testWithoutContext('detects no flutter and dart on path', () async { const String flutterRoot = 'sdk/flutter'; final FlutterValidator flutterValidator = FlutterValidator( platform: FakePlatform(localeName: 'en_US.UTF-8'), flutterVersion: () => FakeFlutterVersion( frameworkVersion: '1.0.0', branch: 'beta' ), devToolsVersion: () => '2.8.0', userMessages: UserMessages(), artifacts: Artifacts.test(), fileSystem: MemoryFileSystem.test(), processManager: FakeProcessManager.any(), operatingSystemUtils: FakeOperatingSystemUtils( name: 'Linux', whichLookup: const <String, File>{}, ), flutterRoot: () => flutterRoot, );
expect(await flutterValidator.validate(), _matchDoctorValidation( validationType: ValidationType.partial, statusInfo: 'Channel beta, 1.0.0, on Linux, locale en_US.UTF-8', messages: contains(const ValidationMessage.hint( 'The flutter binary is not on your path. Consider adding $flutterRoot/bin to your path.', )), )); });
testWithoutContext('allows case differences in paths on Windows', () async { const String flutterRoot = r'c:\path\to\flutter-sdk'; const String osName = 'Microsoft Windows'; final MemoryFileSystem fs = MemoryFileSystem.test( style: FileSystemStyle.windows, ); // The windows' file system is not case sensitive, so changing the case // here should not matter. final File flutterBinary = fs.file('${flutterRoot.toUpperCase()}\\bin\\flutter') ..createSync(recursive: true); final FlutterValidator flutterValidator = FlutterValidator( platform: FakePlatform(operatingSystem: 'windows', localeName: 'en_US.UTF-8'), flutterVersion: () => FakeFlutterVersion( frameworkVersion: '1.0.0', branch: 'beta' ), devToolsVersion: () => '2.8.0', userMessages: UserMessages(), artifacts: Artifacts.test(), fileSystem: fs, processManager: FakeProcessManager.empty(), operatingSystemUtils: FakeOperatingSystemUtils( name: osName, whichLookup: <String, File>{ 'flutter': flutterBinary, }, ), flutterRoot: () => flutterRoot, );
expect(await flutterValidator.validate(), _matchDoctorValidation( validationType: ValidationType.partial, statusInfo: 'Channel beta, 1.0.0, on $osName, locale en_US.UTF-8', messages: everyElement(isA<ValidationMessage>().having( (ValidationMessage message) => message.message, 'message', isNot(contains('Warning: `flutter` on your path resolves to')), )), )); });
testWithoutContext('allows different separator types in paths on Windows', () async { const String flutterRoot = r'c:\path\to\flutter-sdk'; const String osName = 'Microsoft Windows'; final MemoryFileSystem fs = MemoryFileSystem.test( style: FileSystemStyle.windows, ); const String filePath = '$flutterRoot\\bin\\flutter'; // force posix style path separators final File flutterBinary = fs.file(filePath.replaceAll(r'\', '/')) ..createSync(recursive: true); final FlutterValidator flutterValidator = FlutterValidator( platform: FakePlatform(operatingSystem: 'windows', localeName: 'en_US.UTF-8'), flutterVersion: () => FakeFlutterVersion( frameworkVersion: '1.0.0', branch: 'beta' ), devToolsVersion: () => '2.8.0', userMessages: UserMessages(), artifacts: Artifacts.test(), fileSystem: fs, processManager: FakeProcessManager.empty(), operatingSystemUtils: FakeOperatingSystemUtils( name: osName, whichLookup: <String, File>{ 'flutter': flutterBinary, }, ), flutterRoot: () => flutterRoot, );
expect(await flutterValidator.validate(), _matchDoctorValidation( validationType: ValidationType.partial, statusInfo: 'Channel beta, 1.0.0, on $osName, locale en_US.UTF-8', messages: everyElement(isA<ValidationMessage>().having( (ValidationMessage message) => message.message, 'message', isNot(contains('Warning: `flutter` on your path resolves to')), )), )); });
testWithoutContext('detects flutter and dart from outside flutter sdk', () async { final FileSystem fs = MemoryFileSystem.test(); final FlutterValidator flutterValidator = FlutterValidator( platform: FakePlatform(localeName: 'en_US.UTF-8'), flutterVersion: () => FakeFlutterVersion( frameworkVersion: '1.0.0', branch: 'beta' ), devToolsVersion: () => '2.8.0', userMessages: UserMessages(), artifacts: Artifacts.test(), fileSystem: fs, processManager: FakeProcessManager.any(), operatingSystemUtils: FakeOperatingSystemUtils( name: 'Linux', whichLookup: <String, File>{ 'flutter': fs.file('/sdk/flutter-beta')..createSync(recursive: true), 'dart': fs.file('/sdk/flutter-beta')..createSync(recursive: true), }, ), flutterRoot: () => '/sdk/flutter', );
expect(await flutterValidator.validate(), _matchDoctorValidation( validationType: ValidationType.partial, statusInfo: 'Channel beta, 1.0.0, on Linux, locale en_US.UTF-8', messages: contains(const ValidationMessage.hint( 'Warning: `flutter` on your path resolves to /sdk/flutter-beta, which ' 'is not inside your current Flutter SDK checkout at /sdk/flutter. ' 'Consider adding /sdk/flutter/bin to the front of your path.', )), )); });
testWithoutContext('no warnings if flutter & dart binaries are inside the Flutter SDK', () async { final FileSystem fs = MemoryFileSystem.test(); final FlutterValidator flutterValidator = FlutterValidator( platform: FakePlatform(localeName: 'en_US.UTF-8'), flutterVersion: () => FakeFlutterVersion( frameworkVersion: '1.0.0', branch: 'beta' ), devToolsVersion: () => '2.8.0', userMessages: UserMessages(), artifacts: Artifacts.test(), fileSystem: fs, processManager: FakeProcessManager.any(), operatingSystemUtils: FakeOperatingSystemUtils( name: 'Linux', whichLookup: <String, File>{ 'flutter': fs.file('/sdk/flutter/bin/flutter')..createSync(recursive: true), 'dart': fs.file('/sdk/flutter/bin/dart')..createSync(recursive: true), }, ), flutterRoot: () => '/sdk/flutter', );
expect(await flutterValidator.validate(), _matchDoctorValidation( validationType: ValidationType.success, statusInfo: 'Channel beta, 1.0.0, on Linux, locale en_US.UTF-8', messages: isNot(contains(isA<ValidationMessage>().having( (ValidationMessage message) => message.message, 'message', contains('Consider adding /sdk/flutter/bin to the front of your path'), ))), )); });}
class FakeOperatingSystemUtils extends Fake implements OperatingSystemUtils { FakeOperatingSystemUtils({ required this.name, this.hostPlatform = HostPlatform.linux_x64, this.whichLookup, FileSystem? fs, }) { fs ??= MemoryFileSystem.test(); whichLookup ??= <String, File>{ 'flutter': fs.file('/sdk/flutter/bin/flutter')..createSync(recursive: true), 'dart': fs.file('/sdk/flutter/bin/dart')..createSync(recursive: true), }; }
/// A map of [File]s that calls to [which] will return. Map<String, File>? whichLookup;
@override File? which(String execName) => whichLookup![execName];
@override final String name;
@override final HostPlatform hostPlatform;}
class FakeThrowingFlutterVersion extends FakeFlutterVersion { @override String get channel => 'beta';
@override String get frameworkCommitDate { throw VersionCheckError('version error'); }}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535// 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: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/convert.dart';import 'package:flutter_tools/src/localizations/gen_l10n.dart';import 'package:flutter_tools/src/localizations/gen_l10n_types.dart';import 'package:flutter_tools/src/localizations/localizations_utils.dart';import 'package:yaml/yaml.dart';
import '../src/common.dart';import '../src/fake_process_manager.dart';
const String defaultTemplateArbFileName = 'app_en.arb';const String defaultOutputFileString = 'output-localization-file.dart';const String defaultClassNameString = 'AppLocalizations';const String singleMessageArbFileString = '''{ "title": "Title", "@title": { "description": "Title for the application." }}''';const String twoMessageArbFileString = '''{ "title": "Title", "@title": { "description": "Title for the application." }, "subtitle": "Subtitle", "@subtitle": { "description": "Subtitle for the application." }}''';const String esArbFileName = 'app_es.arb';const String singleEsMessageArbFileString = '''{ "title": "Título"}''';const String singleZhMessageArbFileString = '''{ "title": "标题"}''';const String intlImportDartCode = '''import 'package:intl/intl.dart' as intl;''';const String foundationImportDartCode = '''import 'package:flutter/foundation.dart';''';
void _standardFlutterDirectoryL10nSetup(FileSystem fs) { final Directory l10nDirectory = fs.currentDirectory.childDirectory('lib').childDirectory('l10n') ..createSync(recursive: true); l10nDirectory.childFile(defaultTemplateArbFileName) .writeAsStringSync(singleMessageArbFileString); l10nDirectory.childFile(esArbFileName) .writeAsStringSync(singleEsMessageArbFileString); fs.file('pubspec.yaml') ..createSync(recursive: true) ..writeAsStringSync('''flutter: generate: true''');
}
void main() { late MemoryFileSystem fs; late BufferLogger logger; late Artifacts artifacts; late ProcessManager processManager; late String defaultL10nPathString; late String syntheticPackagePath; late String syntheticL10nPackagePath;
LocalizationsGenerator setupLocalizations( Map<String, String> localeToArbFile, { String? yamlFile, String? outputPathString, String? outputFileString, String? headerString, String? headerFile, String? untranslatedMessagesFile, bool useSyntheticPackage = true, bool isFromYaml = false, bool usesNullableGetter = true, String? inputsAndOutputsListPath, List<String>? preferredSupportedLocales, bool useDeferredLoading = false, bool useEscaping = false, bool areResourceAttributeRequired = false, bool suppressWarnings = false, bool relaxSyntax = false, bool useNamedParameters = false, void Function(Directory)? setup, } ) { final Directory l10nDirectory = fs.currentDirectory.childDirectory('lib').childDirectory('l10n') ..createSync(recursive: true); for (final String locale in localeToArbFile.keys) { l10nDirectory.childFile('app_$locale.arb') .writeAsStringSync(localeToArbFile[locale]!); } if (setup != null) { setup(l10nDirectory); } return LocalizationsGenerator( fileSystem: fs, inputPathString: l10nDirectory.path, outputPathString: outputPathString ?? l10nDirectory.path, templateArbFileName: defaultTemplateArbFileName, outputFileString: outputFileString ?? defaultOutputFileString, classNameString: defaultClassNameString, headerString: headerString, headerFile: headerFile, logger: logger, untranslatedMessagesFile: untranslatedMessagesFile, useSyntheticPackage: useSyntheticPackage, inputsAndOutputsListPath: inputsAndOutputsListPath, usesNullableGetter: usesNullableGetter, preferredSupportedLocales: preferredSupportedLocales, useDeferredLoading: useDeferredLoading, useEscaping: useEscaping, areResourceAttributesRequired: areResourceAttributeRequired, suppressWarnings: suppressWarnings, useRelaxedSyntax: relaxSyntax, useNamedParameters: useNamedParameters, ) ..loadResources() ..writeOutputFiles(isFromYaml: isFromYaml); }
String getGeneratedFileContent({String? locale}) { final String fileName = locale == null ? 'output-localization-file.dart' : 'output-localization-file_$locale.dart'; return fs.file( fs.path.join(syntheticL10nPackagePath, fileName) ).readAsStringSync(); }
setUp(() { fs = MemoryFileSystem.test(); logger = BufferLogger.test(); artifacts = Artifacts.test(); processManager = FakeProcessManager.empty();
defaultL10nPathString = fs.path.join('lib', 'l10n'); syntheticPackagePath = fs.path.join('.dart_tool', 'flutter_gen'); syntheticL10nPackagePath = fs.path.join(syntheticPackagePath, 'gen_l10n'); precacheLanguageAndRegionTags(); });
group('Setters', () { testWithoutContext('setInputDirectory fails if the directory does not exist', () { expect( () => LocalizationsGenerator.inputDirectoryFromPath(fs, 'lib', fs.directory('bogus')), throwsA(isA<L10nException>().having( (L10nException e) => e.message, 'message', contains('Make sure that the correct path was provided'), )), ); });
testWithoutContext('setting className fails if input string is empty', () { _standardFlutterDirectoryL10nSetup(fs); expect( () => LocalizationsGenerator.classNameFromString(''), throwsA(isA<L10nException>().having( (L10nException e) => e.message, 'message', contains('cannot be empty'), )), ); });
testWithoutContext('sets absolute path of the target Flutter project', () { // Set up project directory. final Directory l10nDirectory = fs.currentDirectory .childDirectory('absolute') .childDirectory('path') .childDirectory('to') .childDirectory('flutter_project') .childDirectory('lib') .childDirectory('l10n') ..createSync(recursive: true); l10nDirectory.childFile(defaultTemplateArbFileName) .writeAsStringSync(singleMessageArbFileString); l10nDirectory.childFile(esArbFileName) .writeAsStringSync(singleEsMessageArbFileString);
// Run localizations generator in specified absolute path. final String flutterProjectPath = fs.path.join('absolute', 'path', 'to', 'flutter_project'); LocalizationsGenerator( fileSystem: fs, projectPathString: flutterProjectPath, inputPathString: defaultL10nPathString, outputPathString: defaultL10nPathString, templateArbFileName: defaultTemplateArbFileName, outputFileString: defaultOutputFileString, classNameString: defaultClassNameString, logger: logger, ) ..loadResources() ..writeOutputFiles();
// Output files should be generated in the provided absolute path. expect( fs.isFileSync(fs.path.join( flutterProjectPath, '.dart_tool', 'flutter_gen', 'gen_l10n', 'output-localization-file_en.dart', )), true, ); expect( fs.isFileSync(fs.path.join( flutterProjectPath, '.dart_tool', 'flutter_gen', 'gen_l10n', 'output-localization-file_es.dart', )), true, ); });
testWithoutContext('throws error when directory at absolute path does not exist', () { // Set up project directory. final Directory l10nDirectory = fs.currentDirectory .childDirectory('lib') .childDirectory('l10n') ..createSync(recursive: true); l10nDirectory.childFile(defaultTemplateArbFileName) .writeAsStringSync(singleMessageArbFileString); l10nDirectory.childFile(esArbFileName) .writeAsStringSync(singleEsMessageArbFileString);
// Project path should be intentionally a directory that does not exist. expect( () => LocalizationsGenerator( fileSystem: fs, projectPathString: 'absolute/path/to/flutter_project', inputPathString: defaultL10nPathString, outputPathString: defaultL10nPathString, templateArbFileName: defaultTemplateArbFileName, outputFileString: defaultOutputFileString, classNameString: defaultClassNameString, logger: logger, ), throwsA(isA<L10nException>().having( (L10nException e) => e.message, 'message', contains('Directory does not exist'), )), ); });
testWithoutContext('throws error when arb file does not exist', () { // Set up project directory. fs.currentDirectory .childDirectory('lib') .childDirectory('l10n') .createSync(recursive: true);
// Arb file should be nonexistent in the l10n directory. expect( () => LocalizationsGenerator( fileSystem: fs, projectPathString: './', inputPathString: defaultL10nPathString, outputPathString: defaultL10nPathString, templateArbFileName: defaultTemplateArbFileName, outputFileString: defaultOutputFileString, classNameString: defaultClassNameString, logger: logger, ), throwsA(isA<L10nException>().having( (L10nException e) => e.message, 'message', contains(', does not exist.'), )), ); });
group('className should only take valid Dart class names', () { setUp(() { _standardFlutterDirectoryL10nSetup(fs); });
testWithoutContext('fails on string with spaces', () { expect( () => LocalizationsGenerator.classNameFromString('String with spaces'), throwsA(isA<L10nException>().having( (L10nException e) => e.message, 'message', contains('is not a valid public Dart class name'), )), ); });
testWithoutContext('fails on non-alphanumeric symbols', () { expect( () => LocalizationsGenerator.classNameFromString('TestClass@123'), throwsA(isA<L10nException>().having( (L10nException e) => e.message, 'message', contains('is not a valid public Dart class name'), )), ); });
testWithoutContext('fails on camel-case', () { expect( () => LocalizationsGenerator.classNameFromString('camelCaseClassName'), throwsA(isA<L10nException>().having( (L10nException e) => e.message, 'message', contains('is not a valid public Dart class name'), )), ); });
testWithoutContext('fails when starting with a number', () { expect( () => LocalizationsGenerator.classNameFromString('123ClassName'), throwsA(isA<L10nException>().having( (L10nException e) => e.message, 'message', contains('is not a valid public Dart class name'), )), ); }); }); });
testWithoutContext('correctly adds a headerString when it is set', () { final LocalizationsGenerator generator = setupLocalizations(<String, String>{ 'en': singleMessageArbFileString, 'es': singleEsMessageArbFileString, }, headerString: '/// Sample header'); expect(generator.header, '/// Sample header'); });
testWithoutContext('correctly adds a headerFile when it is set', () { final LocalizationsGenerator generator = setupLocalizations(<String, String>{ 'en': singleMessageArbFileString, 'es': singleEsMessageArbFileString, }, headerFile: 'header.txt', setup: (Directory l10nDirectory) { l10nDirectory.childFile('header.txt').writeAsStringSync('/// Sample header in a text file'); }); expect(generator.header, '/// Sample header in a text file'); });
testWithoutContext('sets templateArbFileName with more than one underscore correctly', () { setupLocalizations(<String, String>{ 'en': singleMessageArbFileString, 'es': singleEsMessageArbFileString, }); final Directory outputDirectory = fs.directory(syntheticL10nPackagePath); expect(outputDirectory.childFile('output-localization-file.dart').existsSync(), isTrue); expect(outputDirectory.childFile('output-localization-file_en.dart').existsSync(), isTrue); expect(outputDirectory.childFile('output-localization-file_es.dart').existsSync(), isTrue); });
testWithoutContext('filenames with invalid locales should not be recognized', () { expect( () { // This attempts to create 'app_localizations_en_CA_foo.arb'. setupLocalizations(<String, String>{ 'en': singleMessageArbFileString, 'en_CA_foo': singleMessageArbFileString, }); }, throwsA(isA<L10nException>().having( (L10nException e) => e.message, 'message', contains("The following .arb file's locale could not be determined"), )), ); });
testWithoutContext('correctly creates an untranslated messages file (useSyntheticPackage = true)', () { final String untranslatedMessagesFilePath = fs.path.join('lib', 'l10n', 'unimplemented_message_translations.json'); setupLocalizations(<String, String>{ 'en': twoMessageArbFileString, 'es': singleEsMessageArbFileString, }, untranslatedMessagesFile: untranslatedMessagesFilePath); final String unimplementedOutputString = fs.file(untranslatedMessagesFilePath).readAsStringSync(); try { // Since ARB file is essentially JSON, decoding it should not fail. json.decode(unimplementedOutputString); } on Exception { fail('Parsing arb file should not fail'); } expect(unimplementedOutputString, contains('es')); expect(unimplementedOutputString, contains('subtitle')); });
testWithoutContext('correctly creates an untranslated messages file (useSyntheticPackage = false)', () { final String untranslatedMessagesFilePath = fs.path.join('lib', 'l10n', 'unimplemented_message_translations.json'); setupLocalizations(<String, String>{ 'en': twoMessageArbFileString, 'es': singleMessageArbFileString, }, useSyntheticPackage: false, untranslatedMessagesFile: untranslatedMessagesFilePath); final String unimplementedOutputString = fs.file(untranslatedMessagesFilePath).readAsStringSync(); try { // Since ARB file is essentially JSON, decoding it should not fail. json.decode(unimplementedOutputString); } on Exception { fail('Parsing arb file should not fail'); } expect(unimplementedOutputString, contains('es')); expect(unimplementedOutputString, contains('subtitle')); });
testWithoutContext( 'untranslated messages suggestion is printed when translation is missing: ' 'command line message', () { setupLocalizations(<String, String>{ 'en': twoMessageArbFileString, 'es': singleEsMessageArbFileString, }); expect( logger.statusText, contains('To see a detailed report, use the --untranslated-messages-file'), ); expect( logger.statusText, contains('flutter gen-l10n --untranslated-messages-file=desiredFileName.txt'), ); }, );
testWithoutContext( 'untranslated messages suggestion is printed when translation is missing: ' 'l10n.yaml message', () { setupLocalizations(<String, String>{ 'en': twoMessageArbFileString, 'es': singleEsMessageArbFileString, }, isFromYaml: true); expect( logger.statusText, contains('To see a detailed report, use the untranslated-messages-file'), ); expect( logger.statusText, contains('untranslated-messages-file: desiredFileName.txt'), ); }, );
testWithoutContext( 'unimplemented messages suggestion is not printed when all messages ' 'are fully translated', () { setupLocalizations(<String, String>{ 'en': twoMessageArbFileString, 'es': twoMessageArbFileString, }); expect(logger.statusText, equals('')); }, );
testWithoutContext('untranslated messages file included in generated JSON list of outputs', () { final String untranslatedMessagesFilePath = fs.path.join('lib', 'l10n', 'unimplemented_message_translations.json'); setupLocalizations( <String, String>{ 'en': twoMessageArbFileString, 'es': singleEsMessageArbFileString, }, untranslatedMessagesFile: untranslatedMessagesFilePath, inputsAndOutputsListPath: syntheticL10nPackagePath, ); final File inputsAndOutputsList = fs.file( fs.path.join(syntheticL10nPackagePath, 'gen_l10n_inputs_and_outputs.json') ); expect(inputsAndOutputsList.existsSync(), isTrue); final Map<String, dynamic> jsonResult = json.decode( inputsAndOutputsList.readAsStringSync(), ) as Map<String, dynamic>; expect(jsonResult.containsKey('outputs'), isTrue); final List<dynamic> outputList = jsonResult['outputs'] as List<dynamic>; expect(outputList, contains(contains('unimplemented_message_translations.json'))); });
testWithoutContext( 'uses inputPathString as outputPathString when the outputPathString is ' 'null while not using the synthetic package option', () { _standardFlutterDirectoryL10nSetup(fs); LocalizationsGenerator( fileSystem: fs, inputPathString: defaultL10nPathString, // outputPathString is intentionally not defined templateArbFileName: defaultTemplateArbFileName, outputFileString: defaultOutputFileString, classNameString: defaultClassNameString, useSyntheticPackage: false, logger: logger, ) ..loadResources() ..writeOutputFiles();
final Directory outputDirectory = fs.directory('lib').childDirectory('l10n'); expect(outputDirectory.childFile('output-localization-file.dart').existsSync(), isTrue); expect(outputDirectory.childFile('output-localization-file_en.dart').existsSync(), isTrue); expect(outputDirectory.childFile('output-localization-file_es.dart').existsSync(), isTrue); }, );
testWithoutContext( 'correctly generates output files in non-default output directory if it ' 'already exists while not using the synthetic package option', () { final Directory l10nDirectory = fs.currentDirectory .childDirectory('lib') .childDirectory('l10n') ..createSync(recursive: true); // Create the directory 'lib/l10n/output'. l10nDirectory.childDirectory('output');
l10nDirectory .childFile(defaultTemplateArbFileName) .writeAsStringSync(singleMessageArbFileString); l10nDirectory .childFile(esArbFileName) .writeAsStringSync(singleEsMessageArbFileString);
LocalizationsGenerator( fileSystem: fs, inputPathString: defaultL10nPathString, outputPathString: fs.path.join('lib', 'l10n', 'output'), templateArbFileName: defaultTemplateArbFileName, outputFileString: defaultOutputFileString, classNameString: defaultClassNameString, useSyntheticPackage: false, logger: logger, ) ..loadResources() ..writeOutputFiles();
final Directory outputDirectory = fs.directory('lib').childDirectory('l10n').childDirectory('output'); expect(outputDirectory.existsSync(), isTrue); expect(outputDirectory.childFile('output-localization-file.dart').existsSync(), isTrue); expect(outputDirectory.childFile('output-localization-file_en.dart').existsSync(), isTrue); expect(outputDirectory.childFile('output-localization-file_es.dart').existsSync(), isTrue); }, );
testWithoutContext( 'correctly creates output directory if it does not exist and writes files ' 'in it while not using the synthetic package option', () { _standardFlutterDirectoryL10nSetup(fs);
LocalizationsGenerator( fileSystem: fs, inputPathString: defaultL10nPathString, outputPathString: fs.path.join('lib', 'l10n', 'output'), templateArbFileName: defaultTemplateArbFileName, outputFileString: defaultOutputFileString, classNameString: defaultClassNameString, useSyntheticPackage: false, logger: logger, ) ..loadResources() ..writeOutputFiles();
final Directory outputDirectory = fs.directory('lib').childDirectory('l10n').childDirectory('output'); expect(outputDirectory.existsSync(), isTrue); expect(outputDirectory.childFile('output-localization-file.dart').existsSync(), isTrue); expect(outputDirectory.childFile('output-localization-file_en.dart').existsSync(), isTrue); expect(outputDirectory.childFile('output-localization-file_es.dart').existsSync(), isTrue); }, );
testWithoutContext( 'generates nullable localizations class getter via static `of` method ' 'by default', () { final LocalizationsGenerator generator = setupLocalizations(<String, String>{ 'en': singleMessageArbFileString, 'es': singleEsMessageArbFileString, }); expect(generator.outputDirectory.existsSync(), isTrue); expect(generator.outputDirectory.childFile('output-localization-file.dart').existsSync(), isTrue); expect( generator.outputDirectory.childFile('output-localization-file.dart').readAsStringSync(), contains('static AppLocalizations? of(BuildContext context)'), ); expect( generator.outputDirectory.childFile('output-localization-file.dart').readAsStringSync(), contains('return Localizations.of<AppLocalizations>(context, AppLocalizations);'), ); }, );
testWithoutContext( 'can generate non-nullable localizations class getter via static `of` method ', () { final LocalizationsGenerator generator = setupLocalizations(<String, String>{ 'en': singleMessageArbFileString, 'es': singleEsMessageArbFileString, }, usesNullableGetter: false); expect(generator.outputDirectory.existsSync(), isTrue); expect(generator.outputDirectory.childFile('output-localization-file.dart').existsSync(), isTrue); expect( generator.outputDirectory.childFile('output-localization-file.dart').readAsStringSync(), contains('static AppLocalizations of(BuildContext context)'), ); expect( generator.outputDirectory.childFile('output-localization-file.dart').readAsStringSync(), contains('return Localizations.of<AppLocalizations>(context, AppLocalizations)!;'), ); }, );
testWithoutContext('creates list of inputs and outputs when file path is specified', () { setupLocalizations(<String, String>{ 'en': singleMessageArbFileString, 'es': singleEsMessageArbFileString, }, inputsAndOutputsListPath: syntheticL10nPackagePath); final File inputsAndOutputsList = fs.file( fs.path.join(syntheticL10nPackagePath, 'gen_l10n_inputs_and_outputs.json'), ); expect(inputsAndOutputsList.existsSync(), isTrue);
final Map<String, dynamic> jsonResult = json.decode(inputsAndOutputsList.readAsStringSync()) as Map<String, dynamic>; expect(jsonResult.containsKey('inputs'), isTrue); final List<dynamic> inputList = jsonResult['inputs'] as List<dynamic>; expect(inputList, contains(fs.path.absolute('lib', 'l10n', 'app_en.arb'))); expect(inputList, contains(fs.path.absolute('lib', 'l10n', 'app_es.arb')));
expect(jsonResult.containsKey('outputs'), isTrue); final List<dynamic> outputList = jsonResult['outputs'] as List<dynamic>; expect(outputList, contains(fs.path.absolute(syntheticL10nPackagePath, 'output-localization-file.dart'))); expect(outputList, contains(fs.path.absolute(syntheticL10nPackagePath, 'output-localization-file_en.dart'))); expect(outputList, contains(fs.path.absolute(syntheticL10nPackagePath, 'output-localization-file_es.dart'))); });
testWithoutContext('setting both a headerString and a headerFile should fail', () { expect( () { setupLocalizations( <String, String>{ 'en': singleMessageArbFileString, 'es': singleEsMessageArbFileString, }, headerString: '/// Sample header in a text file', headerFile: 'header.txt', setup: (Directory l10nDirectory) { l10nDirectory.childFile('header.txt').writeAsStringSync('/// Sample header in a text file'); }, ); }, throwsA(isA<L10nException>().having( (L10nException e) => e.message, 'message', contains('Cannot accept both header and header file arguments'), )), ); });
testWithoutContext('setting a headerFile that does not exist should fail', () { expect( () { setupLocalizations(<String, String>{ 'en': singleMessageArbFileString, 'es': singleEsMessageArbFileString, }, headerFile: 'header.txt'); }, throwsA(isA<L10nException>().having( (L10nException e) => e.message, 'message', contains('Failed to read header file'), )), ); });
group('generateLocalizations', () { // Regression test for https://github.com/flutter/flutter/issues/119593 testWithoutContext('other logs from flutter_tools does not affect gen-l10n', () async { _standardFlutterDirectoryL10nSetup(fs);
final Logger logger = BufferLogger.test(); logger.printError('An error output from a different tool in flutter_tools');
// Should run without error. await generateLocalizations( fileSystem: fs, options: LocalizationOptions( arbDir: Uri.directory(defaultL10nPathString).path, outputDir: Uri.directory(defaultL10nPathString, windows: false).path, templateArbFile: Uri.file(defaultTemplateArbFileName, windows: false).path, syntheticPackage: false, ), logger: logger, projectDir: fs.currentDirectory, dependenciesDir: fs.currentDirectory, artifacts: artifacts, processManager: processManager, ); });
testWithoutContext('forwards arguments correctly', () async { _standardFlutterDirectoryL10nSetup(fs); final LocalizationOptions options = LocalizationOptions( header: 'HEADER', arbDir: Uri.directory(defaultL10nPathString).path, useDeferredLoading: true, outputClass: 'Foo', outputLocalizationFile: Uri.file('bar.dart', windows: false).path, outputDir: Uri.directory(defaultL10nPathString, windows: false).path, preferredSupportedLocales: <String>['es'], templateArbFile: Uri.file(defaultTemplateArbFileName, windows: false).path, untranslatedMessagesFile: Uri.file('untranslated', windows: false).path, syntheticPackage: false, requiredResourceAttributes: true, nullableGetter: false, );
// Verify that values are correctly passed through the localizations target. final LocalizationsGenerator generator = await generateLocalizations( fileSystem: fs, options: options, logger: logger, projectDir: fs.currentDirectory, dependenciesDir: fs.currentDirectory, artifacts: artifacts, processManager: processManager, );
expect(generator.inputDirectory.path, '/lib/l10n/'); expect(generator.outputDirectory.path, '/lib/l10n/'); expect(generator.templateArbFile.path, '/lib/l10n/app_en.arb'); expect(generator.baseOutputFile.path, '/lib/l10n/bar.dart'); expect(generator.className, 'Foo'); expect(generator.preferredSupportedLocales.single, LocaleInfo.fromString('es')); expect(generator.header, 'HEADER'); expect(generator.useDeferredLoading, isTrue); expect(generator.inputsAndOutputsListFile?.path, '/gen_l10n_inputs_and_outputs.json'); expect(generator.useSyntheticPackage, isFalse); expect(generator.projectDirectory?.path, '/'); expect(generator.areResourceAttributesRequired, isTrue); expect(generator.untranslatedMessagesFile?.path, 'untranslated'); expect(generator.usesNullableGetter, isFalse);
// Just validate one file. expect(fs.file('/lib/l10n/bar_en.dart').readAsStringSync(), '''HEADER
import 'bar.dart';
/// The translations for English (`en`).class FooEn extends Foo { FooEn([String locale = 'en']) : super(locale);
@override String get title => 'Title';}'''); });
testWithoutContext('throws exception on missing flutter: generate: true flag', () async { _standardFlutterDirectoryL10nSetup(fs);
// Missing flutter: generate: true should throw exception. fs.file('pubspec.yaml') ..createSync(recursive: true) ..writeAsStringSync('''flutter: uses-material-design: true''');
final LocalizationOptions options = LocalizationOptions( header: 'HEADER', headerFile: Uri.file('header', windows: false).path, arbDir: Uri.file('arb', windows: false).path, useDeferredLoading: true, outputClass: 'Foo', outputLocalizationFile: Uri.file('bar', windows: false).path, preferredSupportedLocales: <String>['en_US'], templateArbFile: Uri.file('example.arb', windows: false).path, untranslatedMessagesFile: Uri.file('untranslated', windows: false).path, );
expect( () => generateLocalizations( fileSystem: fs, options: options, logger: BufferLogger.test(), projectDir: fs.currentDirectory, dependenciesDir: fs.currentDirectory, artifacts: artifacts, processManager: processManager, ), throwsToolExit( message: 'Attempted to generate localizations code without having the ' 'flutter: generate flag turned on.', ), ); });
testWithoutContext('uses the same line terminator as pubspec.yaml', () async { _standardFlutterDirectoryL10nSetup(fs);
fs.file('pubspec.yaml') ..createSync(recursive: true) ..writeAsStringSync('''flutter:\r generate: true\r''');
final LocalizationOptions options = LocalizationOptions( arbDir: fs.path.join('lib', 'l10n'), outputClass: defaultClassNameString, outputLocalizationFile: defaultOutputFileString, ); await generateLocalizations( fileSystem: fs, options: options, logger: BufferLogger.test(), projectDir: fs.currentDirectory, dependenciesDir: fs.currentDirectory, artifacts: artifacts, processManager: processManager, ); final String content = getGeneratedFileContent(locale: 'en'); expect(content, contains('\r\n')); });
testWithoutContext('blank lines generated nicely', () async { _standardFlutterDirectoryL10nSetup(fs);
// Test without headers. await generateLocalizations( fileSystem: fs, options: LocalizationOptions( arbDir: Uri.directory(defaultL10nPathString).path, outputDir: Uri.directory(defaultL10nPathString, windows: false).path, templateArbFile: Uri.file(defaultTemplateArbFileName, windows: false).path, syntheticPackage: false, ), logger: BufferLogger.test(), projectDir: fs.currentDirectory, dependenciesDir: fs.currentDirectory, artifacts: artifacts, processManager: processManager, );
expect(fs.file('/lib/l10n/app_localizations_en.dart').readAsStringSync(), '''import 'app_localizations.dart';
/// The translations for English (`en`).class AppLocalizationsEn extends AppLocalizations { AppLocalizationsEn([String locale = 'en']) : super(locale);
@override String get title => 'Title';}''');
// Test with headers. await generateLocalizations( fileSystem: fs, options: LocalizationOptions( header: 'HEADER', arbDir: Uri.directory(defaultL10nPathString).path, outputDir: Uri.directory(defaultL10nPathString, windows: false).path, templateArbFile: Uri.file(defaultTemplateArbFileName, windows: false).path, syntheticPackage: false, ), logger: logger, projectDir: fs.currentDirectory, dependenciesDir: fs.currentDirectory, artifacts: artifacts, processManager: processManager, );
expect(fs.file('/lib/l10n/app_localizations_en.dart').readAsStringSync(), '''HEADER
import 'app_localizations.dart';
/// The translations for English (`en`).class AppLocalizationsEn extends AppLocalizations { AppLocalizationsEn([String locale = 'en']) : super(locale);
@override String get title => 'Title';}'''); }); });
group('loadResources', () { testWithoutContext('correctly initializes supportedLocales and supportedLanguageCodes properties', () { _standardFlutterDirectoryL10nSetup(fs);
final LocalizationsGenerator generator = LocalizationsGenerator( fileSystem: fs, inputPathString: defaultL10nPathString, outputPathString: defaultL10nPathString, templateArbFileName: defaultTemplateArbFileName, outputFileString: defaultOutputFileString, classNameString: defaultClassNameString, logger: logger, ) ..loadResources();
expect(generator.supportedLocales.contains(LocaleInfo.fromString('en')), true); expect(generator.supportedLocales.contains(LocaleInfo.fromString('es')), true); });
testWithoutContext('correctly sorts supportedLocales and supportedLanguageCodes alphabetically', () { final Directory l10nDirectory = fs.currentDirectory.childDirectory('lib').childDirectory('l10n') ..createSync(recursive: true); // Write files in non-alphabetical order so that read performs in that order l10nDirectory.childFile('app_zh.arb') .writeAsStringSync(singleZhMessageArbFileString); l10nDirectory.childFile('app_es.arb') .writeAsStringSync(singleEsMessageArbFileString); l10nDirectory.childFile('app_en.arb') .writeAsStringSync(singleMessageArbFileString);
final LocalizationsGenerator generator = LocalizationsGenerator( fileSystem: fs, inputPathString: defaultL10nPathString, outputPathString: defaultL10nPathString, templateArbFileName: defaultTemplateArbFileName, outputFileString: defaultOutputFileString, classNameString: defaultClassNameString, logger: logger, ) ..loadResources();
expect(generator.supportedLocales.first, LocaleInfo.fromString('en')); expect(generator.supportedLocales.elementAt(1), LocaleInfo.fromString('es')); expect(generator.supportedLocales.elementAt(2), LocaleInfo.fromString('zh')); });
testWithoutContext('adds preferred locales to the top of supportedLocales and supportedLanguageCodes', () { final Directory l10nDirectory = fs.currentDirectory.childDirectory('lib').childDirectory('l10n') ..createSync(recursive: true); l10nDirectory.childFile('app_en.arb') .writeAsStringSync(singleMessageArbFileString); l10nDirectory.childFile('app_es.arb') .writeAsStringSync(singleEsMessageArbFileString); l10nDirectory.childFile('app_zh.arb') .writeAsStringSync(singleZhMessageArbFileString);
const List<String> preferredSupportedLocale = <String>['zh', 'es']; final LocalizationsGenerator generator = LocalizationsGenerator( fileSystem: fs, inputPathString: defaultL10nPathString, outputPathString: defaultL10nPathString, templateArbFileName: defaultTemplateArbFileName, outputFileString: defaultOutputFileString, classNameString: defaultClassNameString, preferredSupportedLocales: preferredSupportedLocale, logger: logger, ) ..loadResources();
expect(generator.supportedLocales.first, LocaleInfo.fromString('zh')); expect(generator.supportedLocales.elementAt(1), LocaleInfo.fromString('es')); expect(generator.supportedLocales.elementAt(2), LocaleInfo.fromString('en')); });
testWithoutContext( 'throws an error attempting to add preferred locales when there is no corresponding arb file for that locale', () { final Directory l10nDirectory = fs.currentDirectory.childDirectory('lib').childDirectory('l10n') ..createSync(recursive: true); l10nDirectory.childFile('app_en.arb') .writeAsStringSync(singleMessageArbFileString); l10nDirectory.childFile('app_es.arb') .writeAsStringSync(singleEsMessageArbFileString); l10nDirectory.childFile('app_zh.arb') .writeAsStringSync(singleZhMessageArbFileString);
const List<String> preferredSupportedLocale = <String>['am', 'es']; expect( () { LocalizationsGenerator( fileSystem: fs, inputPathString: defaultL10nPathString, outputPathString: defaultL10nPathString, templateArbFileName: defaultTemplateArbFileName, outputFileString: defaultOutputFileString, classNameString: defaultClassNameString, preferredSupportedLocales: preferredSupportedLocale, logger: logger, ).loadResources(); }, throwsA(isA<L10nException>().having( (L10nException e) => e.message, 'message', contains("The preferred supported locale, 'am', cannot be added."), )), ); }, );
testWithoutContext('correctly sorts arbPathString alphabetically', () { final Directory l10nDirectory = fs.currentDirectory.childDirectory('lib').childDirectory('l10n') ..createSync(recursive: true); // Write files in non-alphabetical order so that read performs in that order l10nDirectory.childFile('app_zh.arb') .writeAsStringSync(singleZhMessageArbFileString); l10nDirectory.childFile('app_es.arb') .writeAsStringSync(singleEsMessageArbFileString); l10nDirectory.childFile('app_en.arb') .writeAsStringSync(singleMessageArbFileString);
final LocalizationsGenerator generator = LocalizationsGenerator( fileSystem: fs, inputPathString: defaultL10nPathString, outputPathString: defaultL10nPathString, templateArbFileName: defaultTemplateArbFileName, outputFileString: defaultOutputFileString, classNameString: defaultClassNameString, logger: logger, ) ..loadResources();
expect(generator.arbPathStrings.first, fs.path.join('lib', 'l10n', 'app_en.arb')); expect(generator.arbPathStrings.elementAt(1), fs.path.join('lib', 'l10n', 'app_es.arb')); expect(generator.arbPathStrings.elementAt(2), fs.path.join('lib', 'l10n', 'app_zh.arb')); });
testWithoutContext('correctly parses @@locale property in arb file', () { const String arbFileWithEnLocale = '''{ "@@locale": "en", "title": "Title", "@title": { "description": "Title for the application" }}''';
const String arbFileWithZhLocale = '''{ "@@locale": "zh", "title": "标题", "@title": { "description": "Title for the application" }}''';
final Directory l10nDirectory = fs.currentDirectory.childDirectory('lib').childDirectory('l10n') ..createSync(recursive: true); l10nDirectory.childFile('first_file.arb') .writeAsStringSync(arbFileWithEnLocale); l10nDirectory.childFile('second_file.arb') .writeAsStringSync(arbFileWithZhLocale);
final LocalizationsGenerator generator = LocalizationsGenerator( fileSystem: fs, inputPathString: defaultL10nPathString, outputPathString: defaultL10nPathString, templateArbFileName: 'first_file.arb', outputFileString: defaultOutputFileString, classNameString: defaultClassNameString, logger: logger, ) ..loadResources();
expect(generator.supportedLocales.contains(LocaleInfo.fromString('en')), true); expect(generator.supportedLocales.contains(LocaleInfo.fromString('zh')), true); });
testWithoutContext('correctly requires @@locale property in arb file to match the filename locale suffix', () { const String arbFileWithEnLocale = '''{ "@@locale": "en", "title": "Stocks", "@title": { "description": "Title for the Stocks application" }}''';
const String arbFileWithZhLocale = '''{ "@@locale": "zh", "title": "标题", "@title": { "description": "Title for the Stocks application" }}''';
final Directory l10nDirectory = fs.currentDirectory.childDirectory('lib').childDirectory('l10n') ..createSync(recursive: true); l10nDirectory.childFile('app_es.arb') .writeAsStringSync(arbFileWithEnLocale); l10nDirectory.childFile('app_am.arb') .writeAsStringSync(arbFileWithZhLocale);
expect( () { LocalizationsGenerator( fileSystem: fs, inputPathString: defaultL10nPathString, outputPathString: defaultL10nPathString, templateArbFileName: 'app_es.arb', outputFileString: defaultOutputFileString, classNameString: defaultClassNameString, logger: logger, ).loadResources(); }, throwsA(isA<L10nException>().having( (L10nException e) => e.message, 'message', contains('The locale specified in @@locale and the arb filename do not match.'), )), ); });
testWithoutContext("throws when arb file's locale could not be determined", () { fs.currentDirectory.childDirectory('lib').childDirectory('l10n') ..createSync(recursive: true) ..childFile('app.arb') .writeAsStringSync(singleMessageArbFileString); expect( () { LocalizationsGenerator( fileSystem: fs, inputPathString: defaultL10nPathString, outputPathString: defaultL10nPathString, templateArbFileName: 'app.arb', outputFileString: defaultOutputFileString, classNameString: defaultClassNameString, logger: logger, ).loadResources(); }, throwsA(isA<L10nException>().having( (L10nException e) => e.message, 'message', contains('locale could not be determined'), )), ); });
testWithoutContext('throws when an empty string is used as a key', () { const String arbFileStringWithEmptyResourceId = '''{ "market": "MARKET", "": { "description": "This key is invalid" }}''';
final Directory l10nDirectory = fs.currentDirectory.childDirectory('lib').childDirectory('l10n') ..createSync(recursive: true); l10nDirectory.childFile('app_en.arb') .writeAsStringSync(arbFileStringWithEmptyResourceId);
expect( () => LocalizationsGenerator( fileSystem: fs, inputPathString: defaultL10nPathString, outputPathString: defaultL10nPathString, templateArbFileName: 'app_en.arb', outputFileString: defaultOutputFileString, classNameString: defaultClassNameString, logger: logger, ).loadResources(), throwsA(isA<L10nException>().having( (L10nException e) => e.message, 'message', contains('Invalid ARB resource name ""'), )), ); });
testWithoutContext('throws when the same locale is detected more than once', () { const String secondMessageArbFileString = '''{ "market": "MARKET", "@market": { "description": "Label for the Market tab" }}''';
final Directory l10nDirectory = fs.currentDirectory.childDirectory('lib').childDirectory('l10n') ..createSync(recursive: true); l10nDirectory.childFile('app_en.arb') .writeAsStringSync(singleMessageArbFileString); l10nDirectory.childFile('app2_en.arb') .writeAsStringSync(secondMessageArbFileString);
expect( () { LocalizationsGenerator( fileSystem: fs, inputPathString: defaultL10nPathString, outputPathString: defaultL10nPathString, templateArbFileName: 'app_en.arb', outputFileString: defaultOutputFileString, classNameString: defaultClassNameString, logger: logger, ).loadResources(); }, throwsA(isA<L10nException>().having( (L10nException e) => e.message, 'message', contains("Multiple arb files with the same 'en' locale detected"), )), ); });
testWithoutContext('throws when the base locale does not exist', () { final Directory l10nDirectory = fs.currentDirectory.childDirectory('lib').childDirectory('l10n') ..createSync(recursive: true); l10nDirectory.childFile('app_en_US.arb') .writeAsStringSync(singleMessageArbFileString);
expect( () { LocalizationsGenerator( fileSystem: fs, inputPathString: defaultL10nPathString, outputPathString: defaultL10nPathString, templateArbFileName: 'app_en_US.arb', outputFileString: defaultOutputFileString, classNameString: defaultClassNameString, logger: logger, ).loadResources(); }, throwsA(isA<L10nException>().having( (L10nException e) => e.message, 'message', contains('Arb file for a fallback, en, does not exist'), )), ); });
testWithoutContext('AppResourceBundle throws if file contains non-string value', () { const String inputPathString = 'lib/l10n'; const String templateArbFileName = 'app_en.arb'; const String outputFileString = 'app_localizations.dart'; const String classNameString = 'AppLocalizations';
fs.file(fs.path.join(inputPathString, templateArbFileName)) ..createSync(recursive: true) ..writeAsStringSync('{ "helloWorld": "Hello World!" }'); fs.file(fs.path.join(inputPathString, 'app_es.arb')) ..createSync(recursive: true) ..writeAsStringSync('{ "helloWorld": {} }');
final LocalizationsGenerator generator = LocalizationsGenerator( fileSystem: fs, inputPathString: inputPathString, templateArbFileName: templateArbFileName, outputFileString: outputFileString, classNameString: classNameString, logger: logger, ); expect( () => generator.loadResources(), throwsToolExit(message: 'Localized message for key "helloWorld" in ' '"lib/l10n/app_es.arb" is not a string.'), ); }); });
group('writeOutputFiles', () { testWithoutContext('multiple messages with syntax error all log their errors', () { try { setupLocalizations(<String, String>{ 'en': r'''{ "msg1": "{", "msg2": "{ {"}'''}); } on L10nException catch (error) { expect(error.message, equals('Found syntax errors.')); expect(logger.errorText, contains('''[app_en.arb:msg1] ICU Syntax Error: Expected "identifier" but found no tokens. { ^[app_en.arb:msg2] ICU Syntax Error: Expected "identifier" but found "{". { { ^''')); } });
testWithoutContext('no description generates generic comment', () { setupLocalizations(<String, String>{ 'en': r'''{ "helloWorld": "Hello world!"}''' }); expect(getGeneratedFileContent(), contains('/// No description provided for @helloWorld.')); });
testWithoutContext('multiline descriptions are correctly formatted as comments', () { setupLocalizations(<String, String>{ 'en': r'''{ "helloWorld": "Hello world!", "@helloWorld": { "description": "The generic example string in every language.\nUse this for tests!" }}'''}); expect(getGeneratedFileContent(), contains(''' /// The generic example string in every language. /// Use this for tests!''')); });
testWithoutContext('message without placeholders - should generate code comment with description and template message translation', () { setupLocalizations(<String, String> { 'en': singleMessageArbFileString, 'es': singleEsMessageArbFileString, }); final String content = getGeneratedFileContent(); expect(content, contains('/// Title for the application.')); expect(content, contains(''' /// In en, this message translates to: /// **'Title'**''')); });
testWithoutContext('template message translation handles newline characters', () { setupLocalizations(<String, String>{ 'en': r'''{ "title": "Title \n of the application", "@title": { "description": "Title for the application." }}''', 'es': singleEsMessageArbFileString }); final String content = getGeneratedFileContent(); expect(content, contains('/// Title for the application.')); expect(content, contains(r''' /// In en, this message translates to: /// **'Title \n of the application'**''')); });
testWithoutContext('message with placeholders - should generate code comment with description and template message translation', () { setupLocalizations(<String, String>{ 'en': r'''{ "price": "The price of this item is: ${price}", "@price": { "description": "The price of an online shopping cart item.", "placeholders": { "price": { "type": "double", "format": "decimalPattern" } } }}''', 'es': r'''{ "price": "El precio de este artículo es: ${price}"}''' }); final String content = getGeneratedFileContent(); expect(content, contains('/// The price of an online shopping cart item.')); expect(content, contains(r''' /// In en, this message translates to: /// **'The price of this item is: \${price}'**''')); });
testWithoutContext('should generate a file per language', () { setupLocalizations(<String, String>{ 'en': singleMessageArbFileString, 'en_CA': '''{ "title": "Canadian Title"}''' }); expect(getGeneratedFileContent(locale: 'en'), contains('class AppLocalizationsEn extends AppLocalizations')); expect(getGeneratedFileContent(locale: 'en'), contains('class AppLocalizationsEnCa extends AppLocalizationsEn')); expect(() => getGeneratedFileContent(locale: 'en_US'), throwsException); });
testWithoutContext('language imports are sorted when preferredSupportedLocaleString is given', () { const List<String> preferredSupportedLocales = <String>['zh']; setupLocalizations(<String, String>{ 'en': singleMessageArbFileString, 'zh': singleZhMessageArbFileString, 'es': singleEsMessageArbFileString, }, preferredSupportedLocales: preferredSupportedLocales); final String content = getGeneratedFileContent(); expect(content, contains('''import 'output-localization-file_en.dart';import 'output-localization-file_es.dart';import 'output-localization-file_zh.dart';''')); });
// Regression test for https://github.com/flutter/flutter/issues/88356 testWithoutContext('full output file suffix is retained', () { setupLocalizations(<String, String>{ 'en': singleMessageArbFileString, }, outputFileString: 'output-localization-file.g.dart'); final String baseLocalizationsFile = fs.file( fs.path.join(syntheticL10nPackagePath, 'output-localization-file.g.dart'), ).readAsStringSync(); expect(baseLocalizationsFile, contains('''import 'output-localization-file_en.g.dart';'''));
final String englishLocalizationsFile = fs.file( fs.path.join(syntheticL10nPackagePath, 'output-localization-file_en.g.dart'), ).readAsStringSync(); expect(englishLocalizationsFile, contains('''import 'output-localization-file.g.dart';''')); });
testWithoutContext('throws an exception when invalid output file name is passed in', () { expect( () { setupLocalizations(<String, String>{ 'en': singleMessageArbFileString, }, outputFileString: 'asdf'); }, throwsA(isA<L10nException>().having( (L10nException e) => e.message, 'message', allOf( contains('output-localization-file'), contains('asdf'), contains('is invalid'), contains('The file name must have a .dart extension.'), ), )), ); expect( () { setupLocalizations(<String, String>{ 'en': singleMessageArbFileString, }, outputFileString: '.g.dart'); }, throwsA(isA<L10nException>().having( (L10nException e) => e.message, 'message', allOf( contains('output-localization-file'), contains('.g.dart'), contains('is invalid'), contains('The base name cannot be empty.'), ), )), ); });
testWithoutContext('imports are deferred and loaded when useDeferredImports are set', () { setupLocalizations(<String, String>{ 'en': singleMessageArbFileString, }, useDeferredLoading: true); final String content = getGeneratedFileContent(); expect(content, contains('''import 'output-localization-file_en.dart' deferred as output-localization-file_en;''')); expect(content, contains('output-localization-file_en.loadLibrary()')); });
group('placeholder tests', () { testWithoutContext('should automatically infer placeholders that are not explicitly defined', () { setupLocalizations(<String, String>{ 'en': '''{ "helloWorld": "Hello {name}"}''' }); final String content = getGeneratedFileContent(locale: 'en'); expect(content, contains('String helloWorld(Object name) {')); });
testWithoutContext('placeholder parameter list should be consistent between languages', () { setupLocalizations(<String, String>{ 'en': '''{ "helloWorld": "Hello {name}", "@helloWorld": { "placeholders": { "name": {} } }}''', 'es': '''{ "helloWorld": "Hola"}''', }); expect(getGeneratedFileContent(locale: 'en'), contains('String helloWorld(Object name) {')); expect(getGeneratedFileContent(locale: 'es'), contains('String helloWorld(Object name) {')); });
testWithoutContext('braces are ignored as special characters if placeholder does not exist', () { setupLocalizations(<String, String>{ 'en': '''{ "helloWorld": "Hello {name}", "@@helloWorld": { "placeholders": { "names": {} } }}''' }, relaxSyntax: true); final String content = getGeneratedFileContent(locale: 'en'); expect(content, contains("String get helloWorld => 'Hello {name}'")); }); });
group('DateTime tests', () { testWithoutContext('imports package:intl', () { setupLocalizations(<String, String>{ 'en': '''{ "@@locale": "en", "springBegins": "Spring begins on {springStartDate}", "@springBegins": { "description": "The first day of spring", "placeholders": { "springStartDate": { "type": "DateTime", "format": "yMd" } } }}''' }); expect(getGeneratedFileContent(locale: 'en'), contains(intlImportDartCode)); });
testWithoutContext('throws an exception when improperly formatted date is passed in', () { expect( () { setupLocalizations(<String, String>{ 'en': '''{ "springBegins": "Spring begins on {springStartDate}", "@springBegins": { "placeholders": { "springStartDate": { "type": "DateTime", "format": "asdf" } } }}''' }); }, throwsA(isA<L10nException>().having( (L10nException e) => e.message, 'message', allOf( contains('asdf'), contains('springStartDate'), contains('does not have a corresponding DateFormat'), ), )), ); });
testWithoutContext('use standard date format whenever possible', () { setupLocalizations(<String, String>{ 'en': '''{ "springBegins": "Spring begins on {springStartDate}", "@springBegins": { "placeholders": { "springStartDate": { "type": "DateTime", "format": "yMd", "isCustomDateFormat": "true" } } }}''' }); final String content = getGeneratedFileContent(locale: 'en'); expect(content, contains('DateFormat.yMd(localeName)')); });
testWithoutContext('handle arbitrary formatted date', () { setupLocalizations(<String, String>{ 'en': '''{ "@@locale": "en", "springBegins": "Spring begins on {springStartDate}", "@springBegins": { "description": "The first day of spring", "placeholders": { "springStartDate": { "type": "DateTime", "format": "asdf o'clock", "isCustomDateFormat": "true" } } }}''' }); final String content = getGeneratedFileContent(locale: 'en'); expect(content, contains(r"DateFormat('asdf o\'clock', localeName)")); });
testWithoutContext('throws an exception when no format attribute is passed in', () { expect( () { setupLocalizations(<String, String>{ 'en': '''{ "springBegins": "Spring begins on {springStartDate}", "@springBegins": { "description": "The first day of spring", "placeholders": { "springStartDate": { "type": "DateTime" } } }}''' }); }, throwsA(isA<L10nException>().having( (L10nException e) => e.message, 'message', contains('the "format" attribute needs to be set'), )), ); }); });
group('NumberFormat tests', () { testWithoutContext('imports package:intl', () { setupLocalizations(<String, String>{ 'en': '''{ "courseCompletion": "You have completed {progress} of the course.", "@courseCompletion": { "description": "The amount of progress the student has made in their class.", "placeholders": { "progress": { "type": "double", "format": "percentPattern" } } }}''' }); final String content = getGeneratedFileContent(locale: 'en'); expect(content, contains(intlImportDartCode)); });
testWithoutContext('throws an exception when improperly formatted number is passed in', () { expect( () { setupLocalizations(<String, String>{ 'en': '''{ "courseCompletion": "You have completed {progress} of the course.", "@courseCompletion": { "description": "The amount of progress the student has made in their class.", "placeholders": { "progress": { "type": "double", "format": "asdf" } } }}''' }); }, throwsA(isA<L10nException>().having( (L10nException e) => e.message, 'message', allOf( contains('asdf'), contains('progress'), contains('does not have a corresponding NumberFormat'), ), )), ); }); });
group('plural messages', () { testWithoutContext('intl package import should be omitted in subclass files when no plurals are included', () { setupLocalizations(<String, String>{ 'en': singleMessageArbFileString, 'es': singleEsMessageArbFileString, }); expect(getGeneratedFileContent(locale: 'es'), isNot(contains(intlImportDartCode))); });
testWithoutContext('warnings are generated when plural parts are repeated', () { setupLocalizations(<String, String>{ 'en': '''{ "helloWorlds": "{count,plural, =0{Hello}zero{hello} other{hi}}", "@helloWorlds": { "description": "Properly formatted but has redundant zero cases." }}''' }); expect(logger.hadWarningOutput, isTrue); expect(logger.warningText, contains('''[app_en.arb:helloWorlds] ICU Syntax Warning: The plural part specified below is overridden by a later plural part. {count,plural, =0{Hello}zero{hello} other{hi}} ^''')); });
testWithoutContext('undefined plural cases throws syntax error', () { try { setupLocalizations(<String, String>{ 'en': '''{ "count": "{count,plural, =0{None} =1{One} =2{Two} =3{Undefined Behavior!} other{Hmm...}}"}''' }); } on L10nException catch (error) { expect(error.message, contains('Found syntax errors.')); expect(logger.hadErrorOutput, isTrue); expect(logger.errorText, contains('''[app_en.arb:count] The plural cases must be one of "=0", "=1", "=2", "zero", "one", "two", "few", "many", or "other. 3 is not a valid plural case. {count,plural, =0{None} =1{One} =2{Two} =3{Undefined Behavior!} other{Hmm...}} ^''')); } });
testWithoutContext('should automatically infer plural placeholders that are not explicitly defined', () { setupLocalizations(<String, String>{ 'en': '''{ "helloWorlds": "{count,plural, =0{Hello}=1{Hello World}=2{Hello two worlds}few{Hello {count} worlds}many{Hello all {count} worlds}other{Hello other {count} worlds}}", "@helloWorlds": { "description": "Improperly formatted since it has no placeholder attribute." }}''' }); expect(getGeneratedFileContent(locale: 'en'), contains('String helloWorlds(num count) {')); });
testWithoutContext('should throw attempting to generate a plural message with incorrect format for placeholders', () { expect( () { setupLocalizations(<String, String>{ 'en': '''{ "helloWorlds": "{count,plural, =0{Hello}=1{Hello World}=2{Hello two worlds}few{Hello {count} worlds}many{Hello all {count} worlds}other{Hello other {count} worlds}}", "@helloWorlds": { "placeholders": "Incorrectly a string, should be a map." }}''' }); }, throwsA(isA<L10nException>().having( (L10nException e) => e.message, 'message', allOf( contains('is not properly formatted'), contains('Ensure that it is a map with string valued keys'), ), )), ); }); });
group('select messages', () { testWithoutContext('should automatically infer select placeholders that are not explicitly defined', () { setupLocalizations(<String, String>{ 'en': '''{ "genderSelect": "{gender, select, female {She} male {He} other {they} }", "@genderSelect": { "description": "Improperly formatted since it has no placeholder attribute." }}''' }); expect(getGeneratedFileContent(locale: 'en'), contains('String genderSelect(String gender) {')); });
testWithoutContext('should throw attempting to generate a select message with incorrect format for placeholders', () { expect( () { setupLocalizations(<String, String>{ 'en': '''{ "genderSelect": "{gender, select, female {She} male {He} other {they} }", "@genderSelect": { "placeholders": "Incorrectly a string, should be a map." }}''' }); }, throwsA(isA<L10nException>().having( (L10nException e) => e.message, 'message', allOf( contains('is not properly formatted'), contains('Ensure that it is a map with string valued keys'), ), )), ); });
testWithoutContext('should throw attempting to generate a select message with an incorrect message', () { try { setupLocalizations(<String, String>{ 'en': '''{ "genderSelect": "{gender, select,}", "@genderSelect": { "placeholders": { "gender": {} } }}''' }); } on L10nException { expect(logger.errorText, contains('''[app_en.arb:genderSelect] ICU Syntax Error: Select expressions must have an "other" case. {gender, select,} ^''') ); } }); });
group('argument messages', () { testWithoutContext('should generate proper calls to intl.DateFormat', () { setupLocalizations(<String, String>{ 'en': '''{ "datetime": "{today, date, ::yMd}"}''' }); expect(getGeneratedFileContent(locale: 'en'), contains('intl.DateFormat.yMd(localeName).format(today)')); });
testWithoutContext('should generate proper calls to intl.DateFormat when using time', () { setupLocalizations(<String, String>{ 'en': '''{ "datetime": "{current, time, ::jms}"}''' }); expect(getGeneratedFileContent(locale: 'en'), contains('intl.DateFormat.jms(localeName).format(current)')); });
testWithoutContext('should not complain when placeholders are explicitly typed to DateTime', () { setupLocalizations(<String, String>{ 'en': '''{ "datetime": "{today, date, ::yMd}", "@datetime": { "placeholders": { "today": { "type": "DateTime" } } }}''' }); expect(getGeneratedFileContent(locale: 'en'), contains('String datetime(DateTime today) {')); });
testWithoutContext('should automatically infer date time placeholders that are not explicitly defined', () { setupLocalizations(<String, String>{ 'en': '''{ "datetime": "{today, date, ::yMd}"}''' }); expect(getGeneratedFileContent(locale: 'en'), contains('String datetime(DateTime today) {')); });
testWithoutContext('should throw on invalid DateFormat', () { try { setupLocalizations(<String, String>{ 'en': '''{ "datetime": "{today, date, ::yMMMMMd}"}''' }); assert(false); } on L10nException { expect(logger.errorText, contains('Date format "yMMMMMd" for placeholder today does not have a corresponding DateFormat constructor')); } }); });
// All error handling for messages should collect errors on a per-error // basis and log them out individually. Then, it will throw an L10nException. group('error handling tests', () { testWithoutContext('syntax/code-gen errors properly logs errors per message', () { // TODO(thkim1011): Fix error handling so that long indents don't get truncated. // See https://github.com/flutter/flutter/issues/120490. try { setupLocalizations(<String, String>{ 'en': '''{ "hello": "Hello { name", "plural": "This is an incorrectly formatted plural: { count, plural, zero{No frog} one{One frog} other{{count} frogs}", "explanationWithLexingError": "The 'string above is incorrect as it forgets to close the brace", "pluralWithInvalidCase": "{ count, plural, woohoo{huh?} other{lol} }"}''' }, useEscaping: true); } on L10nException { expect(logger.errorText, contains('''[app_en.arb:hello] ICU Syntax Error: Expected "}" but found no tokens. Hello { name ^[app_en.arb:plural] ICU Syntax Error: Expected "}" but found no tokens. This is an incorrectly formatted plural: { count, plural, zero{No frog} one{One frog} other{{count} frogs} ^[app_en.arb:explanationWithLexingError] ICU Lexing Error: Unmatched single quotes. The 'string above is incorrect as it forgets to close the brace ^[app_en.arb:pluralWithInvalidCase] ICU Syntax Error: Plural expressions case must be one of "zero", "one", "two", "few", "many", or "other". { count, plural, woohoo{huh?} other{lol} } ^''')); } });
testWithoutContext('errors thrown in multiple languages are all shown', () { try { setupLocalizations(<String, String>{ 'en': '{ "hello": "Hello { name" }', 'es': '{ "hello": "Hola { name" }', }); } on L10nException { expect(logger.errorText, contains('''[app_en.arb:hello] ICU Syntax Error: Expected "}" but found no tokens. Hello { name ^[app_es.arb:hello] ICU Syntax Error: Expected "}" but found no tokens. Hola { name ^''')); } }); });
testWithoutContext('intl package import should be kept in subclass files when plurals are included', () { const String pluralMessageArb = '''{ "helloWorlds": "{count,plural, =0{Hello} =1{Hello World} =2{Hello two worlds} few{Hello {count} worlds} many{Hello all {count} worlds} other{Hello other {count} worlds}}", "@helloWorlds": { "description": "A plural message", "placeholders": { "count": {} } }}'''; const String pluralMessageEsArb = '''{ "helloWorlds": "{count,plural, =0{ES - Hello} =1{ES - Hello World} =2{ES - Hello two worlds} few{ES - Hello {count} worlds} many{ES - Hello all {count} worlds} other{ES - Hello other {count} worlds}}"}'''; setupLocalizations(<String, String>{ 'en': pluralMessageArb, 'es': pluralMessageEsArb, }); expect(getGeneratedFileContent(locale: 'en'), contains(intlImportDartCode)); expect(getGeneratedFileContent(locale: 'es'), contains(intlImportDartCode)); });
testWithoutContext('intl package import should be kept in subclass files when select is included', () { const String selectMessageArb = '''{ "genderSelect": "{gender, select, female {She} male {He} other {they} }", "@genderSelect": { "description": "A select message", "placeholders": { "gender": {} } }}'''; const String selectMessageEsArb = '''{ "genderSelect": "{gender, select, female {ES - She} male {ES - He} other {ES - they} }"}'''; setupLocalizations(<String, String>{ 'en': selectMessageArb, 'es': selectMessageEsArb, }); expect(getGeneratedFileContent(locale: 'en'), contains(intlImportDartCode)); expect(getGeneratedFileContent(locale: 'es'), contains(intlImportDartCode)); });
testWithoutContext('check indentation on generated files', () { setupLocalizations(<String, String>{ 'en': singleMessageArbFileString, 'es': singleEsMessageArbFileString, }); // Tests a few of the lines in the generated code. // Localizations lookup code final String localizationsFile = getGeneratedFileContent(); expect(localizationsFile.contains(' switch (locale.languageCode) {'), true); expect(localizationsFile.contains(" case 'en': return AppLocalizationsEn();"), true); expect(localizationsFile.contains(" case 'es': return AppLocalizationsEs();"), true); expect(localizationsFile.contains(' }'), true);
// Supported locales list expect(localizationsFile.contains(' static const List<Locale> supportedLocales = <Locale>['), true); expect(localizationsFile.contains(" Locale('en'),"), true); expect(localizationsFile.contains(" Locale('es')"), true); expect(localizationsFile.contains(' ];'), true); });
testWithoutContext('foundation package import should be omitted from file template when deferred loading = true', () { setupLocalizations(<String, String>{ 'en': singleMessageArbFileString, 'es': singleEsMessageArbFileString, }, useDeferredLoading: true); expect(getGeneratedFileContent(), isNot(contains(foundationImportDartCode))); });
testWithoutContext('foundation package import should be kept in file template when deferred loading = false', () { setupLocalizations(<String, String>{ 'en': singleMessageArbFileString, 'es': singleEsMessageArbFileString, }); expect(getGeneratedFileContent(), contains(foundationImportDartCode)); });
testWithoutContext('check for string interpolation rules', () { const String enArbCheckList = '''{ "one": "The number of {one} elapsed is: 44", "@one": { "description": "test one", "placeholders": { "one": { "type": "String" } } }, "two": "哈{two}哈", "@two": { "description": "test two", "placeholders": { "two": { "type": "String" } } }, "three": "m{three}m", "@three": { "description": "test three", "placeholders": { "three": { "type": "String" } } }, "four": "I have to work _{four}_ sometimes.", "@four": { "description": "test four", "placeholders": { "four": { "type": "String" } } }, "five": "{five} elapsed.", "@five": { "description": "test five", "placeholders": { "five": { "type": "String" } } }, "six": "{six}m", "@six": { "description": "test six", "placeholders": { "six": { "type": "String" } } }, "seven": "hours elapsed: {seven}", "@seven": { "description": "test seven", "placeholders": { "seven": { "type": "String" } } }, "eight": " {eight}", "@eight": { "description": "test eight", "placeholders": { "eight": { "type": "String" } } }, "nine": "m{nine}", "@nine": { "description": "test nine", "placeholders": { "nine": { "type": "String" } } }}''';
// It's fine that the arb is identical -- Just checking // generated code for use of '${variable}' vs '$variable' const String esArbCheckList = '''{ "one": "The number of {one} elapsed is: 44", "two": "哈{two}哈", "three": "m{three}m", "four": "I have to work _{four}_ sometimes.", "five": "{five} elapsed.", "six": "{six}m", "seven": "hours elapsed: {seven}", "eight": " {eight}", "nine": "m{nine}"}'''; setupLocalizations(<String, String>{ 'en': enArbCheckList, 'es': esArbCheckList, }); final String localizationsFile = getGeneratedFileContent(locale: 'es'); expect(localizationsFile, contains(r'$one')); expect(localizationsFile, contains(r'$two')); expect(localizationsFile, contains(r'${three}')); expect(localizationsFile, contains(r'${four}')); expect(localizationsFile, contains(r'$five')); expect(localizationsFile, contains(r'${six}m')); expect(localizationsFile, contains(r'$seven')); expect(localizationsFile, contains(r'$eight')); expect(localizationsFile, contains(r'$nine')); });
testWithoutContext('check for string interpolation rules - plurals', () { const String enArbCheckList = '''{ "first": "{count,plural, =0{test {count} test} =1{哈{count}哈} =2{m{count}m} few{_{count}_} many{{count} test} other{{count}m}}", "@first": { "description": "First set of plural messages to test.", "placeholders": { "count": {} } }, "second": "{count,plural, =0{test {count}} other{ {count}}}", "@second": { "description": "Second set of plural messages to test.", "placeholders": { "count": {} } }, "third": "{total,plural, =0{test {total}} other{ {total}}}", "@third": { "description": "Third set of plural messages to test, for number.", "placeholders": { "total": { "type": "int", "format": "compactLong" } } }}''';
// It's fine that the arb is identical -- Just checking // generated code for use of '${variable}' vs '$variable' const String esArbCheckList = '''{ "first": "{count,plural, =0{test {count} test} =1{哈{count}哈} =2{m{count}m} few{_{count}_} many{{count} test} other{{count}m}}", "second": "{count,plural, =0{test {count}} other{ {count}}}"}'''; setupLocalizations(<String, String>{ 'en': enArbCheckList, 'es': esArbCheckList, }); final String localizationsFile = getGeneratedFileContent(locale: 'es'); expect(localizationsFile, contains(r'test $count test')); expect(localizationsFile, contains(r'哈$count哈')); expect(localizationsFile, contains(r'm${count}m')); expect(localizationsFile, contains(r'_${count}_')); expect(localizationsFile, contains(r'$count test')); expect(localizationsFile, contains(r'${count}m')); expect(localizationsFile, contains(r'test $count')); expect(localizationsFile, contains(r' $count')); expect(localizationsFile, contains(r'String totalString = totalNumberFormat')); expect(localizationsFile, contains(r'totalString')); expect(localizationsFile, contains(r'totalString')); });
testWithoutContext( 'should throw with descriptive error message when failing to parse the ' 'arb file', () { const String arbFileWithTrailingComma = '''{ "title": "Stocks", "@title": { "description": "Title for the Stocks application" },}'''; expect( () { setupLocalizations(<String, String>{ 'en': arbFileWithTrailingComma }); }, throwsA(isA<L10nException>().having( (L10nException e) => e.message, 'message', allOf( contains('app_en.arb'), contains('FormatException'), contains('Unexpected character'), ), )), ); }, );
testWithoutContext('should throw when resource is missing resource attribute (isResourceAttributeRequired = true)', () { const String arbFileWithMissingResourceAttribute = '''{ "title": "Stocks"}'''; expect( () { setupLocalizations( <String, String>{ 'en': arbFileWithMissingResourceAttribute }, areResourceAttributeRequired: true, ); }, throwsA(isA<L10nException>().having( (L10nException e) => e.message, 'message', contains('Resource attribute "@title" was not found'), )), ); });
group('checks for method/getter formatting', () { testWithoutContext('cannot contain non-alphanumeric symbols', () { const String nonAlphaNumericArbFile = '''{ "title!!": "Stocks", "@title!!": { "description": "Title for the Stocks application" }}'''; expect( () => setupLocalizations(<String, String>{ 'en': nonAlphaNumericArbFile }), throwsA(isA<L10nException>().having( (L10nException e) => e.message, 'message', contains('Invalid ARB resource name'), )), ); });
testWithoutContext('must start with lowercase character', () { const String nonAlphaNumericArbFile = '''{ "Title": "Stocks", "@Title": { "description": "Title for the Stocks application" }}'''; expect( () => setupLocalizations(<String, String>{ 'en': nonAlphaNumericArbFile }), throwsA(isA<L10nException>().having( (L10nException e) => e.message, 'message', contains('Invalid ARB resource name'), )), ); });
testWithoutContext('cannot start with a number', () { const String nonAlphaNumericArbFile = '''{ "123title": "Stocks", "@123title": { "description": "Title for the Stocks application" }}'''; expect( () => setupLocalizations(<String, String>{ 'en': nonAlphaNumericArbFile }), throwsA(isA<L10nException>().having( (L10nException e) => e.message, 'message', contains('Invalid ARB resource name'), )), ); });
testWithoutContext('can start with and contain a dollar sign', () { const String dollarArbFile = r'''{ "$title$": "Stocks", "@$title$": { "description": "Title for the application" }}'''; setupLocalizations(<String, String>{ 'en': dollarArbFile }); }); });
testWithoutContext('throws when the language code is not supported', () { const String arbFileWithInvalidCode = '''{ "@@locale": "invalid", "title": "invalid"}''';
final Directory l10nDirectory = fs.currentDirectory.childDirectory('lib').childDirectory('l10n') ..createSync(recursive: true); l10nDirectory.childFile('app_invalid.arb') .writeAsStringSync(arbFileWithInvalidCode);
expect( () { LocalizationsGenerator( fileSystem: fs, inputPathString: defaultL10nPathString, outputPathString: defaultL10nPathString, templateArbFileName: 'app_invalid.arb', outputFileString: defaultOutputFileString, classNameString: defaultClassNameString, logger: logger, ) ..loadResources() ..writeOutputFiles(); }, throwsA(isA<L10nException>().having( (L10nException e) => e.message, 'message', contains('"invalid" is not a supported language code.'), )), ); }); });
testWithoutContext('should generate a valid pubspec.yaml file when using synthetic package if it does not already exist', () { setupLocalizations(<String, String>{ 'en': singleMessageArbFileString, }); final Directory outputDirectory = fs.directory(syntheticPackagePath); final File pubspecFile = outputDirectory.childFile('pubspec.yaml'); expect(pubspecFile.existsSync(), isTrue);
final YamlNode yamlNode = loadYamlNode(pubspecFile.readAsStringSync()); expect(yamlNode, isA<YamlMap>());
final YamlMap yamlMap = yamlNode as YamlMap; final String pubspecName = yamlMap['name'] as String; final String pubspecDescription = yamlMap['description'] as String; expect(pubspecName, 'synthetic_package'); expect(pubspecDescription, "The Flutter application's synthetic package."); });
testWithoutContext('should not overwrite existing pubspec.yaml file when using synthetic package', () { final File pubspecFile = fs.file(fs.path.join(syntheticPackagePath, 'pubspec.yaml')) ..createSync(recursive: true) ..writeAsStringSync('abcd'); setupLocalizations(<String, String>{ 'en': singleMessageArbFileString, }); // The original pubspec file should not be overwritten. expect(pubspecFile.readAsStringSync(), 'abcd'); });
testWithoutContext('can use type: int without specifying a format', () { const String arbFile = '''{ "orderNumber": "This is order #{number}.", "@orderNumber": { "description": "The title for an order with a given number.", "placeholders": { "number": { "type": "int" } } }}'''; setupLocalizations(<String, String>{ 'en': arbFile, }); expect(getGeneratedFileContent(locale: 'en'), containsIgnoringWhitespace(r'''String orderNumber(int number) { return 'This is order #$number.';}''')); expect(getGeneratedFileContent(locale: 'en'), isNot(contains(intlImportDartCode))); });
testWithoutContext('app localizations lookup is a public method', () { setupLocalizations(<String, String>{ 'en': singleMessageArbFileString }); expect(getGeneratedFileContent(), containsIgnoringWhitespace(r'''AppLocalizations lookupAppLocalizations(Locale locale) {''')); });
testWithoutContext('escaping with single quotes', () { const String arbFile = '''{ "singleQuote": "Flutter''s amazing!", "@singleQuote": { "description": "A message with a single quote." }}'''; setupLocalizations(<String, String>{ 'en': arbFile }, useEscaping: true); expect(getGeneratedFileContent(locale: 'en'), contains(r"Flutter\'s amazing")); });
testWithoutContext('suppress warnings flag actually suppresses warnings', () { const String pluralMessageWithOverriddenParts = '''{ "helloWorlds": "{count,plural, =0{Hello}zero{hello} other{hi}}", "@helloWorlds": { "description": "Properly formatted but has redundant zero cases.", "placeholders": { "count": {} } }}'''; setupLocalizations( <String, String>{ 'en': pluralMessageWithOverriddenParts }, suppressWarnings: true, ); expect(logger.hadWarningOutput, isFalse); });
testWithoutContext('can use decimalPatternDigits with decimalDigits optional parameter', () { const String arbFile = '''{ "treeHeight": "Tree height is {height}m.", "@treeHeight": { "placeholders": { "height": { "type": "double", "format": "decimalPatternDigits", "optionalParameters": { "decimalDigits": 3 } } } }}'''; setupLocalizations(<String, String>{ 'en': arbFile }); final String localizationsFile = getGeneratedFileContent(locale: 'en'); expect(localizationsFile, containsIgnoringWhitespace(r'''String treeHeight(double height) {''')); expect(localizationsFile, containsIgnoringWhitespace(r'''NumberFormat.decimalPatternDigits( locale: localeName, decimalDigits: 3);''')); });
// Regression test for https://github.com/flutter/flutter/issues/125461. testWithoutContext('dollar signs are escaped properly when there is a select clause', () { const String dollarSignWithSelect = r'''{ "dollarSignWithSelect": "$nice_bug\nHello Bug! Manifistation #1 {selectPlaceholder, select, case{message} other{messageOther}}"}'''; setupLocalizations(<String, String>{ 'en': dollarSignWithSelect }); expect(getGeneratedFileContent(locale: 'en'), contains(r'\$nice_bug\nHello Bug! Manifistation #1 $_temp0')); });
testWithoutContext('can generate method with named parameter', () { const String arbFile = '''{ "helloName": "Hello {name}!", "@helloName": { "description": "A more personal greeting", "placeholders": { "name": { "type": "String", "description": "The name of the person to greet" } } }, "helloNameAndAge": "Hello {name}! You are {age} years old.", "@helloNameAndAge": { "description": "A more personal greeting", "placeholders": { "name": { "type": "String", "description": "The name of the person to greet" }, "age": { "type": "int", "description": "The age of the person to greet" } } }} '''; setupLocalizations(<String, String>{ 'en': arbFile }, useNamedParameters: true); final String localizationsFile = getGeneratedFileContent(locale: 'en'); expect(localizationsFile, containsIgnoringWhitespace(r'''String helloName({required String name}) { ''')); expect(localizationsFile, containsIgnoringWhitespace(r'''String helloNameAndAge({required String name, required int age}) { ''')); });}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277// 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/base/io.dart';import 'package:flutter_tools/src/base/logger.dart';import 'package:flutter_tools/src/devfs.dart';import 'package:flutter_tools/src/project.dart';import 'package:flutter_tools/src/reporting/github_template.dart';
import '../src/common.dart';import '../src/context.dart';
void main() { late BufferLogger logger; late FileSystem fs;
setUp(() { logger = BufferLogger.test(); fs = MemoryFileSystem.test(); });
group('GitHub template creator', () { testWithoutContext('similar issues URL', () { expect( GitHubTemplateCreator.toolCrashSimilarIssuesURL('this is a 100% error'), 'https://github.com/flutter/flutter/issues?q=is%3Aissue+this+is+a+100%25+error', ); });
group('sanitized error message', () { testWithoutContext('ProcessException', () { expect( GitHubTemplateCreator.sanitizedCrashException( const ProcessException('cd', <String>['path/to/something']) ), 'ProcessException: Command: cd, OS error code: 0', ); expect( GitHubTemplateCreator.sanitizedCrashException( const ProcessException('cd', <String>['path/to/something'], 'message') ), 'ProcessException: message Command: cd, OS error code: 0', ); expect( GitHubTemplateCreator.sanitizedCrashException( const ProcessException('cd', <String>['path/to/something'], 'message', -19) ), 'ProcessException: message Command: cd, OS error code: -19', ); });
testWithoutContext('FileSystemException', () { expect( GitHubTemplateCreator.sanitizedCrashException( const FileSystemException('delete failed', 'path/to/something') ), 'FileSystemException: delete failed, null', ); expect( GitHubTemplateCreator.sanitizedCrashException( const FileSystemException('delete failed', 'path/to/something', OSError('message', -19)) ), 'FileSystemException: delete failed, OS Error: message, errno = -19', ); });
testWithoutContext('SocketException', () { expect( GitHubTemplateCreator.sanitizedCrashException( SocketException( 'message', osError: const OSError('message', -19), address: InternetAddress.anyIPv6, port: 2000 ) ), 'SocketException: message, OS Error: message, errno = -19', ); });
testWithoutContext('DevFSException', () { final StackTrace stackTrace = StackTrace.fromString('''#0 _File.open.<anonymous closure> (dart:io/file_impl.dart:366:9)#1 _rootRunUnary (dart:async/zone.dart:1141:38)'''); expect( GitHubTemplateCreator.sanitizedCrashException( DevFSException('message', ArgumentError('argument error message'), stackTrace) ), 'DevFSException: message', ); });
testWithoutContext('ArgumentError', () { expect( GitHubTemplateCreator.sanitizedCrashException( ArgumentError('argument error message') ), 'ArgumentError: Invalid argument(s): argument error message', ); });
testWithoutContext('Error', () { expect( GitHubTemplateCreator.sanitizedCrashException( FakeError() ), 'FakeError: (#0 _File.open.<anonymous closure> (dart:io/file_impl.dart:366:9))', ); });
testWithoutContext('String', () { expect( GitHubTemplateCreator.sanitizedCrashException( 'May have non-tool-internal info, very long string, 0b8abb4724aa590dd0f429683339b' // ignore: missing_whitespace_between_adjacent_strings '24aa590dd0f429683339b1e045a1594d0b8abb4724aa590dd0f429683339b1e045a1594d0b8abb' '24aa590dd0f429683339b1e045a1594d0b8abb4724aa590dd0f429683339b1e045a1594d0b8abb' '24aa590dd0f429683339b1e045a1594d0b8abb4724aa590dd0f429683339b1e045a1594d0b8abb' '24aa590dd0f429683339b1e045a1594d0b8abb4724aa590dd0f429683339b1e045a1594d0b8abb' '24aa590dd0f429683339b1e045a1594d0b8abb4724aa590dd0f429683339b1e045a1594d0b8abb' '24aa590dd0f429683339b1e045a1594d0b8abb4724aa590dd0f429683339b1e045a1594d0b8abb' '24aa590dd0f429683339b1e045a1594d0b8abb4724aa590dd0f429683339b1e045a1594d0b8abb' '24aa590dd0f429683339b1e045a1594d0b8abb4724aa590dd0f429683339b1e045a1594d0b8abb' '24aa590dd0f429683339b1e045a1594d0b8abb4724aa590dd0f429683339b1e045a1594d0b8abb' '24aa590dd0f429683339b1e045a1594d0b8abb4724aa590dd0f429683339b1e045a1594d0b8abb' '24aa590dd0f429683339b1e045a1594d0b8abb4724aa590dd0f429683339b1e045a1594d0b8abb' '24aa590dd0f429683339b1e045a1594d0b8abb4724aa590dd0f429683339b1e045a1594d0b8abb' ), 'String: <1,016 characters>', ); });
testWithoutContext('Exception', () { expect( GitHubTemplateCreator.sanitizedCrashException( Exception('May have non-tool-internal info') ), '_Exception', ); }); });
group('new issue template URL', () { late StackTrace stackTrace; late Error error; const String command = 'flutter test'; const String doctorText = ' [✓] Flutter (Channel report';
setUp(() async { stackTrace = StackTrace.fromString('trace'); error = ArgumentError('argument error message'); });
testUsingContext('shows GitHub issue URL', () async { final GitHubTemplateCreator creator = GitHubTemplateCreator( fileSystem: fs, logger: logger, flutterProjectFactory: FlutterProjectFactory( fileSystem: fs, logger: logger, ), ); expect( await creator.toolCrashIssueTemplateGitHubURL(command, error, stackTrace, doctorText), 'https://github.com/flutter/flutter/issues/new?title=%5Btool_crash%5D+ArgumentError%3A+' 'Invalid+argument%28s%29%3A+argument+error+message&body=%23%23+Command%0A%60%60%60%0A' 'flutter+test%0A%60%60%60%0A%0A%23%23+Steps+to+Reproduce%0A1.+...%0A2.+...%0A3.+...%0' 'A%0A%23%23+Logs%0AArgumentError%3A+Invalid+argument%28s%29%3A+argument+error+message' '%0A%60%60%60%0Atrace%0A%60%60%60%0A%60%60%60%0A+%5B%E2%9C%93%5D+Flutter+%28Channel+r' 'eport%0A%60%60%60%0A%0A%23%23+Flutter+Application+Metadata%0ANo+pubspec+in+working+d' 'irectory.%0A&labels=tool%2Csevere%3A+crash' ); }, overrides: <Type, Generator>{ FileSystem: () => MemoryFileSystem.test(), ProcessManager: () => FakeProcessManager.any(), });
testUsingContext('app metadata', () async { final GitHubTemplateCreator creator = GitHubTemplateCreator( fileSystem: fs, logger: logger, flutterProjectFactory: FlutterProjectFactory( fileSystem: fs, logger: logger, ), ); final Directory projectDirectory = fs.currentDirectory;
projectDirectory .childFile('pubspec.yaml') .writeAsStringSync('''name: failing_appversion: 2.0.1+100flutter: uses-material-design: true module: androidX: true androidPackage: com.example.failing.android iosBundleIdentifier: com.example.failing.ios''');
final File pluginsFile = projectDirectory.childFile('.flutter-plugins'); pluginsFile .writeAsStringSync('''camera=/fake/pub.dartlang.org/camera-0.5.7+2/device_info=/fake/pub.dartlang.org/pub.dartlang.org/device_info-0.4.1+4/ ''');
final File metadataFile = projectDirectory.childFile('.metadata'); metadataFile .writeAsStringSync('''version: revision: 0b8abb4724aa590dd0f429683339b1e045a1594d channel: stable
project_type: app ''');
final String actualURL = await creator.toolCrashIssueTemplateGitHubURL(command, error, stackTrace, doctorText); final String? actualBody = Uri.parse(actualURL).queryParameters['body']; const String expectedBody = '''## Command```flutter test```
## Steps to Reproduce1. ...2. ...3. ...
## LogsArgumentError: Invalid argument(s): argument error message```trace`````` [✓] Flutter (Channel report```
## Flutter Application Metadata**Type**: app**Version**: 2.0.1+100**Material**: true**Android X**: true**Module**: true**Plugin**: false**Android package**: com.example.failing.android**iOS bundle identifier**: com.example.failing.ios**Creation channel**: stable**Creation framework version**: 0b8abb4724aa590dd0f429683339b1e045a1594d### Pluginscamera-0.5.7+2device_info-0.4.1+4
''';
expect(actualBody, expectedBody); }, overrides: <Type, Generator>{ FileSystem: () => fs, ProcessManager: () => FakeProcessManager.any(), }); }); });}
class FakeError extends Error { @override StackTrace get stackTrace => StackTrace.fromString('''#0 _File.open.<anonymous closure> (dart:io/file_impl.dart:366:9)#1 _rootRunUnary (dart:async/zone.dart:1141:38)''');
@override String toString() => 'PII to ignore';}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230// 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/application_package.dart';import 'package:flutter_tools/src/asset.dart';import 'package:flutter_tools/src/build_info.dart';import 'package:flutter_tools/src/build_system/tools/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/project.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:package_config/package_config.dart';import 'package:test/fake.dart';import 'package:vm_service/vm_service.dart' as vm_service;
class FakeDevFs extends Fake implements DevFS { @override Future<void> destroy() async { }
@override List<Uri> sources = <Uri>[];
@override DateTime? lastCompiled;
@override PackageConfig? lastPackageConfig;
@override Set<String> assetPathsToEvict = <String>{};
@override Set<String> shaderPathsToEvict= <String>{};
@override Set<String> scenePathsToEvict= <String>{};
@override Uri? baseUri;}
class FakeDevice extends Fake implements Device { FakeDevice({ TargetPlatform targetPlatform = TargetPlatform.tester, }) : _targetPlatform = targetPlatform;
final TargetPlatform _targetPlatform;
bool disposed = false;
@override bool isSupported() => true;
@override bool supportsHotReload = true;
@override bool supportsHotRestart = true;
@override bool supportsFlutterExit = true;
@override Future<TargetPlatform> get targetPlatform async => _targetPlatform;
@override Future<String> get sdkNameAndVersion async => 'Tester';
@override Future<bool> get isLocalEmulator async => false;
@override String get name => 'Fake Device';
@override Future<bool> stopApp( ApplicationPackage? app, { String? userIdentifier, }) async { return true; }
@override Future<void> dispose() async { disposed = true; }}
class FakeFlutterDevice extends Fake implements FlutterDevice { FakeFlutterDevice(this.device);
bool stoppedEchoingDeviceLog = false; late Future<UpdateFSReport> Function() updateDevFSReportCallback;
@override final FakeDevice device;
@override Future<void> stopEchoingDeviceLog() async { stoppedEchoingDeviceLog = true; }
@override DevFS? devFS = FakeDevFs();
@override FlutterVmService get vmService => FakeFlutterVmService();
@override ResidentCompiler? generator;
@override Future<UpdateFSReport> updateDevFS({ Uri? mainUri, String? target, AssetBundle? bundle, bool bundleFirstUpload = false, bool bundleDirty = false, bool fullRestart = false, String? projectRootPath, String? pathToReload, required String dillOutputPath, required List<Uri> invalidatedFiles, required PackageConfig packageConfig, }) => updateDevFSReportCallback();
@override TargetPlatform? get targetPlatform => device._targetPlatform;}
class TestFlutterDevice extends FlutterDevice { TestFlutterDevice({ required Device device, required this.exception, required ResidentCompiler generator, }) : super(device, buildInfo: BuildInfo.debug, generator: generator, developmentShaderCompiler: const FakeShaderCompiler());
/// The exception to throw when the connect method is called. final Exception exception;
@override Future<void> connect({ ReloadSources? reloadSources, Restart? restart, CompileExpression? compileExpression, GetSkSLMethod? getSkSLMethod, FlutterProject? flutterProject, PrintStructuredErrorLogMethod? printStructuredErrorLogMethod, bool disableServiceAuthCodes = false, bool enableDds = true, bool cacheStartupProfile = false, bool? ipv6 = false, int? hostVmServicePort, int? ddsPort, bool allowExistingDdsInstance = false, }) async { throw exception; }}
class TestHotRunnerConfig extends HotRunnerConfig { TestHotRunnerConfig({this.successfulHotRestartSetup, this.successfulHotReloadSetup}); bool? successfulHotRestartSetup; bool? successfulHotReloadSetup; bool shutdownHookCalled = false; bool updateDevFSCompleteCalled = false;
@override Future<bool?> setupHotRestart() async { assert(successfulHotRestartSetup != null, 'setupHotRestart is not expected to be called in this test.'); return successfulHotRestartSetup; }
@override Future<bool?> setupHotReload() async { assert(successfulHotReloadSetup != null, 'setupHotReload is not expected to be called in this test.'); return successfulHotReloadSetup; }
@override void updateDevFSComplete() { updateDevFSCompleteCalled = true; }
@override Future<void> runPreShutdownOperations() async { shutdownHookCalled = true; }}
class FakeResidentCompiler extends Fake implements ResidentCompiler { @override void accept() {}}
class FakeFlutterVmService extends Fake implements FlutterVmService { @override vm_service.VmService get service => FakeVmService();
@override Future<List<FlutterView>> getFlutterViews({bool returnEarly = false, Duration delay = const Duration(milliseconds: 50)}) async { return <FlutterView>[]; }}
class FakeVmService extends Fake implements vm_service.VmService { @override Future<vm_service.VM> getVM() async => FakeVm();}
class FakeVm extends Fake implements vm_service.VM { @override List<vm_service.IsolateRef> get isolates => <vm_service.IsolateRef>[];}
class FakeShaderCompiler implements DevelopmentShaderCompiler { const FakeShaderCompiler();
@override void configureCompiler(TargetPlatform? platform) { }
@override Future<DevFSContent> recompileShader(DevFSContent inputShader) { throw UnimplementedError(); }}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977// 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:flutter_tools/src/application_package.dart';import 'package:flutter_tools/src/artifacts.dart';import 'package:flutter_tools/src/asset.dart';import 'package:flutter_tools/src/base/file_system.dart';import 'package:flutter_tools/src/base/io.dart';import 'package:flutter_tools/src/base/platform.dart';import 'package:flutter_tools/src/build_info.dart';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:unified_analytics/unified_analytics.dart';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', () { testUsingContext('invalid', () async { expect(HotRunner.validateReloadReport(vm_service.ReloadReport.parse(<String, dynamic>{ 'type': 'ReloadReport', 'success': false, 'details': <String, dynamic>{}, })), false); expect(HotRunner.validateReloadReport(vm_service.ReloadReport.parse(<String, dynamic>{ 'type': 'ReloadReport', 'success': false, 'details': <String, dynamic>{ 'notices': <Map<String, dynamic>>[ ], }, })), false); expect(HotRunner.validateReloadReport(vm_service.ReloadReport.parse(<String, dynamic>{ 'type': 'ReloadReport', 'success': false, 'details': <String, dynamic>{ 'notices': <String, dynamic>{ 'message': 'error', }, }, })), false); expect(HotRunner.validateReloadReport(vm_service.ReloadReport.parse(<String, dynamic>{ 'type': 'ReloadReport', 'success': false, 'details': <String, dynamic>{ 'notices': <Map<String, dynamic>>[], }, })), false); expect(HotRunner.validateReloadReport(vm_service.ReloadReport.parse(<String, dynamic>{ 'type': 'ReloadReport', 'success': false, 'details': <String, dynamic>{ 'notices': <Map<String, dynamic>>[ <String, dynamic>{'message': false}, ], }, })), false); expect(HotRunner.validateReloadReport(vm_service.ReloadReport.parse(<String, dynamic>{ 'type': 'ReloadReport', 'success': false, 'details': <String, dynamic>{ 'notices': <Map<String, dynamic>>[ <String, dynamic>{'message': <String>['error']}, ], }, })), false); expect(HotRunner.validateReloadReport(vm_service.ReloadReport.parse(<String, dynamic>{ 'type': 'ReloadReport', 'success': false, 'details': <String, dynamic>{ 'notices': <Map<String, dynamic>>[ <String, dynamic>{'message': 'error'}, <String, dynamic>{'message': <String>['error']}, ], }, })), false); expect(HotRunner.validateReloadReport(vm_service.ReloadReport.parse(<String, dynamic>{ 'type': 'ReloadReport', 'success': false, 'details': <String, dynamic>{ 'notices': <Map<String, dynamic>>[ <String, dynamic>{'message': 'error'}, ], }, })), false); expect(HotRunner.validateReloadReport(vm_service.ReloadReport.parse(<String, dynamic>{ 'type': 'ReloadReport', 'success': true, })), true); });
testWithoutContext('ReasonForCancelling toString has a hint for specific errors', () { final ReasonForCancelling reasonForCancelling = ReasonForCancelling( message: 'Const class cannot remove fields', );
expect(reasonForCancelling.toString(), contains('Try performing a hot restart instead.')); }); });
group('hotRestart', () { final FakeResidentCompiler residentCompiler = FakeResidentCompiler(); late FileSystem fileSystem; late TestUsage testUsage; late FakeAnalytics fakeAnalytics;
setUp(() { fileSystem = MemoryFileSystem.test(); testUsage = TestUsage(); fakeAnalytics = getInitializedFakeAnalyticsInstance( fs: fileSystem, fakeFlutterVersion: FakeFlutterVersion(), ); });
group('fails to setup', () { late TestHotRunnerConfig failingTestingConfig; setUp(() { failingTestingConfig = TestHotRunnerConfig( successfulHotRestartSetup: false, successfulHotReloadSetup: false, ); });
testUsingContext('setupHotRestart function fails', () async { fileSystem.file('.packages') ..createSync(recursive: true) ..writeAsStringSync('\n'); final FakeDevice device = FakeDevice(); final List<FlutterDevice> devices = <FlutterDevice>[ FlutterDevice(device, generator: residentCompiler, buildInfo: BuildInfo.debug, developmentShaderCompiler: const FakeShaderCompiler()) ..devFS = FakeDevFs(), ]; final OperationResult result = await HotRunner( devices, debuggingOptions: DebuggingOptions.disabled(BuildInfo.debug), target: 'main.dart', devtoolsHandler: createNoOpHandler, analytics: fakeAnalytics,
).restart(fullRestart: true); expect(result.isOk, false); expect(result.message, 'setupHotRestart failed'); expect(failingTestingConfig.updateDevFSCompleteCalled, false); }, overrides: <Type, Generator>{ HotRunnerConfig: () => failingTestingConfig, Artifacts: () => Artifacts.test(), FileSystem: () => fileSystem, Platform: () => FakePlatform(), ProcessManager: () => FakeProcessManager.any(), });
testUsingContext('setupHotReload function fails', () async { fileSystem.file('.packages') ..createSync(recursive: true) ..writeAsStringSync('\n'); final FakeDevice device = FakeDevice(); final FakeFlutterDevice fakeFlutterDevice = FakeFlutterDevice(device); final List<FlutterDevice> devices = <FlutterDevice>[ fakeFlutterDevice, ]; final OperationResult result = await HotRunner( devices, debuggingOptions: DebuggingOptions.disabled(BuildInfo.debug), target: 'main.dart', devtoolsHandler: createNoOpHandler, reassembleHelper: ( List<FlutterDevice?> flutterDevices, Map<FlutterDevice?, List<FlutterView>> viewCache, void Function(String message)? onSlow, String reloadMessage, ) async => ReassembleResult( <FlutterView?, FlutterVmService?>{null: null}, false, true, ), analytics: fakeAnalytics, ).restart(); expect(result.isOk, false); expect(result.message, 'setupHotReload failed'); expect(failingTestingConfig.updateDevFSCompleteCalled, false); }, overrides: <Type, Generator>{ HotRunnerConfig: () => failingTestingConfig, Artifacts: () => Artifacts.test(), FileSystem: () => fileSystem, Platform: () => FakePlatform(), ProcessManager: () => FakeProcessManager.any(), }); });
group('shutdown hook tests', () { late TestHotRunnerConfig shutdownTestingConfig;
setUp(() { shutdownTestingConfig = TestHotRunnerConfig(); });
testUsingContext('shutdown hook called after signal', () async { fileSystem.file('.packages') ..createSync(recursive: true) ..writeAsStringSync('\n'); final FakeDevice device = FakeDevice(); final List<FlutterDevice> devices = <FlutterDevice>[ FlutterDevice(device, generator: residentCompiler, buildInfo: BuildInfo.debug, developmentShaderCompiler: const FakeShaderCompiler()), ]; await HotRunner( devices, debuggingOptions: DebuggingOptions.disabled(BuildInfo.debug), target: 'main.dart', analytics: fakeAnalytics, ).cleanupAfterSignal(); expect(shutdownTestingConfig.shutdownHookCalled, true); }, overrides: <Type, Generator>{ HotRunnerConfig: () => shutdownTestingConfig, Artifacts: () => Artifacts.test(), FileSystem: () => fileSystem, Platform: () => FakePlatform(), ProcessManager: () => FakeProcessManager.any(), });
testUsingContext('shutdown hook called after app stop', () async { fileSystem.file('.packages') ..createSync(recursive: true) ..writeAsStringSync('\n'); final FakeDevice device = FakeDevice(); final List<FlutterDevice> devices = <FlutterDevice>[ FlutterDevice(device, generator: residentCompiler, buildInfo: BuildInfo.debug, developmentShaderCompiler: const FakeShaderCompiler()), ]; await HotRunner( devices, debuggingOptions: DebuggingOptions.disabled(BuildInfo.debug), target: 'main.dart', analytics: fakeAnalytics, ).preExit(); expect(shutdownTestingConfig.shutdownHookCalled, true); }, overrides: <Type, Generator>{ HotRunnerConfig: () => shutdownTestingConfig, Artifacts: () => Artifacts.test(), FileSystem: () => fileSystem, Platform: () => FakePlatform(), ProcessManager: () => FakeProcessManager.any(), }); });
group('successful hot restart', () { late TestHotRunnerConfig testingConfig; setUp(() { testingConfig = TestHotRunnerConfig( successfulHotRestartSetup: true, ); }); testUsingContext('correctly tracks time spent for analytics for hot restart', () async { final FakeDevice device = FakeDevice(); final FakeFlutterDevice fakeFlutterDevice = FakeFlutterDevice(device); final List<FlutterDevice> devices = <FlutterDevice>[ fakeFlutterDevice, ];
fakeFlutterDevice.updateDevFSReportCallback = () async => UpdateFSReport( success: true, invalidatedSourcesCount: 2, syncedBytes: 4, scannedSourcesCount: 8, compileDuration: const Duration(seconds: 16), transferDuration: const Duration(seconds: 32), );
final FakeStopwatchFactory fakeStopwatchFactory = FakeStopwatchFactory( stopwatches: <String, Stopwatch>{ 'fullRestartHelper': FakeStopwatch()..elapsed = const Duration(seconds: 64), 'updateDevFS': FakeStopwatch()..elapsed = const Duration(seconds: 128), }, );
(fakeFlutterDevice.devFS! as FakeDevFs).baseUri = Uri.parse('file:///base_uri');
final OperationResult result = await HotRunner( devices, debuggingOptions: DebuggingOptions.disabled(BuildInfo.debug), target: 'main.dart', devtoolsHandler: createNoOpHandler, stopwatchFactory: fakeStopwatchFactory, analytics: fakeAnalytics, ).restart(fullRestart: true);
expect(result.isOk, true); expect(testUsage.events, <TestUsageEvent>[ const TestUsageEvent('hot', 'restart', parameters: CustomDimensions( hotEventTargetPlatform: 'flutter-tester', hotEventSdkName: 'Tester', hotEventEmulator: false, hotEventFullRestart: true, hotEventOverallTimeInMs: 64000, hotEventSyncedBytes: 4, hotEventInvalidatedSourcesCount: 2, hotEventTransferTimeInMs: 32000, hotEventCompileTimeInMs: 16000, hotEventFindInvalidatedTimeInMs: 128000, hotEventScannedSourcesCount: 8, )), ]);
expect(fakeAnalytics.sentEvents, contains( Event.hotRunnerInfo( label: 'restart', targetPlatform: 'flutter-tester', sdkName: 'Tester', emulator: false, fullRestart: true, syncedBytes: 4, invalidatedSourcesCount: 2, transferTimeInMs: 32000, overallTimeInMs: 64000, compileTimeInMs: 16000, findInvalidatedTimeInMs: 128000, scannedSourcesCount: 8 ) )); expect(testingConfig.updateDevFSCompleteCalled, true); }, overrides: <Type, Generator>{ HotRunnerConfig: () => testingConfig, Artifacts: () => Artifacts.test(), FileSystem: () => fileSystem, Platform: () => FakePlatform(), ProcessManager: () => FakeProcessManager.any(), Usage: () => testUsage, }); });
group('successful hot reload', () { late TestHotRunnerConfig testingConfig; setUp(() { testingConfig = TestHotRunnerConfig( successfulHotReloadSetup: true, ); }); testUsingContext('correctly tracks time spent for analytics for hot reload', () 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), );
final FakeStopwatchFactory fakeStopwatchFactory = FakeStopwatchFactory( stopwatches: <String, Stopwatch>{ 'updateDevFS': FakeStopwatch()..elapsed = const Duration(seconds: 64), 'reloadSources:reload': FakeStopwatch()..elapsed = const Duration(seconds: 128), 'reloadSources:reassemble': FakeStopwatch()..elapsed = const Duration(seconds: 256), 'reloadSources:vm': FakeStopwatch()..elapsed = const Duration(seconds: 512), }, );
(fakeFlutterDevice.devFS! as FakeDevFs).baseUri = Uri.parse('file:///base_uri');
final OperationResult result = await HotRunner( devices, debuggingOptions: DebuggingOptions.disabled(BuildInfo.debug), target: 'main.dart', devtoolsHandler: createNoOpHandler, stopwatchFactory: fakeStopwatchFactory, analytics: fakeAnalytics, reloadSourcesHelper: ( HotRunner hotRunner, List<FlutterDevice?> flutterDevices, bool? pause, Map<String, dynamic> firstReloadDetails, String? targetPlatform, String? sdkName, bool? emulator, String? reason, Usage usage, Analytics? analytics, ) async { firstReloadDetails['finalLibraryCount'] = 2; firstReloadDetails['receivedLibraryCount'] = 3; firstReloadDetails['receivedClassesCount'] = 4; firstReloadDetails['receivedProceduresCount'] = 5; return OperationResult.ok; }, reassembleHelper: ( List<FlutterDevice?> flutterDevices, Map<FlutterDevice?, List<FlutterView>> viewCache, void Function(String message)? onSlow, String reloadMessage, ) async => ReassembleResult( <FlutterView?, FlutterVmService?>{null: null}, false, true, ), ).restart();
expect(result.isOk, true); expect(testUsage.events, <TestUsageEvent>[ const TestUsageEvent('hot', 'reload', parameters: CustomDimensions( hotEventFinalLibraryCount: 2, hotEventSyncedLibraryCount: 3, hotEventSyncedClassesCount: 4, hotEventSyncedProceduresCount: 5, hotEventSyncedBytes: 8, hotEventInvalidatedSourcesCount: 6, hotEventTransferTimeInMs: 32000, hotEventOverallTimeInMs: 128000, hotEventTargetPlatform: 'flutter-tester', hotEventSdkName: 'Tester', hotEventEmulator: false, hotEventFullRestart: false, hotEventCompileTimeInMs: 16000, hotEventFindInvalidatedTimeInMs: 64000, hotEventScannedSourcesCount: 16, hotEventReassembleTimeInMs: 256000, hotEventReloadVMTimeInMs: 512000, )), ]); expect(fakeAnalytics.sentEvents, contains( Event.hotRunnerInfo( label: 'reload', targetPlatform: 'flutter-tester', sdkName: 'Tester', emulator: false, fullRestart: false, finalLibraryCount: 2, syncedLibraryCount: 3, syncedClassesCount: 4, syncedProceduresCount: 5, syncedBytes: 8, invalidatedSourcesCount: 6, transferTimeInMs: 32000, overallTimeInMs: 128000, compileTimeInMs: 16000, findInvalidatedTimeInMs: 64000, scannedSourcesCount: 16, reassembleTimeInMs: 256000, reloadVMTimeInMs: 512000 ), )); expect(testingConfig.updateDevFSCompleteCalled, true); }, overrides: <Type, Generator>{ HotRunnerConfig: () => testingConfig, Artifacts: () => Artifacts.test(), FileSystem: () => fileSystem, Platform: () => FakePlatform(), ProcessManager: () => FakeProcessManager.any(), Usage: () => testUsage, }); });
group('hot restart that failed to sync dev fs', () { late TestHotRunnerConfig testingConfig; setUp(() { testingConfig = TestHotRunnerConfig( successfulHotRestartSetup: true, ); }); testUsingContext('still calls the devfs complete callback', () async { final FakeDevice device = FakeDevice(); final FakeFlutterDevice fakeFlutterDevice = FakeFlutterDevice(device); final List<FlutterDevice> devices = <FlutterDevice>[ fakeFlutterDevice, ]; fakeFlutterDevice.updateDevFSReportCallback = () async => throw Exception('updateDevFS failed');
final HotRunner runner = HotRunner( devices, debuggingOptions: DebuggingOptions.disabled(BuildInfo.debug), target: 'main.dart', devtoolsHandler: createNoOpHandler, analytics: fakeAnalytics, );
await expectLater(runner.restart(fullRestart: true), throwsA(isA<Exception>().having((Exception e) => e.toString(), 'message', 'Exception: updateDevFS failed'))); expect(testingConfig.updateDevFSCompleteCalled, true); }, overrides: <Type, Generator>{ HotRunnerConfig: () => testingConfig, Artifacts: () => Artifacts.test(), FileSystem: () => fileSystem, Platform: () => FakePlatform(), ProcessManager: () => FakeProcessManager.any(), Usage: () => testUsage, }); });
group('hot reload that failed to sync dev fs', () { late TestHotRunnerConfig testingConfig; setUp(() { testingConfig = TestHotRunnerConfig( successfulHotReloadSetup: true, ); }); testUsingContext('still calls the devfs complete callback', () async { final FakeDevice device = FakeDevice(); final FakeFlutterDevice fakeFlutterDevice = FakeFlutterDevice(device); final List<FlutterDevice> devices = <FlutterDevice>[ fakeFlutterDevice, ]; fakeFlutterDevice.updateDevFSReportCallback = () async => throw Exception('updateDevFS failed');
final HotRunner runner = HotRunner( devices, debuggingOptions: DebuggingOptions.disabled(BuildInfo.debug), target: 'main.dart', devtoolsHandler: createNoOpHandler, analytics: fakeAnalytics, );
await expectLater(runner.restart(), throwsA(isA<Exception>().having((Exception e) => e.toString(), 'message', 'Exception: updateDevFS failed'))); expect(testingConfig.updateDevFSCompleteCalled, true); }, overrides: <Type, Generator>{ HotRunnerConfig: () => testingConfig, Artifacts: () => Artifacts.test(), FileSystem: () => fileSystem, Platform: () => FakePlatform(), ProcessManager: () => FakeProcessManager.any(), Usage: () => testUsage, }); }); });
group('hot attach', () { late FileSystem fileSystem; late FakeAnalytics fakeAnalytics;
setUp(() { fileSystem = MemoryFileSystem.test(); fakeAnalytics = getInitializedFakeAnalyticsInstance( fs: fileSystem, fakeFlutterVersion: FakeFlutterVersion(), ); });
testUsingContext('Exits with code 2 when HttpException is thrown ' 'during VM service connection', () async { fileSystem.file('.packages') ..createSync(recursive: true) ..writeAsStringSync('\n');
final FakeResidentCompiler residentCompiler = FakeResidentCompiler(); final FakeDevice device = FakeDevice(); final List<FlutterDevice> devices = <FlutterDevice>[ TestFlutterDevice( device: device, generator: residentCompiler, exception: const HttpException('Connection closed before full header was received, ' 'uri = http://127.0.0.1:63394/5ZmLv8A59xY=/ws'), ), ];
final int exitCode = await HotRunner(devices, debuggingOptions: DebuggingOptions.enabled(BuildInfo.debug), target: 'main.dart', analytics: fakeAnalytics, ).attach(needsFullRestart: false); expect(exitCode, 2); }, overrides: <Type, Generator>{ HotRunnerConfig: () => TestHotRunnerConfig(), Artifacts: () => Artifacts.test(), FileSystem: () => fileSystem, Platform: () => FakePlatform(), ProcessManager: () => FakeProcessManager.any(), }); });
group('hot cleanupAtFinish()', () { late FileSystem fileSystem; late FakeAnalytics fakeAnalytics;
setUp(() { fileSystem = MemoryFileSystem.test(); fakeAnalytics = getInitializedFakeAnalyticsInstance( fs: fileSystem, fakeFlutterVersion: FakeFlutterVersion(), ); });
testUsingContext('disposes each device', () async { final FakeDevice device1 = FakeDevice(); final FakeDevice device2 = FakeDevice(); final FakeFlutterDevice flutterDevice1 = FakeFlutterDevice(device1); final FakeFlutterDevice flutterDevice2 = FakeFlutterDevice(device2);
final List<FlutterDevice> devices = <FlutterDevice>[ flutterDevice1, flutterDevice2, ];
await HotRunner(devices, debuggingOptions: DebuggingOptions.enabled(BuildInfo.debug), target: 'main.dart', analytics: fakeAnalytics, ).cleanupAtFinish();
expect(device1.disposed, true); expect(device2.disposed, true);
expect(flutterDevice1.stoppedEchoingDeviceLog, true); expect(flutterDevice2.stoppedEchoingDeviceLog, true); }); });
group('native assets', () { late TestHotRunnerConfig testingConfig; late FileSystem fileSystem; late FakeAnalytics fakeAnalytics;
setUp(() { fileSystem = MemoryFileSystem.test(); testingConfig = TestHotRunnerConfig( successfulHotRestartSetup: true, ); fakeAnalytics = getInitializedFakeAnalyticsInstance( fs: fileSystem, fakeFlutterVersion: FakeFlutterVersion(), ); }); 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, analytics: fakeAnalytics, ); 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.fuchsia_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, analytics: fakeAnalytics, ); expect( () => hotRunner.run(), throwsToolExit( message: 'Package(s) bar require the native assets feature. ' 'This feature has not yet been implemented for `TargetPlatform.fuchsia_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 { @override Future<void> destroy() async { }
@override List<Uri> sources = <Uri>[];
@override DateTime? lastCompiled;
@override PackageConfig? lastPackageConfig;
@override Set<String> assetPathsToEvict = <String>{};
@override Set<String> shaderPathsToEvict= <String>{};
@override Set<String> scenePathsToEvict= <String>{};
@override Uri? baseUri;}
class FakeDevice extends Fake implements Device { FakeDevice({ TargetPlatform targetPlatform = TargetPlatform.tester, }) : _targetPlatform = targetPlatform;
final TargetPlatform _targetPlatform;
bool disposed = false;
@override bool isSupported() => true;
@override bool supportsHotReload = true;
@override bool supportsHotRestart = true;
@override bool supportsFlutterExit = true;
@override Future<TargetPlatform> get targetPlatform async => _targetPlatform;
@override Future<String> get sdkNameAndVersion async => 'Tester';
@override Future<bool> get isLocalEmulator async => false;
@override String get name => 'Fake Device';
@override Future<bool> stopApp( ApplicationPackage? app, { String? userIdentifier, }) async { return true; }
@override Future<void> dispose() async { disposed = true; }}
class FakeFlutterDevice extends Fake implements FlutterDevice { FakeFlutterDevice(this.device);
bool stoppedEchoingDeviceLog = false; late Future<UpdateFSReport> Function() updateDevFSReportCallback;
@override final FakeDevice device;
@override Future<void> stopEchoingDeviceLog() async { stoppedEchoingDeviceLog = true; }
@override DevFS? devFS = FakeDevFs();
@override FlutterVmService get vmService => FakeFlutterVmService();
@override ResidentCompiler? generator;
@override Future<UpdateFSReport> updateDevFS({ Uri? mainUri, String? target, AssetBundle? bundle, DateTime? firstBuildTime, bool bundleFirstUpload = false, bool bundleDirty = false, bool fullRestart = false, String? projectRootPath, String? pathToReload, required String dillOutputPath, required List<Uri> invalidatedFiles, required PackageConfig packageConfig, }) => updateDevFSReportCallback();
@override TargetPlatform? get targetPlatform => device._targetPlatform;}
class TestFlutterDevice extends FlutterDevice { TestFlutterDevice({ required Device device, required this.exception, required ResidentCompiler generator, }) : super(device, buildInfo: BuildInfo.debug, generator: generator, developmentShaderCompiler: const FakeShaderCompiler());
/// The exception to throw when the connect method is called. final Exception exception;
@override Future<void> connect({ ReloadSources? reloadSources, Restart? restart, CompileExpression? compileExpression, GetSkSLMethod? getSkSLMethod, FlutterProject? flutterProject, PrintStructuredErrorLogMethod? printStructuredErrorLogMethod, bool disableServiceAuthCodes = false, bool enableDds = true, bool cacheStartupProfile = false, bool? ipv6 = false, int? hostVmServicePort, int? ddsPort, bool allowExistingDdsInstance = false, }) async { throw exception; }}
class TestHotRunnerConfig extends HotRunnerConfig { TestHotRunnerConfig({this.successfulHotRestartSetup, this.successfulHotReloadSetup}); bool? successfulHotRestartSetup; bool? successfulHotReloadSetup; bool shutdownHookCalled = false; bool updateDevFSCompleteCalled = false;
@override Future<bool?> setupHotRestart() async { assert(successfulHotRestartSetup != null, 'setupHotRestart is not expected to be called in this test.'); return successfulHotRestartSetup; }
@override Future<bool?> setupHotReload() async { assert(successfulHotReloadSetup != null, 'setupHotReload is not expected to be called in this test.'); return successfulHotReloadSetup; }
@override void updateDevFSComplete() { updateDevFSCompleteCalled = true; }
@override Future<void> runPreShutdownOperations() async { shutdownHookCalled = true; }}
class FakeResidentCompiler extends Fake implements ResidentCompiler { @override void accept() {}}
class FakeFlutterVmService extends Fake implements FlutterVmService { @override vm_service.VmService get service => FakeVmService();
@override Future<List<FlutterView>> getFlutterViews({bool returnEarly = false, Duration delay = const Duration(milliseconds: 50)}) async { return <FlutterView>[]; }}
class FakeVmService extends Fake implements vm_service.VmService { @override Future<vm_service.VM> getVM() async => FakeVm();}
class FakeVm extends Fake implements vm_service.VM { @override List<vm_service.IsolateRef> get isolates => <vm_service.IsolateRef>[];}
class FakeShaderCompiler implements DevelopmentShaderCompiler { const FakeShaderCompiler();
@override void configureCompiler( TargetPlatform? platform, { required ImpellerStatus impellerStatus, }) { }
@override Future<DevFSContent> recompileShader(DevFSContent inputShader) { throw UnimplementedError(); }}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178// 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/html_utils.dart';
import '../src/common.dart';
const String htmlSample1 = '''<!DOCTYPE html><html><head> <title></title> <base href="/foo/222/"> <meta charset="utf-8"> <link rel="icon" type="image/png" href="favicon.png"/></head><body> <div></div> <script src="main.dart.js"></script></body></html>''';
const String htmlSample2 = '''<!DOCTYPE html><html><head> <title></title> <base href="$kBaseHrefPlaceholder"> <meta charset="utf-8"> <link rel="icon" type="image/png" href="favicon.png"/></head><body> <div></div> <script src="main.dart.js"></script> <script> const serviceWorkerVersion = null; </script> <script> navigator.serviceWorker.register('flutter_service_worker.js'); </script></body></html>''';
const String htmlSampleLegacyVar = '''<!DOCTYPE html><html><head> <title></title> <base href="$kBaseHrefPlaceholder"> <meta charset="utf-8"> <link rel="icon" type="image/png" href="favicon.png"/></head><body> <div></div> <script src="main.dart.js"></script> <script> var serviceWorkerVersion = null; </script> <script> navigator.serviceWorker.register('flutter_service_worker.js'); </script></body></html>''';
String htmlSample2Replaced({ required String baseHref, required String serviceWorkerVersion,}) => '''<!DOCTYPE html><html><head> <title></title> <base href="$baseHref"> <meta charset="utf-8"> <link rel="icon" type="image/png" href="favicon.png"/></head><body> <div></div> <script src="main.dart.js"></script> <script> const serviceWorkerVersion = "$serviceWorkerVersion"; </script> <script> navigator.serviceWorker.register('flutter_service_worker.js?v=$serviceWorkerVersion'); </script></body></html>''';
const String htmlSample3 = '''<!DOCTYPE html><html><head> <title></title> <meta charset="utf-8"> <link rel="icon" type="image/png" href="favicon.png"/></head><body> <div></div> <script src="main.dart.js"></script></body></html>''';
void main() { test('can parse baseHref', () { expect(IndexHtml('<base href="/foo/111/">').getBaseHref(), 'foo/111'); expect(IndexHtml(htmlSample1).getBaseHref(), 'foo/222'); expect(IndexHtml(htmlSample2).getBaseHref(), ''); // Placeholder base href. });
test('handles missing baseHref', () { expect(IndexHtml('').getBaseHref(), ''); expect(IndexHtml('<base>').getBaseHref(), ''); expect(IndexHtml(htmlSample3).getBaseHref(), ''); });
test('throws on invalid baseHref', () { expect(() => IndexHtml('<base href>').getBaseHref(), throwsToolExit()); expect(() => IndexHtml('<base href="">').getBaseHref(), throwsToolExit()); expect(() => IndexHtml('<base href="foo/111">').getBaseHref(), throwsToolExit()); expect( () => IndexHtml('<base href="foo/111/">').getBaseHref(), throwsToolExit(), ); expect( () => IndexHtml('<base href="/foo/111">').getBaseHref(), throwsToolExit(), ); });
test('applies substitutions', () { final IndexHtml indexHtml = IndexHtml(htmlSample2); indexHtml.applySubstitutions( baseHref: '/foo/333/', serviceWorkerVersion: 'v123xyz', ); expect( indexHtml.content, htmlSample2Replaced( baseHref: '/foo/333/', serviceWorkerVersion: 'v123xyz', ), ); });
test('applies substitutions with legacy var version syntax', () { final IndexHtml indexHtml = IndexHtml(htmlSampleLegacyVar); indexHtml.applySubstitutions( baseHref: '/foo/333/', serviceWorkerVersion: 'v123xyz', ); expect( indexHtml.content, htmlSample2Replaced( baseHref: '/foo/333/', serviceWorkerVersion: 'v123xyz', ), ); });
test('re-parses after substitutions', () { final IndexHtml indexHtml = IndexHtml(htmlSample2); expect(indexHtml.getBaseHref(), ''); // Placeholder base href.
indexHtml.applySubstitutions( baseHref: '/foo/333/', serviceWorkerVersion: 'v123xyz', ); // The parsed base href should be updated after substitutions. expect(indexHtml.getBaseHref(), 'foo/333'); });}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256// 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:flutter_tools/src/application_package.dart';import 'package:flutter_tools/src/base/io.dart' as io;import 'package:flutter_tools/src/base/logger.dart';import 'package:flutter_tools/src/build_info.dart';import 'package:flutter_tools/src/device.dart';import 'package:flutter_tools/src/project.dart';import 'package:flutter_tools/src/test/integration_test_device.dart';import 'package:flutter_tools/src/test/test_device.dart';import 'package:flutter_tools/src/vmservice.dart';import 'package:stream_channel/stream_channel.dart';import 'package:test/fake.dart';import 'package:vm_service/vm_service.dart' as vm_service;
import '../src/context.dart';import '../src/fake_devices.dart';import '../src/fake_vm_services.dart';
final vm_service.Isolate isolate = vm_service.Isolate( id: '1', pauseEvent: vm_service.Event( kind: vm_service.EventKind.kResume, timestamp: 0 ), breakpoints: <vm_service.Breakpoint>[], libraries: <vm_service.LibraryRef>[ vm_service.LibraryRef( id: '1', uri: 'file:///hello_world/main.dart', name: '', ), ], livePorts: 0, name: 'test', number: '1', pauseOnExit: false, runnable: true, startTime: 0, isSystemIsolate: false, isolateFlags: <vm_service.IsolateFlag>[], extensionRPCs: <String>[kIntegrationTestMethod],);
final FlutterView fakeFlutterView = FlutterView( id: 'a', uiIsolate: isolate,);
final FakeVmServiceRequest listViewsRequest = FakeVmServiceRequest( method: kListViewsMethod, jsonResponse: <String, Object>{ 'views': <Object>[ fakeFlutterView.toJson(), ], },);
final Uri vmServiceUri = Uri.parse('http://localhost:1234');
void main() { late FakeVmServiceHost fakeVmServiceHost; late TestDevice testDevice;
setUp(() { testDevice = IntegrationTestTestDevice( id: 1, device: FakeDevice( 'ephemeral', 'ephemeral', type: PlatformType.android, launchResult: LaunchResult.succeeded(vmServiceUri: vmServiceUri), ), debuggingOptions: DebuggingOptions.enabled( BuildInfo.debug, ), userIdentifier: '', compileExpression: null, );
fakeVmServiceHost = FakeVmServiceHost(requests: <VmServiceExpectation>[ const FakeVmServiceRequest( method: 'streamListen', args: <String, Object>{ 'streamId': 'Isolate', }, ), listViewsRequest, FakeVmServiceRequest( method: 'getIsolate', jsonResponse: isolate.toJson(), args: <String, Object>{ 'isolateId': '1', }, ), const FakeVmServiceRequest( method: 'streamCancel', args: <String, Object>{ 'streamId': 'Isolate', }, ), const FakeVmServiceRequest( method: 'streamListen', args: <String, Object>{ 'streamId': 'Extension', }, ), ]); });
testUsingContext('will not start when package missing', () async { await expectLater( testDevice.start('entrypointPath'), throwsA( isA<TestDeviceException>().having( (Exception e) => e.toString(), 'description', contains('No application found for TargetPlatform.android_arm'), ), ), ); });
testUsingContext('Can start the entrypoint', () async { await testDevice.start('entrypointPath');
expect(await testDevice.vmServiceUri, vmServiceUri); expect(testDevice.finished, doesNotComplete); }, overrides: <Type, Generator>{ ApplicationPackageFactory: () => FakeApplicationPackageFactory(), VMServiceConnector: () => (Uri httpUri, { ReloadSources? reloadSources, Restart? restart, CompileExpression? compileExpression, GetSkSLMethod? getSkSLMethod, FlutterProject? flutterProject, PrintStructuredErrorLogMethod? printStructuredErrorLogMethod, io.CompressionOptions? compression, Device? device, Logger? logger, }) async => fakeVmServiceHost.vmService, });
testUsingContext('Can kill the started device', () async { await testDevice.start('entrypointPath'); await testDevice.kill();
expect(testDevice.finished, completes); }, overrides: <Type, Generator>{ ApplicationPackageFactory: () => FakeApplicationPackageFactory(), VMServiceConnector: () => (Uri httpUri, { ReloadSources? reloadSources, Restart? restart, CompileExpression? compileExpression, GetSkSLMethod? getSkSLMethod, FlutterProject? flutterProject, PrintStructuredErrorLogMethod? printStructuredErrorLogMethod, io.CompressionOptions? compression, Device? device, Logger? logger, }) async => fakeVmServiceHost.vmService, });
testUsingContext('when the device starts without providing an vmService URI', () async { final TestDevice testDevice = IntegrationTestTestDevice( id: 1, device: FakeDevice( 'ephemeral', 'ephemeral', type: PlatformType.android, launchResult: LaunchResult.succeeded(), ), debuggingOptions: DebuggingOptions.enabled( BuildInfo.debug, ), userIdentifier: '', compileExpression: null, );
expect(() => testDevice.start('entrypointPath'), throwsA(isA<TestDeviceException>())); }, overrides: <Type, Generator>{ VMServiceConnector: () => (Uri httpUri, { ReloadSources? reloadSources, Restart? restart, CompileExpression? compileExpression, GetSkSLMethod? getSkSLMethod, FlutterProject? flutterProject, PrintStructuredErrorLogMethod? printStructuredErrorLogMethod, io.CompressionOptions? compression, Device? device, }) async => fakeVmServiceHost.vmService, });
testUsingContext('when the device fails to start', () async { final TestDevice testDevice = IntegrationTestTestDevice( id: 1, device: FakeDevice( 'ephemeral', 'ephemeral', type: PlatformType.android, launchResult: LaunchResult.failed(), ), debuggingOptions: DebuggingOptions.enabled( BuildInfo.debug, ), userIdentifier: '', compileExpression: null, );
expect(() => testDevice.start('entrypointPath'), throwsA(isA<TestDeviceException>())); }, overrides: <Type, Generator>{ VMServiceConnector: () => (Uri httpUri, { ReloadSources? reloadSources, Restart? restart, CompileExpression? compileExpression, GetSkSLMethod? getSkSLMethod, FlutterProject? flutterProject, PrintStructuredErrorLogMethod? printStructuredErrorLogMethod, io.CompressionOptions? compression, Device? device, }) async => fakeVmServiceHost.vmService, });
testUsingContext('Can handle closing of the VM service', () async { final StreamChannel<String> channel = await testDevice.start('entrypointPath'); await fakeVmServiceHost.vmService.dispose(); expect(await channel.stream.isEmpty, true); }, overrides: <Type, Generator>{ ApplicationPackageFactory: () => FakeApplicationPackageFactory(), VMServiceConnector: () => (Uri httpUri, { ReloadSources? reloadSources, Restart? restart, CompileExpression? compileExpression, GetSkSLMethod? getSkSLMethod, FlutterProject? flutterProject, PrintStructuredErrorLogMethod? printStructuredErrorLogMethod, io.CompressionOptions? compression, Device? device, Logger? logger, }) async => fakeVmServiceHost.vmService, });}
class FakeApplicationPackageFactory extends Fake implements ApplicationPackageFactory { @override Future<ApplicationPackage> getPackageForPlatform( TargetPlatform platform, { BuildInfo? buildInfo, File? applicationBinary, }) async => FakeApplicationPackage();}
class FakeApplicationPackage extends Fake implements ApplicationPackage { }123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433// 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:flutter_tools/src/base/file_system.dart';import 'package:flutter_tools/src/convert.dart';import 'package:flutter_tools/src/license_collector.dart';import 'package:package_config/package_config.dart';
import '../src/common.dart';
const String _kMitLicense = r'''MIT License
Copyright (c) 6789 Lester
Permission is hereby granted, free of charge, to any person obtaining a copyof this software and associated documentation files (the "Software"), to dealin the Software without restriction, including without limitation the rightsto use, copy, modify, merge, publish, distribute, sublicense, and/or sellcopies of the Software, and to permit persons to whom the Software isfurnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in allcopies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS ORIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THEAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHERLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THESOFTWARE.''';
const String _kApacheLicense = r''' Apache License Version 2.0, January 2004 http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files.
"Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions:
(a) You must give any other recipients of the Work or Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License.
You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives.
Copyright 1234 Tester
Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.''';
void main() { late FileSystem fileSystem; late LicenseCollector licenseCollector;
setUp(() { fileSystem = MemoryFileSystem.test(); licenseCollector = LicenseCollector(fileSystem: fileSystem); });
testWithoutContext('processes dependent licenses according to instructions', () async { fileSystem.file('foo/NOTICES') ..createSync(recursive: true) ..writeAsStringSync(_kMitLicense); fileSystem.file('bar/NOTICES') ..createSync(recursive: true) ..writeAsStringSync(_kApacheLicense); // NOTICES is preferred over LICENSE fileSystem.file('bar/LICENSE') ..createSync(recursive: true) ..writeAsStringSync('SHOULD NOT BE INCLUDED'); fileSystem.file('fizz/LICENSE') ..createSync(recursive: true) ..writeAsStringSync(_kMitLicense); // intentionally a duplicate
final File packageConfigFile = fileSystem.file('package_config.json') ..writeAsStringSync(json.encode( <String, Object>{ 'configVersion': 2, 'packages': <Object>[ <String, Object>{ 'name': 'foo', 'rootUri': 'file:///foo/', 'packageUri': 'lib/', 'languageVersion': '2.2', }, <String, Object>{ 'name': 'bar', 'rootUri': 'file:///bar/', 'packageUri': 'lib/', 'languageVersion': '2.2', }, <String, Object>{ 'name': 'fizz', 'rootUri': 'file:///fizz/', 'packageUri': 'lib/', 'languageVersion': '2.2', }, ], } )); final PackageConfig packageConfig = await loadPackageConfig(packageConfigFile.absolute); final LicenseResult result = licenseCollector.obtainLicenses(packageConfig, <String, List<File>>{});
// All included licenses are combined in the result. expect(result.combinedLicenses, contains(_kApacheLicense)); expect(result.combinedLicenses, contains(_kMitLicense));
// String from LICENSE file was not included when NOTICES exists. expect(result.combinedLicenses, isNot(contains('SHOULD NOT BE INCLUDED')));
// Licenses are de-duplicated correctly. expect(result.combinedLicenses.split(LicenseCollector.licenseSeparator), hasLength(2));
// All input licenses included in result. final Iterable<String> filePaths = result.dependencies.map((File file) => file.path); expect(filePaths, unorderedEquals(<String>[ '/foo/NOTICES', '/bar/NOTICES', '/fizz/LICENSE', ])); });
testWithoutContext('includes additional LICENSE files as specified by pubspec.yaml', () async { fileSystem.file('foo/NOTICES') ..createSync(recursive: true) ..writeAsStringSync(_kMitLicense); fileSystem.file('bar/NOTICES') ..createSync(recursive: true) ..writeAsStringSync(_kApacheLicense); fileSystem.file('foo.txt').writeAsStringSync('foo.txt'); fileSystem.file('bar.txt').writeAsStringSync('bar.txt');
final File packageConfigFile = fileSystem.file('package_config.json') ..writeAsStringSync(json.encode( <String, Object>{ 'configVersion': 2, 'packages': <Object>[ <String, Object>{ 'name': 'foo', 'rootUri': 'file:///foo/', 'packageUri': 'lib/', 'languageVersion': '2.2', }, <String, Object>{ 'name': 'bar', 'rootUri': 'file:///bar/', 'packageUri': 'lib/', 'languageVersion': '2.2', }, ], } )); final PackageConfig packageConfig = await loadPackageConfig(packageConfigFile.absolute); final LicenseResult result = licenseCollector.obtainLicenses(packageConfig, <String, List<File>>{ 'foo': <File>[fileSystem.file('foo.txt').absolute], 'bar': <File>[fileSystem.file('bar.txt').absolute], });
// Additional license files are included in the result. expect(result.combinedLicenses, contains(_kApacheLicense)); expect(result.combinedLicenses, contains(_kMitLicense)); expect(result.combinedLicenses, contains('foo.txt')); expect(result.combinedLicenses, contains('bar.txt'));
// All input licenses included in result. final Iterable<String> filePaths = result.dependencies.map((File file) => file.path); expect(filePaths, unorderedEquals(<String>[ '/foo/NOTICES', '/bar/NOTICES', '/foo.txt', '/bar.txt', ])); });
testWithoutContext('Returns a LicenseResult with an error message if an additional LICENSE file does not exist', () async { fileSystem.file('foo/NOTICES') ..createSync(recursive: true) ..writeAsStringSync(_kMitLicense);
final File packageConfigFile = fileSystem.file('package_config.json') ..writeAsStringSync(json.encode( <String, Object>{ 'configVersion': 2, 'packages': <Object>[ <String, Object>{ 'name': 'foo', 'rootUri': 'file:///foo/', 'packageUri': 'lib/', 'languageVersion': '2.2', }, ], } )); final PackageConfig packageConfig = await loadPackageConfig(packageConfigFile.absolute);
final LicenseResult licenseResult = licenseCollector.obtainLicenses(packageConfig, <String, List<File>>{ 'foo': <File>[fileSystem.file('foo.txt').absolute, fileSystem.file('foo_2.txt').absolute], // Files do not exist. });
expect(licenseResult.combinedLicenses, ''); expect(licenseResult.dependencies, isEmpty); expect(licenseResult.errorMessages, <String>[ 'package foo specified an additional license at /foo.txt, but this file does not exist.', 'package foo specified an additional license at /foo_2.txt, but this file does not exist.', ]); });
testWithoutContext('Returns a LicenseResult with an error message if an additional license file is not valid utf8', () async { fileSystem.file('foo/NOTICES') ..createSync(recursive: true) ..writeAsStringSync(_kMitLicense); fileSystem.file('foo.txt') ..createSync(recursive: true) ..writeAsBytesSync(<int>[0xFFFE]);
final File packageConfigFile = fileSystem.file('package_config.json') ..writeAsStringSync(json.encode( <String, Object>{ 'configVersion': 2, 'packages': <Object>[ <String, Object>{ 'name': 'foo', 'rootUri': 'file:///foo/', 'packageUri': 'lib/', 'languageVersion': '2.2', }, ], } )); final PackageConfig packageConfig = await loadPackageConfig(packageConfigFile.absolute);
final LicenseResult licenseResult = licenseCollector.obtainLicenses(packageConfig, <String, List<File>>{ 'foo': <File>[fileSystem.file('foo.txt').absolute], });
expect(licenseResult.combinedLicenses, ''); expect(licenseResult.dependencies, isEmpty); expect(licenseResult.errorMessages.single, 'package foo specified an additional license at /foo.txt, but this file could not be read:' "\nFileSystemException: Invalid UTF-8 byte, path = '/foo.txt'", ); });}12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058// 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:flutter_tools/src/base/io.dart';import 'package:flutter_tools/src/base/logger.dart';import 'package:flutter_tools/src/build_info.dart';import 'package:flutter_tools/src/device_port_forwarder.dart';import 'package:flutter_tools/src/ios/devices.dart';import 'package:flutter_tools/src/mdns_discovery.dart';import 'package:flutter_tools/src/project.dart';import 'package:flutter_tools/src/reporting/reporting.dart';import 'package:multicast_dns/multicast_dns.dart';import 'package:test/fake.dart';import 'package:unified_analytics/unified_analytics.dart';
import '../src/common.dart';import '../src/fakes.dart';
void main() { group('mDNS Discovery', () { final int future = DateTime.now().add(const Duration(days: 1)).millisecondsSinceEpoch;
setUp(() { setNetworkInterfaceLister( ({ bool? includeLoopback, bool? includeLinkLocal, InternetAddressType? type, }) async => <NetworkInterface>[], ); });
tearDown(() { resetNetworkInterfaceLister(); });
group('for attach', () { late MDnsClient emptyClient;
setUp(() { emptyClient = FakeMDnsClient(<PtrResourceRecord>[], <String, List<SrvResourceRecord>>{}); });
testWithoutContext('Find result in preliminary client', () async { final MDnsClient client = FakeMDnsClient( <PtrResourceRecord>[ PtrResourceRecord('foo', future, domainName: 'bar'), ], <String, List<SrvResourceRecord>>{ 'bar': <SrvResourceRecord>[ SrvResourceRecord('bar', future, port: 123, weight: 1, priority: 1, target: 'appId'), ], }, );
final MDnsVmServiceDiscovery portDiscovery = MDnsVmServiceDiscovery( mdnsClient: emptyClient, preliminaryMDnsClient: client, logger: BufferLogger.test(), flutterUsage: TestUsage(), analytics: NoOpAnalytics(), );
final MDnsVmServiceDiscoveryResult? result = await portDiscovery.queryForAttach(); expect(result, isNotNull); });
testWithoutContext('Do not find result in preliminary client, but find in main client', () async { final MDnsClient client = FakeMDnsClient( <PtrResourceRecord>[ PtrResourceRecord('foo', future, domainName: 'bar'), ], <String, List<SrvResourceRecord>>{ 'bar': <SrvResourceRecord>[ SrvResourceRecord('bar', future, port: 123, weight: 1, priority: 1, target: 'appId'), ], }, );
final MDnsVmServiceDiscovery portDiscovery = MDnsVmServiceDiscovery( mdnsClient: client, preliminaryMDnsClient: emptyClient, logger: BufferLogger.test(), flutterUsage: TestUsage(), analytics: NoOpAnalytics(), );
final MDnsVmServiceDiscoveryResult? result = await portDiscovery.queryForAttach(); expect(result, isNotNull); });
testWithoutContext('Find multiple in preliminary client', () async { final MDnsClient client = FakeMDnsClient( <PtrResourceRecord>[ PtrResourceRecord('foo', future, domainName: 'bar'), PtrResourceRecord('baz', future, domainName: 'fiz'), ], <String, List<SrvResourceRecord>>{ 'bar': <SrvResourceRecord>[ SrvResourceRecord('bar', future, port: 123, weight: 1, priority: 1, target: 'appId'), ], 'fiz': <SrvResourceRecord>[ SrvResourceRecord('fiz', future, port: 321, weight: 1, priority: 1, target: 'local'), ], }, );
final MDnsVmServiceDiscovery portDiscovery = MDnsVmServiceDiscovery( mdnsClient: emptyClient, preliminaryMDnsClient: client, logger: BufferLogger.test(), flutterUsage: TestUsage(), analytics: NoOpAnalytics(), );
expect(portDiscovery.queryForAttach, throwsToolExit()); });
testWithoutContext('Find duplicates in preliminary client', () async { final MDnsClient client = FakeMDnsClient( <PtrResourceRecord>[ PtrResourceRecord('foo', future, domainName: 'bar'), PtrResourceRecord('foo', future, domainName: 'bar'), ], <String, List<SrvResourceRecord>>{ 'bar': <SrvResourceRecord>[ SrvResourceRecord('bar', future, port: 123, weight: 1, priority: 1, target: 'appId'), ], }, );
final MDnsVmServiceDiscovery portDiscovery = MDnsVmServiceDiscovery( mdnsClient: emptyClient, preliminaryMDnsClient: client, logger: BufferLogger.test(), flutterUsage: TestUsage(), analytics: NoOpAnalytics(), );
final MDnsVmServiceDiscoveryResult? result = await portDiscovery.queryForAttach(); expect(result, isNotNull); });
testWithoutContext('Find similar named in preliminary client', () async { final MDnsClient client = FakeMDnsClient( <PtrResourceRecord>[ PtrResourceRecord('foo', future, domainName: 'bar'), PtrResourceRecord('foo', future, domainName: 'bar (2)'), ], <String, List<SrvResourceRecord>>{ 'bar': <SrvResourceRecord>[ SrvResourceRecord('bar', future, port: 123, weight: 1, priority: 1, target: 'appId'), ], 'bar (2)': <SrvResourceRecord>[ SrvResourceRecord('bar', future, port: 123, weight: 1, priority: 1, target: 'appId'), ], }, );
final MDnsVmServiceDiscovery portDiscovery = MDnsVmServiceDiscovery( mdnsClient: emptyClient, preliminaryMDnsClient: client, logger: BufferLogger.test(), flutterUsage: TestUsage(), analytics: NoOpAnalytics(), );
expect(portDiscovery.queryForAttach, throwsToolExit()); });
testWithoutContext('No ports available', () async { final MDnsVmServiceDiscovery portDiscovery = MDnsVmServiceDiscovery( mdnsClient: emptyClient, preliminaryMDnsClient: emptyClient, logger: BufferLogger.test(), flutterUsage: TestUsage(), analytics: NoOpAnalytics(), );
final int? port = (await portDiscovery.queryForAttach())?.port; expect(port, isNull); });
testWithoutContext('Prints helpful message when there is no ipv4 link local address.', () async { final BufferLogger logger = BufferLogger.test(); final MemoryFileSystem fs = MemoryFileSystem.test(); final FakeAnalytics fakeAnalytics = getInitializedFakeAnalyticsInstance( fs: fs, fakeFlutterVersion: FakeFlutterVersion(), ); final MDnsVmServiceDiscovery portDiscovery = MDnsVmServiceDiscovery( mdnsClient: emptyClient, preliminaryMDnsClient: emptyClient, logger: logger, flutterUsage: TestUsage(), analytics: fakeAnalytics, ); final Uri? uri = await portDiscovery.getVMServiceUriForAttach( '', FakeIOSDevice(), ); expect(uri, isNull); expect(logger.errorText, contains('Personal Hotspot')); expect(fakeAnalytics.sentEvents, contains( Event.appleUsageEvent( workflow: 'ios-mdns', parameter: 'no-ipv4-link-local', ) )); });
testWithoutContext('One port available, no appId', () async { final MDnsClient client = FakeMDnsClient( <PtrResourceRecord>[ PtrResourceRecord('foo', future, domainName: 'bar'), ], <String, List<SrvResourceRecord>>{ 'bar': <SrvResourceRecord>[ SrvResourceRecord('bar', future, port: 123, weight: 1, priority: 1, target: 'appId'), ], }, );
final MDnsVmServiceDiscovery portDiscovery = MDnsVmServiceDiscovery( mdnsClient: client, preliminaryMDnsClient: emptyClient, logger: BufferLogger.test(), flutterUsage: TestUsage(), analytics: NoOpAnalytics(), ); final int? port = (await portDiscovery.queryForAttach())?.port; expect(port, 123); });
testWithoutContext('One port available, no appId, with authCode', () async { final MDnsClient client = FakeMDnsClient( <PtrResourceRecord>[ PtrResourceRecord('foo', future, domainName: 'bar'), ], <String, List<SrvResourceRecord>>{ 'bar': <SrvResourceRecord>[ SrvResourceRecord('bar', future, port: 123, weight: 1, priority: 1, target: 'appId'), ], }, txtResponse: <String, List<TxtResourceRecord>>{ 'bar': <TxtResourceRecord>[ TxtResourceRecord('bar', future, text: 'authCode=xyz\n'), ], }, );
final MDnsVmServiceDiscovery portDiscovery = MDnsVmServiceDiscovery( mdnsClient: client, preliminaryMDnsClient: emptyClient, logger: BufferLogger.test(), flutterUsage: TestUsage(), analytics: NoOpAnalytics(), ); final MDnsVmServiceDiscoveryResult? result = await portDiscovery.queryForAttach(); expect(result?.port, 123); expect(result?.authCode, 'xyz/'); });
testWithoutContext('Multiple ports available, with appId', () async { final MDnsClient client = FakeMDnsClient( <PtrResourceRecord>[ PtrResourceRecord('foo', future, domainName: 'bar'), PtrResourceRecord('baz', future, domainName: 'fiz'), ], <String, List<SrvResourceRecord>>{ 'bar': <SrvResourceRecord>[ SrvResourceRecord('bar', future, port: 123, weight: 1, priority: 1, target: 'appId'), ], 'fiz': <SrvResourceRecord>[ SrvResourceRecord('fiz', future, port: 321, weight: 1, priority: 1, target: 'local'), ], }, );
final MDnsVmServiceDiscovery portDiscovery = MDnsVmServiceDiscovery( mdnsClient: client, preliminaryMDnsClient: emptyClient, logger: BufferLogger.test(), flutterUsage: TestUsage(), analytics: NoOpAnalytics(), ); final int? port = (await portDiscovery.queryForAttach(applicationId: 'fiz'))?.port; expect(port, 321); });
testWithoutContext('Multiple ports available per process, with appId', () async { final MDnsClient client = FakeMDnsClient( <PtrResourceRecord>[ PtrResourceRecord('foo', future, domainName: 'bar'), PtrResourceRecord('baz', future, domainName: 'fiz'), ], <String, List<SrvResourceRecord>>{ 'bar': <SrvResourceRecord>[ SrvResourceRecord('bar', future, port: 1234, weight: 1, priority: 1, target: 'appId'), SrvResourceRecord('bar', future, port: 123, weight: 1, priority: 1, target: 'appId'), ], 'fiz': <SrvResourceRecord>[ SrvResourceRecord('fiz', future, port: 4321, weight: 1, priority: 1, target: 'local'), SrvResourceRecord('fiz', future, port: 321, weight: 1, priority: 1, target: 'local'), ], }, );
final MDnsVmServiceDiscovery portDiscovery = MDnsVmServiceDiscovery( mdnsClient: client, preliminaryMDnsClient: emptyClient, logger: BufferLogger.test(), flutterUsage: TestUsage(), analytics: NoOpAnalytics(), ); final int? port = (await portDiscovery.queryForAttach(applicationId: 'bar'))?.port; expect(port, 1234); });
testWithoutContext('Throws Exception when client throws OSError on start', () async { final MDnsClient client = FakeMDnsClient( <PtrResourceRecord>[], <String, List<SrvResourceRecord>>{}, osErrorOnStart: true, );
final MDnsVmServiceDiscovery portDiscovery = MDnsVmServiceDiscovery( mdnsClient: client, preliminaryMDnsClient: emptyClient, logger: BufferLogger.test(), flutterUsage: TestUsage(), analytics: NoOpAnalytics(), ); expect( () async => portDiscovery.queryForAttach(), throwsException, ); });
testWithoutContext('Correctly builds VM Service URI with hostVmservicePort == 0', () async { final MDnsClient client = FakeMDnsClient( <PtrResourceRecord>[ PtrResourceRecord('foo', future, domainName: 'bar'), ], <String, List<SrvResourceRecord>>{ 'bar': <SrvResourceRecord>[ SrvResourceRecord('bar', future, port: 123, weight: 1, priority: 1, target: 'appId'), ], }, );
final FakeIOSDevice device = FakeIOSDevice(); final MDnsVmServiceDiscovery portDiscovery = MDnsVmServiceDiscovery( mdnsClient: client, preliminaryMDnsClient: emptyClient, logger: BufferLogger.test(), flutterUsage: TestUsage(), analytics: NoOpAnalytics(), ); final Uri? uri = await portDiscovery.getVMServiceUriForAttach('bar', device, hostVmservicePort: 0); expect(uri.toString(), 'http://127.0.0.1:123/'); });
testWithoutContext('Get wireless device IP (iPv4)', () async { final MDnsClient client = FakeMDnsClient( <PtrResourceRecord>[ PtrResourceRecord('foo', future, domainName: 'bar'), ], <String, List<SrvResourceRecord>>{ 'bar': <SrvResourceRecord>[ SrvResourceRecord('bar', future, port: 1234, weight: 1, priority: 1, target: 'appId'), ], }, ipResponse: <String, List<IPAddressResourceRecord>>{ 'appId': <IPAddressResourceRecord>[ IPAddressResourceRecord('Device IP', 0, address: InternetAddress.tryParse('111.111.111.111')!), ], }, txtResponse: <String, List<TxtResourceRecord>>{ 'bar': <TxtResourceRecord>[ TxtResourceRecord('bar', future, text: 'authCode=xyz\n'), ], }, );
final FakeIOSDevice device = FakeIOSDevice(); final MDnsVmServiceDiscovery portDiscovery = MDnsVmServiceDiscovery( mdnsClient: client, preliminaryMDnsClient: emptyClient, logger: BufferLogger.test(), flutterUsage: TestUsage(), analytics: NoOpAnalytics(), ); final Uri? uri = await portDiscovery.getVMServiceUriForAttach( 'bar', device, useDeviceIPAsHost: true, ); expect(uri.toString(), 'http://111.111.111.111:1234/xyz/'); });
testWithoutContext('Get wireless device IP (iPv6)', () async { final MDnsClient client = FakeMDnsClient( <PtrResourceRecord>[ PtrResourceRecord('foo', future, domainName: 'bar'), ], <String, List<SrvResourceRecord>>{ 'bar': <SrvResourceRecord>[ SrvResourceRecord('bar', future, port: 1234, weight: 1, priority: 1, target: 'appId'), ], }, ipResponse: <String, List<IPAddressResourceRecord>>{ 'appId': <IPAddressResourceRecord>[ IPAddressResourceRecord('Device IP', 0, address: InternetAddress.tryParse('1111:1111:1111:1111:1111:1111:1111:1111')!), ], }, txtResponse: <String, List<TxtResourceRecord>>{ 'bar': <TxtResourceRecord>[ TxtResourceRecord('bar', future, text: 'authCode=xyz\n'), ], }, );
final FakeIOSDevice device = FakeIOSDevice(); final MDnsVmServiceDiscovery portDiscovery = MDnsVmServiceDiscovery( mdnsClient: client, preliminaryMDnsClient: emptyClient, logger: BufferLogger.test(), flutterUsage: TestUsage(), analytics: NoOpAnalytics(), ); final Uri? uri = await portDiscovery.getVMServiceUriForAttach( 'bar', device, useDeviceIPAsHost: true, ); expect(uri.toString(), 'http://[1111:1111:1111:1111:1111:1111:1111:1111]:1234/xyz/'); });
testWithoutContext('Throw error if unable to find VM service with app id and device port', () async { final MDnsClient client = FakeMDnsClient( <PtrResourceRecord>[ PtrResourceRecord('foo', future, domainName: 'srv-foo'), PtrResourceRecord('bar', future, domainName: 'srv-bar'), PtrResourceRecord('baz', future, domainName: 'srv-boo'), ], <String, List<SrvResourceRecord>>{ 'srv-foo': <SrvResourceRecord>[ SrvResourceRecord('srv-foo', future, port: 123, weight: 1, priority: 1, target: 'target-foo'), ], 'srv-bar': <SrvResourceRecord>[ SrvResourceRecord('srv-bar', future, port: 123, weight: 1, priority: 1, target: 'target-bar'), ], 'srv-baz': <SrvResourceRecord>[ SrvResourceRecord('srv-baz', future, port: 123, weight: 1, priority: 1, target: 'target-baz'), ], }, ); final FakeIOSDevice device = FakeIOSDevice(); final MDnsVmServiceDiscovery portDiscovery = MDnsVmServiceDiscovery( mdnsClient: client, preliminaryMDnsClient: emptyClient, logger: BufferLogger.test(), flutterUsage: TestUsage(), analytics: NoOpAnalytics(), ); expect( portDiscovery.getVMServiceUriForAttach( 'srv-bar', device, deviceVmservicePort: 321, ), throwsToolExit( message: 'Did not find a Dart VM Service advertised for srv-bar on port 321.' ), ); });
testWithoutContext('Throw error if unable to find VM Service with app id', () async { final MDnsClient client = FakeMDnsClient( <PtrResourceRecord>[ PtrResourceRecord('foo', future, domainName: 'srv-foo'), ], <String, List<SrvResourceRecord>>{ 'srv-foo': <SrvResourceRecord>[ SrvResourceRecord('srv-foo', future, port: 123, weight: 1, priority: 1, target: 'target-foo'), ], }, ); final FakeIOSDevice device = FakeIOSDevice(); final MDnsVmServiceDiscovery portDiscovery = MDnsVmServiceDiscovery( mdnsClient: client, preliminaryMDnsClient: emptyClient, logger: BufferLogger.test(), flutterUsage: TestUsage(), analytics: NoOpAnalytics(), ); expect( portDiscovery.getVMServiceUriForAttach( 'srv-asdf', device, ), throwsToolExit( message: 'Did not find a Dart VM Service advertised for srv-asdf.' ), ); }); });
group('for launch', () { testWithoutContext('Ensure either port or device name are provided', () async { final MDnsClient client = FakeMDnsClient(<PtrResourceRecord>[], <String, List<SrvResourceRecord>>{});
final MDnsVmServiceDiscovery portDiscovery = MDnsVmServiceDiscovery( mdnsClient: client, logger: BufferLogger.test(), flutterUsage: TestUsage(), analytics: NoOpAnalytics(), );
expect(() async => portDiscovery.queryForLaunch(applicationId: 'app-id'), throwsAssertionError); });
testWithoutContext('No ports available', () async { final MDnsClient client = FakeMDnsClient(<PtrResourceRecord>[], <String, List<SrvResourceRecord>>{});
final MDnsVmServiceDiscovery portDiscovery = MDnsVmServiceDiscovery( mdnsClient: client, logger: BufferLogger.test(), flutterUsage: TestUsage(), analytics: NoOpAnalytics(), );
final MDnsVmServiceDiscoveryResult? result = await portDiscovery.queryForLaunch( applicationId: 'app-id', deviceVmservicePort: 123, );
expect(result, null); });
testWithoutContext('Prints helpful message when there is no ipv4 link local address.', () async { final MDnsClient client = FakeMDnsClient(<PtrResourceRecord>[], <String, List<SrvResourceRecord>>{}); final BufferLogger logger = BufferLogger.test(); final MDnsVmServiceDiscovery portDiscovery = MDnsVmServiceDiscovery( mdnsClient: client, logger: logger, flutterUsage: TestUsage(), analytics: NoOpAnalytics(), );
final Uri? uri = await portDiscovery.getVMServiceUriForLaunch( '', FakeIOSDevice(), deviceVmservicePort: 0, ); expect(uri, isNull); expect(logger.errorText, contains('Personal Hotspot')); });
testWithoutContext('Throws Exception when client throws OSError on start', () async { final MDnsClient client = FakeMDnsClient( <PtrResourceRecord>[], <String, List<SrvResourceRecord>>{}, osErrorOnStart: true, );
final MDnsVmServiceDiscovery portDiscovery = MDnsVmServiceDiscovery( mdnsClient: client, logger: BufferLogger.test(), flutterUsage: TestUsage(), analytics: NoOpAnalytics(), ); expect( () async => portDiscovery.queryForLaunch(applicationId: 'app-id', deviceVmservicePort: 123), throwsException, ); });
testWithoutContext('Correctly builds VM Service URI with hostVmservicePort == 0', () async { final MDnsClient client = FakeMDnsClient( <PtrResourceRecord>[ PtrResourceRecord('foo', future, domainName: 'bar'), ], <String, List<SrvResourceRecord>>{ 'bar': <SrvResourceRecord>[ SrvResourceRecord('bar', future, port: 123, weight: 1, priority: 1, target: 'appId'), ], }, );
final FakeIOSDevice device = FakeIOSDevice(); final MDnsVmServiceDiscovery portDiscovery = MDnsVmServiceDiscovery( mdnsClient: client, logger: BufferLogger.test(), flutterUsage: TestUsage(), analytics: NoOpAnalytics(), ); final Uri? uri = await portDiscovery.getVMServiceUriForLaunch( 'bar', device, hostVmservicePort: 0, deviceVmservicePort: 123, ); expect(uri.toString(), 'http://127.0.0.1:123/'); });
testWithoutContext('Get wireless device IP (iPv4)', () async { final MDnsClient client = FakeMDnsClient( <PtrResourceRecord>[ PtrResourceRecord('foo', future, domainName: 'bar'), ], <String, List<SrvResourceRecord>>{ 'bar': <SrvResourceRecord>[ SrvResourceRecord('bar', future, port: 1234, weight: 1, priority: 1, target: 'appId'), ], }, ipResponse: <String, List<IPAddressResourceRecord>>{ 'appId': <IPAddressResourceRecord>[ IPAddressResourceRecord('Device IP', 0, address: InternetAddress.tryParse('111.111.111.111')!), ], }, txtResponse: <String, List<TxtResourceRecord>>{ 'bar': <TxtResourceRecord>[ TxtResourceRecord('bar', future, text: 'authCode=xyz\n'), ], }, );
final FakeIOSDevice device = FakeIOSDevice(); final MDnsVmServiceDiscovery portDiscovery = MDnsVmServiceDiscovery( mdnsClient: client, logger: BufferLogger.test(), flutterUsage: TestUsage(), analytics: NoOpAnalytics(), ); final Uri? uri = await portDiscovery.getVMServiceUriForLaunch( 'bar', device, useDeviceIPAsHost: true, deviceVmservicePort: 1234, ); expect(uri.toString(), 'http://111.111.111.111:1234/xyz/'); });
testWithoutContext('Get wireless device IP (iPv6)', () async { final MDnsClient client = FakeMDnsClient( <PtrResourceRecord>[ PtrResourceRecord('foo', future, domainName: 'bar'), ], <String, List<SrvResourceRecord>>{ 'bar': <SrvResourceRecord>[ SrvResourceRecord('bar', future, port: 1234, weight: 1, priority: 1, target: 'appId'), ], }, ipResponse: <String, List<IPAddressResourceRecord>>{ 'appId': <IPAddressResourceRecord>[ IPAddressResourceRecord('Device IP', 0, address: InternetAddress.tryParse('1111:1111:1111:1111:1111:1111:1111:1111')!), ], }, txtResponse: <String, List<TxtResourceRecord>>{ 'bar': <TxtResourceRecord>[ TxtResourceRecord('bar', future, text: 'authCode=xyz\n'), ], }, );
final FakeIOSDevice device = FakeIOSDevice(); final MDnsVmServiceDiscovery portDiscovery = MDnsVmServiceDiscovery( mdnsClient: client, logger: BufferLogger.test(), flutterUsage: TestUsage(), analytics: NoOpAnalytics(), ); final Uri? uri = await portDiscovery.getVMServiceUriForLaunch( 'bar', device, useDeviceIPAsHost: true, deviceVmservicePort: 1234, ); expect(uri.toString(), 'http://[1111:1111:1111:1111:1111:1111:1111:1111]:1234/xyz/'); });
testWithoutContext('Throw error if unable to find VM Service with app id and device port', () async { final MDnsClient client = FakeMDnsClient( <PtrResourceRecord>[ PtrResourceRecord('foo', future, domainName: 'srv-foo'), PtrResourceRecord('bar', future, domainName: 'srv-bar'), PtrResourceRecord('baz', future, domainName: 'srv-boo'), ], <String, List<SrvResourceRecord>>{ 'srv-foo': <SrvResourceRecord>[ SrvResourceRecord('srv-foo', future, port: 123, weight: 1, priority: 1, target: 'target-foo'), ], 'srv-bar': <SrvResourceRecord>[ SrvResourceRecord('srv-bar', future, port: 123, weight: 1, priority: 1, target: 'target-bar'), ], 'srv-baz': <SrvResourceRecord>[ SrvResourceRecord('srv-baz', future, port: 123, weight: 1, priority: 1, target: 'target-baz'), ], }, ); final FakeIOSDevice device = FakeIOSDevice(); final MDnsVmServiceDiscovery portDiscovery = MDnsVmServiceDiscovery( mdnsClient: client, logger: BufferLogger.test(), flutterUsage: TestUsage(), analytics: NoOpAnalytics(), ); expect( portDiscovery.getVMServiceUriForLaunch( 'srv-bar', device, deviceVmservicePort: 321, ), throwsToolExit( message:'Did not find a Dart VM Service advertised for srv-bar on port 321.'), ); });
testWithoutContext('Matches on application id and device name', () async { final MDnsClient client = FakeMDnsClient( <PtrResourceRecord>[ PtrResourceRecord('foo', future, domainName: 'srv-foo'), PtrResourceRecord('bar', future, domainName: 'srv-bar'), PtrResourceRecord('baz', future, domainName: 'srv-boo'), ], <String, List<SrvResourceRecord>>{ 'srv-bar': <SrvResourceRecord>[ SrvResourceRecord('srv-foo', future, port: 123, weight: 1, priority: 1, target: 'My-Phone.local'), ], }, ); final FakeIOSDevice device = FakeIOSDevice( name: 'My Phone', ); final MDnsVmServiceDiscovery portDiscovery = MDnsVmServiceDiscovery( mdnsClient: client, logger: BufferLogger.test(), flutterUsage: TestUsage(), analytics: NoOpAnalytics(), );
final Uri? uri = await portDiscovery.getVMServiceUriForLaunch( 'srv-bar', device, ); expect(uri.toString(), 'http://127.0.0.1:123/'); });
testWithoutContext('Throw error if unable to find VM Service with app id and device name', () async { final MDnsClient client = FakeMDnsClient( <PtrResourceRecord>[ PtrResourceRecord('foo', future, domainName: 'srv-foo'), PtrResourceRecord('bar', future, domainName: 'srv-bar'), PtrResourceRecord('baz', future, domainName: 'srv-boo'), ], <String, List<SrvResourceRecord>>{ 'srv-foo': <SrvResourceRecord>[ SrvResourceRecord('srv-foo', future, port: 123, weight: 1, priority: 1, target: 'target-foo'), ], }, ); final FakeIOSDevice device = FakeIOSDevice( name: 'My Phone', ); final MDnsVmServiceDiscovery portDiscovery = MDnsVmServiceDiscovery( mdnsClient: client, logger: BufferLogger.test(), flutterUsage: TestUsage(), analytics: NoOpAnalytics(), ); expect( portDiscovery.getVMServiceUriForLaunch( 'srv-bar', device, ), throwsToolExit( message:'Did not find a Dart VM Service advertised for srv-bar'), ); }); });
group('deviceNameMatchesTargetName', () { testWithoutContext('compares case insensitive and without spaces, hypthens, .local', () { final MDnsVmServiceDiscovery portDiscovery = MDnsVmServiceDiscovery( mdnsClient: FakeMDnsClient( <PtrResourceRecord>[], <String, List<SrvResourceRecord>>{}, ), logger: BufferLogger.test(), flutterUsage: TestUsage(), analytics: NoOpAnalytics(), );
expect(portDiscovery.deviceNameMatchesTargetName('My phone', 'My-Phone.local'), isTrue); });
testWithoutContext('includes numbers in comparison', () { final MDnsVmServiceDiscovery portDiscovery = MDnsVmServiceDiscovery( mdnsClient: FakeMDnsClient( <PtrResourceRecord>[], <String, List<SrvResourceRecord>>{}, ), logger: BufferLogger.test(), flutterUsage: TestUsage(), analytics: NoOpAnalytics(), ); expect(portDiscovery.deviceNameMatchesTargetName('My phone', 'My-Phone-2.local'), isFalse); }); });
testWithoutContext('Find firstMatchingVmService with many available and no application id', () async { final MDnsClient client = FakeMDnsClient( <PtrResourceRecord>[ PtrResourceRecord('foo', future, domainName: 'srv-foo'), PtrResourceRecord('bar', future, domainName: 'srv-bar'), PtrResourceRecord('baz', future, domainName: 'srv-boo'), ], <String, List<SrvResourceRecord>>{ 'srv-foo': <SrvResourceRecord>[ SrvResourceRecord('srv-foo', future, port: 123, weight: 1, priority: 1, target: 'target-foo'), ], 'srv-bar': <SrvResourceRecord>[ SrvResourceRecord('srv-bar', future, port: 123, weight: 1, priority: 1, target: 'target-bar'), ], 'srv-baz': <SrvResourceRecord>[ SrvResourceRecord('srv-baz', future, port: 123, weight: 1, priority: 1, target: 'target-baz'), ], }, );
final MDnsVmServiceDiscovery portDiscovery = MDnsVmServiceDiscovery( mdnsClient: client, logger: BufferLogger.test(), flutterUsage: TestUsage(), analytics: NoOpAnalytics(), ); final MDnsVmServiceDiscoveryResult? result = await portDiscovery.firstMatchingVmService(client); expect(result?.domainName, 'srv-foo'); });
testWithoutContext('Find firstMatchingVmService app id', () async { final MDnsClient client = FakeMDnsClient( <PtrResourceRecord>[ PtrResourceRecord('foo', future, domainName: 'srv-foo'), PtrResourceRecord('bar', future, domainName: 'srv-bar'), PtrResourceRecord('baz', future, domainName: 'srv-boo'), ], <String, List<SrvResourceRecord>>{ 'srv-foo': <SrvResourceRecord>[ SrvResourceRecord('srv-foo', future, port: 111, weight: 1, priority: 1, target: 'target-foo'), ], 'srv-bar': <SrvResourceRecord>[ SrvResourceRecord('srv-bar', future, port: 222, weight: 1, priority: 1, target: 'target-bar'), SrvResourceRecord('srv-bar', future, port: 333, weight: 1, priority: 1, target: 'target-bar-2'), ], 'srv-baz': <SrvResourceRecord>[ SrvResourceRecord('srv-baz', future, port: 444, weight: 1, priority: 1, target: 'target-baz'), ], }, );
final MDnsVmServiceDiscovery portDiscovery = MDnsVmServiceDiscovery( mdnsClient: client, logger: BufferLogger.test(), flutterUsage: TestUsage(), analytics: NoOpAnalytics(), ); final MDnsVmServiceDiscoveryResult? result = await portDiscovery.firstMatchingVmService( client, applicationId: 'srv-bar' ); expect(result?.domainName, 'srv-bar'); expect(result?.port, 222); }); testWithoutContext('find with no txt record', () async { final MDnsClient client = FakeMDnsClient( <PtrResourceRecord>[ PtrResourceRecord('foo', future, domainName: 'srv-foo'), ], <String, List<SrvResourceRecord>>{ 'srv-foo': <SrvResourceRecord>[ SrvResourceRecord('srv-foo', future, port: 111, weight: 1, priority: 1, target: 'target-foo'), ], }, ipResponse: <String, List<IPAddressResourceRecord>>{ 'target-foo': <IPAddressResourceRecord>[ IPAddressResourceRecord('target-foo', 0, address: InternetAddress.tryParse('111.111.111.111')!), ], }, );
final MDnsVmServiceDiscovery portDiscovery = MDnsVmServiceDiscovery( mdnsClient: client, logger: BufferLogger.test(), flutterUsage: TestUsage(), analytics: NoOpAnalytics(), ); final MDnsVmServiceDiscoveryResult? result = await portDiscovery.firstMatchingVmService( client, applicationId: 'srv-foo', useDeviceIPAsHost: true, ); expect(result?.domainName, 'srv-foo'); expect(result?.port, 111); expect(result?.authCode, ''); expect(result?.ipAddress?.address, '111.111.111.111'); }); testWithoutContext('find with empty txt record', () async { final MDnsClient client = FakeMDnsClient( <PtrResourceRecord>[ PtrResourceRecord('foo', future, domainName: 'srv-foo'), ], <String, List<SrvResourceRecord>>{ 'srv-foo': <SrvResourceRecord>[ SrvResourceRecord('srv-foo', future, port: 111, weight: 1, priority: 1, target: 'target-foo'), ], }, txtResponse: <String, List<TxtResourceRecord>>{ 'srv-foo': <TxtResourceRecord>[ TxtResourceRecord('srv-foo', future, text: ''), ], }, ipResponse: <String, List<IPAddressResourceRecord>>{ 'target-foo': <IPAddressResourceRecord>[ IPAddressResourceRecord('target-foo', 0, address: InternetAddress.tryParse('111.111.111.111')!), ], }, );
final MDnsVmServiceDiscovery portDiscovery = MDnsVmServiceDiscovery( mdnsClient: client, logger: BufferLogger.test(), flutterUsage: TestUsage(), analytics: NoOpAnalytics(), ); final MDnsVmServiceDiscoveryResult? result = await portDiscovery.firstMatchingVmService( client, applicationId: 'srv-foo', useDeviceIPAsHost: true, ); expect(result?.domainName, 'srv-foo'); expect(result?.port, 111); expect(result?.authCode, ''); expect(result?.ipAddress?.address, '111.111.111.111'); }); testWithoutContext('find with valid txt record', () async { final MDnsClient client = FakeMDnsClient( <PtrResourceRecord>[ PtrResourceRecord('foo', future, domainName: 'srv-foo'), ], <String, List<SrvResourceRecord>>{ 'srv-foo': <SrvResourceRecord>[ SrvResourceRecord('srv-foo', future, port: 111, weight: 1, priority: 1, target: 'target-foo'), ], }, txtResponse: <String, List<TxtResourceRecord>>{ 'srv-foo': <TxtResourceRecord>[ TxtResourceRecord('srv-foo', future, text: 'authCode=xyz\n'), ], }, ipResponse: <String, List<IPAddressResourceRecord>>{ 'target-foo': <IPAddressResourceRecord>[ IPAddressResourceRecord('target-foo', 0, address: InternetAddress.tryParse('111.111.111.111')!), ], }, );
final MDnsVmServiceDiscovery portDiscovery = MDnsVmServiceDiscovery( mdnsClient: client, logger: BufferLogger.test(), flutterUsage: TestUsage(), analytics: NoOpAnalytics(), ); final MDnsVmServiceDiscoveryResult? result = await portDiscovery.firstMatchingVmService( client, applicationId: 'srv-foo', useDeviceIPAsHost: true, ); expect(result?.domainName, 'srv-foo'); expect(result?.port, 111); expect(result?.authCode, 'xyz/'); expect(result?.ipAddress?.address, '111.111.111.111'); }); });}
class FakeMDnsClient extends Fake implements MDnsClient { FakeMDnsClient(this.ptrRecords, this.srvResponse, { this.txtResponse = const <String, List<TxtResourceRecord>>{}, this.ipResponse = const <String, List<IPAddressResourceRecord>>{}, this.osErrorOnStart = false, });
final List<PtrResourceRecord> ptrRecords; final Map<String, List<SrvResourceRecord>> srvResponse; final Map<String, List<TxtResourceRecord>> txtResponse; final Map<String, List<IPAddressResourceRecord>> ipResponse; final bool osErrorOnStart;
@override Future<void> start({ InternetAddress? listenAddress, NetworkInterfacesFactory? interfacesFactory, int mDnsPort = 5353, InternetAddress? mDnsAddress, }) async { if (osErrorOnStart) { throw const OSError('Operation not supported on socket', 102); } }
@override Stream<T> lookup<T extends ResourceRecord>( ResourceRecordQuery query, { Duration timeout = const Duration(seconds: 5), }) { if (T == PtrResourceRecord && query.fullyQualifiedName == MDnsVmServiceDiscovery.dartVmServiceName) { return Stream<PtrResourceRecord>.fromIterable(ptrRecords) as Stream<T>; } if (T == SrvResourceRecord) { final String key = query.fullyQualifiedName; return Stream<SrvResourceRecord>.fromIterable(srvResponse[key] ?? <SrvResourceRecord>[]) as Stream<T>; } if (T == TxtResourceRecord) { final String key = query.fullyQualifiedName; return Stream<TxtResourceRecord>.fromIterable(txtResponse[key] ?? <TxtResourceRecord>[]) as Stream<T>; } if (T == IPAddressResourceRecord) { final String key = query.fullyQualifiedName; return Stream<IPAddressResourceRecord>.fromIterable(ipResponse[key] ?? <IPAddressResourceRecord>[]) as Stream<T>; } throw UnsupportedError('Unsupported query type $T'); }
@override void stop() {}}
class FakeIOSDevice extends Fake implements IOSDevice { FakeIOSDevice({this.name = 'iPhone'});
@override final String name;
@override Future<TargetPlatform> get targetPlatform async => TargetPlatform.ios;
@override bool isSupported() => true;
@override bool isSupportedForProject(FlutterProject flutterProject) => true;
@override DevicePortForwarder get portForwarder => const NoOpDevicePortForwarder();}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600// 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/localizations/gen_l10n_types.dart';import 'package:flutter_tools/src/localizations/message_parser.dart';import '../src/common.dart';
void main() { // Going to test that operator== is overloaded properly since the rest // of the test depends on it. testWithoutContext('node equality', () { final Node actual = Node( ST.placeholderExpr, 0, expectedSymbolCount: 3, children: <Node>[ Node.openBrace(0), Node.string(1, 'var'), Node.closeBrace(4), ], );
final Node expected = Node( ST.placeholderExpr, 0, expectedSymbolCount: 3, children: <Node>[ Node.openBrace(0), Node.string(1, 'var'), Node.closeBrace(4), ], ); expect(actual, equals(expected));
final Node wrongType = Node( ST.pluralExpr, 0, expectedSymbolCount: 3, children: <Node>[ Node.openBrace(0), Node.string(1, 'var'), Node.closeBrace(4), ], ); expect(actual, isNot(equals(wrongType)));
final Node wrongPosition = Node( ST.placeholderExpr, 1, expectedSymbolCount: 3, children: <Node>[ Node.openBrace(0), Node.string(1, 'var'), Node.closeBrace(4), ], ); expect(actual, isNot(equals(wrongPosition)));
final Node wrongChildrenCount = Node( ST.placeholderExpr, 0, expectedSymbolCount: 3, children: <Node>[ Node.string(1, 'var'), Node.closeBrace(4), ], ); expect(actual, isNot(equals(wrongChildrenCount)));
final Node wrongChild = Node( ST.placeholderExpr, 0, expectedSymbolCount: 3, children: <Node>[ Node.closeBrace(0), Node.string(1, 'var'), Node.closeBrace(4), ], ); expect(actual, isNot(equals(wrongChild))); });
testWithoutContext('lexer basic', () { final List<Node> tokens1 = Parser( 'helloWorld', 'app_en.arb', 'Hello {name}' ).lexIntoTokens(); expect(tokens1, equals(<Node>[ Node.string(0, 'Hello '), Node.openBrace(6), Node.identifier(7, 'name'), Node.closeBrace(11), ]));
final List<Node> tokens2 = Parser( 'plural', 'app_en.arb', 'There are {count} {count, plural, =1{cat} other{cats}}' ).lexIntoTokens(); expect(tokens2, equals(<Node>[ Node.string(0, 'There are '), Node.openBrace(10), Node.identifier(11, 'count'), Node.closeBrace(16), Node.string(17, ' '), Node.openBrace(18), Node.identifier(19, 'count'), Node.comma(24), Node.pluralKeyword(26), Node.comma(32), Node.equalSign(34), Node.number(35, '1'), Node.openBrace(36), Node.string(37, 'cat'), Node.closeBrace(40), Node.otherKeyword(42), Node.openBrace(47), Node.string(48, 'cats'), Node.closeBrace(52), Node.closeBrace(53), ]));
final List<Node> tokens3 = Parser( 'gender', 'app_en.arb', '{gender, select, male{he} female{she} other{they}}' ).lexIntoTokens(); expect(tokens3, equals(<Node>[ Node.openBrace(0), Node.identifier(1, 'gender'), Node.comma(7), Node.selectKeyword(9), Node.comma(15), Node.identifier(17, 'male'), Node.openBrace(21), Node.string(22, 'he'), Node.closeBrace(24), Node.identifier(26, 'female'), Node.openBrace(32), Node.string(33, 'she'), Node.closeBrace(36), Node.otherKeyword(38), Node.openBrace(43), Node.string(44, 'they'), Node.closeBrace(48), Node.closeBrace(49), ])); });
testWithoutContext('lexer recursive', () { final List<Node> tokens = Parser( 'plural', 'app_en.arb', '{count, plural, =1{{gender, select, male{he} female{she}}} other{they}}' ).lexIntoTokens(); expect(tokens, equals(<Node>[ Node.openBrace(0), Node.identifier(1, 'count'), Node.comma(6), Node.pluralKeyword(8), Node.comma(14), Node.equalSign(16), Node.number(17, '1'), Node.openBrace(18), Node.openBrace(19), Node.identifier(20, 'gender'), Node.comma(26), Node.selectKeyword(28), Node.comma(34), Node.identifier(36, 'male'), Node.openBrace(40), Node.string(41, 'he'), Node.closeBrace(43), Node.identifier(45, 'female'), Node.openBrace(51), Node.string(52, 'she'), Node.closeBrace(55), Node.closeBrace(56), Node.closeBrace(57), Node.otherKeyword(59), Node.openBrace(64), Node.string(65, 'they'), Node.closeBrace(69), Node.closeBrace(70), ])); });
testWithoutContext('lexer escaping', () { final List<Node> tokens1 = Parser('escaping', 'app_en.arb', "''", useEscaping: true).lexIntoTokens(); expect(tokens1, equals(<Node>[Node.string(0, "'")]));
final List<Node> tokens2 = Parser('escaping', 'app_en.arb', "'hello world { name }'", useEscaping: true).lexIntoTokens(); expect(tokens2, equals(<Node>[Node.string(0, 'hello world { name }')]));
final List<Node> tokens3 = Parser('escaping', 'app_en.arb', "'{ escaped string }' { not escaped }", useEscaping: true).lexIntoTokens(); expect(tokens3, equals(<Node>[ Node.string(0, '{ escaped string }'), Node.string(20, ' '), Node.openBrace(21), Node.identifier(23, 'not'), Node.identifier(27, 'escaped'), Node.closeBrace(35), ]));
final List<Node> tokens4 = Parser('escaping', 'app_en.arb', "Flutter''s amazing!", useEscaping: true).lexIntoTokens(); expect(tokens4, equals(<Node>[ Node.string(0, 'Flutter'), Node.string(7, "'"), Node.string(9, 's amazing!'), ]));
final List<Node> tokens5 = Parser('escaping', 'app_en.arb', "'Flutter''s amazing!'", useEscaping: true).lexIntoTokens(); expect(tokens5, equals(<Node>[ Node(ST.string, 0, value: 'Flutter'), Node(ST.string, 9, value: "'s amazing!"), ])); });
testWithoutContext('lexer identifier names can be "select" or "plural"', () { final List<Node> tokens = Parser('keywords', 'app_en.arb', '{ select } { plural, select, singular{test} other{hmm} }').lexIntoTokens(); expect(tokens[1].value, equals('select')); expect(tokens[1].type, equals(ST.identifier)); expect(tokens[5].value, equals('plural')); expect(tokens[5].type, equals(ST.identifier)); });
testWithoutContext('lexer identifier names can contain underscores', () { final List<Node> tokens = Parser('keywords', 'app_en.arb', '{ test_placeholder } { test_select, select, singular{test} other{hmm} }').lexIntoTokens(); expect(tokens[1].value, equals('test_placeholder')); expect(tokens[1].type, equals(ST.identifier)); expect(tokens[5].value, equals('test_select')); expect(tokens[5].type, equals(ST.identifier)); });
testWithoutContext('lexer identifier names can contain the strings select or plural', () { final List<Node> tokens = Parser('keywords', 'app_en.arb', '{ selectTest } { pluralTest, select, singular{test} other{hmm} }').lexIntoTokens(); expect(tokens[1].value, equals('selectTest')); expect(tokens[1].type, equals(ST.identifier)); expect(tokens[5].value, equals('pluralTest')); expect(tokens[5].type, equals(ST.identifier)); });
testWithoutContext('lexer: lexically correct but syntactically incorrect', () { final List<Node> tokens = Parser( 'syntax', 'app_en.arb', 'string { identifier { string { identifier } } }' ).lexIntoTokens(); expect(tokens, equals(<Node>[ Node.string(0, 'string '), Node.openBrace(7), Node.identifier(9, 'identifier'), Node.openBrace(20), Node.string(21, ' string '), Node.openBrace(29), Node.identifier(31, 'identifier'), Node.closeBrace(42), Node.string(43, ' '), Node.closeBrace(44), Node.closeBrace(46), ])); });
testWithoutContext('lexer unmatched single quote', () { const String message = "here''s an unmatched single quote: '"; const String expectedError = '''[app_en.arb:escaping] ICU Lexing Error: Unmatched single quotes. here''s an unmatched single quote: ' ^'''; expect( () => Parser('escaping', 'app_en.arb', message, useEscaping: true).lexIntoTokens(), throwsA(isA<L10nException>().having( (L10nException e) => e.message, 'message', contains(expectedError), ))); });
testWithoutContext('lexer unexpected character', () { const String message = '{ * }'; const String expectedError = '''[app_en.arb:lex] ICU Lexing Error: Unexpected character. { * } ^'''; expect( () => Parser('lex', 'app_en.arb', message).lexIntoTokens(), throwsA(isA<L10nException>().having( (L10nException e) => e.message, 'message', contains(expectedError), ))); });
testWithoutContext('relaxed lexer', () { final List<Node> tokens1 = Parser( 'string', 'app_en.arb', '{ }', placeholders: <String>[], ).lexIntoTokens(); expect(tokens1, equals(<Node>[ Node(ST.string, 0, value: '{'), Node(ST.string, 1, value: ' '), Node(ST.string, 2, value: '}') ]));
final List<Node> tokens2 = Parser( 'string', 'app_en.arb', '{ notAPlaceholder }', placeholders: <String>['isAPlaceholder'], ).lexIntoTokens(); expect(tokens2, equals(<Node>[ Node(ST.string, 0, value: '{'), Node(ST.string, 1, value: ' notAPlaceholder '), Node(ST.string, 18, value: '}') ]));
final List<Node> tokens3 = Parser( 'string', 'app_en.arb', '{ isAPlaceholder }', placeholders: <String>['isAPlaceholder'], ).lexIntoTokens(); expect(tokens3, equals(<Node>[ Node(ST.openBrace, 0, value: '{'), Node(ST.identifier, 2, value: 'isAPlaceholder'), Node(ST.closeBrace, 17, value: '}') ])); });
testWithoutContext('relaxed lexer complex', () { const String message = '{ notPlaceholder } {count,plural, =0{Hello} =1{Hello World} =2{Hello two worlds} few{Hello {count} worlds} many{Hello all {count} worlds} other{Hello other {count} worlds}}'; final List<Node> tokens = Parser( 'string', 'app_en.arb', message, placeholders: <String>['count'], ).lexIntoTokens(); expect(tokens[0].type, equals(ST.string)); });
testWithoutContext('parser basic', () { expect(Parser('helloWorld', 'app_en.arb', 'Hello {name}').parse(), equals( Node(ST.message, 0, children: <Node>[ Node(ST.string, 0, value: 'Hello '), Node(ST.placeholderExpr, 6, children: <Node>[ Node(ST.openBrace, 6, value: '{'), Node(ST.identifier, 7, value: 'name'), Node(ST.closeBrace, 11, value: '}') ]) ]) ));
expect(Parser('argumentTest', 'app_en.arb', 'Today is {date, date, ::yMMd}').parse(), equals( Node(ST.message, 0, children: <Node>[ Node(ST.string, 0, value: 'Today is '), Node(ST.argumentExpr, 9, children: <Node>[ Node(ST.openBrace, 9, value: '{'), Node(ST.identifier, 10, value: 'date'), Node(ST.comma, 14, value: ','), Node(ST.argType, 16, children: <Node>[ Node(ST.date, 16, value: 'date'), ]), Node(ST.comma, 20, value: ','), Node(ST.colon, 22, value: ':'), Node(ST.colon, 23, value: ':'), Node(ST.identifier, 24, value: 'yMMd'), Node(ST.closeBrace, 28, value: '}'), ]), ]) ));
expect(Parser( 'plural', 'app_en.arb', 'There are {count} {count, plural, =1{cat} other{cats}}' ).parse(), equals( Node(ST.message, 0, children: <Node>[ Node(ST.string, 0, value: 'There are '), Node(ST.placeholderExpr, 10, children: <Node>[ Node(ST.openBrace, 10, value: '{'), Node(ST.identifier, 11, value: 'count'), Node(ST.closeBrace, 16, value: '}') ]), Node(ST.string, 17, value: ' '), Node(ST.pluralExpr, 18, children: <Node>[ Node(ST.openBrace, 18, value: '{'), Node(ST.identifier, 19, value: 'count'), Node(ST.comma, 24, value: ','), Node(ST.plural, 26, value: 'plural'), Node(ST.comma, 32, value: ','), Node(ST.pluralParts, 34, children: <Node>[ Node(ST.pluralPart, 34, children: <Node>[ Node(ST.equalSign, 34, value: '='), Node(ST.number, 35, value: '1'), Node(ST.openBrace, 36, value: '{'), Node(ST.message, 37, children: <Node>[ Node(ST.string, 37, value: 'cat') ]), Node(ST.closeBrace, 40, value: '}') ]), Node(ST.pluralPart, 42, children: <Node>[ Node(ST.other, 42, value: 'other'), Node(ST.openBrace, 47, value: '{'), Node(ST.message, 48, children: <Node>[ Node(ST.string, 48, value: 'cats') ]), Node(ST.closeBrace, 52, value: '}') ]) ]), Node(ST.closeBrace, 53, value: '}') ]), ]), ));
expect(Parser( 'gender', 'app_en.arb', '{gender, select, male{he} female{she} other{they}}' ).parse(), equals( Node(ST.message, 0, children: <Node>[ Node(ST.selectExpr, 0, children: <Node>[ Node(ST.openBrace, 0, value: '{'), Node(ST.identifier, 1, value: 'gender'), Node(ST.comma, 7, value: ','), Node(ST.select, 9, value: 'select'), Node(ST.comma, 15, value: ','), Node(ST.selectParts, 17, children: <Node>[ Node(ST.selectPart, 17, children: <Node>[ Node(ST.identifier, 17, value: 'male'), Node(ST.openBrace, 21, value: '{'), Node(ST.message, 22, children: <Node>[ Node(ST.string, 22, value: 'he'), ]), Node(ST.closeBrace, 24, value: '}'), ]), Node(ST.selectPart, 26, children: <Node>[ Node(ST.identifier, 26, value: 'female'), Node(ST.openBrace, 32, value: '{'), Node(ST.message, 33, children: <Node>[ Node(ST.string, 33, value: 'she'), ]), Node(ST.closeBrace, 36, value: '}'), ]), Node(ST.selectPart, 38, children: <Node>[ Node(ST.other, 38, value: 'other'), Node(ST.openBrace, 43, value: '{'), Node(ST.message, 44, children: <Node>[ Node(ST.string, 44, value: 'they'), ]), Node(ST.closeBrace, 48, value: '}'), ]), ]), Node(ST.closeBrace, 49, value: '}'), ]), ]) )); });
testWithoutContext('parser escaping', () { expect(Parser('escaping', 'app_en.arb', "Flutter''s amazing!", useEscaping: true).parse(), equals( Node(ST.message, 0, children: <Node>[ Node(ST.string, 0, value: 'Flutter'), Node(ST.string, 7, value: "'"), Node(ST.string, 9, value: 's amazing!'), ]) ));
expect(Parser('escaping', 'app_en.arb', "'Flutter''s amazing!'", useEscaping: true).parse(), equals( Node(ST.message, 0, children: <Node> [ Node(ST.string, 0, value: 'Flutter'), Node(ST.string, 9, value: "'s amazing!"), ]) )); });
testWithoutContext('parser recursive', () { expect(Parser( 'pluralGender', 'app_en.arb', '{count, plural, =1{{gender, select, male{he} female{she} other{they}}} other{they}}' ).parse(), equals( Node(ST.message, 0, children: <Node>[ Node(ST.pluralExpr, 0, children: <Node>[ Node(ST.openBrace, 0, value: '{'), Node(ST.identifier, 1, value: 'count'), Node(ST.comma, 6, value: ','), Node(ST.plural, 8, value: 'plural'), Node(ST.comma, 14, value: ','), Node(ST.pluralParts, 16, children: <Node>[ Node(ST.pluralPart, 16, children: <Node>[ Node(ST.equalSign, 16, value: '='), Node(ST.number, 17, value: '1'), Node(ST.openBrace, 18, value: '{'), Node(ST.message, 19, children: <Node>[ Node(ST.selectExpr, 19, children: <Node>[ Node(ST.openBrace, 19, value: '{'), Node(ST.identifier, 20, value: 'gender'), Node(ST.comma, 26, value: ','), Node(ST.select, 28, value: 'select'), Node(ST.comma, 34, value: ','), Node(ST.selectParts, 36, children: <Node>[ Node(ST.selectPart, 36, children: <Node>[ Node(ST.identifier, 36, value: 'male'), Node(ST.openBrace, 40, value: '{'), Node(ST.message, 41, children: <Node>[ Node(ST.string, 41, value: 'he'), ]), Node(ST.closeBrace, 43, value: '}'), ]), Node(ST.selectPart, 45, children: <Node>[ Node(ST.identifier, 45, value: 'female'), Node(ST.openBrace, 51, value: '{'), Node(ST.message, 52, children: <Node>[ Node(ST.string, 52, value: 'she'), ]), Node(ST.closeBrace, 55, value: '}'), ]), Node(ST.selectPart, 57, children: <Node>[ Node(ST.other, 57, value: 'other'), Node(ST.openBrace, 62, value: '{'), Node(ST.message, 63, children: <Node>[ Node(ST.string, 63, value: 'they'), ]), Node(ST.closeBrace, 67, value: '}'), ]), ]), Node(ST.closeBrace, 68, value: '}'), ]), ]), Node(ST.closeBrace, 69, value: '}'), ]), Node(ST.pluralPart, 71, children: <Node>[ Node(ST.other, 71, value: 'other'), Node(ST.openBrace, 76, value: '{'), Node(ST.message, 77, children: <Node>[ Node(ST.string, 77, value: 'they'), ]), Node(ST.closeBrace, 81, value: '}'), ]), ]), Node(ST.closeBrace, 82, value: '}'), ]), ]) )); });
testWithoutContext('parser unexpected token', () { // unexpected token const String expectedError1 = '''[app_en.arb:unexpectedToken] ICU Syntax Error: Expected "}" but found "=". { placeholder = ^'''; expect( () => Parser('unexpectedToken', 'app_en.arb', '{ placeholder =').parseIntoTree(), throwsA(isA<L10nException>().having( (L10nException e) => e.message, 'message', contains(expectedError1), )));
const String expectedError2 = '''[app_en.arb:unexpectedToken] ICU Syntax Error: Expected "number" but found "}". { count, plural, = } ^'''; expect( () => Parser('unexpectedToken', 'app_en.arb', '{ count, plural, = }').parseIntoTree(), throwsA(isA<L10nException>().having( (L10nException e) => e.message, 'message', contains(expectedError2), )));
const String expectedError3 = '''[app_en.arb:unexpectedToken] ICU Syntax Error: Expected "identifier" but found ",". { , plural , = } ^'''; expect( () => Parser('unexpectedToken', 'app_en.arb', '{ , plural , = }').parseIntoTree(), throwsA(isA<L10nException>().having( (L10nException e) => e.message, 'message', contains(expectedError3), ))); });
testWithoutContext('parser allows select cases with numbers', () { final Node node = Parser('numberSelect', 'app_en.arb', '{ count, select, 0{none} 100{perfect} other{required!} }').parse(); final Node selectExpr = node.children[0]; final Node selectParts = selectExpr.children[5]; final Node selectPart = selectParts.children[0]; expect(selectPart.children[0].value, equals('0')); expect(selectPart.children[1].value, equals('{')); expect(selectPart.children[2].type, equals(ST.message)); expect(selectPart.children[3].value, equals('}')); });}12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758// 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:flutter_tools/src/base/file_system.dart';import 'package:flutter_tools/src/base/logger.dart';import 'package:flutter_tools/src/persistent_tool_state.dart';import 'package:flutter_tools/src/version.dart';
import '../src/common.dart';
void main() { testWithoutContext('state can be set and persists', () { final MemoryFileSystem fileSystem = MemoryFileSystem.test(); final Directory directory = fileSystem.directory('state_dir'); directory.createSync(); final File stateFile = directory.childFile('.flutter_tool_state'); final PersistentToolState state1 = PersistentToolState.test( directory: directory, logger: BufferLogger.test(), ); expect(state1.shouldRedisplayWelcomeMessage, null); state1.setShouldRedisplayWelcomeMessage(true); expect(stateFile.existsSync(), true); expect(state1.shouldRedisplayWelcomeMessage, true); state1.setShouldRedisplayWelcomeMessage(false); expect(state1.shouldRedisplayWelcomeMessage, false);
final PersistentToolState state2 = PersistentToolState.test( directory: directory, logger: BufferLogger.test(), ); expect(state2.shouldRedisplayWelcomeMessage, false); });
testWithoutContext('channel versions can be cached and stored', () { final MemoryFileSystem fileSystem = MemoryFileSystem.test(); final Directory directory = fileSystem.directory('state_dir')..createSync(); final PersistentToolState state1 = PersistentToolState.test( directory: directory, logger: BufferLogger.test(), );
state1.updateLastActiveVersion('abc', Channel.master); state1.updateLastActiveVersion('ghi', Channel.beta); state1.updateLastActiveVersion('jkl', Channel.stable);
final PersistentToolState state2 = PersistentToolState.test( directory: directory, logger: BufferLogger.test(), );
expect(state2.lastActiveVersion(Channel.master), 'abc'); expect(state2.lastActiveVersion(Channel.beta), 'ghi'); expect(state2.lastActiveVersion(Channel.stable), 'jkl'); });}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423// 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:flutter_tools/src/base/file_system.dart';import 'package:flutter_tools/src/platform_plugins.dart';import 'package:flutter_tools/src/plugins.dart';import 'package:yaml/yaml.dart';
import '../src/common.dart';
const String _kTestPluginName = 'test_plugin_name';const String _kTestPluginPath = 'test_plugin_path';
void main() { testWithoutContext('Plugin creation from the legacy format', () { final MemoryFileSystem fileSystem = MemoryFileSystem.test(); const String pluginYamlRaw = 'androidPackage: com.flutter.dev\n' 'iosPrefix: FLT\n' 'pluginClass: SamplePlugin\n';
final YamlMap pluginYaml = loadYaml(pluginYamlRaw) as YamlMap; final Plugin plugin = Plugin.fromYaml( _kTestPluginName, _kTestPluginPath, pluginYaml, null, const <String>[], fileSystem: fileSystem, );
final AndroidPlugin androidPlugin = plugin.platforms[AndroidPlugin.kConfigKey]! as AndroidPlugin; final IOSPlugin iosPlugin = plugin.platforms[IOSPlugin.kConfigKey]! as IOSPlugin;
expect(iosPlugin.pluginClass, 'SamplePlugin'); expect(iosPlugin.classPrefix, 'FLT'); expect(iosPlugin.sharedDarwinSource, isFalse); expect(androidPlugin.pluginClass, 'SamplePlugin'); expect(androidPlugin.package, 'com.flutter.dev'); });
testWithoutContext('Plugin creation from the multi-platform format', () { final MemoryFileSystem fileSystem = MemoryFileSystem.test(); const String pluginYamlRaw = 'platforms:\n' ' android:\n' ' package: com.flutter.dev\n' ' pluginClass: ASamplePlugin\n' ' ios:\n' ' pluginClass: ISamplePlugin\n' ' sharedDarwinSource: true\n' ' linux:\n' ' pluginClass: LSamplePlugin\n' ' macos:\n' ' pluginClass: MSamplePlugin\n' ' sharedDarwinSource: true\n' ' web:\n' ' pluginClass: WebSamplePlugin\n' ' fileName: web_plugin.dart\n' ' windows:\n' ' pluginClass: WinSamplePlugin\n';
final YamlMap pluginYaml = loadYaml(pluginYamlRaw) as YamlMap; final Plugin plugin = Plugin.fromYaml( _kTestPluginName, _kTestPluginPath, pluginYaml, null, const <String>[], fileSystem: fileSystem, );
final AndroidPlugin androidPlugin = plugin.platforms[AndroidPlugin.kConfigKey]! as AndroidPlugin; final IOSPlugin iosPlugin = plugin.platforms[IOSPlugin.kConfigKey]! as IOSPlugin; final LinuxPlugin linuxPlugin = plugin.platforms[LinuxPlugin.kConfigKey]! as LinuxPlugin; final MacOSPlugin macOSPlugin = plugin.platforms[MacOSPlugin.kConfigKey]! as MacOSPlugin; final WebPlugin webPlugin = plugin.platforms[WebPlugin.kConfigKey]! as WebPlugin; final WindowsPlugin windowsPlugin = plugin.platforms[WindowsPlugin.kConfigKey]! as WindowsPlugin;
expect(iosPlugin.pluginClass, 'ISamplePlugin'); expect(iosPlugin.classPrefix, ''); expect(iosPlugin.sharedDarwinSource, isTrue); expect(androidPlugin.pluginClass, 'ASamplePlugin'); expect(androidPlugin.package, 'com.flutter.dev'); expect(linuxPlugin.pluginClass, 'LSamplePlugin'); expect(macOSPlugin.pluginClass, 'MSamplePlugin'); expect(macOSPlugin.sharedDarwinSource, isTrue); expect(webPlugin.pluginClass, 'WebSamplePlugin'); expect(webPlugin.fileName, 'web_plugin.dart'); expect(windowsPlugin.pluginClass, 'WinSamplePlugin'); });
testWithoutContext('Plugin parsing of unknown fields are allowed (allows some future compatibility)', () { final MemoryFileSystem fileSystem = MemoryFileSystem.test(); const String pluginYamlRaw = 'implements: same_plugin\n' // this should be ignored by the tool 'platforms:\n' ' android:\n' ' package: com.flutter.dev\n' ' pluginClass: ASamplePlugin\n' ' anUnknownField: ASamplePlugin\n' // this should be ignored by the tool ' ios:\n' ' pluginClass: ISamplePlugin\n' ' linux:\n' ' pluginClass: LSamplePlugin\n' ' macos:\n' ' pluginClass: MSamplePlugin\n' ' web:\n' ' pluginClass: WebSamplePlugin\n' ' fileName: web_plugin.dart\n' ' windows:\n' ' pluginClass: WinSamplePlugin\n';
final YamlMap pluginYaml = loadYaml(pluginYamlRaw) as YamlMap; final Plugin plugin = Plugin.fromYaml( _kTestPluginName, _kTestPluginPath, pluginYaml, null, const <String>[], fileSystem: fileSystem, );
final AndroidPlugin androidPlugin = plugin.platforms[AndroidPlugin.kConfigKey]! as AndroidPlugin; final IOSPlugin iosPlugin = plugin.platforms[IOSPlugin.kConfigKey]! as IOSPlugin; final LinuxPlugin linuxPlugin = plugin.platforms[LinuxPlugin.kConfigKey]! as LinuxPlugin; final MacOSPlugin macOSPlugin = plugin.platforms[MacOSPlugin.kConfigKey]! as MacOSPlugin; final WebPlugin webPlugin = plugin.platforms[WebPlugin.kConfigKey]! as WebPlugin; final WindowsPlugin windowsPlugin = plugin.platforms[WindowsPlugin.kConfigKey]! as WindowsPlugin;
expect(iosPlugin.pluginClass, 'ISamplePlugin'); expect(iosPlugin.classPrefix, ''); expect(iosPlugin.sharedDarwinSource, isFalse); expect(androidPlugin.pluginClass, 'ASamplePlugin'); expect(androidPlugin.package, 'com.flutter.dev'); expect(linuxPlugin.pluginClass, 'LSamplePlugin'); expect(macOSPlugin.pluginClass, 'MSamplePlugin'); expect(macOSPlugin.sharedDarwinSource, isFalse); expect(webPlugin.pluginClass, 'WebSamplePlugin'); expect(webPlugin.fileName, 'web_plugin.dart'); expect(windowsPlugin.pluginClass, 'WinSamplePlugin'); });
testWithoutContext('Plugin parsing allows for Dart-only plugins without a pluginClass', () { final FileSystem fileSystem = MemoryFileSystem.test(); const String pluginYamlRaw = 'implements: same_plugin\n' // this should be ignored by the tool 'platforms:\n' ' android:\n' ' dartPluginClass: ASamplePlugin\n' ' ios:\n' ' dartPluginClass: ISamplePlugin\n' ' linux:\n' ' dartPluginClass: LSamplePlugin\n' ' macos:\n' ' dartPluginClass: MSamplePlugin\n' ' windows:\n' ' dartPluginClass: WinSamplePlugin\n';
final YamlMap pluginYaml = loadYaml(pluginYamlRaw) as YamlMap; final Plugin plugin = Plugin.fromYaml( _kTestPluginName, _kTestPluginPath, pluginYaml, null, const <String>[], fileSystem: fileSystem, );
final AndroidPlugin androidPlugin = plugin.platforms[AndroidPlugin.kConfigKey]! as AndroidPlugin; final IOSPlugin iOSPlugin = plugin.platforms[IOSPlugin.kConfigKey]! as IOSPlugin; final LinuxPlugin linuxPlugin = plugin.platforms[LinuxPlugin.kConfigKey]! as LinuxPlugin; final MacOSPlugin macOSPlugin = plugin.platforms[MacOSPlugin.kConfigKey]! as MacOSPlugin; final WindowsPlugin windowsPlugin = plugin.platforms[WindowsPlugin.kConfigKey]! as WindowsPlugin;
expect(androidPlugin.pluginClass, isNull); expect(iOSPlugin.pluginClass, isNull); expect(linuxPlugin.pluginClass, isNull); expect(macOSPlugin.pluginClass, isNull); expect(windowsPlugin.pluginClass, isNull); expect(androidPlugin.dartPluginClass, 'ASamplePlugin'); expect(iOSPlugin.dartPluginClass, 'ISamplePlugin'); expect(linuxPlugin.dartPluginClass, 'LSamplePlugin'); expect(macOSPlugin.dartPluginClass, 'MSamplePlugin'); expect(windowsPlugin.dartPluginClass, 'WinSamplePlugin'); });
testWithoutContext('Plugin parsing of legacy format and multi-platform format together is not allowed ' 'and fatal error message contains plugin name', () { final FileSystem fileSystem = MemoryFileSystem.test(); const String pluginYamlRaw = 'androidPackage: com.flutter.dev\n' 'platforms:\n' ' android:\n' ' package: com.flutter.dev\n';
final YamlMap pluginYaml = loadYaml(pluginYamlRaw) as YamlMap;
expect( () => Plugin.fromYaml( _kTestPluginName, _kTestPluginPath, pluginYaml, null, const <String>[], fileSystem: fileSystem, ), throwsToolExit(message: _kTestPluginName), ); });
testWithoutContext('Plugin parsing allows a default_package field', () { final FileSystem fileSystem = MemoryFileSystem.test(); const String pluginYamlRaw = 'platforms:\n' ' android:\n' ' default_package: sample_package_android\n' ' ios:\n' ' default_package: sample_package_ios\n' ' linux:\n' ' default_package: sample_package_linux\n' ' macos:\n' ' default_package: sample_package_macos\n' ' web:\n' ' default_package: sample_package_web\n' ' windows:\n' ' default_package: sample_package_windows\n';
final YamlMap pluginYaml = loadYaml(pluginYamlRaw) as YamlMap; final Plugin plugin = Plugin.fromYaml( _kTestPluginName, _kTestPluginPath, pluginYaml, null, const <String>[], fileSystem: fileSystem, );
expect(plugin.platforms, <String, PluginPlatform>{}); expect(plugin.defaultPackagePlatforms, <String, String>{ 'android': 'sample_package_android', 'ios': 'sample_package_ios', 'linux': 'sample_package_linux', 'macos': 'sample_package_macos', 'windows': 'sample_package_windows', }); expect(plugin.pluginDartClassPlatforms, <String, String>{}); });
testWithoutContext('Desktop plugin parsing allows a dartPluginClass field', () { final FileSystem fileSystem = MemoryFileSystem.test(); const String pluginYamlRaw = 'platforms:\n' ' linux:\n' ' dartPluginClass: LinuxClass\n' ' macos:\n' ' dartPluginClass: MacOSClass\n' ' windows:\n' ' dartPluginClass: WindowsClass\n';
final YamlMap pluginYaml = loadYaml(pluginYamlRaw) as YamlMap; final Plugin plugin = Plugin.fromYaml( _kTestPluginName, _kTestPluginPath, pluginYaml, null, const <String>[], fileSystem: fileSystem, );
expect(plugin.pluginDartClassPlatforms, <String, String>{ 'linux': 'LinuxClass', 'macos': 'MacOSClass', 'windows': 'WindowsClass', }); });
testWithoutContext('Windows allows supported mode lists', () { final FileSystem fileSystem = MemoryFileSystem.test(); const String pluginYamlRaw = 'platforms:\n' ' windows:\n' ' pluginClass: WinSamplePlugin\n' ' supportedVariants:\n' ' - win32\n';
final YamlMap pluginYaml = loadYaml(pluginYamlRaw) as YamlMap; final Plugin plugin = Plugin.fromYaml( _kTestPluginName, _kTestPluginPath, pluginYaml, null, const <String>[], fileSystem: fileSystem, );
final WindowsPlugin windowsPlugin = plugin.platforms[WindowsPlugin.kConfigKey]! as WindowsPlugin; expect(windowsPlugin.supportedVariants, <PluginPlatformVariant>[ PluginPlatformVariant.win32, ]); });
testWithoutContext('Web plugin tool exits if fileName field missing', () { final FileSystem fileSystem = MemoryFileSystem.test(); const String pluginYamlRaw = 'platforms:\n' ' web:\n' ' pluginClass: WebSamplePlugin\n';
final YamlMap pluginYaml = loadYaml(pluginYamlRaw) as YamlMap; expect( () => Plugin.fromYaml( _kTestPluginName, _kTestPluginPath, pluginYaml, null, const <String>[], fileSystem: fileSystem, ), throwsToolExit( message: 'The plugin `$_kTestPluginName` is missing the required field `fileName` in pubspec.yaml', ), ); });
testWithoutContext('Windows assumes win32 when no variants are given', () { final FileSystem fileSystem = MemoryFileSystem.test(); const String pluginYamlRaw = 'platforms:\n' ' windows:\n' ' pluginClass: WinSamplePlugin\n';
final YamlMap pluginYaml = loadYaml(pluginYamlRaw) as YamlMap; final Plugin plugin = Plugin.fromYaml( _kTestPluginName, _kTestPluginPath, pluginYaml, null, const <String>[], fileSystem: fileSystem, );
final WindowsPlugin windowsPlugin = plugin.platforms[WindowsPlugin.kConfigKey]! as WindowsPlugin; expect(windowsPlugin.supportedVariants, <PluginPlatformVariant>[ PluginPlatformVariant.win32, ]); });
testWithoutContext('Windows ignores unknown variants', () { final FileSystem fileSystem = MemoryFileSystem.test(); const String pluginYamlRaw = 'platforms:\n' ' windows:\n' ' pluginClass: WinSamplePlugin\n' ' supportedVariants:\n' ' - not_yet_invented_variant\n';
final YamlMap pluginYaml = loadYaml(pluginYamlRaw) as YamlMap; final Plugin plugin = Plugin.fromYaml( _kTestPluginName, _kTestPluginPath, pluginYaml, null, const <String>[], fileSystem: fileSystem, );
final WindowsPlugin windowsPlugin = plugin.platforms[WindowsPlugin.kConfigKey]! as WindowsPlugin; expect(windowsPlugin.supportedVariants, <PluginPlatformVariant>{}); });
testWithoutContext('Plugin parsing throws a fatal error on an empty plugin', () { final MemoryFileSystem fileSystem = MemoryFileSystem.test(); final YamlMap? pluginYaml = loadYaml('') as YamlMap?;
expect( () => Plugin.fromYaml( _kTestPluginName, _kTestPluginPath, pluginYaml, null, const <String>[], fileSystem: fileSystem, ), throwsToolExit(message: 'Invalid "plugin" specification.'), ); });
testWithoutContext('Plugin parsing throws a fatal error on empty platforms', () { final MemoryFileSystem fileSystem = MemoryFileSystem.test(); const String pluginYamlRaw = 'platforms:\n'; final YamlMap pluginYaml = loadYaml(pluginYamlRaw) as YamlMap;
expect( () => Plugin.fromYaml( _kTestPluginName, _kTestPluginPath, pluginYaml, null, const <String>[], fileSystem: fileSystem, ), throwsToolExit(message: 'Invalid "platforms" specification.'), ); });
test('Plugin parsing throws a fatal error on an empty platform key', () { final MemoryFileSystem fileSystem = MemoryFileSystem.test(); const String pluginYamlRaw = 'platforms:\n' ' android:\n';
final YamlMap pluginYaml = loadYaml(pluginYamlRaw) as YamlMap; expect( () => Plugin.fromYaml( _kTestPluginName, _kTestPluginPath, pluginYaml, null, const <String>[], fileSystem: fileSystem, ), throwsToolExit(message: 'Invalid "android" plugin specification.'), ); });}1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954// 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:convert';
import 'package:file/file.dart';import 'package:file/memory.dart';import 'package:file_testing/file_testing.dart';import 'package:flutter_tools/src/base/os.dart';import 'package:flutter_tools/src/base/platform.dart';import 'package:flutter_tools/src/base/time.dart';import 'package:flutter_tools/src/base/utils.dart';import 'package:flutter_tools/src/features.dart';import 'package:flutter_tools/src/flutter_manifest.dart';import 'package:flutter_tools/src/flutter_plugins.dart';import 'package:flutter_tools/src/globals.dart' as globals;import 'package:flutter_tools/src/ios/xcodeproj.dart';import 'package:flutter_tools/src/plugins.dart';import 'package:flutter_tools/src/preview_device.dart';import 'package:flutter_tools/src/project.dart';import 'package:flutter_tools/src/version.dart';import 'package:test/fake.dart';import 'package:yaml/yaml.dart';
import '../src/common.dart';import '../src/context.dart';import '../src/fakes.dart' hide FakeOperatingSystemUtils;import '../src/pubspec_schema.dart';
/// Information for a platform entry in the 'platforms' section of a plugin's/// pubspec.yaml.class _PluginPlatformInfo { const _PluginPlatformInfo({ this.pluginClass, this.dartPluginClass, this.androidPackage, this.sharedDarwinSource = false, this.fileName }) : assert(pluginClass != null || dartPluginClass != null), assert(androidPackage == null || pluginClass != null);
/// The pluginClass entry, if any. final String? pluginClass;
/// The dartPluginClass entry, if any. final String? dartPluginClass;
/// The package entry for an Android plugin implementation using pluginClass. final String? androidPackage;
final bool sharedDarwinSource;
/// The fileName entry for a web plugin implementation. final String? fileName;
/// Returns the body of a platform section for a plugin's pubspec, properly /// indented. String get indentedPubspecSection { const String indentation = ' '; return <String>[ if (pluginClass != null) '${indentation}pluginClass: $pluginClass', if (dartPluginClass != null) '${indentation}dartPluginClass: $dartPluginClass', if (androidPackage != null) '${indentation}package: $androidPackage', if (sharedDarwinSource) '${indentation}sharedDarwinSource: true', if (fileName != null) '${indentation}fileName: $fileName', ].join('\n'); }}
void main() { group('plugins', () { late FileSystem fs; late FakeFlutterProject flutterProject; late FakeFlutterManifest flutterManifest; late FakeIosProject iosProject; late FakeMacOSProject macosProject; late FakeAndroidProject androidProject; late FakeWebProject webProject; late FakeWindowsProject windowsProject; late FakeLinuxProject linuxProject; late FakeSystemClock systemClock; late FlutterVersion flutterVersion; // A Windows-style filesystem. This is not populated by default, so tests // using it instead of fs must re-run any necessary setup (e.g., // setUpProject). late FileSystem fsWindows; const String pubCachePath = '/path/to/.pub-cache/hosted/pub.dartlang.org/foo-1.2.3'; const String ephemeralPackagePath = '/path/to/app/linux/flutter/ephemeral/foo-1.2.3';
// Adds basic properties to the flutterProject and its subprojects. void setUpProject(FileSystem fileSystem) { flutterProject = FakeFlutterProject(); flutterManifest = FakeFlutterManifest();
flutterProject ..manifest = flutterManifest ..directory = fileSystem.systemTempDirectory.childDirectory('app') ..flutterPluginsFile = flutterProject.directory.childFile('.flutter-plugins') ..flutterPluginsDependenciesFile = flutterProject.directory.childFile('.flutter-plugins-dependencies');
iosProject = FakeIosProject(); flutterProject.ios = iosProject; final Directory iosDirectory = flutterProject.directory.childDirectory('ios'); iosProject ..pluginRegistrantHost = flutterProject.directory.childDirectory('Runner') ..podfile = iosDirectory.childFile('Podfile') ..podManifestLock = iosDirectory.childFile('Podfile.lock') ..testExists = false;
macosProject = FakeMacOSProject(); flutterProject.macos = macosProject; final Directory macosDirectory = flutterProject.directory.childDirectory('macos'); final Directory macosManagedDirectory = macosDirectory.childDirectory('Flutter'); macosProject ..podfile = macosDirectory.childFile('Podfile') ..podManifestLock = macosDirectory.childFile('Podfile.lock') ..managedDirectory = macosManagedDirectory ..exists = false;
androidProject = FakeAndroidProject(); flutterProject.android = androidProject; final Directory androidDirectory = flutterProject.directory.childDirectory('android'); androidProject ..pluginRegistrantHost = androidDirectory.childDirectory('app') ..hostAppGradleRoot = androidDirectory ..exists = false ..embeddingVersion = AndroidEmbeddingVersion.v2;
webProject = FakeWebProject(); flutterProject.web = webProject; webProject ..libDirectory = flutterProject.directory.childDirectory('lib') ..exists = false;
windowsProject = FakeWindowsProject(); flutterProject.windows = windowsProject; final Directory windowsManagedDirectory = flutterProject.directory.childDirectory('windows').childDirectory('flutter'); windowsProject ..managedDirectory = windowsManagedDirectory ..cmakeFile = windowsManagedDirectory.parent.childFile('CMakeLists.txt') ..generatedPluginCmakeFile = windowsManagedDirectory.childFile('generated_plugins.mk') ..pluginSymlinkDirectory = windowsManagedDirectory.childDirectory('ephemeral').childDirectory('.plugin_symlinks') ..exists = false;
linuxProject = FakeLinuxProject(); flutterProject.linux = linuxProject; final Directory linuxManagedDirectory = flutterProject.directory.childDirectory('linux').childDirectory('flutter'); final Directory linuxEphemeralDirectory = linuxManagedDirectory.childDirectory('ephemeral'); linuxProject ..managedDirectory = linuxManagedDirectory ..ephemeralDirectory = linuxEphemeralDirectory ..pluginSymlinkDirectory = linuxEphemeralDirectory.childDirectory('.plugin_symlinks') ..cmakeFile = linuxManagedDirectory.parent.childFile('CMakeLists.txt') ..generatedPluginCmakeFile = linuxManagedDirectory.childFile('generated_plugins.mk') ..exists = false; }
setUp(() async { fs = MemoryFileSystem.test(); fsWindows = MemoryFileSystem(style: FileSystemStyle.windows); systemClock = FakeSystemClock() ..currentTime = DateTime(1970); flutterVersion = FakeFlutterVersion(frameworkVersion: '1.0.0');
// Add basic properties to the Flutter project and subprojects setUpProject(fs); flutterProject.directory.childFile('.packages').createSync(recursive: true); });
// Makes fake plugin packages for each plugin, adds them to flutterProject, // and returns their directories. // // If an entry contains a path separator, it will be treated as a path for // the location of the package, with the name being the last component. // Otherwise it will be treated as a name, and put in a default location // (a fake pub cache). List<Directory> createFakePlugins(FileSystem fileSystem, List<String> pluginNamesOrPaths) { const String pluginYamlTemplate = ''' flutter: plugin: platforms: ios: pluginClass: PLUGIN_CLASS macos: pluginClass: PLUGIN_CLASS windows: pluginClass: PLUGIN_CLASS linux: pluginClass: PLUGIN_CLASS web: pluginClass: PLUGIN_CLASS fileName: lib/PLUGIN_CLASS.dart android: pluginClass: PLUGIN_CLASS package: AndroidPackage ''';
final List<Directory> directories = <Directory>[]; final Directory fakePubCache = fileSystem.systemTempDirectory.childDirectory('cache'); final File packagesFile = flutterProject.directory.childFile('.packages') ..createSync(recursive: true); for (final String nameOrPath in pluginNamesOrPaths) { final String name = fileSystem.path.basename(nameOrPath); final Directory pluginDirectory = (nameOrPath == name) ? fakePubCache.childDirectory(name) : fileSystem.directory(nameOrPath); packagesFile.writeAsStringSync( '$name:${pluginDirectory.childFile('lib').uri}\n', mode: FileMode.writeOnlyAppend); pluginDirectory.childFile('pubspec.yaml') ..createSync(recursive: true) ..writeAsStringSync(pluginYamlTemplate.replaceAll('PLUGIN_CLASS', sentenceCase(camelCase(name)))); directories.add(pluginDirectory); } return directories; }
// Makes a fake plugin package, adds it to flutterProject, and returns its directory. Directory createFakePlugin(FileSystem fileSystem) { return createFakePlugins(fileSystem, <String>['some_plugin'])[0]; }
void createNewJavaPlugin1() { final Directory pluginUsingJavaAndNewEmbeddingDir = fs.systemTempDirectory.createTempSync('flutter_plugin_using_java_and_new_embedding_dir.'); pluginUsingJavaAndNewEmbeddingDir .childFile('pubspec.yaml') .writeAsStringSync('''flutter: plugin: androidPackage: plugin1 pluginClass: UseNewEmbedding '''); pluginUsingJavaAndNewEmbeddingDir .childDirectory('android') .childDirectory('src') .childDirectory('main') .childDirectory('java') .childDirectory('plugin1') .childFile('UseNewEmbedding.java') ..createSync(recursive: true) ..writeAsStringSync('import io.flutter.embedding.engine.plugins.FlutterPlugin;');
flutterProject.directory .childFile('.packages') .writeAsStringSync( 'plugin1:${pluginUsingJavaAndNewEmbeddingDir.childDirectory('lib').uri}\n', mode: FileMode.append, ); }
Directory createPluginWithInvalidAndroidPackage() { final Directory pluginUsingJavaAndNewEmbeddingDir = fs.systemTempDirectory.createTempSync('flutter_plugin_invalid_package.'); pluginUsingJavaAndNewEmbeddingDir .childFile('pubspec.yaml') .writeAsStringSync('''flutter: plugin: androidPackage: plugin1.invalid pluginClass: UseNewEmbedding '''); pluginUsingJavaAndNewEmbeddingDir .childDirectory('android') .childDirectory('src') .childDirectory('main') .childDirectory('java') .childDirectory('plugin1') .childDirectory('correct') .childFile('UseNewEmbedding.java') ..createSync(recursive: true) ..writeAsStringSync('import io.flutter.embedding.engine.plugins.FlutterPlugin;');
flutterProject.directory .childFile('.packages') .writeAsStringSync( 'plugin1:${pluginUsingJavaAndNewEmbeddingDir.childDirectory('lib').uri}\n', mode: FileMode.append, ); return pluginUsingJavaAndNewEmbeddingDir; }
void createNewKotlinPlugin2() { final Directory pluginUsingKotlinAndNewEmbeddingDir = fs.systemTempDirectory.createTempSync('flutter_plugin_using_kotlin_and_new_embedding_dir.'); pluginUsingKotlinAndNewEmbeddingDir .childFile('pubspec.yaml') .writeAsStringSync('''flutter: plugin: androidPackage: plugin2 pluginClass: UseNewEmbedding '''); pluginUsingKotlinAndNewEmbeddingDir .childDirectory('android') .childDirectory('src') .childDirectory('main') .childDirectory('kotlin') .childDirectory('plugin2') .childFile('UseNewEmbedding.kt') ..createSync(recursive: true) ..writeAsStringSync('import io.flutter.embedding.engine.plugins.FlutterPlugin');
flutterProject.directory .childFile('.packages') .writeAsStringSync( 'plugin2:${pluginUsingKotlinAndNewEmbeddingDir.childDirectory('lib').uri}\n', mode: FileMode.append, ); }
void createOldJavaPlugin(String pluginName) { final Directory pluginUsingOldEmbeddingDir = fs.systemTempDirectory.createTempSync('flutter_plugin_using_old_embedding_dir.'); pluginUsingOldEmbeddingDir .childFile('pubspec.yaml') .writeAsStringSync('''flutter: plugin: androidPackage: $pluginName pluginClass: UseOldEmbedding '''); pluginUsingOldEmbeddingDir .childDirectory('android') .childDirectory('src') .childDirectory('main') .childDirectory('java') .childDirectory(pluginName) .childFile('UseOldEmbedding.java') .createSync(recursive: true);
flutterProject.directory .childFile('.packages') .writeAsStringSync( '$pluginName:${pluginUsingOldEmbeddingDir.childDirectory('lib').uri}\n', mode: FileMode.append, ); }
void createDualSupportJavaPlugin4() { final Directory pluginUsingJavaAndNewEmbeddingDir = fs.systemTempDirectory.createTempSync('flutter_plugin_using_java_and_new_embedding_dir.'); pluginUsingJavaAndNewEmbeddingDir .childFile('pubspec.yaml') .writeAsStringSync('''flutter: plugin: androidPackage: plugin4 pluginClass: UseBothEmbedding'''); pluginUsingJavaAndNewEmbeddingDir .childDirectory('android') .childDirectory('src') .childDirectory('main') .childDirectory('java') .childDirectory('plugin4') .childFile('UseBothEmbedding.java') ..createSync(recursive: true) ..writeAsStringSync( 'import io.flutter.embedding.engine.plugins.FlutterPlugin;\n' 'PluginRegistry\n' 'registerWith(Irrelevant registrar)\n' );
flutterProject.directory .childFile('.packages') .writeAsStringSync( 'plugin4:${pluginUsingJavaAndNewEmbeddingDir.childDirectory('lib').uri}', mode: FileMode.append, ); }
Directory createLegacyPluginWithDependencies({ required String name, required List<String> dependencies, }) {
final Directory pluginDirectory = fs.systemTempDirectory.createTempSync('flutter_plugin.'); pluginDirectory .childFile('pubspec.yaml') .writeAsStringSync('''name: $nameflutter: plugin: androidPackage: plugin2 pluginClass: UseNewEmbeddingdependencies:'''); for (final String dependency in dependencies) { pluginDirectory .childFile('pubspec.yaml') .writeAsStringSync(' $dependency:\n', mode: FileMode.append); } flutterProject.directory .childFile('.packages') .writeAsStringSync( '$name:${pluginDirectory.childDirectory('lib').uri}\n', mode: FileMode.append, ); return pluginDirectory; }
Directory createPlugin({ required String name, required Map<String, _PluginPlatformInfo> platforms, List<String> dependencies = const <String>[], }) {
final Iterable<String> platformSections = platforms.entries.map((MapEntry<String, _PluginPlatformInfo> entry) => ''' ${entry.key}:${entry.value.indentedPubspecSection}'''); final Directory pluginDirectory = fs.systemTempDirectory.createTempSync('flutter_plugin.'); pluginDirectory .childFile('pubspec.yaml') .writeAsStringSync('''name: $nameflutter: plugin: platforms:${platformSections.join('\n')}
dependencies:'''); for (final String dependency in dependencies) { pluginDirectory .childFile('pubspec.yaml') .writeAsStringSync(' $dependency:\n', mode: FileMode.append); } flutterProject.directory .childFile('.packages') .writeAsStringSync( '$name:${pluginDirectory.childDirectory('lib').uri}\n', mode: FileMode.append, ); return pluginDirectory; }
// Creates the files that would indicate that pod install has run for the // given project. void simulatePodInstallRun(XcodeBasedProject project) { project.podManifestLock.createSync(recursive: true); }
group('refreshPlugins', () { testUsingContext('Refreshing the plugin list is a no-op when the plugins list stays empty', () async { await refreshPluginsList(flutterProject);
expect(flutterProject.flutterPluginsFile.existsSync(), false); expect(flutterProject.flutterPluginsDependenciesFile.existsSync(), false); }, overrides: <Type, Generator>{ FileSystem: () => fs, ProcessManager: () => FakeProcessManager.any(), });
testUsingContext('Refreshing the plugin list deletes the plugin file when there were plugins but no longer are', () async { flutterProject.flutterPluginsFile.createSync(); flutterProject.flutterPluginsDependenciesFile.createSync();
await refreshPluginsList(flutterProject);
expect(flutterProject.flutterPluginsFile.existsSync(), false); expect(flutterProject.flutterPluginsDependenciesFile.existsSync(), false); }, overrides: <Type, Generator>{ FileSystem: () => fs, ProcessManager: () => FakeProcessManager.any(), });
testUsingContext('Refreshing the plugin list creates a sorted plugin directory when there are plugins', () async { createFakePlugins(fs, <String>[ 'plugin_d', 'plugin_a', '/local_plugins/plugin_c', '/local_plugins/plugin_b', ]);
iosProject.testExists = true;
await refreshPluginsList(flutterProject);
expect(flutterProject.flutterPluginsFile.existsSync(), true); expect(flutterProject.flutterPluginsDependenciesFile.existsSync(), true);
final String pluginsFileContents = flutterProject.flutterPluginsFile.readAsStringSync(); expect(pluginsFileContents.indexOf('plugin_a'), lessThan(pluginsFileContents.indexOf('plugin_b'))); expect(pluginsFileContents.indexOf('plugin_b'), lessThan(pluginsFileContents.indexOf('plugin_c'))); expect(pluginsFileContents.indexOf('plugin_c'), lessThan(pluginsFileContents.indexOf('plugin_d'))); }, overrides: <Type, Generator>{ FileSystem: () => fs, ProcessManager: () => FakeProcessManager.any(), });
testUsingContext( 'Refreshing the plugin list modifies .flutter-plugins ' 'and .flutter-plugins-dependencies when there are plugins', () async { final Directory pluginA = createLegacyPluginWithDependencies(name: 'plugin-a', dependencies: const <String>['plugin-b', 'plugin-c', 'random-package']); final Directory pluginB = createLegacyPluginWithDependencies(name: 'plugin-b', dependencies: const <String>['plugin-c']); final Directory pluginC = createLegacyPluginWithDependencies(name: 'plugin-c', dependencies: const <String>[]); iosProject.testExists = true;
final DateTime dateCreated = DateTime(1970); systemClock.currentTime = dateCreated;
await refreshPluginsList(flutterProject);
// Verify .flutter-plugins-dependencies is configured correctly. expect(flutterProject.flutterPluginsFile.existsSync(), true); expect(flutterProject.flutterPluginsDependenciesFile.existsSync(), true); expect(flutterProject.flutterPluginsFile.readAsStringSync(), '# This is a generated file; do not edit or check into version control.\n' 'plugin-a=${pluginA.path}/\n' 'plugin-b=${pluginB.path}/\n' 'plugin-c=${pluginC.path}/\n' );
final String pluginsString = flutterProject.flutterPluginsDependenciesFile.readAsStringSync(); final Map<String, dynamic> jsonContent = json.decode(pluginsString) as Map<String, dynamic>; expect(jsonContent['info'], 'This is a generated file; do not edit or check into version control.');
final Map<String, dynamic> plugins = jsonContent['plugins'] as Map<String, dynamic>; final List<dynamic> expectedPlugins = <dynamic>[ <String, dynamic> { 'name': 'plugin-a', 'path': '${pluginA.path}/', 'native_build': true, 'dependencies': <String>[ 'plugin-b', 'plugin-c', ], }, <String, dynamic> { 'name': 'plugin-b', 'path': '${pluginB.path}/', 'native_build': true, 'dependencies': <String>[ 'plugin-c', ], }, <String, dynamic> { 'name': 'plugin-c', 'path': '${pluginC.path}/', 'native_build': true, 'dependencies': <String>[], }, ]; expect(plugins['ios'], expectedPlugins); expect(plugins['android'], expectedPlugins); expect(plugins['macos'], <dynamic>[]); expect(plugins['windows'], <dynamic>[]); expect(plugins['linux'], <dynamic>[]); expect(plugins['web'], <dynamic>[]);
final List<dynamic> expectedDependencyGraph = <dynamic>[ <String, dynamic> { 'name': 'plugin-a', 'dependencies': <String>[ 'plugin-b', 'plugin-c', ], }, <String, dynamic> { 'name': 'plugin-b', 'dependencies': <String>[ 'plugin-c', ], }, <String, dynamic> { 'name': 'plugin-c', 'dependencies': <String>[], }, ];
expect(jsonContent['dependencyGraph'], expectedDependencyGraph); expect(jsonContent['date_created'], dateCreated.toString()); expect(jsonContent['version'], '1.0.0');
// Make sure tests are updated if a new object is added/removed. final List<String> expectedKeys = <String>[ 'info', 'plugins', 'dependencyGraph', 'date_created', 'version', ]; expect(jsonContent.keys, expectedKeys); }, overrides: <Type, Generator>{ FileSystem: () => fs, ProcessManager: () => FakeProcessManager.any(), SystemClock: () => systemClock, FlutterVersion: () => flutterVersion, });
testUsingContext( '.flutter-plugins-dependencies contains plugin platform info', () async { createPlugin( name: 'plugin-a', platforms: const <String, _PluginPlatformInfo>{ // Native-only; should include native build. 'android': _PluginPlatformInfo(pluginClass: 'Foo', androidPackage: 'bar.foo'), // Hybrid native and Dart; should include native build. 'ios': _PluginPlatformInfo(pluginClass: 'Foo', dartPluginClass: 'Bar', sharedDarwinSource: true), // Web; should not have the native build key at all since it doesn't apply. 'web': _PluginPlatformInfo(pluginClass: 'Foo', fileName: 'lib/foo.dart'), // Dart-only; should not include native build. 'windows': _PluginPlatformInfo(dartPluginClass: 'Foo'), }); iosProject.testExists = true;
final DateTime dateCreated = DateTime(1970); systemClock.currentTime = dateCreated;
await refreshPluginsList(flutterProject);
expect(flutterProject.flutterPluginsDependenciesFile.existsSync(), true); final String pluginsString = flutterProject.flutterPluginsDependenciesFile.readAsStringSync(); final Map<String, dynamic> jsonContent = json.decode(pluginsString) as Map<String, dynamic>; final Map<String, dynamic>? actualPlugins = jsonContent['plugins'] as Map<String, dynamic>?;
final Map<String, Object> expectedPlugins = <String, Object>{ 'ios': <Map<String, Object>>[ <String, Object>{ 'name': 'plugin-a', 'path': '/.tmp_rand0/flutter_plugin.rand0/', 'shared_darwin_source': true, 'native_build': true, 'dependencies': <String>[] } ], 'android': <Map<String, Object>>[ <String, Object>{ 'name': 'plugin-a', 'path': '/.tmp_rand0/flutter_plugin.rand0/', 'native_build': true, 'dependencies': <String>[] } ], 'macos': <Map<String, Object>>[], 'linux': <Map<String, Object>>[], 'windows': <Map<String, Object>>[ <String, Object>{ 'name': 'plugin-a', 'path': '/.tmp_rand0/flutter_plugin.rand0/', 'native_build': false, 'dependencies': <String>[] } ], 'web': <Map<String, Object>>[ <String, Object>{ 'name': 'plugin-a', 'path': '/.tmp_rand0/flutter_plugin.rand0/', 'dependencies': <String>[] } ] }; expect(actualPlugins, expectedPlugins); }, overrides: <Type, Generator>{ FileSystem: () => fs, ProcessManager: () => FakeProcessManager.any(), SystemClock: () => systemClock, FlutterVersion: () => flutterVersion, });
testUsingContext('Changes to the plugin list invalidates the Cocoapod lockfiles', () async { simulatePodInstallRun(iosProject); simulatePodInstallRun(macosProject); createFakePlugin(fs); iosProject.testExists = true; macosProject.exists = true;
await refreshPluginsList(flutterProject, iosPlatform: true, macOSPlatform: true); expect(iosProject.podManifestLock.existsSync(), false); expect(macosProject.podManifestLock.existsSync(), false); }, overrides: <Type, Generator>{ FileSystem: () => fs, ProcessManager: () => FakeProcessManager.any(), SystemClock: () => systemClock, FlutterVersion: () => flutterVersion, });
testUsingContext('No changes to the plugin list does not invalidate the Cocoapod lockfiles', () async { createFakePlugin(fs); iosProject.testExists = true; macosProject.exists = true;
// First call will create the .flutter-plugins-dependencies and the legacy .flutter-plugins file. // Since there was no plugins list, the lock files will be invalidated. // The second call is where the plugins list is compared to the existing one, and if there is no change, // the podfiles shouldn't be invalidated. await refreshPluginsList(flutterProject, iosPlatform: true, macOSPlatform: true); simulatePodInstallRun(iosProject); simulatePodInstallRun(macosProject);
await refreshPluginsList(flutterProject); expect(iosProject.podManifestLock.existsSync(), true); expect(macosProject.podManifestLock.existsSync(), true); }, overrides: <Type, Generator>{ FileSystem: () => fs, ProcessManager: () => FakeProcessManager.any(), SystemClock: () => systemClock, FlutterVersion: () => flutterVersion, }); });
group('injectPlugins', () { FakeXcodeProjectInterpreter? xcodeProjectInterpreter;
setUp(() { xcodeProjectInterpreter = FakeXcodeProjectInterpreter(); });
testUsingContext('Registrant uses old embedding in app project', () async { androidProject.embeddingVersion = AndroidEmbeddingVersion.v1;
await injectPlugins(flutterProject, androidPlatform: true);
final File registrant = flutterProject.directory .childDirectory(fs.path.join('android', 'app', 'src', 'main', 'java', 'io', 'flutter', 'plugins')) .childFile('GeneratedPluginRegistrant.java');
expect(registrant.existsSync(), isTrue); expect(registrant.readAsStringSync(), contains('package io.flutter.plugins')); expect(registrant.readAsStringSync(), contains('class GeneratedPluginRegistrant')); expect(registrant.readAsStringSync(), contains('public static void registerWith(PluginRegistry registry)')); }, overrides: <Type, Generator>{ FileSystem: () => fs, ProcessManager: () => FakeProcessManager.any(), });
testUsingContext('Registrant uses new embedding if app uses new embedding', () async { androidProject.embeddingVersion = AndroidEmbeddingVersion.v2;
await injectPlugins(flutterProject, androidPlatform: true);
final File registrant = flutterProject.directory .childDirectory(fs.path.join('android', 'app', 'src', 'main', 'java', 'io', 'flutter', 'plugins')) .childFile('GeneratedPluginRegistrant.java');
expect(registrant.existsSync(), isTrue); expect(registrant.readAsStringSync(), contains('package io.flutter.plugins')); expect(registrant.readAsStringSync(), contains('class GeneratedPluginRegistrant')); expect(registrant.readAsStringSync(), contains('public static void registerWith(@NonNull FlutterEngine flutterEngine)')); }, overrides: <Type, Generator>{ FileSystem: () => fs, ProcessManager: () => FakeProcessManager.any(), });
testUsingContext('Registrant uses shim for plugins using old embedding if app uses new embedding', () async { androidProject.embeddingVersion = AndroidEmbeddingVersion.v2;
createNewJavaPlugin1(); createNewKotlinPlugin2(); createOldJavaPlugin('plugin3');
await injectPlugins(flutterProject, androidPlatform: true);
final File registrant = flutterProject.directory .childDirectory(fs.path.join('android', 'app', 'src', 'main', 'java', 'io', 'flutter', 'plugins')) .childFile('GeneratedPluginRegistrant.java');
expect(registrant.readAsStringSync(), contains('flutterEngine.getPlugins().add(new plugin1.UseNewEmbedding());')); expect(registrant.readAsStringSync(), contains('flutterEngine.getPlugins().add(new plugin2.UseNewEmbedding());')); expect(registrant.readAsStringSync(), contains('plugin3.UseOldEmbedding.registerWith(shimPluginRegistry.registrarFor("plugin3.UseOldEmbedding"));'));
// There should be no warning message expect(testLogger.statusText, isNot(contains('go/android-plugin-migration'))); }, overrides: <Type, Generator>{ FileSystem: () => fs, ProcessManager: () => FakeProcessManager.any(), XcodeProjectInterpreter: () => xcodeProjectInterpreter, });
testUsingContext('exits the tool if an app uses the v1 embedding and a plugin only supports the v2 embedding', () async { androidProject.embeddingVersion = AndroidEmbeddingVersion.v1;
createNewJavaPlugin1();
await expectLater( () async { await injectPlugins(flutterProject, androidPlatform: true); }, throwsToolExit( message: 'The plugin `plugin1` requires your app to be migrated to the Android embedding v2. ' 'Follow the steps on the migration doc above and re-run this command.' ), ); }, overrides: <Type, Generator>{ FileSystem: () => fs, ProcessManager: () => FakeProcessManager.any(), XcodeProjectInterpreter: () => xcodeProjectInterpreter, });
// Issue: https://github.com/flutter/flutter/issues/47803 testUsingContext('exits the tool if a plugin sets an invalid android package in pubspec.yaml', () async { androidProject.embeddingVersion = AndroidEmbeddingVersion.v1;
final Directory pluginDir = createPluginWithInvalidAndroidPackage();
await expectLater( () async { await injectPlugins(flutterProject, androidPlatform: true); }, throwsToolExit( message: "The plugin `plugin1` doesn't have a main class defined in " '${pluginDir.path}/android/src/main/java/plugin1/invalid/UseNewEmbedding.java or ' '${pluginDir.path}/android/src/main/kotlin/plugin1/invalid/UseNewEmbedding.kt. ' "This is likely to due to an incorrect `androidPackage: plugin1.invalid` or `mainClass` entry in the plugin's pubspec.yaml.\n" 'If you are the author of this plugin, fix the `androidPackage` entry or move the main class to any of locations used above. ' 'Otherwise, please contact the author of this plugin and consider using a different plugin in the meanwhile.', ), ); }, overrides: <Type, Generator>{ FileSystem: () => fs, ProcessManager: () => FakeProcessManager.any(), XcodeProjectInterpreter: () => xcodeProjectInterpreter, });
testUsingContext('old embedding app uses a plugin that supports v1 and v2 embedding works', () async { androidProject.embeddingVersion = AndroidEmbeddingVersion.v1;
createDualSupportJavaPlugin4();
await injectPlugins(flutterProject, androidPlatform: true);
final File registrant = flutterProject.directory .childDirectory(fs.path.join('android', 'app', 'src', 'main', 'java', 'io', 'flutter', 'plugins')) .childFile('GeneratedPluginRegistrant.java');
expect(registrant.existsSync(), isTrue); expect(registrant.readAsStringSync(), contains('package io.flutter.plugins')); expect(registrant.readAsStringSync(), contains('class GeneratedPluginRegistrant')); expect(registrant.readAsStringSync(), contains('UseBothEmbedding.registerWith(registry.registrarFor("plugin4.UseBothEmbedding"));')); }, overrides: <Type, Generator>{ FileSystem: () => fs, ProcessManager: () => FakeProcessManager.any(), XcodeProjectInterpreter: () => xcodeProjectInterpreter, });
testUsingContext('new embedding app uses a plugin that supports v1 and v2 embedding', () async { androidProject.embeddingVersion = AndroidEmbeddingVersion.v2;
createDualSupportJavaPlugin4();
await injectPlugins(flutterProject, androidPlatform: true);
final File registrant = flutterProject.directory .childDirectory(fs.path.join('android', 'app', 'src', 'main', 'java', 'io', 'flutter', 'plugins')) .childFile('GeneratedPluginRegistrant.java');
expect(registrant.existsSync(), isTrue); expect(registrant.readAsStringSync(), contains('package io.flutter.plugins')); expect(registrant.readAsStringSync(), contains('class GeneratedPluginRegistrant')); expect(registrant.readAsStringSync(), contains('flutterEngine.getPlugins().add(new plugin4.UseBothEmbedding());')); }, overrides: <Type, Generator>{ FileSystem: () => fs, ProcessManager: () => FakeProcessManager.any(), XcodeProjectInterpreter: () => xcodeProjectInterpreter, });
testUsingContext('Modules use new embedding', () async { flutterProject.isModule = true; androidProject.embeddingVersion = AndroidEmbeddingVersion.v2;
await injectPlugins(flutterProject, androidPlatform: true);
final File registrant = flutterProject.directory .childDirectory(fs.path.join('android', 'app', 'src', 'main', 'java', 'io', 'flutter', 'plugins')) .childFile('GeneratedPluginRegistrant.java');
expect(registrant.existsSync(), isTrue); expect(registrant.readAsStringSync(), contains('package io.flutter.plugins')); expect(registrant.readAsStringSync(), contains('class GeneratedPluginRegistrant')); expect(registrant.readAsStringSync(), contains('public static void registerWith(@NonNull FlutterEngine flutterEngine)')); }, overrides: <Type, Generator>{ FileSystem: () => fs, ProcessManager: () => FakeProcessManager.any(), });
testUsingContext('Module using old plugin shows warning', () async { flutterProject.isModule = true; androidProject.embeddingVersion = AndroidEmbeddingVersion.v2;
createOldJavaPlugin('plugin3');
await injectPlugins(flutterProject, androidPlatform: true);
final File registrant = flutterProject.directory .childDirectory(fs.path.join('android', 'app', 'src', 'main', 'java', 'io', 'flutter', 'plugins')) .childFile('GeneratedPluginRegistrant.java'); expect(registrant.readAsStringSync(), contains('plugin3.UseOldEmbedding.registerWith(shimPluginRegistry.registrarFor("plugin3.UseOldEmbedding"));')); expect(testLogger.warningText, equals( 'The plugin `plugin3` uses a deprecated version of the Android embedding.\n' 'To avoid unexpected runtime failures, or future build failures, try to see if this plugin supports the Android V2 embedding. ' 'Otherwise, consider removing it since a future release of Flutter will remove these deprecated APIs.\n' 'If you are plugin author, take a look at the docs for migrating the plugin to the V2 embedding: https://flutter.dev/go/android-plugin-migration.\n')); }, overrides: <Type, Generator>{ FileSystem: () => fs, ProcessManager: () => FakeProcessManager.any(), XcodeProjectInterpreter: () => xcodeProjectInterpreter, });
testUsingContext('Module using new plugin shows no warnings', () async { flutterProject.isModule = true; androidProject.embeddingVersion = AndroidEmbeddingVersion.v2;
createNewJavaPlugin1();
await injectPlugins(flutterProject, androidPlatform: true);
final File registrant = flutterProject.directory .childDirectory(fs.path.join('android', 'app', 'src', 'main', 'java', 'io', 'flutter', 'plugins')) .childFile('GeneratedPluginRegistrant.java'); expect(registrant.readAsStringSync(), contains('flutterEngine.getPlugins().add(new plugin1.UseNewEmbedding());'));
expect(testLogger.errorText, isNot(contains('go/android-plugin-migration'))); }, overrides: <Type, Generator>{ FileSystem: () => fs, ProcessManager: () => FakeProcessManager.any(), XcodeProjectInterpreter: () => xcodeProjectInterpreter, });
testUsingContext('Module using plugin with v1 and v2 support shows no warning', () async { flutterProject.isModule = true; androidProject.embeddingVersion = AndroidEmbeddingVersion.v2;
createDualSupportJavaPlugin4();
await injectPlugins(flutterProject, androidPlatform: true);
final File registrant = flutterProject.directory .childDirectory(fs.path.join('android', 'app', 'src', 'main', 'java', 'io', 'flutter', 'plugins')) .childFile('GeneratedPluginRegistrant.java'); expect(registrant.readAsStringSync(), contains('flutterEngine.getPlugins().add(new plugin4.UseBothEmbedding());'));
expect(testLogger.errorText, isNot(contains('go/android-plugin-migration'))); }, overrides: <Type, Generator>{ FileSystem: () => fs, ProcessManager: () => FakeProcessManager.any(), XcodeProjectInterpreter: () => xcodeProjectInterpreter, });
testUsingContext('App using plugin with v1 and v2 support shows no warning', () async { flutterProject.isModule = false; androidProject.embeddingVersion = AndroidEmbeddingVersion.v2;
createDualSupportJavaPlugin4();
await injectPlugins(flutterProject, androidPlatform: true);
final File registrant = flutterProject.directory .childDirectory(fs.path.join('android', 'app', 'src', 'main', 'java', 'io', 'flutter', 'plugins')) .childFile('GeneratedPluginRegistrant.java'); expect(registrant.readAsStringSync(), contains('flutterEngine.getPlugins().add(new plugin4.UseBothEmbedding());'));
expect(testLogger.errorText, isNot(contains('go/android-plugin-migration'))); }, overrides: <Type, Generator>{ FileSystem: () => fs, ProcessManager: () => FakeProcessManager.any(), XcodeProjectInterpreter: () => xcodeProjectInterpreter, });
testUsingContext('App using the v1 embedding shows warning', () async { flutterProject.isModule = false; androidProject.embeddingVersion = AndroidEmbeddingVersion.v1;
await injectPlugins(flutterProject, androidPlatform: true);
expect(testLogger.warningText, equals( 'This app is using a deprecated version of the Android embedding.\n' 'To avoid unexpected runtime failures, or future build failures, try to migrate this app to the V2 embedding.\n' 'Take a look at the docs for migrating an app: https://github.com/flutter/flutter/wiki/Upgrading-pre-1.12-Android-projects\n' )); }, overrides: <Type, Generator>{ FileSystem: () => fs, ProcessManager: () => FakeProcessManager.any(), XcodeProjectInterpreter: () => xcodeProjectInterpreter, });
testUsingContext('Module using multiple old plugins all show warnings', () async { flutterProject.isModule = true; androidProject.embeddingVersion = AndroidEmbeddingVersion.v2;
createOldJavaPlugin('plugin3'); createOldJavaPlugin('plugin4');
await injectPlugins(flutterProject, androidPlatform: true);
final File registrant = flutterProject.directory .childDirectory(fs.path.join('android', 'app', 'src', 'main', 'java', 'io', 'flutter', 'plugins')) .childFile('GeneratedPluginRegistrant.java'); expect(registrant.readAsStringSync(), contains('plugin3.UseOldEmbedding.registerWith(shimPluginRegistry.registrarFor("plugin3.UseOldEmbedding"));')); expect(registrant.readAsStringSync(), contains('plugin4.UseOldEmbedding.registerWith(shimPluginRegistry.registrarFor("plugin4.UseOldEmbedding"));')); expect(testLogger.warningText, equals( 'The plugins `plugin3, plugin4` use a deprecated version of the Android embedding.\n' 'To avoid unexpected runtime failures, or future build failures, try to see if these plugins support the Android V2 embedding. ' 'Otherwise, consider removing them since a future release of Flutter will remove these deprecated APIs.\n' 'If you are plugin author, take a look at the docs for migrating the plugin to the V2 embedding: https://flutter.dev/go/android-plugin-migration.\n' )); }, overrides: <Type, Generator>{ FileSystem: () => fs, ProcessManager: () => FakeProcessManager.any(), XcodeProjectInterpreter: () => xcodeProjectInterpreter, });
testUsingContext('App using multiple old plugins all show warnings', () async { flutterProject.isModule = false; androidProject.embeddingVersion = AndroidEmbeddingVersion.v2;
createOldJavaPlugin('plugin3'); createOldJavaPlugin('plugin4');
await injectPlugins(flutterProject, androidPlatform: true);
final File registrant = flutterProject.directory .childDirectory(fs.path.join('android', 'app', 'src', 'main', 'java', 'io', 'flutter', 'plugins')) .childFile('GeneratedPluginRegistrant.java'); expect(registrant.readAsStringSync(), contains('plugin3.UseOldEmbedding.registerWith(shimPluginRegistry.registrarFor("plugin3.UseOldEmbedding"));')); expect(registrant.readAsStringSync(), contains('plugin4.UseOldEmbedding.registerWith(shimPluginRegistry.registrarFor("plugin4.UseOldEmbedding"));')); expect(testLogger.warningText, equals( 'The plugins `plugin3, plugin4` use a deprecated version of the Android embedding.\n' 'To avoid unexpected runtime failures, or future build failures, try to see if these plugins support the Android V2 embedding. ' 'Otherwise, consider removing them since a future release of Flutter will remove these deprecated APIs.\n' 'If you are plugin author, take a look at the docs for migrating the plugin to the V2 embedding: https://flutter.dev/go/android-plugin-migration.\n' )); }, overrides: <Type, Generator>{ FileSystem: () => fs, ProcessManager: () => FakeProcessManager.any(), XcodeProjectInterpreter: () => xcodeProjectInterpreter, });
testUsingContext('Module using multiple old and new plugins should be wrapped with try catch', () async { flutterProject.isModule = true; androidProject.embeddingVersion = AndroidEmbeddingVersion.v2;
createOldJavaPlugin('abcplugin1'); createNewJavaPlugin1();
await injectPlugins(flutterProject, androidPlatform: true);
final File registrant = flutterProject.directory .childDirectory(fs.path.join('android', 'app', 'src', 'main', 'java', 'io', 'flutter', 'plugins')) .childFile('GeneratedPluginRegistrant.java'); const String newPluginName = 'flutterEngine.getPlugins().add(new plugin1.UseNewEmbedding());'; const String oldPluginName = 'abcplugin1.UseOldEmbedding.registerWith(shimPluginRegistry.registrarFor("abcplugin1.UseOldEmbedding"));'; final String content = registrant.readAsStringSync(); for (final String plugin in <String>[newPluginName,oldPluginName]) { expect(content, contains(plugin)); expect(content.split(plugin).first.trim().endsWith('try {'), isTrue); expect(content.split(plugin).last.trim().startsWith('} catch (Exception e) {'), isTrue); } }, overrides: <Type, Generator>{ FileSystem: () => fs, ProcessManager: () => FakeProcessManager.any(), XcodeProjectInterpreter: () => xcodeProjectInterpreter, });
testUsingContext('Does not throw when AndroidManifest.xml is not found', () async { final File manifest = fs.file('AndroidManifest.xml'); androidProject.appManifestFile = manifest; await injectPlugins(flutterProject, androidPlatform: true); }, overrides: <Type, Generator>{ FileSystem: () => fs, ProcessManager: () => FakeProcessManager.any(), });
testUsingContext("Registrant for web doesn't escape slashes in imports", () async { flutterProject.isModule = true; final Directory webPluginWithNestedFile = fs.systemTempDirectory.createTempSync('flutter_web_plugin_with_nested.'); webPluginWithNestedFile.childFile('pubspec.yaml').writeAsStringSync(''' flutter: plugin: platforms: web: pluginClass: WebPlugin fileName: src/web_plugin.dart '''); webPluginWithNestedFile .childDirectory('lib') .childDirectory('src') .childFile('web_plugin.dart') .createSync(recursive: true);
flutterProject.directory .childFile('.packages') .writeAsStringSync('''web_plugin_with_nested:${webPluginWithNestedFile.childDirectory('lib').uri}''');
final Directory destination = flutterProject.directory.childDirectory('lib'); await injectBuildTimePluginFiles(flutterProject, webPlatform: true, destination: destination);
final File registrant = flutterProject.directory .childDirectory('lib') .childFile('web_plugin_registrant.dart');
expect(registrant.existsSync(), isTrue); expect(registrant.readAsStringSync(), contains("import 'package:web_plugin_with_nested/src/web_plugin.dart';")); }, overrides: <Type, Generator>{ FileSystem: () => fs, ProcessManager: () => FakeProcessManager.any(), });
testUsingContext('Injecting creates generated Android registrant, but does not include Dart-only plugins', () async { // Create a plugin without a pluginClass. final Directory pluginDirectory = createFakePlugin(fs); pluginDirectory.childFile('pubspec.yaml').writeAsStringSync('''flutter: plugin: platforms: android: dartPluginClass: SomePlugin ''');
await injectPlugins(flutterProject, androidPlatform: true);
final File registrantFile = androidProject.pluginRegistrantHost .childDirectory(fs.path.join('src', 'main', 'java', 'io', 'flutter', 'plugins')) .childFile('GeneratedPluginRegistrant.java');
expect(registrantFile, exists); expect(registrantFile, isNot(contains('SomePlugin'))); }, overrides: <Type, Generator>{ FileSystem: () => fs, ProcessManager: () => FakeProcessManager.any(), });
testUsingContext('Injecting creates generated iOS registrant, but does not include Dart-only plugins', () async { flutterProject.isModule = true; // Create a plugin without a pluginClass. final Directory pluginDirectory = createFakePlugin(fs); pluginDirectory.childFile('pubspec.yaml').writeAsStringSync('''flutter: plugin: platforms: ios: dartPluginClass: SomePlugin ''');
await injectPlugins(flutterProject, iosPlatform: true);
final File registrantFile = iosProject.pluginRegistrantImplementation;
expect(registrantFile, exists); expect(registrantFile, isNot(contains('SomePlugin'))); }, overrides: <Type, Generator>{ FileSystem: () => fs, ProcessManager: () => FakeProcessManager.any(), });
testUsingContext('Injecting creates generated macos registrant, but does not include Dart-only plugins', () async { flutterProject.isModule = true; // Create a plugin without a pluginClass. final Directory pluginDirectory = createFakePlugin(fs); pluginDirectory.childFile('pubspec.yaml').writeAsStringSync('''flutter: plugin: platforms: macos: dartPluginClass: SomePlugin ''');
await injectPlugins(flutterProject, macOSPlatform: true);
final File registrantFile = macosProject.managedDirectory.childFile('GeneratedPluginRegistrant.swift');
expect(registrantFile, exists); expect(registrantFile, isNot(contains('SomePlugin'))); }, overrides: <Type, Generator>{ FileSystem: () => fs, ProcessManager: () => FakeProcessManager.any(), });
testUsingContext("pluginClass: none doesn't trigger registrant entry on macOS", () async { flutterProject.isModule = true; // Create a plugin without a pluginClass. final Directory pluginDirectory = createFakePlugin(fs); pluginDirectory.childFile('pubspec.yaml').writeAsStringSync('''flutter: plugin: platforms: macos: pluginClass: none dartPluginClass: SomePlugin ''');
await injectPlugins(flutterProject, macOSPlatform: true);
final File registrantFile = macosProject.managedDirectory.childFile('GeneratedPluginRegistrant.swift');
expect(registrantFile, exists); expect(registrantFile, isNot(contains('SomePlugin'))); expect(registrantFile, isNot(contains('none'))); }, overrides: <Type, Generator>{ FileSystem: () => fs, ProcessManager: () => FakeProcessManager.any(), });
testUsingContext('Invalid yaml does not crash plugin lookup.', () async { flutterProject.isModule = true; // Create a plugin without a pluginClass. final Directory pluginDirectory = createFakePlugin(fs); pluginDirectory.childFile('pubspec.yaml').writeAsStringSync(r'''"aws ... \"Branch\": $BITBUCKET_BRANCH, \"Date\": $(date +"%m-%d-%y"), \"Time\": $(date +"%T")}\" ''');
await injectPlugins(flutterProject, macOSPlatform: true);
final File registrantFile = macosProject.managedDirectory.childFile('GeneratedPluginRegistrant.swift');
expect(registrantFile, exists); }, overrides: <Type, Generator>{ FileSystem: () => fs, ProcessManager: () => FakeProcessManager.any(), });
testUsingContext('Injecting creates generated Linux registrant', () async { createFakePlugin(fs);
await injectPlugins(flutterProject, linuxPlatform: true);
final File registrantHeader = linuxProject.managedDirectory.childFile('generated_plugin_registrant.h'); final File registrantImpl = linuxProject.managedDirectory.childFile('generated_plugin_registrant.cc');
expect(registrantHeader.existsSync(), isTrue); expect(registrantImpl.existsSync(), isTrue); expect(registrantImpl.readAsStringSync(), contains('some_plugin_register_with_registrar')); }, overrides: <Type, Generator>{ FileSystem: () => fs, ProcessManager: () => FakeProcessManager.any(), });
testUsingContext('Injecting creates generated Linux registrant, but does not include Dart-only plugins', () async { // Create a plugin without a pluginClass. final Directory pluginDirectory = createFakePlugin(fs); pluginDirectory.childFile('pubspec.yaml').writeAsStringSync('''flutter: plugin: platforms: linux: dartPluginClass: SomePlugin ''');
await injectPlugins(flutterProject, linuxPlatform: true);
final File registrantImpl = linuxProject.managedDirectory.childFile('generated_plugin_registrant.cc');
expect(registrantImpl, exists); expect(registrantImpl, isNot(contains('SomePlugin'))); expect(registrantImpl, isNot(contains('some_plugin'))); }, overrides: <Type, Generator>{ FileSystem: () => fs, ProcessManager: () => FakeProcessManager.any(), });
testUsingContext("pluginClass: none doesn't trigger registrant entry on Linux", () async { // Create a plugin without a pluginClass. final Directory pluginDirectory = createFakePlugin(fs); pluginDirectory.childFile('pubspec.yaml').writeAsStringSync('''flutter: plugin: platforms: linux: pluginClass: none dartPluginClass: SomePlugin ''');
await injectPlugins(flutterProject, linuxPlatform: true);
final File registrantImpl = linuxProject.managedDirectory.childFile('generated_plugin_registrant.cc');
expect(registrantImpl, exists); expect(registrantImpl, isNot(contains('SomePlugin'))); expect(registrantImpl, isNot(contains('none'))); }, overrides: <Type, Generator>{ FileSystem: () => fs, ProcessManager: () => FakeProcessManager.any(), });
testUsingContext('Injecting creates generated Linux plugin Cmake file', () async { createFakePlugin(fs);
await injectPlugins(flutterProject, linuxPlatform: true);
final File pluginMakefile = linuxProject.generatedPluginCmakeFile;
expect(pluginMakefile.existsSync(), isTrue); final String contents = pluginMakefile.readAsStringSync(); expect(contents, contains('some_plugin')); expect(contents, contains(r'target_link_libraries(${BINARY_NAME} PRIVATE ${plugin}_plugin)')); expect(contents, contains(r'list(APPEND PLUGIN_BUNDLED_LIBRARIES $<TARGET_FILE:${plugin}_plugin>)')); expect(contents, contains(r'list(APPEND PLUGIN_BUNDLED_LIBRARIES ${${plugin}_bundled_libraries})')); }, overrides: <Type, Generator>{ FileSystem: () => fs, ProcessManager: () => FakeProcessManager.any(), });
testUsingContext('Generated Linux plugin files sorts by plugin name', () async { createFakePlugins(fs, <String>[ 'plugin_d', 'plugin_a', '/local_plugins/plugin_c', '/local_plugins/plugin_b', ]);
await injectPlugins(flutterProject, linuxPlatform: true);
final File pluginCmakeFile = linuxProject.generatedPluginCmakeFile; final File pluginRegistrant = linuxProject.managedDirectory.childFile('generated_plugin_registrant.cc'); for (final File file in <File>[pluginCmakeFile, pluginRegistrant]) { final String contents = file.readAsStringSync(); expect(contents.indexOf('plugin_a'), lessThan(contents.indexOf('plugin_b'))); expect(contents.indexOf('plugin_b'), lessThan(contents.indexOf('plugin_c'))); expect(contents.indexOf('plugin_c'), lessThan(contents.indexOf('plugin_d'))); } }, overrides: <Type, Generator>{ FileSystem: () => fs, ProcessManager: () => FakeProcessManager.any(), });
testUsingContext('Injecting creates generated Windows registrant', () async { createFakePlugin(fs);
await injectPlugins(flutterProject, windowsPlatform: true);
final File registrantHeader = windowsProject.managedDirectory.childFile('generated_plugin_registrant.h'); final File registrantImpl = windowsProject.managedDirectory.childFile('generated_plugin_registrant.cc');
expect(registrantHeader.existsSync(), isTrue); expect(registrantImpl.existsSync(), isTrue); expect(registrantImpl.readAsStringSync(), contains('SomePluginRegisterWithRegistrar')); }, overrides: <Type, Generator>{ FileSystem: () => fs, ProcessManager: () => FakeProcessManager.any(), });
testUsingContext('Injecting creates generated Windows registrant, but does not include Dart-only plugins', () async { // Create a plugin without a pluginClass. final Directory pluginDirectory = createFakePlugin(fs); pluginDirectory.childFile('pubspec.yaml').writeAsStringSync('''flutter: plugin: platforms: windows: dartPluginClass: SomePlugin ''');
await injectPlugins(flutterProject, windowsPlatform: true);
final File registrantImpl = windowsProject.managedDirectory.childFile('generated_plugin_registrant.cc');
expect(registrantImpl, exists); expect(registrantImpl, isNot(contains('SomePlugin'))); }, overrides: <Type, Generator>{ FileSystem: () => fs, ProcessManager: () => FakeProcessManager.any(), });
testUsingContext("pluginClass: none doesn't trigger registrant entry on Windows", () async { // Create a plugin without a pluginClass. final Directory pluginDirectory = createFakePlugin(fs); pluginDirectory.childFile('pubspec.yaml').writeAsStringSync('''flutter: plugin: platforms: windows: pluginClass: none dartPluginClass: SomePlugin ''');
await injectPlugins(flutterProject, windowsPlatform: true);
final File registrantImpl = windowsProject.managedDirectory.childFile('generated_plugin_registrant.cc');
expect(registrantImpl, exists); expect(registrantImpl, isNot(contains('SomePlugin'))); expect(registrantImpl, isNot(contains('none'))); }, overrides: <Type, Generator>{ FileSystem: () => fs, ProcessManager: () => FakeProcessManager.any(), });
testUsingContext('Generated Windows plugin files sorts by plugin name', () async { createFakePlugins(fs, <String>[ 'plugin_d', 'plugin_a', '/local_plugins/plugin_c', '/local_plugins/plugin_b', ]);
await injectPlugins(flutterProject, windowsPlatform: true);
final File pluginCmakeFile = windowsProject.generatedPluginCmakeFile; final File pluginRegistrant = windowsProject.managedDirectory.childFile('generated_plugin_registrant.cc'); for (final File file in <File>[pluginCmakeFile, pluginRegistrant]) { final String contents = file.readAsStringSync(); expect(contents.indexOf('plugin_a'), lessThan(contents.indexOf('plugin_b'))); expect(contents.indexOf('plugin_b'), lessThan(contents.indexOf('plugin_c'))); expect(contents.indexOf('plugin_c'), lessThan(contents.indexOf('plugin_d'))); } }, overrides: <Type, Generator>{ FileSystem: () => fs, ProcessManager: () => FakeProcessManager.any(), });
testUsingContext('Generated plugin CMake files always use posix-style paths', () async { // Re-run the setup using the Windows filesystem. setUpProject(fsWindows); createFakePlugin(fsWindows);
await injectPlugins(flutterProject, linuxPlatform: true, windowsPlatform: true);
for (final CmakeBasedProject? project in <CmakeBasedProject?>[linuxProject, windowsProject]) { final File pluginCmakefile = project!.generatedPluginCmakeFile;
expect(pluginCmakefile.existsSync(), isTrue); final String contents = pluginCmakefile.readAsStringSync(); expect(contents, contains('add_subdirectory(flutter/ephemeral/.plugin_symlinks')); } }, overrides: <Type, Generator>{ FileSystem: () => fsWindows, ProcessManager: () => FakeProcessManager.any(), });
testUsingContext('injectPlugins will validate if all plugins in the project are part of the passed allowedPlugins', () async { // Re-run the setup using the Windows filesystem. setUpProject(fsWindows); createFakePlugins(fsWindows, const <String>['plugin_one', 'plugin_two']);
expect( () => injectPlugins( flutterProject, linuxPlatform: true, windowsPlatform: true, allowedPlugins: PreviewDevice.supportedPubPlugins, ), throwsToolExit(message: '''The Flutter Preview device does not support the following plugins from your pubspec.yaml:
[plugin_one, plugin_two]'''), ); }, overrides: <Type, Generator>{ FileSystem: () => fsWindows, ProcessManager: () => FakeProcessManager.empty(), }); });
group('createPluginSymlinks', () { FeatureFlags? featureFlags;
setUp(() { featureFlags = TestFeatureFlags(isLinuxEnabled: true, isWindowsEnabled: true); });
testUsingContext('Symlinks are created for Linux plugins', () async { linuxProject.exists = true; createFakePlugin(fs); // refreshPluginsList should call createPluginSymlinks. await refreshPluginsList(flutterProject);
expect(linuxProject.pluginSymlinkDirectory.childLink('some_plugin').existsSync(), true); }, overrides: <Type, Generator>{ FileSystem: () => fs, ProcessManager: () => FakeProcessManager.any(), FeatureFlags: () => featureFlags, });
testUsingContext('Symlinks are created for Windows plugins', () async { windowsProject.exists = true; createFakePlugin(fs); // refreshPluginsList should call createPluginSymlinks. await refreshPluginsList(flutterProject);
expect(windowsProject.pluginSymlinkDirectory.childLink('some_plugin').existsSync(), true); }, overrides: <Type, Generator>{ FileSystem: () => fs, ProcessManager: () => FakeProcessManager.any(), FeatureFlags: () => featureFlags, });
testUsingContext('Existing symlinks are removed when no longer in use with force', () { linuxProject.exists = true; windowsProject.exists = true;
final List<File> dummyFiles = <File>[ flutterProject.linux.pluginSymlinkDirectory.childFile('dummy'), flutterProject.windows.pluginSymlinkDirectory.childFile('dummy'), ]; for (final File file in dummyFiles) { file.createSync(recursive: true); }
createPluginSymlinks(flutterProject, force: true);
for (final File file in dummyFiles) { expect(file.existsSync(), false); } }, overrides: <Type, Generator>{ FileSystem: () => fs, ProcessManager: () => FakeProcessManager.any(), FeatureFlags: () => featureFlags, });
testUsingContext('Existing symlinks are removed automatically on refresh when no longer in use', () async { linuxProject.exists = true; windowsProject.exists = true;
final List<File> dummyFiles = <File>[ flutterProject.linux.pluginSymlinkDirectory.childFile('dummy'), flutterProject.windows.pluginSymlinkDirectory.childFile('dummy'), ]; for (final File file in dummyFiles) { file.createSync(recursive: true); }
// refreshPluginsList should remove existing links and recreate on changes. createFakePlugin(fs); await refreshPluginsList(flutterProject);
for (final File file in dummyFiles) { expect(file.existsSync(), false); } }, overrides: <Type, Generator>{ FileSystem: () => fs, ProcessManager: () => FakeProcessManager.any(), FeatureFlags: () => featureFlags, });
testUsingContext('createPluginSymlinks is a no-op without force when up to date', () { linuxProject.exists = true; windowsProject.exists = true;
final List<File> dummyFiles = <File>[ flutterProject.linux.pluginSymlinkDirectory.childFile('dummy'), flutterProject.windows.pluginSymlinkDirectory.childFile('dummy'), ]; for (final File file in dummyFiles) { file.createSync(recursive: true); }
// Without force, this should do nothing to existing files. createPluginSymlinks(flutterProject);
for (final File file in dummyFiles) { expect(file.existsSync(), true); } }, overrides: <Type, Generator>{ FileSystem: () => fs, ProcessManager: () => FakeProcessManager.any(), FeatureFlags: () => featureFlags, });
testUsingContext('createPluginSymlinks repairs missing links', () async { linuxProject.exists = true; windowsProject.exists = true; createFakePlugin(fs); await refreshPluginsList(flutterProject);
final List<Link> links = <Link>[ linuxProject.pluginSymlinkDirectory.childLink('some_plugin'), windowsProject.pluginSymlinkDirectory.childLink('some_plugin'), ]; for (final Link link in links) { link.deleteSync(); } createPluginSymlinks(flutterProject);
for (final Link link in links) { expect(link.existsSync(), true); } }, overrides: <Type, Generator>{ FileSystem: () => fs, ProcessManager: () => FakeProcessManager.any(), FeatureFlags: () => featureFlags, }); });
group('pubspec', () { late Directory projectDir; late Directory tempDir;
setUp(() { tempDir = globals.fs.systemTempDirectory.createTempSync('flutter_plugin_test.'); projectDir = tempDir.childDirectory('flutter_project'); });
tearDown(() { tryToDelete(tempDir); });
void createPubspecFile(String yamlString) { projectDir.childFile('pubspec.yaml')..createSync(recursive: true)..writeAsStringSync(yamlString); }
testUsingContext('validatePubspecForPlugin works', () async { const String pluginYaml = ''' flutter: plugin: platforms: ios: pluginClass: SomePlugin macos: pluginClass: SomePlugin windows: pluginClass: SomePlugin linux: pluginClass: SomePlugin web: pluginClass: SomePlugin fileName: lib/SomeFile.dart android: pluginClass: SomePlugin package: AndroidPackage '''; createPubspecFile(pluginYaml); validatePubspecForPlugin(projectDir: projectDir.absolute.path, pluginClass: 'SomePlugin', expectedPlatforms: <String>[ 'ios', 'macos', 'windows', 'linux', 'android', 'web', ], androidIdentifier: 'AndroidPackage', webFileName: 'lib/SomeFile.dart'); });
testUsingContext('createPlatformsYamlMap should create the correct map', () async { final YamlMap map = Plugin.createPlatformsYamlMap(<String>['ios', 'android', 'linux'], 'PluginClass', 'some.android.package'); expect(map['ios'], <String, String> { 'pluginClass' : 'PluginClass', }); expect(map['android'], <String, String> { 'pluginClass' : 'PluginClass', 'package': 'some.android.package', }); expect(map['linux'], <String, String> { 'pluginClass' : 'PluginClass', }); });
testUsingContext('createPlatformsYamlMap should create empty map', () async { final YamlMap map = Plugin.createPlatformsYamlMap(<String>[], 'foo', 'bar'); expect(map.isEmpty, true); });
});
testWithoutContext('Symlink failures give developer mode instructions on recent versions of Windows', () async { final Platform platform = FakePlatform(operatingSystem: 'windows'); final FakeOperatingSystemUtils os = FakeOperatingSystemUtils('Microsoft Windows [Version 10.0.14972.1]');
const FileSystemException e = FileSystemException('', '', OSError('', 1314));
expect( () => handleSymlinkException( e, platform: platform, os: os, source: pubCachePath, destination: ephemeralPackagePath, ), throwsToolExit(message: 'start ms-settings:developers'), ); });
testWithoutContext('Symlink ERROR_ACCESS_DENIED failures show developers paths that were used', () async { final Platform platform = FakePlatform(operatingSystem: 'windows'); final FakeOperatingSystemUtils os = FakeOperatingSystemUtils('Microsoft Windows [Version 10.0.14972.1]');
const FileSystemException e = FileSystemException('', '', OSError('', 5));
expect( () => handleSymlinkException( e, platform: platform, os: os, source: pubCachePath, destination: ephemeralPackagePath, ), throwsToolExit( message: 'ERROR_ACCESS_DENIED file system exception thrown while trying to create a symlink from $pubCachePath to $ephemeralPackagePath', ), ); });
testWithoutContext('Symlink failures instruct developers to run as administrator on older versions of Windows', () async { final Platform platform = FakePlatform(operatingSystem: 'windows'); final FakeOperatingSystemUtils os = FakeOperatingSystemUtils('Microsoft Windows [Version 10.0.14393]');
const FileSystemException e = FileSystemException('', '', OSError('', 1314));
expect( () => handleSymlinkException( e, platform: platform, os: os, source: pubCachePath, destination: ephemeralPackagePath, ), throwsToolExit(message: 'administrator'), ); });
testWithoutContext('Symlink failures instruct developers to have their project on the same drive as their SDK', () async { final Platform platform = FakePlatform(operatingSystem: 'windows'); final FakeOperatingSystemUtils os = FakeOperatingSystemUtils('Microsoft Windows [Version 10.0.14972]');
const FileSystemException e = FileSystemException('', '', OSError('', 1));
expect( () => handleSymlinkException( e, platform: platform, os: os, source: pubCachePath, destination: ephemeralPackagePath, ), throwsToolExit(message: 'Try moving your Flutter project to the same drive as your Flutter SDK'), ); });
testWithoutContext('Symlink failures only give instructions for specific errors', () async { final Platform platform = FakePlatform(operatingSystem: 'windows'); final FakeOperatingSystemUtils os = FakeOperatingSystemUtils('Microsoft Windows [Version 10.0.14393]');
const FileSystemException e = FileSystemException('', '', OSError('', 999));
expect( () => handleSymlinkException( e, platform: platform, os: os, source: pubCachePath, destination: ephemeralPackagePath, ), returnsNormally, ); }); });}
class FakeFlutterManifest extends Fake implements FlutterManifest { @override Set<String> get dependencies => <String>{};}
class FakeXcodeProjectInterpreter extends Fake implements XcodeProjectInterpreter { @override bool get isInstalled => false;}
class FakeFlutterProject extends Fake implements FlutterProject { @override bool isModule = false;
@override late FlutterManifest manifest;
@override late Directory directory;
@override late File flutterPluginsFile;
@override late File flutterPluginsDependenciesFile;
@override late IosProject ios;
@override late AndroidProject android;
@override late WebProject web;
@override late MacOSProject macos;
@override late LinuxProject linux;
@override late WindowsProject windows;}
class FakeMacOSProject extends Fake implements MacOSProject { @override String pluginConfigKey = 'macos';
bool exists = false;
@override late File podfile;
@override late File podManifestLock;
@override late Directory managedDirectory;
@override bool existsSync() => exists;}
class FakeIosProject extends Fake implements IosProject { @override String pluginConfigKey = 'ios';
bool testExists = false;
@override bool existsSync() => testExists;
@override bool get exists => testExists;
@override late Directory pluginRegistrantHost;
@override File get pluginRegistrantHeader => pluginRegistrantHost.childFile('GeneratedPluginRegistrant.h');
@override File get pluginRegistrantImplementation => pluginRegistrantHost.childFile('GeneratedPluginRegistrant.m');
@override late File podfile;
@override late File podManifestLock;}
class FakeAndroidProject extends Fake implements AndroidProject { @override String pluginConfigKey = 'android';
bool exists = false;
@override late Directory pluginRegistrantHost;
@override late Directory hostAppGradleRoot;
@override late File appManifestFile;
late AndroidEmbeddingVersion embeddingVersion;
@override bool existsSync() => exists;
@override AndroidEmbeddingVersion getEmbeddingVersion() { return embeddingVersion; }
@override AndroidEmbeddingVersionResult computeEmbeddingVersion() { return AndroidEmbeddingVersionResult(embeddingVersion, 'reasons for version'); }}
class FakeWebProject extends Fake implements WebProject { @override String pluginConfigKey = 'web';
@override late Directory libDirectory;
bool exists = false;
@override bool existsSync() => exists;}
class FakeWindowsProject extends Fake implements WindowsProject { @override String pluginConfigKey = 'windows';
@override late Directory managedDirectory;
@override late Directory ephemeralDirectory;
@override late Directory pluginSymlinkDirectory;
@override late File cmakeFile;
@override late File generatedPluginCmakeFile; bool exists = false;
@override bool existsSync() => exists;}
class FakeLinuxProject extends Fake implements LinuxProject { @override String pluginConfigKey = 'linux';
@override late Directory managedDirectory;
@override late Directory ephemeralDirectory;
@override late Directory pluginSymlinkDirectory;
@override late File cmakeFile;
@override late File generatedPluginCmakeFile; bool exists = false;
@override bool existsSync() => exists;
}
class FakeOperatingSystemUtils extends Fake implements OperatingSystemUtils { FakeOperatingSystemUtils(this.name);
@override final String name;}
class FakeSystemClock extends Fake implements SystemClock { late DateTime currentTime;
@override DateTime now() { return currentTime; }}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208// 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 'package:file/memory.dart';import 'package:flutter_tools/src/application_package.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/bundle.dart';import 'package:flutter_tools/src/bundle_builder.dart';import 'package:flutter_tools/src/cache.dart';import 'package:flutter_tools/src/device.dart';import 'package:flutter_tools/src/preview_device.dart';import 'package:flutter_tools/src/project.dart';import 'package:meta/meta.dart';import 'package:test/fake.dart';
import '../src/common.dart';import '../src/context.dart';import '../src/fakes.dart';
void main() { String? flutterRootBackup; late MemoryFileSystem fs; late File previewBinary;
setUp(() { fs = MemoryFileSystem.test(style: FileSystemStyle.windows); Cache.flutterRoot = r'C:\path\to\flutter'; previewBinary = fs.file('${Cache.flutterRoot}\\bin\\cache\\artifacts\\flutter_preview\\flutter_preview.exe'); previewBinary.createSync(recursive: true); flutterRootBackup = Cache.flutterRoot; });
tearDown(() { Cache.flutterRoot = flutterRootBackup; });
testWithoutContext('PreviewDevice defaults', () async { final PreviewDevice device = PreviewDevice( artifacts: Artifacts.test(), fileSystem: fs, processManager: FakeProcessManager.any(), previewBinary: previewBinary, logger: BufferLogger.test(), );
expect(await device.isLocalEmulator, false); expect(device.name, 'Preview'); expect(await device.sdkNameAndVersion, 'preview'); expect(await device.targetPlatform, TargetPlatform.windows_x64); expect(device.category, Category.desktop); expect(device.ephemeral, false); expect(device.id, 'preview');
expect(device.isSupported(), true); expect(device.isSupportedForProject(FakeFlutterProject()), true); expect(await device.isLatestBuildInstalled(FakeApplicationPackage()), false); expect(await device.isAppInstalled(FakeApplicationPackage()), false); expect(await device.uninstallApp(FakeApplicationPackage()), true); });
testUsingContext('Can build a simulator app', () async { final Completer<void> completer = Completer<void>(); final BufferLogger logger = BufferLogger.test(); final PreviewDevice device = PreviewDevice( artifacts: Artifacts.test(), fileSystem: fs, previewBinary: previewBinary, processManager: FakeProcessManager.list(<FakeCommand>[ FakeCommand( command: const <String>[ r'C:\.tmp_rand0\flutter_preview.rand0\flutter_preview.exe', ], stdout: 'The Dart VM service is listening on http://127.0.0.1:64494/fZ_B2N6JRwY=/\n', completer: completer, ), ]), logger: logger, builderFactory: () => FakeBundleBuilder(fs), ); final Directory previewDeviceCacheDir = fs .directory('Artifact.windowsDesktopPath.TargetPlatform.windows_x64.debug') ..createSync(recursive: true); previewDeviceCacheDir.childFile('flutter_windows.dll').writeAsStringSync('1010101'); previewDeviceCacheDir.childFile('icudtl.dat').writeAsStringSync('1010101');
final LaunchResult result = await device.startApp( FakeApplicationPackage(), debuggingOptions: DebuggingOptions.enabled(BuildInfo.debug), );
expect(result.started, true); expect(result.vmServiceUri, Uri.parse('http://127.0.0.1:64494/fZ_B2N6JRwY=/')); });
group('PreviewDeviceDiscovery', () { late Artifacts artifacts; late ProcessManager processManager; final FakePlatform windowsPlatform = FakePlatform(operatingSystem: 'windows'); final FakePlatform macPlatform = FakePlatform(operatingSystem: 'macos'); final FakePlatform linuxPlatform = FakePlatform(); final TestFeatureFlags featureFlags = TestFeatureFlags(isPreviewDeviceEnabled: true);
setUp(() { artifacts = Artifacts.test(fileSystem: fs); processManager = FakeProcessManager.empty(); });
testWithoutContext('PreviewDeviceDiscovery on linux', () async { final PreviewDeviceDiscovery discovery = PreviewDeviceDiscovery( artifacts: artifacts, fileSystem: fs, logger: BufferLogger.test(), processManager: processManager, platform: linuxPlatform, featureFlags: featureFlags, );
final List<Device> devices = await discovery.devices();
expect(devices, isEmpty); });
testWithoutContext('PreviewDeviceDiscovery on macOS', () async { final PreviewDeviceDiscovery discovery = PreviewDeviceDiscovery( artifacts: artifacts, fileSystem: fs, logger: BufferLogger.test(), processManager: processManager, platform: macPlatform, featureFlags: featureFlags, );
final List<Device> devices = await discovery.devices();
expect(devices, isEmpty); });
testWithoutContext('PreviewDeviceDiscovery on Windows returns preview when binary exists', () async { // ensure Flutter preview binary exists in cache. fs.file(artifacts.getArtifactPath(Artifact.flutterPreviewDevice)).writeAsBytesSync(<int>[1, 0, 0, 1]); final PreviewDeviceDiscovery discovery = PreviewDeviceDiscovery( artifacts: artifacts, fileSystem: fs, logger: BufferLogger.test(), processManager: processManager, platform: windowsPlatform, featureFlags: featureFlags, );
final List<Device> devices = await discovery.devices();
expect(devices, hasLength(1)); final Device previewDevice = devices.first; expect(previewDevice, isA<PreviewDevice>()); });
testWithoutContext('PreviewDeviceDiscovery on Windows returns nothing when binary does not exist', () async { final PreviewDeviceDiscovery discovery = PreviewDeviceDiscovery( artifacts: artifacts, fileSystem: fs, logger: BufferLogger.test(), processManager: processManager, platform: windowsPlatform, featureFlags: featureFlags, );
final List<Device> devices = await discovery.devices();
expect(devices, isEmpty); }); });}
class FakeFlutterProject extends Fake implements FlutterProject { }class FakeApplicationPackage extends Fake implements ApplicationPackage { }class FakeBundleBuilder extends Fake implements BundleBuilder { FakeBundleBuilder(this.fileSystem);
final FileSystem fileSystem;
@override Future<void> build({ required TargetPlatform platform, required BuildInfo buildInfo, FlutterProject? project, String? mainPath, String manifestPath = defaultManifestPath, String? applicationKernelFilePath, String? depfilePath, String? assetDirPath, bool buildNativeAssets = true, @visibleForTesting BuildSystem? buildSystem }) async { final Directory assetDirectory = fileSystem .directory(assetDirPath) .childDirectory('flutter_assets') ..createSync(recursive: true); assetDirectory.childFile('kernel_blob.bin').createSync(); }}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198// 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:flutter_tools/src/base/file_system.dart';import 'package:flutter_tools/src/base/logger.dart';import 'package:flutter_tools/src/base/multi_root_file_system.dart';import 'package:flutter_tools/src/base/platform.dart';import 'package:flutter_tools/src/convert.dart';import 'package:flutter_tools/src/run_hot.dart';import 'package:package_config/package_config.dart';
import '../src/common.dart';
// assumption: tests have a timeout less than 100 daysfinal DateTime inFuture = DateTime.now().add(const Duration(days: 100));
void main() { for (final bool asyncScanning in <bool>[true, false]) { testWithoutContext('No last compile, asyncScanning: $asyncScanning', () async { final FileSystem fileSystem = MemoryFileSystem.test(); final ProjectFileInvalidator projectFileInvalidator = ProjectFileInvalidator( fileSystem: fileSystem, platform: FakePlatform(), logger: BufferLogger.test(), ); fileSystem.file('.packages').writeAsStringSync('\n');
expect( (await projectFileInvalidator.findInvalidated( lastCompiled: null, urisToMonitor: <Uri>[], packagesPath: '.packages', asyncScanning: asyncScanning, packageConfig: PackageConfig.empty, )).uris, isEmpty, ); });
testWithoutContext('Empty project, asyncScanning: $asyncScanning', () async { final FileSystem fileSystem = MemoryFileSystem.test(); final ProjectFileInvalidator projectFileInvalidator = ProjectFileInvalidator( fileSystem: fileSystem, platform: FakePlatform(), logger: BufferLogger.test(), ); fileSystem.file('.packages').writeAsStringSync('\n');
expect( (await projectFileInvalidator.findInvalidated( lastCompiled: inFuture, urisToMonitor: <Uri>[], packagesPath: '.packages', asyncScanning: asyncScanning, packageConfig: PackageConfig.empty, )).uris, isEmpty, ); });
testWithoutContext('Non-existent files are ignored, asyncScanning: $asyncScanning', () async { final FileSystem fileSystem = MemoryFileSystem.test(); final ProjectFileInvalidator projectFileInvalidator = ProjectFileInvalidator( fileSystem: MemoryFileSystem.test(), platform: FakePlatform(), logger: BufferLogger.test(), ); fileSystem.file('.packages').writeAsStringSync('\n');
expect( (await projectFileInvalidator.findInvalidated( lastCompiled: inFuture, urisToMonitor: <Uri>[Uri.parse('/not-there-anymore'),], packagesPath: '.packages', asyncScanning: asyncScanning, packageConfig: PackageConfig.empty, )).uris, isEmpty, ); });
testWithoutContext('Picks up changes to the .packages file and updates package_config.json, asyncScanning: $asyncScanning', () async { final DateTime past = DateTime.now().subtract(const Duration(seconds: 1)); final FileSystem fileSystem = MemoryFileSystem.test(); const PackageConfig packageConfig = PackageConfig.empty; final ProjectFileInvalidator projectFileInvalidator = ProjectFileInvalidator( fileSystem: fileSystem, platform: FakePlatform(), logger: BufferLogger.test(), ); fileSystem.file('.packages') .writeAsStringSync('\n'); fileSystem.file('.dart_tool/package_config.json') ..createSync(recursive: true) ..writeAsStringSync(json.encode(<String, Object>{ 'configVersion': 2, 'packages': <Object>[], }));
final InvalidationResult invalidationResult = await projectFileInvalidator.findInvalidated( lastCompiled: null, urisToMonitor: <Uri>[], packagesPath: '.packages', asyncScanning: asyncScanning, packageConfig: packageConfig, ); expect(invalidationResult.uris, isEmpty); fileSystem.file('.packages').setLastModifiedSync(DateTime.now());
final InvalidationResult secondInvalidation = await projectFileInvalidator.findInvalidated( lastCompiled: past, urisToMonitor: <Uri>[], packagesPath: '.packages', asyncScanning: asyncScanning, packageConfig: packageConfig, ); expect(secondInvalidation.uris, unorderedEquals(<Uri>[ Uri.parse('.packages'), Uri.parse('.dart_tool/package_config.json'), ])); });
testWithoutContext('Picks up changes to the .packages file and updates PackageConfig, asyncScanning: $asyncScanning', () async { final FileSystem fileSystem = MemoryFileSystem.test(); const PackageConfig packageConfig = PackageConfig.empty; final ProjectFileInvalidator projectFileInvalidator = ProjectFileInvalidator( fileSystem: fileSystem, platform: FakePlatform(), logger: BufferLogger.test(), ); fileSystem.file('.packages') .writeAsStringSync('\n');
final InvalidationResult invalidationResult = await projectFileInvalidator.findInvalidated( lastCompiled: null, urisToMonitor: <Uri>[], packagesPath: '.packages', asyncScanning: asyncScanning, packageConfig: packageConfig, );
// Initial package config is re-used. expect(invalidationResult.packageConfig, packageConfig);
fileSystem.file('.packages') .writeAsStringSync('foo:lib/\n'); final DateTime packagesUpdated = fileSystem.statSync('.packages') .modified;
final InvalidationResult nextInvalidationResult = await projectFileInvalidator .findInvalidated( lastCompiled: packagesUpdated.subtract(const Duration(seconds: 1)), urisToMonitor: <Uri>[], packagesPath: '.packages', asyncScanning: asyncScanning, packageConfig: PackageConfig.empty, );
expect(nextInvalidationResult.uris, contains(Uri.parse('.packages'))); // The PackageConfig should have been recreated too expect(nextInvalidationResult.packageConfig, isNot(invalidationResult.packageConfig)); });
testWithoutContext('Works with MultiRootFileSystem uris, asyncScanning: $asyncScanning', () async { final FileSystem fileSystem = MemoryFileSystem.test(); final FileSystem multiRootFileSystem = MultiRootFileSystem( delegate: fileSystem, scheme: 'scheme', roots: <String>[ '/root', ], ); final ProjectFileInvalidator projectFileInvalidator = ProjectFileInvalidator( fileSystem: multiRootFileSystem, platform: FakePlatform(), logger: BufferLogger.test(), );
expect( (await projectFileInvalidator.findInvalidated( lastCompiled: inFuture, urisToMonitor: <Uri>[ Uri.parse('file1'), Uri.parse('file:///file2'), Uri.parse('scheme:///file3'), ], packagesPath: '.packages', asyncScanning: asyncScanning, packageConfig: PackageConfig.empty, )).uris, isEmpty, ); }); }}12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727// 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/android/android_sdk.dart';import 'package:flutter_tools/src/android/android_studio.dart';import 'package:flutter_tools/src/android/gradle_utils.dart' as gradle_utils;import 'package:flutter_tools/src/android/java.dart';import 'package:flutter_tools/src/base/file_system.dart';import 'package:flutter_tools/src/base/logger.dart';import 'package:flutter_tools/src/base/os.dart';import 'package:flutter_tools/src/base/version.dart';import 'package:flutter_tools/src/build_info.dart';import 'package:flutter_tools/src/cache.dart';import 'package:flutter_tools/src/convert.dart';import 'package:flutter_tools/src/features.dart';import 'package:flutter_tools/src/flutter_manifest.dart';import 'package:flutter_tools/src/globals.dart' as globals;import 'package:flutter_tools/src/ios/plist_parser.dart';import 'package:flutter_tools/src/ios/xcodeproj.dart';import 'package:flutter_tools/src/project.dart';import 'package:meta/meta.dart';import 'package:test/fake.dart';
import '../src/common.dart';import '../src/context.dart';import '../src/fakes.dart';
void main() { // TODO(zanderso): remove once FlutterProject is fully refactored. // this is safe since no tests have expectations on the test logger. final BufferLogger logger = BufferLogger.test();
group('Project', () { group('construction', () { testWithoutContext('invalid utf8 throws a tool exit', () { final FileSystem fileSystem = MemoryFileSystem.test(); final FlutterProjectFactory projectFactory = FlutterProjectFactory( fileSystem: fileSystem, logger: BufferLogger.test(), ); fileSystem.file('pubspec.yaml').writeAsBytesSync(<int>[0xFFFE]);
/// Technically this should throw a FileSystemException but this is /// currently a bug in package:file. expect( () => projectFactory.fromDirectory(fileSystem.currentDirectory), throwsToolExit(), ); });
_testInMemory('fails on invalid pubspec.yaml', () async { final Directory directory = globals.fs.directory('myproject'); directory.childFile('pubspec.yaml') ..createSync(recursive: true) ..writeAsStringSync(invalidPubspec);
expect( () => FlutterProject.fromDirectory(directory), throwsToolExit(), ); });
_testInMemory('fails on pubspec.yaml parse failure', () async { final Directory directory = globals.fs.directory('myproject'); directory.childFile('pubspec.yaml') ..createSync(recursive: true) ..writeAsStringSync(parseErrorPubspec);
expect( () => FlutterProject.fromDirectory(directory), throwsToolExit(), ); });
_testInMemory('fails on invalid example/pubspec.yaml', () async { final Directory directory = globals.fs.directory('myproject'); directory.childDirectory('example').childFile('pubspec.yaml') ..createSync(recursive: true) ..writeAsStringSync(invalidPubspec);
expect( () => FlutterProject.fromDirectory(directory), throwsToolExit(), ); });
_testInMemory('treats missing pubspec.yaml as empty', () async { final Directory directory = globals.fs.directory('myproject') ..createSync(recursive: true); expect(FlutterProject.fromDirectory(directory).manifest.isEmpty, true, ); });
_testInMemory('reads valid pubspec.yaml', () async { final Directory directory = globals.fs.directory('myproject'); directory.childFile('pubspec.yaml') ..createSync(recursive: true) ..writeAsStringSync(validPubspec); expect( FlutterProject.fromDirectory(directory).manifest.appName, 'hello', ); });
_testInMemory('reads dependencies from pubspec.yaml', () async { final Directory directory = globals.fs.directory('myproject'); directory.childFile('pubspec.yaml') ..createSync(recursive: true) ..writeAsStringSync(validPubspecWithDependencies); expect( FlutterProject.fromDirectory(directory).manifest.dependencies, <String>{'plugin_a', 'plugin_b'}, ); });
_testInMemory('sets up location', () async { final Directory directory = globals.fs.directory('myproject'); expect( FlutterProject.fromDirectory(directory).directory.absolute.path, directory.absolute.path, ); expect( FlutterProject.fromDirectoryTest(directory).directory.absolute.path, directory.absolute.path, ); expect( FlutterProject.current().directory.absolute.path, globals.fs.currentDirectory.absolute.path, ); }); });
group('ensure ready for platform-specific tooling', () { _testInMemory('does nothing, if project is not created', () async { final FlutterProject project = FlutterProject( globals.fs.directory('not_created'), FlutterManifest.empty(logger: logger), FlutterManifest.empty(logger: logger), ); await project.regeneratePlatformSpecificTooling(); expectNotExists(project.directory); }); _testInMemory('does nothing in plugin or package root project', () async { final FlutterProject project = await aPluginProject(); await project.regeneratePlatformSpecificTooling(); expectNotExists(project.ios.hostAppRoot.childDirectory('Runner').childFile('GeneratedPluginRegistrant.h')); expectNotExists(androidPluginRegistrant(project.android.hostAppGradleRoot.childDirectory('app'))); expectNotExists(project.ios.hostAppRoot.childDirectory('Flutter').childFile('Generated.xcconfig')); expectNotExists(project.android.hostAppGradleRoot.childFile('local.properties')); }); _testInMemory('works if there is an "example" folder', () async { final FlutterProject project = await someProject(); // The presence of an "example" folder used to be used as an indicator // that a project was a plugin, but shouldn't be as this creates false // positives. project.directory.childDirectory('example').createSync(); await project.regeneratePlatformSpecificTooling(); expectExists(project.ios.hostAppRoot.childDirectory('Runner').childFile('GeneratedPluginRegistrant.h')); expectExists(androidPluginRegistrant(project.android.hostAppGradleRoot.childDirectory('app'))); expectExists(project.ios.hostAppRoot.childDirectory('Flutter').childFile('Generated.xcconfig')); expectExists(project.android.hostAppGradleRoot.childFile('local.properties')); }); _testInMemory('injects plugins for iOS', () async { final FlutterProject project = await someProject(); await project.regeneratePlatformSpecificTooling(); expectExists(project.ios.hostAppRoot.childDirectory('Runner').childFile('GeneratedPluginRegistrant.h')); }); _testInMemory('generates Xcode configuration for iOS', () async { final FlutterProject project = await someProject(); await project.regeneratePlatformSpecificTooling(); expectExists(project.ios.hostAppRoot.childDirectory('Flutter').childFile('Generated.xcconfig')); }); _testInMemory('injects plugins for Android', () async { final FlutterProject project = await someProject(); await project.regeneratePlatformSpecificTooling(); expectExists(androidPluginRegistrant(project.android.hostAppGradleRoot.childDirectory('app'))); }); _testInMemory('updates local properties for Android', () async { final FlutterProject project = await someProject(); await project.regeneratePlatformSpecificTooling(); expectExists(project.android.hostAppGradleRoot.childFile('local.properties')); }); _testInMemory('checkForDeprecation fails on invalid android app manifest file', () async { // This is not a valid Xml document const String invalidManifest = '<manifest></application>'; final FlutterProject project = await someProject(androidManifestOverride: invalidManifest, includePubspec: true);
expect( () => project.checkForDeprecation(deprecationBehavior: DeprecationBehavior.ignore), throwsToolExit(message: 'Please ensure that the android manifest is a valid XML document and try again.'), ); }); _testInMemory('Android project not on v2 embedding shows a warning', () async { final FlutterProject project = await someProject(includePubspec: true); // The default someProject with an empty <manifest> already indicates // v1 embedding, as opposed to having <meta-data // android:name="flutterEmbedding" android:value="2" />.
project.checkForDeprecation(deprecationBehavior: DeprecationBehavior.ignore); expect(testLogger.statusText, contains('https://github.com/flutter/flutter/wiki/Upgrading-pre-1.12-Android-projects')); }); _testInMemory('Android project not on v2 embedding exits', () async { final FlutterProject project = await someProject(includePubspec: true); // The default someProject with an empty <manifest> already indicates // v1 embedding, as opposed to having <meta-data // android:name="flutterEmbedding" android:value="2" />.
await expectToolExitLater( Future<dynamic>.sync(() => project.checkForDeprecation(deprecationBehavior: DeprecationBehavior.exit)), contains('Build failed due to use of deprecated Android v1 embedding.') ); expect(testLogger.statusText, contains('https://github.com/flutter/flutter/wiki/Upgrading-pre-1.12-Android-projects')); expect(testLogger.statusText, contains('No `<meta-data android:name="flutterEmbedding" android:value="2"/>` in ')); }); _testInMemory('Project not on v2 embedding does not warn if deprecation status is irrelevant', () async { final FlutterProject project = await someProject(includePubspec: true); // The default someProject with an empty <manifest> already indicates // v1 embedding, as opposed to having <meta-data // android:name="flutterEmbedding" android:value="2" />.
// Default is "DeprecationBehavior.none" project.checkForDeprecation(); expect(testLogger.statusText, isEmpty); }); _testInMemory('Android project not on v2 embedding ignore continues', () async { final FlutterProject project = await someProject(includePubspec: true); // The default someProject with an empty <manifest> already indicates // v1 embedding, as opposed to having <meta-data // android:name="flutterEmbedding" android:value="2" />.
project.checkForDeprecation(deprecationBehavior: DeprecationBehavior.ignore); expect(testLogger.statusText, contains('https://github.com/flutter/flutter/wiki/Upgrading-pre-1.12-Android-projects')); }); _testInMemory('Android project no pubspec continues', () async { final FlutterProject project = await someProject(); // The default someProject with an empty <manifest> already indicates // v1 embedding, as opposed to having <meta-data // android:name="flutterEmbedding" android:value="2" />.
project.checkForDeprecation(deprecationBehavior: DeprecationBehavior.ignore); expect(testLogger.statusText, isNot(contains('https://github.com/flutter/flutter/wiki/Upgrading-pre-1.12-Android-projects'))); }); _testInMemory('Android plugin project does not throw v1 embedding deprecation warning', () async { final FlutterProject project = await aPluginProject();
project.checkForDeprecation(deprecationBehavior: DeprecationBehavior.exit); expect(testLogger.statusText, isNot(contains('https://github.com/flutter/flutter/wiki/Upgrading-pre-1.12-Android-projects'))); expect(testLogger.statusText, isNot(contains('No `<meta-data android:name="flutterEmbedding" android:value="2"/>` in '))); }); _testInMemory('Android plugin without example app does not show a warning', () async { final FlutterProject project = await aPluginProject(); project.example.directory.deleteSync();
await project.regeneratePlatformSpecificTooling(); expect(testLogger.statusText, isNot(contains('https://github.com/flutter/flutter/wiki/Upgrading-pre-1.12-Android-projects'))); }); _testInMemory('updates local properties for Android', () async { final FlutterProject project = await someProject(); await project.regeneratePlatformSpecificTooling(); expectExists(project.android.hostAppGradleRoot.childFile('local.properties')); }); testUsingContext('injects plugins for macOS', () async { final FlutterProject project = await someProject(); project.macos.managedDirectory.createSync(recursive: true); await project.regeneratePlatformSpecificTooling(); expectExists(project.macos.pluginRegistrantImplementation); }, overrides: <Type, Generator>{ FileSystem: () => MemoryFileSystem.test(), ProcessManager: () => FakeProcessManager.any(), FeatureFlags: () => TestFeatureFlags(isMacOSEnabled: true), FlutterProjectFactory: () => FlutterProjectFactory( logger: logger, fileSystem: globals.fs, ), }); testUsingContext('generates Xcode configuration for macOS', () async { final FlutterProject project = await someProject(); project.macos.managedDirectory.createSync(recursive: true); await project.regeneratePlatformSpecificTooling(); expectExists(project.macos.generatedXcodePropertiesFile); }, overrides: <Type, Generator>{ FileSystem: () => MemoryFileSystem.test(), ProcessManager: () => FakeProcessManager.any(), FeatureFlags: () => TestFeatureFlags(isMacOSEnabled: true), FlutterProjectFactory: () => FlutterProjectFactory( logger: logger, fileSystem: globals.fs, ), }); testUsingContext('injects plugins for Linux', () async { final FlutterProject project = await someProject(); project.linux.cmakeFile.createSync(recursive: true); await project.regeneratePlatformSpecificTooling(); expectExists(project.linux.managedDirectory.childFile('generated_plugin_registrant.h')); expectExists(project.linux.managedDirectory.childFile('generated_plugin_registrant.cc')); }, overrides: <Type, Generator>{ FileSystem: () => MemoryFileSystem.test(), ProcessManager: () => FakeProcessManager.any(), FeatureFlags: () => TestFeatureFlags(isLinuxEnabled: true), FlutterProjectFactory: () => FlutterProjectFactory( logger: logger, fileSystem: globals.fs, ), }); testUsingContext('injects plugins for Windows', () async { final FlutterProject project = await someProject(); project.windows.cmakeFile.createSync(recursive: true); await project.regeneratePlatformSpecificTooling(); expectExists(project.windows.managedDirectory.childFile('generated_plugin_registrant.h')); expectExists(project.windows.managedDirectory.childFile('generated_plugin_registrant.cc')); }, overrides: <Type, Generator>{ FileSystem: () => MemoryFileSystem.test(), ProcessManager: () => FakeProcessManager.any(), FeatureFlags: () => TestFeatureFlags(isWindowsEnabled: true), FlutterProjectFactory: () => FlutterProjectFactory( logger: logger, fileSystem: globals.fs, ), }); _testInMemory('creates Android library in module', () async { final FlutterProject project = await aModuleProject(); await project.regeneratePlatformSpecificTooling(); expectExists(project.android.hostAppGradleRoot.childFile('settings.gradle')); expectExists(project.android.hostAppGradleRoot.childFile('local.properties')); expectExists(androidPluginRegistrant(project.android.hostAppGradleRoot.childDirectory('Flutter'))); }); _testInMemory('creates iOS pod in module', () async { final FlutterProject project = await aModuleProject(); await project.regeneratePlatformSpecificTooling(); final Directory flutter = project.ios.hostAppRoot.childDirectory('Flutter'); expectExists(flutter.childFile('podhelper.rb')); expectExists(flutter.childFile('flutter_export_environment.sh')); expectExists(flutter.childFile('Generated.xcconfig')); final Directory pluginRegistrantClasses = flutter .childDirectory('FlutterPluginRegistrant') .childDirectory('Classes'); expectExists(pluginRegistrantClasses.childFile('GeneratedPluginRegistrant.h')); expectExists(pluginRegistrantClasses.childFile('GeneratedPluginRegistrant.m')); });
testUsingContext('Version.json info is correct', () { final MemoryFileSystem fileSystem = MemoryFileSystem.test(); final FlutterManifest manifest = FlutterManifest.createFromString(''' name: test version: 1.0.0+3 ''', logger: BufferLogger.test())!; final FlutterProject project = FlutterProject(fileSystem.systemTempDirectory, manifest, manifest); final Map<String, dynamic> versionInfo = jsonDecode(project.getVersionInfo()) as Map<String, dynamic>; expect(versionInfo['app_name'],'test'); expect(versionInfo['version'],'1.0.0'); expect(versionInfo['build_number'],'3'); expect(versionInfo['package_name'],'test'); }); _testInMemory('gets xcworkspace directory', () async { final FlutterProject project = await someProject(); project.ios.xcodeProject.createSync(); project.ios.hostAppRoot.childFile('._Runner.xcworkspace').createSync(recursive: true); project.ios.hostAppRoot.childFile('Runner.xcworkspace').createSync(recursive: true);
expect(project.ios.xcodeWorkspace?.basename, 'Runner.xcworkspace'); }); _testInMemory('no xcworkspace directory found', () async { final FlutterProject project = await someProject(); project.ios.xcodeProject.createSync(); expect(project.ios.xcodeWorkspace?.basename, null); }); });
group('module status', () { _testInMemory('is known for module', () async { final FlutterProject project = await aModuleProject(); expect(project.isModule, isTrue); expect(project.android.isModule, isTrue); expect(project.ios.isModule, isTrue); expect(project.android.hostAppGradleRoot.basename, '.android'); expect(project.ios.hostAppRoot.basename, '.ios'); }); _testInMemory('is known for non-module', () async { final FlutterProject project = await someProject(); expect(project.isModule, isFalse); expect(project.android.isModule, isFalse); expect(project.ios.isModule, isFalse); expect(project.android.hostAppGradleRoot.basename, 'android'); expect(project.ios.hostAppRoot.basename, 'ios'); }); });
group('example', () { _testInMemory('exists for plugin in legacy format', () async { final FlutterProject project = await aPluginProject(); expect(project.isPlugin, isTrue); expect(project.hasExampleApp, isTrue); }); _testInMemory('exists for plugin in multi-platform format', () async { final FlutterProject project = await aPluginProject(legacy: false); expect(project.hasExampleApp, isTrue); }); _testInMemory('does not exist for non-plugin', () async { final FlutterProject project = await someProject(); expect(project.isPlugin, isFalse); expect(project.hasExampleApp, isFalse); }); });
group('java gradle agp compatibility', () { Future<FlutterProject?> configureGradleAgpForTest({ required String gradleV, required String agpV, }) async { final FlutterProject project = await someProject(); addRootGradleFile(project.directory, gradleFileContent: () { return '''dependencies { classpath 'com.android.tools.build:gradle:$agpV'}'''; }); addGradleWrapperFile(project.directory, gradleV); return project; }
// Tests in this group that use overrides and _testInMemory should // be placed in their own group to avoid test pollution. This is // especially important for filesystem. group('_', () { final FakeProcessManager processManager; final Java java; final AndroidStudio androidStudio; final FakeAndroidSdkWithDir androidSdk; final FileSystem fileSystem = getFileSystemForPlatform(); java = FakeJava(version: Version(17, 0, 2)); processManager = FakeProcessManager.empty(); androidStudio = FakeAndroidStudio(); androidSdk = FakeAndroidSdkWithDir(fileSystem.currentDirectory); fileSystem.currentDirectory .childDirectory(androidStudio.javaPath!) .createSync(); _testInMemory( 'flamingo values are compatible', () async { final FlutterProject? project = await configureGradleAgpForTest( gradleV: '8.0', agpV: '7.4.2', ); final CompatibilityResult value = await project!.android.hasValidJavaGradleAgpVersions(); expect(value.success, isTrue); }, java: java, androidStudio: androidStudio, processManager: processManager, androidSdk: androidSdk, ); }); group('_', () { final FakeProcessManager processManager; final Java java; final AndroidStudio androidStudio; final FakeAndroidSdkWithDir androidSdk; final FileSystem fileSystem = getFileSystemForPlatform(); java = FakeJava(version: const Version.withText(1, 8, 0, '1.8.0_242')); processManager = FakeProcessManager.empty(); androidStudio = FakeAndroidStudio(); androidSdk = FakeAndroidSdkWithDir(fileSystem.currentDirectory); fileSystem.currentDirectory .childDirectory(androidStudio.javaPath!) .createSync(); _testInMemory( 'java 8 era values are compatible', () async { final FlutterProject? project = await configureGradleAgpForTest( gradleV: '6.7.1', agpV: '4.2.0', ); final CompatibilityResult value = await project!.android.hasValidJavaGradleAgpVersions(); expect(value.success, isTrue); }, java: java, androidStudio: androidStudio, processManager: processManager, androidSdk: androidSdk, ); });
group('_', () { final FakeProcessManager processManager; final Java java; final AndroidStudio androidStudio; final FakeAndroidSdkWithDir androidSdk; final FileSystem fileSystem = getFileSystemForPlatform(); processManager = FakeProcessManager.empty(); java = FakeJava(version: Version(11, 0, 14)); androidStudio = FakeAndroidStudio(); androidSdk = FakeAndroidSdkWithDir(fileSystem.currentDirectory); fileSystem.currentDirectory .childDirectory(androidStudio.javaPath!) .createSync(); _testInMemory( 'electric eel era values are compatible', () async { final FlutterProject? project = await configureGradleAgpForTest( gradleV: '7.3.3', agpV: '7.2.0', ); final CompatibilityResult value = await project!.android.hasValidJavaGradleAgpVersions(); expect(value.success, isTrue); }, java: java, androidStudio: androidStudio, processManager: processManager, androidSdk: androidSdk, ); }); group('_', () { const String javaV = '17.0.2'; const String gradleV = '6.7.3'; const String agpV = '7.2.0';
final FakeProcessManager processManager; final Java java; final AndroidStudio androidStudio; final FakeAndroidSdkWithDir androidSdk; final FileSystem fileSystem = getFileSystemForPlatform(); processManager = FakeProcessManager.empty(); java = FakeJava(version: Version.parse(javaV)); androidStudio = FakeAndroidStudio(); androidSdk = FakeAndroidSdkWithDir(fileSystem.currentDirectory); fileSystem.currentDirectory .childDirectory(androidStudio.javaPath!) .createSync(); _testInMemory( 'incompatible everything', () async {
final FlutterProject? project = await configureGradleAgpForTest( gradleV: gradleV, agpV: agpV, ); final CompatibilityResult value = await project!.android.hasValidJavaGradleAgpVersions(); expect(value.success, isFalse); // Should not have the valid string expect( value.description, isNot( contains(RegExp(AndroidProject.validJavaGradleAgpString)))); // On gradle/agp error print help url and gradle and agp versions. expect(value.description, contains(RegExp(AndroidProject.gradleAgpCompatUrl))); expect(value.description, contains(RegExp(gradleV))); expect(value.description, contains(RegExp(agpV))); // On gradle/agp error print help url and java and gradle versions. expect(value.description, contains(RegExp(AndroidProject.javaGradleCompatUrl))); expect(value.description, contains(RegExp(javaV))); expect(value.description, contains(RegExp(gradleV))); }, java: java, androidStudio: androidStudio, processManager: processManager, androidSdk: androidSdk, ); }); group('_', () { const String javaV = '17.0.2'; const String gradleV = '6.7.3'; const String agpV = '4.2.0';
final FakeProcessManager processManager; final Java java; final AndroidStudio androidStudio; final FakeAndroidSdkWithDir androidSdk; final FileSystem fileSystem = getFileSystemForPlatform(); processManager = FakeProcessManager.empty(); java = FakeJava(version: Version(17, 0, 2)); androidStudio = FakeAndroidStudio(); androidSdk = FakeAndroidSdkWithDir(fileSystem.currentDirectory); fileSystem.currentDirectory .childDirectory(androidStudio.javaPath!) .createSync(); _testInMemory( 'incompatible java/gradle only', () async { final FlutterProject? project = await configureGradleAgpForTest( gradleV: gradleV, agpV: agpV, ); final CompatibilityResult value = await project!.android.hasValidJavaGradleAgpVersions(); expect(value.success, isFalse); // Should not have the valid string. expect( value.description, isNot( contains(RegExp(AndroidProject.validJavaGradleAgpString)))); // On gradle/agp error print help url and java and gradle versions. expect(value.description, contains(RegExp(AndroidProject.javaGradleCompatUrl))); expect(value.description, contains(RegExp(javaV))); expect(value.description, contains(RegExp(gradleV))); }, java: java, androidStudio: androidStudio, processManager: processManager, androidSdk: androidSdk, ); }); group('_', () { final FakeProcessManager processManager; final Java java; final AndroidStudio androidStudio; final FakeAndroidSdkWithDir androidSdk; final FileSystem fileSystem = getFileSystemForPlatform(); java = FakeJava(version: Version(11, 0, 2)); processManager = FakeProcessManager.empty(); androidStudio = FakeAndroidStudio(); androidSdk = FakeAndroidSdkWithDir(fileSystem.currentDirectory); fileSystem.currentDirectory .childDirectory(androidStudio.javaPath!) .createSync(); _testInMemory( 'incompatible gradle/agp only', () async { const String gradleV = '7.0.3'; const String agpV = '7.1.0'; final FlutterProject? project = await configureGradleAgpForTest( gradleV: gradleV, agpV: agpV, ); final CompatibilityResult value = await project!.android.hasValidJavaGradleAgpVersions(); expect(value.success, isFalse); // Should not have the valid string. expect( value.description, isNot( contains(RegExp(AndroidProject.validJavaGradleAgpString)))); // On gradle/agp error print help url and gradle and agp versions. expect(value.description, contains(RegExp(AndroidProject.gradleAgpCompatUrl))); expect(value.description, contains(RegExp(gradleV))); expect(value.description, contains(RegExp(agpV))); }, java: java, androidStudio: androidStudio, processManager: processManager, androidSdk: androidSdk, ); }); group('_', () { final FakeProcessManager processManager; final Java java; final AndroidStudio androidStudio; final FakeAndroidSdkWithDir androidSdk; final FileSystem fileSystem = getFileSystemForPlatform(); java = FakeJava(version: Version(11, 0, 2)); processManager = FakeProcessManager.empty(); androidStudio = FakeAndroidStudio(); androidSdk = FakeAndroidSdkWithDir(fileSystem.currentDirectory); fileSystem.currentDirectory .childDirectory(androidStudio.javaPath!) .createSync(); _testInMemory( 'null agp only', () async { const String gradleV = '7.0.3'; final FlutterProject? project = await configureGradleAgpForTest( gradleV: gradleV, agpV: '', ); final CompatibilityResult value = await project!.android.hasValidJavaGradleAgpVersions(); expect(value.success, isFalse); // Should not have the valid string. expect( value.description, isNot( contains(RegExp(AndroidProject.validJavaGradleAgpString)))); // On gradle/agp error print help url null value for agp. expect(value.description, contains(RegExp(AndroidProject.gradleAgpCompatUrl))); expect(value.description, contains(RegExp(gradleV))); expect(value.description, contains(RegExp('null'))); }, java: java, androidStudio: androidStudio, processManager: processManager, androidSdk: androidSdk, ); }); });
group('language', () { late XcodeProjectInterpreter xcodeProjectInterpreter; late MemoryFileSystem fs; late FlutterProjectFactory flutterProjectFactory; setUp(() { fs = MemoryFileSystem.test(); xcodeProjectInterpreter = XcodeProjectInterpreter.test(processManager: FakeProcessManager.any()); flutterProjectFactory = FlutterProjectFactory( logger: logger, fileSystem: fs, ); });
_testInMemory('default host app language', () async { final FlutterProject project = await someProject(); expect(project.android.isKotlin, isFalse); });
testUsingContext('kotlin host app language', () async { final FlutterProject project = await someProject();
addAndroidGradleFile(project.directory, gradleFileContent: () { return '''apply plugin: 'com.android.application'apply plugin: 'kotlin-android''''; }); expect(project.android.isKotlin, isTrue); }, overrides: <Type, Generator>{ FileSystem: () => fs, ProcessManager: () => FakeProcessManager.any(), XcodeProjectInterpreter: () => xcodeProjectInterpreter, FlutterProjectFactory: () => flutterProjectFactory, }); });
group('With mocked context', () { late MemoryFileSystem fs; late FakePlistParser testPlistUtils; late FakeXcodeProjectInterpreter xcodeProjectInterpreter; late FlutterProjectFactory flutterProjectFactory; setUp(() { fs = MemoryFileSystem.test(); testPlistUtils = FakePlistParser(); xcodeProjectInterpreter = FakeXcodeProjectInterpreter(); flutterProjectFactory = FlutterProjectFactory( fileSystem: fs, logger: logger, ); });
void testWithMocks(String description, Future<void> Function() testMethod) { testUsingContext(description, testMethod, overrides: <Type, Generator>{ FileSystem: () => fs, ProcessManager: () => FakeProcessManager.any(), PlistParser: () => testPlistUtils, XcodeProjectInterpreter: () => xcodeProjectInterpreter, FlutterProjectFactory: () => flutterProjectFactory, }); }
group('universal link', () { testWithMocks('build with flavor', () async { final FlutterProject project = await someProject(); project.ios.xcodeProject.createSync(); project.ios.defaultHostInfoPlist.createSync(recursive: true); const String entitlementFilePath = 'myEntitlement.Entitlement'; project.ios.hostAppRoot.childFile(entitlementFilePath).createSync(recursive: true);
const XcodeProjectBuildContext buildContext = XcodeProjectBuildContext( target: 'Runner', configuration: 'config', ); xcodeProjectInterpreter.buildSettingsByBuildContext[buildContext] = <String, String>{ IosProject.kProductBundleIdKey: 'io.flutter.someProject', IosProject.kTeamIdKey: 'ABC', IosProject.kEntitlementFilePathKey: entitlementFilePath, 'SUFFIX': 'suffix', }; xcodeProjectInterpreter.xcodeProjectInfo = XcodeProjectInfo(<String>[], <String>[], <String>['Runner'], logger); testPlistUtils.setProperty(PlistParser.kCFBundleIdentifierKey, r'$(PRODUCT_BUNDLE_IDENTIFIER).$(SUFFIX)'); testPlistUtils.setProperty( PlistParser.kAssociatedDomainsKey, <String>[ 'applinks:example.com', 'applinks:example2.com', ], ); final String outputFilePath = await project.ios.outputsUniversalLinkSettings( target: 'Runner', configuration: 'config', ); final File outputFile = fs.file(outputFilePath); final Map<String, Object?> json = jsonDecode(outputFile.readAsStringSync()) as Map<String, Object?>;
expect( json['associatedDomains'], unorderedEquals( <String>[ 'example.com', 'example2.com', ], ), ); expect(json['teamIdentifier'], 'ABC'); expect(json['bundleIdentifier'], 'io.flutter.someProject.suffix'); });
testWithMocks('can handle entitlement file in nested directory structure.', () async { final FlutterProject project = await someProject(); project.ios.xcodeProject.createSync(); project.ios.defaultHostInfoPlist.createSync(recursive: true); const String entitlementFilePath = 'nested/somewhere/myEntitlement.Entitlement'; project.ios.hostAppRoot.childFile(entitlementFilePath).createSync(recursive: true);
const XcodeProjectBuildContext buildContext = XcodeProjectBuildContext( target: 'Runner', configuration: 'config', ); xcodeProjectInterpreter.buildSettingsByBuildContext[buildContext] = <String, String>{ IosProject.kProductBundleIdKey: 'io.flutter.someProject', IosProject.kTeamIdKey: 'ABC', IosProject.kEntitlementFilePathKey: entitlementFilePath, 'SUFFIX': 'suffix', }; xcodeProjectInterpreter.xcodeProjectInfo = XcodeProjectInfo(<String>[], <String>[], <String>['Runner'], logger); testPlistUtils.setProperty(PlistParser.kCFBundleIdentifierKey, r'$(PRODUCT_BUNDLE_IDENTIFIER).$(SUFFIX)'); testPlistUtils.setProperty( PlistParser.kAssociatedDomainsKey, <String>[ 'applinks:example.com', 'applinks:example2.com', ], );
final String outputFilePath = await project.ios.outputsUniversalLinkSettings( target: 'Runner', configuration: 'config', ); final File outputFile = fs.file(outputFilePath); final Map<String, Object?> json = jsonDecode(outputFile.readAsStringSync()) as Map<String, Object?>; expect( json['associatedDomains'], unorderedEquals( <String>[ 'example.com', 'example2.com', ], ), ); expect(json['teamIdentifier'], 'ABC'); expect(json['bundleIdentifier'], 'io.flutter.someProject.suffix'); });
testWithMocks('return empty when no entitlement', () async { final FlutterProject project = await someProject(); project.ios.xcodeProject.createSync(); project.ios.defaultHostInfoPlist.createSync(recursive: true);
const XcodeProjectBuildContext buildContext = XcodeProjectBuildContext( target: 'Runner', configuration: 'config', ); xcodeProjectInterpreter.buildSettingsByBuildContext[buildContext] = <String, String>{ IosProject.kProductBundleIdKey: 'io.flutter.someProject', IosProject.kTeamIdKey: 'ABC', }; xcodeProjectInterpreter.xcodeProjectInfo = XcodeProjectInfo(<String>[], <String>[], <String>['Runner'], logger); testPlistUtils.setProperty(PlistParser.kCFBundleIdentifierKey, r'$(PRODUCT_BUNDLE_IDENTIFIER)'); final String outputFilePath = await project.ios.outputsUniversalLinkSettings( target: 'Runner', configuration: 'config', ); final File outputFile = fs.file(outputFilePath); final Map<String, Object?> json = jsonDecode(outputFile.readAsStringSync()) as Map<String, Object?>; expect(json['teamIdentifier'], 'ABC'); expect(json['bundleIdentifier'], 'io.flutter.someProject'); expect(json['associatedDomains'], unorderedEquals(<String>[])); }); });
group('product bundle identifier', () { testWithMocks('null, if no build settings or plist entries', () async { final FlutterProject project = await someProject(); expect(await project.ios.productBundleIdentifier(null), isNull); });
testWithMocks('from build settings, if no plist', () async { final FlutterProject project = await someProject(); project.ios.xcodeProject.createSync(); const XcodeProjectBuildContext buildContext = XcodeProjectBuildContext(scheme: 'Runner'); xcodeProjectInterpreter.buildSettingsByBuildContext[buildContext] = <String, String>{ IosProject.kProductBundleIdKey: 'io.flutter.someProject', }; xcodeProjectInterpreter.xcodeProjectInfo = XcodeProjectInfo(<String>[], <String>[], <String>['Runner'], logger);
expect(await project.ios.productBundleIdentifier(null), 'io.flutter.someProject'); });
testWithMocks('from project file, if no plist or build settings', () async { final FlutterProject project = await someProject(); xcodeProjectInterpreter.xcodeProjectInfo = XcodeProjectInfo(<String>[], <String>[], <String>['Runner'], logger);
addIosProjectFile(project.directory, projectFileContent: () { return projectFileWithBundleId('io.flutter.someProject'); }); expect(await project.ios.productBundleIdentifier(null), 'io.flutter.someProject'); });
testWithMocks('from plist, if no variables', () async { final FlutterProject project = await someProject(); project.ios.defaultHostInfoPlist.createSync(recursive: true); testPlistUtils.setProperty('CFBundleIdentifier', 'io.flutter.someProject'); expect(await project.ios.productBundleIdentifier(null), 'io.flutter.someProject'); });
testWithMocks('from build settings and plist, if default variable', () async { final FlutterProject project = await someProject(); project.ios.xcodeProject.createSync(); const XcodeProjectBuildContext buildContext = XcodeProjectBuildContext(scheme: 'Runner'); xcodeProjectInterpreter.buildSettingsByBuildContext[buildContext] = <String, String>{ IosProject.kProductBundleIdKey: 'io.flutter.someProject', }; xcodeProjectInterpreter.xcodeProjectInfo = XcodeProjectInfo(<String>[], <String>[], <String>['Runner'], logger); testPlistUtils.setProperty('CFBundleIdentifier', r'$(PRODUCT_BUNDLE_IDENTIFIER)');
expect(await project.ios.productBundleIdentifier(null), 'io.flutter.someProject'); });
testWithMocks('from build settings and plist, by substitution', () async { final FlutterProject project = await someProject(); project.ios.xcodeProject.createSync(); project.ios.defaultHostInfoPlist.createSync(recursive: true); const XcodeProjectBuildContext buildContext = XcodeProjectBuildContext(scheme: 'Runner'); xcodeProjectInterpreter.buildSettingsByBuildContext[buildContext] = <String, String>{ IosProject.kProductBundleIdKey: 'io.flutter.someProject', 'SUFFIX': 'suffix', }; xcodeProjectInterpreter.xcodeProjectInfo = XcodeProjectInfo(<String>[], <String>[], <String>['Runner'], logger); testPlistUtils.setProperty('CFBundleIdentifier', r'$(PRODUCT_BUNDLE_IDENTIFIER).$(SUFFIX)');
expect(await project.ios.productBundleIdentifier(null), 'io.flutter.someProject.suffix'); });
testWithMocks('Always pass parsing org on ios project with flavors', () async { final FlutterProject project = await someProject(); addIosProjectFile(project.directory, projectFileContent: () { return projectFileWithBundleId('io.flutter.someProject', qualifier: "'"); }); project.ios.xcodeProject.createSync(); xcodeProjectInterpreter.xcodeProjectInfo = XcodeProjectInfo(<String>[], <String>[], <String>['free', 'paid'], logger);
expect(await project.organizationNames, <String>[]); });
testWithMocks('fails with no flavor and defined schemes', () async { final FlutterProject project = await someProject(); project.ios.xcodeProject.createSync(); xcodeProjectInterpreter.xcodeProjectInfo = XcodeProjectInfo(<String>[], <String>[], <String>['free', 'paid'], logger);
await expectToolExitLater( project.ios.productBundleIdentifier(null), contains('You must specify a --flavor option to select one of the available schemes.'), ); });
testWithMocks('handles case insensitive flavor', () async { final FlutterProject project = await someProject(); project.ios.xcodeProject.createSync(); const XcodeProjectBuildContext buildContext = XcodeProjectBuildContext(scheme: 'Free'); xcodeProjectInterpreter.buildSettingsByBuildContext[buildContext] = <String, String>{ IosProject.kProductBundleIdKey: 'io.flutter.someProject', }; xcodeProjectInterpreter.xcodeProjectInfo = XcodeProjectInfo(<String>[], <String>[], <String>['Free'], logger); const BuildInfo buildInfo = BuildInfo(BuildMode.debug, 'free', treeShakeIcons: false);
expect(await project.ios.productBundleIdentifier(buildInfo), 'io.flutter.someProject'); });
testWithMocks('fails with flavor and default schemes', () async { final FlutterProject project = await someProject(); project.ios.xcodeProject.createSync(); xcodeProjectInterpreter.xcodeProjectInfo = XcodeProjectInfo(<String>[], <String>[], <String>['Runner'], logger); const BuildInfo buildInfo = BuildInfo(BuildMode.debug, 'free', treeShakeIcons: false);
await expectToolExitLater( project.ios.productBundleIdentifier(buildInfo), contains('The Xcode project does not define custom schemes. You cannot use the --flavor option.'), ); });
testWithMocks('empty surrounded by quotes', () async { final FlutterProject project = await someProject(); xcodeProjectInterpreter.xcodeProjectInfo = XcodeProjectInfo(<String>[], <String>[], <String>['Runner'], logger); addIosProjectFile(project.directory, projectFileContent: () { return projectFileWithBundleId('', qualifier: '"'); }); expect(await project.ios.productBundleIdentifier(null), ''); });
testWithMocks('surrounded by double quotes', () async { final FlutterProject project = await someProject(); xcodeProjectInterpreter.xcodeProjectInfo = XcodeProjectInfo(<String>[], <String>[], <String>['Runner'], logger); addIosProjectFile(project.directory, projectFileContent: () { return projectFileWithBundleId('io.flutter.someProject', qualifier: '"'); }); expect(await project.ios.productBundleIdentifier(null), 'io.flutter.someProject'); });
testWithMocks('surrounded by single quotes', () async { final FlutterProject project = await someProject(); xcodeProjectInterpreter.xcodeProjectInfo = XcodeProjectInfo(<String>[], <String>[], <String>['Runner'], logger); addIosProjectFile(project.directory, projectFileContent: () { return projectFileWithBundleId('io.flutter.someProject', qualifier: "'"); }); expect(await project.ios.productBundleIdentifier(null), 'io.flutter.someProject'); }); }); });
group('application bundle name', () { late MemoryFileSystem fs; late FakeXcodeProjectInterpreter mockXcodeProjectInterpreter; setUp(() { fs = MemoryFileSystem.test(); mockXcodeProjectInterpreter = FakeXcodeProjectInterpreter(); });
testUsingContext('app product name defaults to Runner.app', () async { final FlutterProject project = await someProject(); expect(await project.ios.hostAppBundleName(null), 'Runner.app'); }, overrides: <Type, Generator>{ FileSystem: () => fs, ProcessManager: () => FakeProcessManager.any(), XcodeProjectInterpreter: () => mockXcodeProjectInterpreter, });
testUsingContext('app product name xcodebuild settings', () async { final FlutterProject project = await someProject(); project.ios.xcodeProject.createSync(); const XcodeProjectBuildContext buildContext = XcodeProjectBuildContext(scheme: 'Runner'); mockXcodeProjectInterpreter.buildSettingsByBuildContext[buildContext] = <String, String>{ 'FULL_PRODUCT_NAME': 'My App.app', }; mockXcodeProjectInterpreter.xcodeProjectInfo = XcodeProjectInfo(<String>[], <String>[], <String>['Runner'], logger);
expect(await project.ios.hostAppBundleName(null), 'My App.app'); }, overrides: <Type, Generator>{ FileSystem: () => fs, ProcessManager: () => FakeProcessManager.any(), XcodeProjectInterpreter: () => mockXcodeProjectInterpreter, }); });
group('organization names set', () { _testInMemory('is empty, if project not created', () async { final FlutterProject project = await someProject(); expect(await project.organizationNames, isEmpty); }); _testInMemory('is empty, if no platform folders exist', () async { final FlutterProject project = await someProject(); project.directory.createSync(); expect(await project.organizationNames, isEmpty); }); _testInMemory('is populated from iOS bundle identifier', () async { final FlutterProject project = await someProject(); addIosProjectFile(project.directory, projectFileContent: () { return projectFileWithBundleId('io.flutter.someProject', qualifier: "'"); }); expect(await project.organizationNames, <String>['io.flutter']); }); _testInMemory('is populated from Android application ID', () async { final FlutterProject project = await someProject(); addAndroidGradleFile(project.directory, gradleFileContent: () { return gradleFileWithApplicationId('io.flutter.someproject'); }); expect(await project.organizationNames, <String>['io.flutter']); }); _testInMemory('is populated from iOS bundle identifier in plugin example', () async { final FlutterProject project = await someProject(); addIosProjectFile(project.example.directory, projectFileContent: () { return projectFileWithBundleId('io.flutter.someProject', qualifier: "'"); }); expect(await project.organizationNames, <String>['io.flutter']); }); _testInMemory('is populated from Android application ID in plugin example', () async { final FlutterProject project = await someProject(); addAndroidGradleFile(project.example.directory, gradleFileContent: () { return gradleFileWithApplicationId('io.flutter.someproject'); }); expect(await project.organizationNames, <String>['io.flutter']); }); _testInMemory('is populated from Android group in plugin', () async { final FlutterProject project = await someProject(); addAndroidWithGroup(project.directory, 'io.flutter.someproject'); expect(await project.organizationNames, <String>['io.flutter']); }); _testInMemory('is singleton, if sources agree', () async { final FlutterProject project = await someProject(); addIosProjectFile(project.directory, projectFileContent: () { return projectFileWithBundleId('io.flutter.someProject'); }); addAndroidGradleFile(project.directory, gradleFileContent: () { return gradleFileWithApplicationId('io.flutter.someproject'); }); expect(await project.organizationNames, <String>['io.flutter']); }); _testInMemory('is non-singleton, if sources disagree', () async { final FlutterProject project = await someProject(); addIosProjectFile(project.directory, projectFileContent: () { return projectFileWithBundleId('io.flutter.someProject'); }); addAndroidGradleFile(project.directory, gradleFileContent: () { return gradleFileWithApplicationId('io.clutter.someproject'); }); expect( await project.organizationNames, <String>['io.flutter', 'io.clutter'], ); }); }); }); group('watch companion', () { late MemoryFileSystem fs; late FakePlistParser testPlistParser; late FakeXcodeProjectInterpreter mockXcodeProjectInterpreter; late FlutterProjectFactory flutterProjectFactory; setUp(() { fs = MemoryFileSystem.test(); testPlistParser = FakePlistParser(); mockXcodeProjectInterpreter = FakeXcodeProjectInterpreter(); flutterProjectFactory = FlutterProjectFactory( fileSystem: fs, logger: logger, ); });
testUsingContext('cannot find bundle identifier', () async { final FlutterProject project = await someProject(); final XcodeProjectInfo projectInfo = XcodeProjectInfo(<String>['WatchTarget'], <String>[], <String>[], logger); expect( await project.ios.containsWatchCompanion( projectInfo: projectInfo, buildInfo: BuildInfo.debug, deviceId: '123', ), isFalse, ); }, overrides: <Type, Generator>{ FileSystem: () => fs, ProcessManager: () => FakeProcessManager.any(), PlistParser: () => testPlistParser, XcodeProjectInterpreter: () => mockXcodeProjectInterpreter, FlutterProjectFactory: () => flutterProjectFactory, });
group('with bundle identifier', () { setUp(() { const XcodeProjectBuildContext buildContext = XcodeProjectBuildContext(scheme: 'Runner'); mockXcodeProjectInterpreter.buildSettingsByBuildContext[buildContext] = <String, String>{ IosProject.kProductBundleIdKey: 'io.flutter.someProject', }; mockXcodeProjectInterpreter.xcodeProjectInfo = XcodeProjectInfo(<String>['Runner', 'WatchTarget'], <String>[], <String>['Runner', 'WatchScheme'], logger); });
testUsingContext('no Info.plist in target', () async { final FlutterProject project = await someProject(); expect( await project.ios.containsWatchCompanion( projectInfo: mockXcodeProjectInterpreter.xcodeProjectInfo, buildInfo: BuildInfo.debug, deviceId: '123', ), isFalse, ); }, overrides: <Type, Generator>{ FileSystem: () => fs, ProcessManager: () => FakeProcessManager.any(), PlistParser: () => testPlistParser, XcodeProjectInterpreter: () => mockXcodeProjectInterpreter, FlutterProjectFactory: () => flutterProjectFactory, });
testUsingContext('Info.plist in target does not contain WKCompanionAppBundleIdentifier', () async { final FlutterProject project = await someProject(); project.ios.hostAppRoot.childDirectory('WatchTarget').childFile('Info.plist').createSync(recursive: true);
expect( await project.ios.containsWatchCompanion( projectInfo: mockXcodeProjectInterpreter.xcodeProjectInfo, buildInfo: BuildInfo.debug, deviceId: '123', ), isFalse, ); }, overrides: <Type, Generator>{ FileSystem: () => fs, ProcessManager: () => FakeProcessManager.any(), PlistParser: () => testPlistParser, XcodeProjectInterpreter: () => mockXcodeProjectInterpreter, FlutterProjectFactory: () => flutterProjectFactory, });
testUsingContext('target WKCompanionAppBundleIdentifier is not project bundle identifier', () async { final FlutterProject project = await someProject(); project.ios.hostAppRoot.childDirectory('WatchTarget').childFile('Info.plist').createSync(recursive: true);
testPlistParser.setProperty('WKCompanionAppBundleIdentifier', 'io.flutter.someOTHERproject'); expect( await project.ios.containsWatchCompanion( projectInfo: mockXcodeProjectInterpreter.xcodeProjectInfo, buildInfo: BuildInfo.debug, deviceId: '123', ), isFalse, ); }, overrides: <Type, Generator>{ FileSystem: () => fs, ProcessManager: () => FakeProcessManager.any(), PlistParser: () => testPlistParser, XcodeProjectInterpreter: () => mockXcodeProjectInterpreter, FlutterProjectFactory: () => flutterProjectFactory, });
testUsingContext('has watch companion in plist', () async { final FlutterProject project = await someProject(); project.ios.xcodeProject.createSync(); project.ios.hostAppRoot.childDirectory('WatchTarget').childFile('Info.plist').createSync(recursive: true); testPlistParser.setProperty('WKCompanionAppBundleIdentifier', 'io.flutter.someProject');
expect( await project.ios.containsWatchCompanion( projectInfo: mockXcodeProjectInterpreter.xcodeProjectInfo, buildInfo: BuildInfo.debug, deviceId: '123', ), isTrue, ); }, overrides: <Type, Generator>{ FileSystem: () => fs, ProcessManager: () => FakeProcessManager.any(), PlistParser: () => testPlistParser, XcodeProjectInterpreter: () => mockXcodeProjectInterpreter, FlutterProjectFactory: () => flutterProjectFactory, });
testUsingContext('has watch companion in plist with xcode variable', () async { final FlutterProject project = await someProject(); project.ios.xcodeProject.createSync(); const XcodeProjectBuildContext buildContext = XcodeProjectBuildContext( scheme: 'Runner', deviceId: '123', ); mockXcodeProjectInterpreter.buildSettingsByBuildContext[buildContext] = <String, String>{ IosProject.kProductBundleIdKey: 'io.flutter.someProject', }; project.ios.hostAppRoot.childDirectory('WatchTarget').childFile('Info.plist').createSync(recursive: true); testPlistParser.setProperty('WKCompanionAppBundleIdentifier', r'$(PRODUCT_BUNDLE_IDENTIFIER)');
expect( await project.ios.containsWatchCompanion( projectInfo: mockXcodeProjectInterpreter.xcodeProjectInfo, buildInfo: BuildInfo.debug, deviceId: '123', ), isTrue, ); }, overrides: <Type, Generator>{ FileSystem: () => fs, ProcessManager: () => FakeProcessManager.any(), PlistParser: () => testPlistParser, XcodeProjectInterpreter: () => mockXcodeProjectInterpreter, FlutterProjectFactory: () => flutterProjectFactory, });
testUsingContext('has watch companion in other scheme build settings', () async { final FlutterProject project = await someProject(); project.ios.xcodeProject.createSync(); project.ios.xcodeProjectInfoFile.writeAsStringSync(''' Build settings for action build and target "WatchTarget": INFOPLIST_KEY_WKCompanionAppBundleIdentifier = io.flutter.someProject''');
const XcodeProjectBuildContext buildContext = XcodeProjectBuildContext( scheme: 'Runner', deviceId: '123', ); mockXcodeProjectInterpreter.buildSettingsByBuildContext[buildContext] = <String, String>{ IosProject.kProductBundleIdKey: 'io.flutter.someProject', };
const XcodeProjectBuildContext watchBuildContext = XcodeProjectBuildContext( scheme: 'WatchScheme', deviceId: '123', isWatch: true, ); mockXcodeProjectInterpreter.buildSettingsByBuildContext[watchBuildContext] = <String, String>{ 'INFOPLIST_KEY_WKCompanionAppBundleIdentifier': 'io.flutter.someProject', };
expect( await project.ios.containsWatchCompanion( projectInfo: mockXcodeProjectInterpreter.xcodeProjectInfo, buildInfo: BuildInfo.debug, deviceId: '123', ), isTrue, ); }, overrides: <Type, Generator>{ FileSystem: () => fs, ProcessManager: () => FakeProcessManager.any(), PlistParser: () => testPlistParser, XcodeProjectInterpreter: () => mockXcodeProjectInterpreter, FlutterProjectFactory: () => flutterProjectFactory, });
testUsingContext('has watch companion in other scheme build settings with xcode variable', () async { final FlutterProject project = await someProject(); project.ios.xcodeProject.createSync(); project.ios.xcodeProjectInfoFile.writeAsStringSync(r''' Build settings for action build and target "WatchTarget": INFOPLIST_KEY_WKCompanionAppBundleIdentifier = $(PRODUCT_BUNDLE_IDENTIFIER)'''); const XcodeProjectBuildContext buildContext = XcodeProjectBuildContext( scheme: 'Runner', deviceId: '123' ); mockXcodeProjectInterpreter.buildSettingsByBuildContext[buildContext] = <String, String>{ IosProject.kProductBundleIdKey: 'io.flutter.someProject', };
const XcodeProjectBuildContext watchBuildContext = XcodeProjectBuildContext( scheme: 'WatchScheme', deviceId: '123', isWatch: true, ); mockXcodeProjectInterpreter.buildSettingsByBuildContext[watchBuildContext] = <String, String>{ IosProject.kProductBundleIdKey: 'io.flutter.someProject', 'INFOPLIST_KEY_WKCompanionAppBundleIdentifier': r'$(PRODUCT_BUNDLE_IDENTIFIER)', };
expect( await project.ios.containsWatchCompanion( projectInfo: mockXcodeProjectInterpreter.xcodeProjectInfo, buildInfo: BuildInfo.debug, deviceId: '123', ), isTrue, ); }, overrides: <Type, Generator>{ FileSystem: () => fs, ProcessManager: () => FakeProcessManager.any(), PlistParser: () => testPlistParser, XcodeProjectInterpreter: () => mockXcodeProjectInterpreter, FlutterProjectFactory: () => flutterProjectFactory, }); }); });}
Future<FlutterProject> someProject({ String? androidManifestOverride, bool includePubspec = false,}) async { final Directory directory = globals.fs.directory('some_project'); directory.childDirectory('.dart_tool') .childFile('package_config.json') ..createSync(recursive: true) ..writeAsStringSync('{"configVersion":2,"packages":[]}'); if (includePubspec) { directory.childFile('pubspec.yaml') ..createSync(recursive: true) ..writeAsStringSync(validPubspec); } directory.childDirectory('ios').createSync(recursive: true); final Directory androidDirectory = directory .childDirectory('android') ..createSync(recursive: true); androidDirectory .childFile('AndroidManifest.xml') .writeAsStringSync(androidManifestOverride ?? '<manifest></manifest>'); return FlutterProject.fromDirectory(directory);}
Future<FlutterProject> aPluginProject({bool legacy = true}) async { final Directory directory = globals.fs.directory('plugin_project'); directory.childDirectory('ios').createSync(recursive: true); directory.childDirectory('android').createSync(recursive: true); directory.childDirectory('example').createSync(recursive: true); String pluginPubSpec; if (legacy) { pluginPubSpec = '''name: my_pluginflutter: plugin: androidPackage: com.example pluginClass: MyPlugin iosPrefix: FLT'''; } else { pluginPubSpec = '''name: my_pluginflutter: plugin: platforms: android: package: com.example pluginClass: MyPlugin ios: pluginClass: MyPlugin linux: pluginClass: MyPlugin macos: pluginClass: MyPlugin windows: pluginClass: MyPlugin'''; } directory.childFile('pubspec.yaml').writeAsStringSync(pluginPubSpec); return FlutterProject.fromDirectory(directory);}
Future<FlutterProject> aModuleProject() async { final Directory directory = globals.fs.directory('module_project'); directory .childDirectory('.dart_tool') .childFile('package_config.json') ..createSync(recursive: true) ..writeAsStringSync('{"configVersion":2,"packages":[]}'); directory.childFile('pubspec.yaml').writeAsStringSync('''name: my_moduleflutter: module: androidPackage: com.example'''); return FlutterProject.fromDirectory(directory);}
/// Executes the [testMethod] in a context where the file system/// is in memory.@isTestvoid _testInMemory( String description, Future<void> Function() testMethod, { FileSystem? fileSystem, Java? java, AndroidStudio? androidStudio, ProcessManager? processManager, AndroidSdk? androidSdk,}) { Cache.flutterRoot = getFlutterRoot(); final FileSystem testFileSystem = fileSystem ?? getFileSystemForPlatform(); testFileSystem.directory('.dart_tool').childFile('package_config.json') ..createSync(recursive: true) ..writeAsStringSync('{"configVersion":2,"packages":[]}'); // Transfer needed parts of the Flutter installation folder // to the in-memory file system used during testing. final Logger logger = BufferLogger.test(); transfer( Cache( fileSystem: globals.fs, logger: logger, artifacts: <ArtifactSet>[], osUtils: OperatingSystemUtils( fileSystem: globals.fs, logger: logger, platform: globals.platform, processManager: globals.processManager, ), platform: globals.platform, ).getArtifactDirectory('gradle_wrapper'), testFileSystem); transfer( globals.fs .directory(Cache.flutterRoot) .childDirectory('packages') .childDirectory('flutter_tools') .childDirectory('templates'), testFileSystem); // Set up enough of the packages to satisfy the templating code. final File packagesFile = testFileSystem .directory(Cache.flutterRoot) .childDirectory('packages') .childDirectory('flutter_tools') .childDirectory('.dart_tool') .childFile('package_config.json'); final Directory dummyTemplateImagesDirectory = testFileSystem.directory(Cache.flutterRoot).parent; dummyTemplateImagesDirectory.createSync(recursive: true); packagesFile.createSync(recursive: true); packagesFile.writeAsStringSync(json.encode(<String, Object>{ 'configVersion': 2, 'packages': <Object>[ <String, Object>{ 'name': 'flutter_template_images', 'rootUri': dummyTemplateImagesDirectory.uri.toString(), 'packageUri': 'lib/', 'languageVersion': '2.6', }, ], }));
testUsingContext( description, testMethod, overrides: <Type, Generator>{ FileSystem: () => testFileSystem, ProcessManager: () => processManager ?? FakeProcessManager.any(), Java : () => java, AndroidStudio: () => androidStudio ?? FakeAndroidStudio(), // Intentionlly null if not set. Some ios tests fail if this is a fake. AndroidSdk: () => androidSdk, Cache: () => Cache( logger: globals.logger, fileSystem: testFileSystem, osUtils: globals.os, platform: globals.platform, artifacts: <ArtifactSet>[], ), FlutterProjectFactory: () => FlutterProjectFactory( fileSystem: testFileSystem, logger: globals.logger, ), }, );}
/// Transfers files and folders from the local file system's Flutter/// installation to an (in-memory) file system used for testing.void transfer(FileSystemEntity entity, FileSystem target) { if (entity is Directory) { target.directory(entity.absolute.path).createSync(recursive: true); for (final FileSystemEntity child in entity.listSync()) { transfer(child, target); } } else if (entity is File) { target.file(entity.absolute.path).writeAsBytesSync(entity.readAsBytesSync(), flush: true); } else { throw Exception('Unsupported FileSystemEntity ${entity.runtimeType}'); }}
void expectExists(FileSystemEntity entity) { expect(entity.existsSync(), isTrue);}
void expectNotExists(FileSystemEntity entity) { expect(entity.existsSync(), isFalse);}
void addIosProjectFile(Directory directory, {required String Function() projectFileContent}) { directory .childDirectory('ios') .childDirectory('Runner.xcodeproj') .childFile('project.pbxproj') ..createSync(recursive: true) ..writeAsStringSync(projectFileContent());}
void addAndroidGradleFile(Directory directory, { required String Function() gradleFileContent }) { directory .childDirectory('android') .childDirectory('app') .childFile('build.gradle') ..createSync(recursive: true) ..writeAsStringSync(gradleFileContent());}
void addRootGradleFile(Directory directory, {required String Function() gradleFileContent}) { directory.childDirectory('android').childFile('build.gradle') ..createSync(recursive: true) ..writeAsStringSync(gradleFileContent());}
void addGradleWrapperFile(Directory directory, String gradleVersion) { directory .childDirectory('android') .childDirectory(gradle_utils.gradleDirectoryName) .childDirectory(gradle_utils.gradleWrapperDirectoryName) .childFile(gradle_utils.gradleWrapperPropertiesFilename) ..createSync(recursive: true) ..writeAsStringSync('''distributionBase=GRADLE_USER_HOMEdistributionPath=wrapper/distszipStoreBase=GRADLE_USER_HOMEzipStorePath=wrapper/distsdistributionUrl=https://services.gradle.org/distributions/gradle-$gradleVersion-all.zip''');}
FileSystem getFileSystemForPlatform() { return MemoryFileSystem( style: globals.platform.isWindows ? FileSystemStyle.windows : FileSystemStyle.posix, );}
void addAndroidWithGroup(Directory directory, String id) { directory.childDirectory('android').childFile('build.gradle') ..createSync(recursive: true) ..writeAsStringSync(gradleFileWithGroupId(id));}
String get validPubspec => '''name: helloflutter:''';
String get validPubspecWithDependencies => '''name: helloflutter:
dependencies: plugin_a: plugin_b:''';
String get invalidPubspec => '''name: helloflutter: invalid:''';
String get parseErrorPubspec => '''name: hello# Whitespace is important.flutter: something: something_else:''';
String projectFileWithBundleId(String id, {String? qualifier}) { return '''97C147061CF9000F007C117D /* Debug */ = { isa = XCBuildConfiguration; baseConfigurationReference = 9740EEB21CF90195004384FC /* Debug.xcconfig */; buildSettings = { PRODUCT_BUNDLE_IDENTIFIER = ${qualifier ?? ''}$id${qualifier ?? ''}; PRODUCT_NAME = "\$(TARGET_NAME)"; }; name = Debug;};''';}
String gradleFileWithApplicationId(String id) { return '''apply plugin: 'com.android.application'android { compileSdk 34
defaultConfig { applicationId '$id' }}''';}
String gradleFileWithGroupId(String id) { return '''group '$id'version '1.0-SNAPSHOT'
apply plugin: 'com.android.library'
android { compileSdk 34}''';}
File androidPluginRegistrant(Directory parent) { return parent.childDirectory('src') .childDirectory('main') .childDirectory('java') .childDirectory('io') .childDirectory('flutter') .childDirectory('plugins') .childFile('GeneratedPluginRegistrant.java');}
class FakeXcodeProjectInterpreter extends Fake implements XcodeProjectInterpreter { final Map<XcodeProjectBuildContext, Map<String, String>> buildSettingsByBuildContext = <XcodeProjectBuildContext, Map<String, String>>{}; late XcodeProjectInfo xcodeProjectInfo;
@override Future<Map<String, String>> getBuildSettings(String projectPath, { XcodeProjectBuildContext? buildContext, Duration timeout = const Duration(minutes: 1), }) async { if (buildSettingsByBuildContext[buildContext] == null) { return <String, String>{}; } return buildSettingsByBuildContext[buildContext]!; }
@override Future<XcodeProjectInfo> getInfo(String projectPath, {String? projectFilename}) async { return xcodeProjectInfo; }
@override bool get isInstalled => true;}
class FakeAndroidSdkWithDir extends Fake implements AndroidSdk { FakeAndroidSdkWithDir(this._directory);
final Directory _directory;
@override Directory get directory => _directory;}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899// 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:flutter_tools/src/project.dart';import 'package:flutter_tools/src/project_validator.dart';import 'package:flutter_tools/src/project_validator_result.dart';
import '../src/common.dart';
class ProjectValidatorTaskImpl extends ProjectValidator {
@override Future<List<ProjectValidatorResult>> start(FlutterProject project) async { const ProjectValidatorResult error = ProjectValidatorResult( name: 'result_1', value: 'this is an error', status: StatusProjectValidator.error, );
const ProjectValidatorResult success = ProjectValidatorResult( name: 'result_2', value: 'correct', status: StatusProjectValidator.success, );
const ProjectValidatorResult warning = ProjectValidatorResult( name: 'result_3', value: 'this passed', status: StatusProjectValidator.success, warning: 'with a warning' );
return <ProjectValidatorResult>[error, success, warning]; }
@override bool supportsProject(FlutterProject project) { return true; }
@override String get title => 'Impl';}
void main() { group('ProjectValidatorResult', () {
testWithoutContext('success status', () { const ProjectValidatorResult result = ProjectValidatorResult( name: 'name', value: 'value', status: StatusProjectValidator.success, ); expect(result.toString(), 'name: value'); expect(result.status, StatusProjectValidator.success); });
testWithoutContext('success status with warning', () { const ProjectValidatorResult result = ProjectValidatorResult( name: 'name', value: 'value', status: StatusProjectValidator.success, warning: 'my warning' ); expect(result.toString(), 'name: value (warning: my warning)'); expect(result.status, StatusProjectValidator.success); });
testWithoutContext('error status', () { const ProjectValidatorResult result = ProjectValidatorResult( name: 'name', value: 'my error', status: StatusProjectValidator.error, ); expect(result.toString(), 'name: my error'); expect(result.status, StatusProjectValidator.error); }); });
group('ProjectValidatorTask', () { late ProjectValidatorTaskImpl task;
setUp(() { task = ProjectValidatorTaskImpl(); });
testWithoutContext('error status', () async { final MemoryFileSystem fs = MemoryFileSystem.test(); final FlutterProject project = FlutterProject.fromDirectoryTest(fs.currentDirectory); final List<ProjectValidatorResult> results = await task.start(project); expect(results.length, 3); expect(results[0].toString(), 'result_1: this is an error'); expect(results[1].toString(), 'result_2: correct'); expect(results[2].toString(), 'result_3: this passed (warning: with a warning)'); }); });}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417// 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:fake_async/fake_async.dart';import 'package:flutter_tools/src/base/logger.dart';import 'package:flutter_tools/src/device_port_forwarder.dart';import 'package:flutter_tools/src/protocol_discovery.dart';
import '../src/common.dart';import '../src/fake_devices.dart';
void main() { group('service_protocol discovery', () { late FakeDeviceLogReader logReader; late ProtocolDiscovery discoverer;
setUp(() { logReader = FakeDeviceLogReader(); discoverer = ProtocolDiscovery.vmService( logReader, ipv6: false, throttleDuration: const Duration(milliseconds: 5), logger: BufferLogger.test(), ); });
testWithoutContext('returns non-null uri future', () async { expect(discoverer.uri, isNotNull); });
group('no port forwarding', () { tearDown(() { discoverer.cancel(); logReader.dispose(); });
testWithoutContext('discovers uri if logs already produced output', () async { logReader.addLine('HELLO WORLD'); logReader.addLine('The Dart VM service is listening on http://127.0.0.1:9999'); final Uri uri = (await discoverer.uri)!; expect(uri.port, 9999); expect('$uri', 'http://127.0.0.1:9999'); });
testWithoutContext('does not discover uri with no host', () async { final Future<Uri?> pendingUri = discoverer.uri; logReader.addLine('The Dart VM service is listening on http12asdasdsd9999'); await Future<void>.delayed(const Duration(milliseconds: 10)); logReader.addLine('The Dart VM service is listening on http://127.0.0.1:9999');
await Future<void>.delayed(Duration.zero);
final Uri uri = (await pendingUri)!; expect(uri, isNotNull); expect(uri.port, 9999); expect('$uri', 'http://127.0.0.1:9999'); });
testWithoutContext('discovers uri if logs already produced output and no listener is attached', () async { logReader.addLine('HELLO WORLD'); logReader.addLine('The Dart VM service is listening on http://127.0.0.1:9999');
await Future<void>.delayed(Duration.zero);
final Uri uri = (await discoverer.uri)!; expect(uri, isNotNull); expect(uri.port, 9999); expect('$uri', 'http://127.0.0.1:9999'); });
testWithoutContext('uri throws if logs produce bad line and no listener is attached', () async { logReader.addLine('The Dart VM service is listening on http://127.0.0.1:apple');
await Future<void>.delayed(Duration.zero);
expect(discoverer.uri, throwsA(isFormatException)); });
testWithoutContext('discovers uri if logs not yet produced output', () async { final Future<Uri?> uriFuture = discoverer.uri; logReader.addLine('The Dart VM service is listening on http://127.0.0.1:3333'); final Uri uri = (await uriFuture)!; expect(uri.port, 3333); expect('$uri', 'http://127.0.0.1:3333'); });
testWithoutContext('discovers uri with Ascii Esc code', () async { logReader.addLine('The Dart VM service is listening on http://127.0.0.1:3333\x1b['); final Uri uri = (await discoverer.uri)!; expect(uri.port, 3333); expect('$uri', 'http://127.0.0.1:3333'); });
testWithoutContext('uri throws if logs produce bad line', () async { logReader.addLine('The Dart VM service is listening on http://127.0.0.1:apple'); expect(discoverer.uri, throwsA(isFormatException)); });
testWithoutContext('uri is null when the log reader closes early', () async { final Future<Uri?> uriFuture = discoverer.uri; await logReader.dispose();
expect(await uriFuture, isNull); });
testWithoutContext('uri waits for correct log line', () async { final Future<Uri?> uriFuture = discoverer.uri; logReader.addLine('VM Service not listening...'); final Uri timeoutUri = Uri.parse('http://timeout'); final Uri? actualUri = await uriFuture.timeout( const Duration(milliseconds: 100), onTimeout: () => timeoutUri, ); expect(actualUri, timeoutUri); });
testWithoutContext('discovers uri if log line contains Android prefix', () async { logReader.addLine('I/flutter : The Dart VM service is listening on http://127.0.0.1:52584'); final Uri uri = (await discoverer.uri)!; expect(uri.port, 52584); expect('$uri', 'http://127.0.0.1:52584'); });
testWithoutContext('discovers uri if log line contains auth key', () async { final Future<Uri?> uriFuture = discoverer.uri; logReader.addLine('I/flutter : The Dart VM service is listening on http://127.0.0.1:54804/PTwjm8Ii8qg=/'); final Uri uri = (await uriFuture)!; expect(uri.port, 54804); expect('$uri', 'http://127.0.0.1:54804/PTwjm8Ii8qg=/'); });
testWithoutContext('discovers uri if log line contains non-localhost', () async { final Future<Uri?> uriFuture = discoverer.uri; logReader.addLine('I/flutter : The Dart VM service is listening on http://127.0.0.1:54804/PTwjm8Ii8qg=/'); final Uri uri = (await uriFuture)!; expect(uri.port, 54804); expect('$uri', 'http://127.0.0.1:54804/PTwjm8Ii8qg=/'); });
testWithoutContext('skips uri if port does not match the requested vmservice - requested last', () async { discoverer = ProtocolDiscovery.vmService( logReader, ipv6: false, devicePort: 12346, throttleDuration: const Duration(milliseconds: 200), logger: BufferLogger.test(), ); final Future<Uri?> uriFuture = discoverer.uri; logReader.addLine('I/flutter : The Dart VM service is listening on http://127.0.0.1:12345/PTwjm8Ii8qg=/'); logReader.addLine('I/flutter : The Dart VM service is listening on http://127.0.0.1:12346/PTwjm8Ii8qg=/'); final Uri uri = (await uriFuture)!; expect(uri.port, 12346); expect('$uri', 'http://127.0.0.1:12346/PTwjm8Ii8qg=/'); });
testWithoutContext('skips uri if port does not match the requested vmservice - requested first', () async { discoverer = ProtocolDiscovery.vmService( logReader, ipv6: false, devicePort: 12346, throttleDuration: const Duration(milliseconds: 200), logger: BufferLogger.test(), ); final Future<Uri?> uriFuture = discoverer.uri; logReader.addLine('I/flutter : The Dart VM service is listening on http://127.0.0.1:12346/PTwjm8Ii8qg=/'); logReader.addLine('I/flutter : The Dart VM service is listening on http://127.0.0.1:12345/PTwjm8Ii8qg=/'); final Uri uri = (await uriFuture)!; expect(uri.port, 12346); expect('$uri', 'http://127.0.0.1:12346/PTwjm8Ii8qg=/'); });
testWithoutContext('first uri in the stream is the last one from the log', () async { logReader.addLine('I/flutter : The Dart VM service is listening on http://127.0.0.1:12346/PTwjm8Ii8qg=/'); logReader.addLine('I/flutter : The Dart VM service is listening on http://127.0.0.1:12345/PTwjm8Ii8qg=/'); final Uri uri = await discoverer.uris.first; expect(uri.port, 12345); expect('$uri', 'http://127.0.0.1:12345/PTwjm8Ii8qg=/'); });
testWithoutContext('first uri in the stream is the last one from the log that matches the port', () async { discoverer = ProtocolDiscovery.vmService( logReader, ipv6: false, devicePort: 12345, throttleDuration: const Duration(milliseconds: 200), logger: BufferLogger.test(), ); logReader.addLine('I/flutter : The Dart VM service is listening on http://127.0.0.1:12346/PTwjm8Ii8qg=/'); logReader.addLine('I/flutter : The Dart VM service is listening on http://127.0.0.1:12345/PTwjm8Ii8qg=/'); logReader.addLine('I/flutter : The Dart VM service is listening on http://127.0.0.1:12344/PTwjm8Ii8qg=/'); final Uri uri = await discoverer.uris.first; expect(uri.port, 12345); expect('$uri', 'http://127.0.0.1:12345/PTwjm8Ii8qg=/'); });
testWithoutContext('protocol discovery does not crash if the log reader is closed while delaying', () async { discoverer = ProtocolDiscovery.vmService( logReader, ipv6: false, devicePort: 12346, throttleDuration: const Duration(milliseconds: 10), logger: BufferLogger.test(), ); final Future<List<Uri>> results = discoverer.uris.toList(); logReader.addLine('I/flutter : The Dart VM service is listening on http://127.0.0.1:12346/PTwjm8Ii8qg=/'); logReader.addLine('I/flutter : The Dart VM service is listening on http://127.0.0.1:12346/PTwjm8Ii8qg=/'); await logReader.dispose();
// Give time for throttle to finish. await Future<void>.delayed(const Duration(milliseconds: 11)); expect(await results, isEmpty); });
testWithoutContext('uris in the stream are throttled', () async { const Duration kThrottleDuration = Duration(milliseconds: 10);
FakeAsync().run((FakeAsync time) { discoverer = ProtocolDiscovery.vmService( logReader, ipv6: false, throttleDuration: kThrottleDuration, logger: BufferLogger.test(), );
final List<Uri> discoveredUris = <Uri>[]; discoverer.uris.listen((Uri uri) { discoveredUris.add(uri); });
logReader.addLine('I/flutter : The Dart VM service is listening on http://127.0.0.1:12346/PTwjm8Ii8qg=/'); logReader.addLine('I/flutter : The Dart VM service is listening on http://127.0.0.1:12345/PTwjm8Ii8qg=/');
time.elapse(kThrottleDuration);
logReader.addLine('I/flutter : The Dart VM service is listening on http://127.0.0.1:12344/PTwjm8Ii8qg=/'); logReader.addLine('I/flutter : The Dart VM service is listening on http://127.0.0.1:12343/PTwjm8Ii8qg=/');
time.elapse(kThrottleDuration);
expect(discoveredUris.length, 2); expect(discoveredUris[0].port, 12345); expect('${discoveredUris[0]}', 'http://127.0.0.1:12345/PTwjm8Ii8qg=/'); expect(discoveredUris[1].port, 12343); expect('${discoveredUris[1]}', 'http://127.0.0.1:12343/PTwjm8Ii8qg=/'); }); });
testWithoutContext('uris in the stream are throttled when they match the port', () async { const Duration kThrottleTimeInMilliseconds = Duration(milliseconds: 10);
FakeAsync().run((FakeAsync time) { discoverer = ProtocolDiscovery.vmService( logReader, ipv6: false, devicePort: 12345, throttleDuration: kThrottleTimeInMilliseconds, logger: BufferLogger.test(), );
final List<Uri> discoveredUris = <Uri>[]; discoverer.uris.listen((Uri uri) { discoveredUris.add(uri); });
logReader.addLine('I/flutter : The Dart VM service is listening on http://127.0.0.1:12346/PTwjm8Ii8qg=/'); logReader.addLine('I/flutter : The Dart VM service is listening on http://127.0.0.1:12345/PTwjm8Ii8qg=/');
time.elapse(kThrottleTimeInMilliseconds);
logReader.addLine('I/flutter : The Dart VM service is listening on http://127.0.0.1:12345/PTwjm8Ii8qc=/'); logReader.addLine('I/flutter : The Dart VM service is listening on http://127.0.0.1:12344/PTwjm8Ii8qf=/');
time.elapse(kThrottleTimeInMilliseconds);
expect(discoveredUris.length, 2); expect(discoveredUris[0].port, 12345); expect('${discoveredUris[0]}', 'http://127.0.0.1:12345/PTwjm8Ii8qg=/'); expect(discoveredUris[1].port, 12345); expect('${discoveredUris[1]}', 'http://127.0.0.1:12345/PTwjm8Ii8qc=/'); }); }); });
group('port forwarding', () { testWithoutContext('default port', () async { final FakeDeviceLogReader logReader = FakeDeviceLogReader(); final ProtocolDiscovery discoverer = ProtocolDiscovery.vmService( logReader, portForwarder: MockPortForwarder(99), ipv6: false, logger: BufferLogger.test(), );
// Get next port future. final Future<Uri?> nextUri = discoverer.uri; logReader.addLine('I/flutter : The Dart VM service is listening on http://127.0.0.1:54804/PTwjm8Ii8qg=/'); final Uri uri = (await nextUri)!; expect(uri.port, 99); expect('$uri', 'http://127.0.0.1:99/PTwjm8Ii8qg=/');
await discoverer.cancel(); await logReader.dispose(); });
testWithoutContext('specified port', () async { final FakeDeviceLogReader logReader = FakeDeviceLogReader(); final ProtocolDiscovery discoverer = ProtocolDiscovery.vmService( logReader, portForwarder: MockPortForwarder(99), hostPort: 1243, ipv6: false, logger: BufferLogger.test(), );
// Get next port future. final Future<Uri?> nextUri = discoverer.uri; logReader.addLine('I/flutter : The Dart VM service is listening on http://127.0.0.1:54804/PTwjm8Ii8qg=/'); final Uri uri = (await nextUri)!; expect(uri.port, 1243); expect('$uri', 'http://127.0.0.1:1243/PTwjm8Ii8qg=/');
await discoverer.cancel(); await logReader.dispose(); });
testWithoutContext('specified port zero', () async { final FakeDeviceLogReader logReader = FakeDeviceLogReader(); final ProtocolDiscovery discoverer = ProtocolDiscovery.vmService( logReader, portForwarder: MockPortForwarder(99), hostPort: 0, ipv6: false, logger: BufferLogger.test(), );
// Get next port future. final Future<Uri?> nextUri = discoverer.uri; logReader.addLine('I/flutter : The Dart VM service is listening on http://127.0.0.1:54804/PTwjm8Ii8qg=/'); final Uri uri = (await nextUri)!; expect(uri.port, 99); expect('$uri', 'http://127.0.0.1:99/PTwjm8Ii8qg=/');
await discoverer.cancel(); await logReader.dispose(); });
testWithoutContext('ipv6', () async { final FakeDeviceLogReader logReader = FakeDeviceLogReader(); final ProtocolDiscovery discoverer = ProtocolDiscovery.vmService( logReader, portForwarder: MockPortForwarder(99), hostPort: 54777, ipv6: true, logger: BufferLogger.test(), );
// Get next port future. final Future<Uri?> nextUri = discoverer.uri; logReader.addLine('I/flutter : The Dart VM service is listening on http://127.0.0.1:54804/PTwjm8Ii8qg=/'); final Uri uri = (await nextUri)!; expect(uri.port, 54777); expect('$uri', 'http://[::1]:54777/PTwjm8Ii8qg=/');
await discoverer.cancel(); await logReader.dispose(); });
testWithoutContext('ipv6 with Ascii Escape code', () async { final FakeDeviceLogReader logReader = FakeDeviceLogReader(); final ProtocolDiscovery discoverer = ProtocolDiscovery.vmService( logReader, portForwarder: MockPortForwarder(99), hostPort: 54777, ipv6: true, logger: BufferLogger.test(), );
// Get next port future. final Future<Uri?> nextUri = discoverer.uri; logReader.addLine('I/flutter : The Dart VM service is listening on http://[::1]:54777/PTwjm8Ii8qg=/\x1b['); final Uri uri = (await nextUri)!; expect(uri.port, 54777); expect('$uri', 'http://[::1]:54777/PTwjm8Ii8qg=/');
await discoverer.cancel(); await logReader.dispose(); }); }); });}
class MockPortForwarder extends DevicePortForwarder { MockPortForwarder([this.availablePort]);
final int? availablePort;
@override Future<int> forward(int devicePort, { int? hostPort }) async { hostPort ??= 0; if (hostPort == 0) { return availablePort!; } return hostPort; }
@override List<ForwardedPort> get forwardedPorts => throw UnimplementedError();
@override Future<void> unforward(ForwardedPort forwardedPort) { throw UnimplementedError(); }
@override Future<void> dispose() async {}}1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677// 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:flutter_tools/src/base/file_system.dart';import 'package:flutter_tools/src/project.dart';import 'package:flutter_tools/src/project_validator.dart';import 'package:flutter_tools/src/project_validator_result.dart';
import '../src/common.dart';import '../src/context.dart';
void main() { late FileSystem fileSystem;
group('PubDependenciesProjectValidator', () {
setUp(() { fileSystem = MemoryFileSystem.test(); });
testWithoutContext('success when all dependencies are hosted', () async { final ProcessManager processManager = FakeProcessManager.list(<FakeCommand>[ const FakeCommand( command: <String>['dart', 'pub', 'deps', '--json'], stdout: '{"packages": [{"dependencies": ["abc"], "source": "hosted"}]}', ), ]); final PubDependenciesProjectValidator validator = PubDependenciesProjectValidator(processManager);
final List<ProjectValidatorResult> result = await validator.start( FlutterProject.fromDirectoryTest(fileSystem.currentDirectory) ); const String expected = 'All pub dependencies are hosted on https://pub.dartlang.org'; expect(result.length, 1); expect(result[0].value, expected); expect(result[0].status, StatusProjectValidator.info); });
testWithoutContext('error when command dart pub deps fails', () async { final ProcessManager processManager = FakeProcessManager.list(<FakeCommand>[ const FakeCommand( command: <String>['dart', 'pub', 'deps', '--json'], stderr: 'command fail', ), ]); final PubDependenciesProjectValidator validator = PubDependenciesProjectValidator(processManager);
final List<ProjectValidatorResult> result = await validator.start( FlutterProject.fromDirectoryTest(fileSystem.currentDirectory) ); const String expected = 'command fail'; expect(result.length, 1); expect(result[0].value, expected); expect(result[0].status, StatusProjectValidator.error); });
testWithoutContext('info on dependencies not hosted', () async { final ProcessManager processManager = FakeProcessManager.list(<FakeCommand>[ const FakeCommand( command: <String>['dart', 'pub', 'deps', '--json'], stdout: '{"packages": [{"dependencies": ["dep1", "dep2"], "source": "other"}]}', ), ]); final PubDependenciesProjectValidator validator = PubDependenciesProjectValidator(processManager);
final List<ProjectValidatorResult> result = await validator.start( FlutterProject.fromDirectoryTest(fileSystem.currentDirectory) ); const String expected = 'dep1, dep2 are not hosted'; expect(result.length, 1); expect(result[0].value, expected); expect(result[0].status, StatusProjectValidator.info); }); });}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501// 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 'package:flutter_tools/src/base/dds.dart';import 'package:flutter_tools/src/base/logger.dart';import 'package:flutter_tools/src/build_info.dart';import 'package:flutter_tools/src/cache.dart';import 'package:flutter_tools/src/device.dart';import 'package:flutter_tools/src/devtools_launcher.dart';import 'package:flutter_tools/src/resident_devtools_handler.dart';import 'package:flutter_tools/src/resident_runner.dart';import 'package:flutter_tools/src/vmservice.dart';import 'package:test/fake.dart';import 'package:vm_service/vm_service.dart' as vm_service;
import '../src/common.dart';import '../src/fake_process_manager.dart';import '../src/fake_vm_services.dart';import '../src/fakes.dart';
final vm_service.Isolate isolate = vm_service.Isolate( id: '1', pauseEvent: vm_service.Event( kind: vm_service.EventKind.kResume, timestamp: 0 ), breakpoints: <vm_service.Breakpoint>[], libraries: <vm_service.LibraryRef>[ vm_service.LibraryRef( id: '1', uri: 'file:///hello_world/main.dart', name: '', ), ], livePorts: 0, name: 'test', number: '1', pauseOnExit: false, runnable: true, startTime: 0, isSystemIsolate: false, isolateFlags: <vm_service.IsolateFlag>[], extensionRPCs: <String>['ext.flutter.connectedVmServiceUri'],);
final FakeVmServiceRequest listViews = FakeVmServiceRequest( method: kListViewsMethod, jsonResponse: <String, Object>{ 'views': <Object>[ FlutterView( id: 'a', uiIsolate: isolate, ).toJson(), ], },);
void main() { Cache.flutterRoot = '';
testWithoutContext('Does not serve devtools if launcher is null', () async { final ResidentDevtoolsHandler handler = FlutterResidentDevtoolsHandler( null, FakeResidentRunner(), BufferLogger.test(), );
await handler.serveAndAnnounceDevTools(flutterDevices: <FlutterDevice>[]);
expect(handler.activeDevToolsServer, null); });
testWithoutContext('Does not serve devtools if ResidentRunner does not support the service protocol', () async { final ResidentDevtoolsHandler handler = FlutterResidentDevtoolsHandler( FakeDevtoolsLauncher(), FakeResidentRunner()..supportsServiceProtocol = false, BufferLogger.test(), );
await handler.serveAndAnnounceDevTools(flutterDevices: <FlutterDevice>[]);
expect(handler.activeDevToolsServer, null); });
testWithoutContext('Can use devtools with existing devtools URI', () async { final DevtoolsServerLauncher launcher = DevtoolsServerLauncher( processManager: FakeProcessManager.empty(), dartExecutable: 'dart', logger: BufferLogger.test(), botDetector: const FakeBotDetector(false), ); final ResidentDevtoolsHandler handler = FlutterResidentDevtoolsHandler( // Uses real devtools instance which should be a no-op if // URI is already set. launcher, FakeResidentRunner(), BufferLogger.test(), );
await handler.serveAndAnnounceDevTools( devToolsServerAddress: Uri.parse('http://localhost:8181'), flutterDevices: <FlutterDevice>[], );
expect(handler.activeDevToolsServer!.host, 'localhost'); expect(handler.activeDevToolsServer!.port, 8181); });
testWithoutContext('serveAndAnnounceDevTools with attached device does not fail on null vm service', () async { final ResidentDevtoolsHandler handler = FlutterResidentDevtoolsHandler( FakeDevtoolsLauncher() ..activeDevToolsServer = DevToolsServerAddress('localhost', 8080) ..devToolsUrl = Uri.parse('http://localhost:8080'), FakeResidentRunner(), BufferLogger.test(), );
// VM Service is intentionally null final FakeFlutterDevice device = FakeFlutterDevice();
await handler.serveAndAnnounceDevTools( flutterDevices: <FlutterDevice>[device], ); });
testWithoutContext('serveAndAnnounceDevTools with invokes devtools and vm_service setter', () async { final ResidentDevtoolsHandler handler = FlutterResidentDevtoolsHandler( FakeDevtoolsLauncher() ..activeDevToolsServer = DevToolsServerAddress('localhost', 8080) ..devToolsUrl = Uri.parse('http://localhost:8080'), FakeResidentRunner(), BufferLogger.test(), ); final FakeVmServiceHost fakeVmServiceHost = FakeVmServiceHost(requests: <VmServiceExpectation>[ const FakeVmServiceRequest( method: 'streamListen', args: <String, Object>{ 'streamId': 'Isolate', } ), listViews, FakeVmServiceRequest( method: 'getIsolate', jsonResponse: isolate.toJson(), args: <String, Object>{ 'isolateId': '1', }, ), const FakeVmServiceRequest( method: 'streamCancel', args: <String, Object>{ 'streamId': 'Isolate', }, ), listViews, listViews, const FakeVmServiceRequest( method: 'ext.flutter.activeDevToolsServerAddress', args: <String, Object>{ 'isolateId': '1', 'value': 'http://localhost:8080', }, ), const FakeVmServiceRequest( method: 'ext.flutter.connectedVmServiceUri', args: <String, Object>{ 'isolateId': '1', 'value': 'http://localhost:1234', }, ), ], httpAddress: Uri.parse('http://localhost:1234'));
final FakeFlutterDevice device = FakeFlutterDevice() ..vmService = fakeVmServiceHost.vmService;
await handler.serveAndAnnounceDevTools( flutterDevices: <FlutterDevice>[device], ); });
testWithoutContext('serveAndAnnounceDevTools will bail if launching devtools fails', () async { final ResidentDevtoolsHandler handler = FlutterResidentDevtoolsHandler( FakeDevtoolsLauncher()..activeDevToolsServer = null, FakeResidentRunner(), BufferLogger.test(), ); final FakeVmServiceHost fakeVmServiceHost = FakeVmServiceHost(requests: <VmServiceExpectation>[], httpAddress: Uri.parse('http://localhost:1234'));
final FakeFlutterDevice device = FakeFlutterDevice() ..vmService = fakeVmServiceHost.vmService;
await handler.serveAndAnnounceDevTools( flutterDevices: <FlutterDevice>[device], ); });
testWithoutContext('serveAndAnnounceDevTools with web device', () async { final ResidentDevtoolsHandler handler = FlutterResidentDevtoolsHandler( FakeDevtoolsLauncher() ..activeDevToolsServer = DevToolsServerAddress('localhost', 8080) ..devToolsUrl = Uri.parse('http://localhost:8080'), FakeResidentRunner(), BufferLogger.test(), ); final FakeVmServiceHost fakeVmServiceHost = FakeVmServiceHost(requests: <VmServiceExpectation>[ const FakeVmServiceRequest( method: 'streamListen', args: <String, Object>{ 'streamId': 'Isolate', } ), listViews, FakeVmServiceRequest( method: 'getIsolate', jsonResponse: isolate.toJson(), args: <String, Object>{ 'isolateId': '1', }, ), const FakeVmServiceRequest( method: 'streamCancel', args: <String, Object>{ 'streamId': 'Isolate', }, ), const FakeVmServiceRequest( method: 'ext.flutter.activeDevToolsServerAddress', args: <String, Object>{ 'value': 'http://localhost:8080', }, ), const FakeVmServiceRequest( method: 'ext.flutter.connectedVmServiceUri', args: <String, Object>{ 'value': 'http://localhost:1234', }, ), ], httpAddress: Uri.parse('http://localhost:1234'));
final FakeFlutterDevice device = FakeFlutterDevice() ..vmService = fakeVmServiceHost.vmService ..targetPlatform = TargetPlatform.web_javascript;
await handler.serveAndAnnounceDevTools( flutterDevices: <FlutterDevice>[device], ); });
testWithoutContext('serveAndAnnounceDevTools with skips calling service extensions when VM service disappears', () async { final ResidentDevtoolsHandler handler = FlutterResidentDevtoolsHandler( FakeDevtoolsLauncher()..activeDevToolsServer = DevToolsServerAddress('localhost', 8080), FakeResidentRunner(), BufferLogger.test(), ); final FakeVmServiceHost fakeVmServiceHost = FakeVmServiceHost(requests: <VmServiceExpectation>[ const FakeVmServiceRequest( method: 'streamListen', args: <String, Object>{ 'streamId': 'Isolate', }, ), const FakeVmServiceRequest( method: kListViewsMethod, error: FakeRPCError(code: RPCErrorCodes.kServiceDisappeared), ), const FakeVmServiceRequest( method: 'streamCancel', args: <String, Object>{ 'streamId': 'Isolate', }, error: FakeRPCError(code: RPCErrorCodes.kServiceDisappeared), ), ], httpAddress: Uri.parse('http://localhost:1234'));
final FakeFlutterDevice device = FakeFlutterDevice() ..vmService = fakeVmServiceHost.vmService;
await handler.serveAndAnnounceDevTools( flutterDevices: <FlutterDevice>[device], ); });
testWithoutContext('serveAndAnnounceDevTools with multiple devices and VM service disappears on one', () async { final ResidentDevtoolsHandler handler = FlutterResidentDevtoolsHandler( FakeDevtoolsLauncher() ..activeDevToolsServer = DevToolsServerAddress('localhost', 8080) ..devToolsUrl = Uri.parse('http://localhost:8080'), FakeResidentRunner(), BufferLogger.test(), );
final FakeVmServiceHost vmServiceHost = FakeVmServiceHost(requests: <VmServiceExpectation>[ const FakeVmServiceRequest( method: 'streamListen', args: <String, Object>{ 'streamId': 'Isolate', }, ), listViews, FakeVmServiceRequest( method: 'getIsolate', jsonResponse: isolate.toJson(), args: <String, Object>{ 'isolateId': '1', }, ), const FakeVmServiceRequest( method: 'streamCancel', args: <String, Object>{ 'streamId': 'Isolate', }, ), listViews, listViews, const FakeVmServiceRequest( method: 'ext.flutter.activeDevToolsServerAddress', args: <String, Object>{ 'isolateId': '1', 'value': 'http://localhost:8080', }, ), const FakeVmServiceRequest( method: 'ext.flutter.connectedVmServiceUri', args: <String, Object>{ 'isolateId': '1', 'value': 'http://localhost:1234', }, ), ], httpAddress: Uri.parse('http://localhost:1234'));
final FakeVmServiceHost vmServiceHostThatDisappears = FakeVmServiceHost(requests: <VmServiceExpectation>[ const FakeVmServiceRequest( method: 'streamListen', args: <String, Object>{ 'streamId': 'Isolate', }, ), const FakeVmServiceRequest( method: kListViewsMethod, error: FakeRPCError(code: RPCErrorCodes.kServiceDisappeared), ), const FakeVmServiceRequest( method: 'streamCancel', args: <String, Object>{ 'streamId': 'Isolate', }, error: FakeRPCError(code: RPCErrorCodes.kServiceDisappeared), ), ], httpAddress: Uri.parse('http://localhost:5678'));
await handler.serveAndAnnounceDevTools( flutterDevices: <FlutterDevice>[ FakeFlutterDevice() ..vmService = vmServiceHostThatDisappears.vmService, FakeFlutterDevice() ..vmService = vmServiceHost.vmService, ], ); });
testWithoutContext('Does not launch devtools in browser if launcher is null', () async { final FlutterResidentDevtoolsHandler handler = FlutterResidentDevtoolsHandler( null, FakeResidentRunner(), BufferLogger.test(), );
handler.launchDevToolsInBrowser(flutterDevices: <FlutterDevice>[]); expect(handler.launchedInBrowser, isFalse); expect(handler.activeDevToolsServer, null); });
testWithoutContext('Does not launch devtools in browser if ResidentRunner does not support the service protocol', () async { final FlutterResidentDevtoolsHandler handler = FlutterResidentDevtoolsHandler( FakeDevtoolsLauncher(), FakeResidentRunner()..supportsServiceProtocol = false, BufferLogger.test(), );
handler.launchDevToolsInBrowser(flutterDevices: <FlutterDevice>[]); expect(handler.launchedInBrowser, isFalse); expect(handler.activeDevToolsServer, null); });
testWithoutContext('launchDevToolsInBrowser launches after _devToolsLauncher.ready completes', () async { final Completer<void> completer = Completer<void>(); final FlutterResidentDevtoolsHandler handler = FlutterResidentDevtoolsHandler( FakeDevtoolsLauncher() ..devToolsUrl = null // We need to set [activeDevToolsServer] to simulate the state we would // be in after serving devtools completes. ..activeDevToolsServer = DevToolsServerAddress('localhost', 8080) ..readyCompleter = completer, FakeResidentRunner(), BufferLogger.test(), );
expect(handler.launchDevToolsInBrowser(flutterDevices: <FlutterDevice>[]), isTrue); expect(handler.launchedInBrowser, isFalse);
completer.complete(); // Await a short delay to give DevTools time to launch. await Future<void>.delayed(const Duration(microseconds: 100));
expect(handler.launchedInBrowser, isTrue); });
testWithoutContext('launchDevToolsInBrowser launches successfully', () async { final FlutterResidentDevtoolsHandler handler = FlutterResidentDevtoolsHandler( FakeDevtoolsLauncher() ..devToolsUrl = Uri(host: 'localhost', port: 8080) ..activeDevToolsServer = DevToolsServerAddress('localhost', 8080), FakeResidentRunner(), BufferLogger.test(), );
expect(handler.launchDevToolsInBrowser(flutterDevices: <FlutterDevice>[]), isTrue); expect(handler.launchedInBrowser, isTrue); });
testWithoutContext('Converts a VM Service URI with a query parameter to a pretty display string', () { const String value = 'http://127.0.0.1:9100?uri=http%3A%2F%2F127.0.0.1%3A57922%2F_MXpzytpH20%3D%2F'; final Uri uri = Uri.parse(value);
expect(urlToDisplayString(uri), 'http://127.0.0.1:9100?uri=http://127.0.0.1:57922/_MXpzytpH20=/'); });}
class FakeDevtoolsLauncher extends Fake implements DevtoolsLauncher { @override DevToolsServerAddress? activeDevToolsServer;
@override Uri? devToolsUrl;
@override Future<DevToolsServerAddress?> serve() async => null;
@override Future<void> get ready => readyCompleter.future;
Completer<void> readyCompleter = Completer<void>()..complete();}
class FakeResidentRunner extends Fake implements ResidentRunner { @override bool supportsServiceProtocol = true;
@override bool reportedDebuggers = false;
@override DebuggingOptions debuggingOptions = DebuggingOptions.disabled(BuildInfo.debug);}
class FakeFlutterDevice extends Fake implements FlutterDevice { @override final Device device = FakeDevice();
@override FlutterVmService? vmService;
@override TargetPlatform targetPlatform = TargetPlatform.android_arm;}
class FakeDevice extends Fake implements Device { @override DartDevelopmentService get dds => FakeDartDevelopmentService();}
class FakeDartDevelopmentService extends Fake implements DartDevelopmentService { bool started = false; bool disposed = false;
@override final Uri uri = Uri.parse('http://127.0.0.1:1234/');
@override Future<void> startDartDevelopmentService( Uri observatoryUri, { required Logger logger, int? hostPort, bool? ipv6, bool? disableServiceAuthCodes, bool cacheStartupProfile = false, }) async { started = true; }
@override Future<void> shutdown() async { disposed = true; }
@override void setExternalDevToolsUri(Uri uri) {}}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545// 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 'package:dds/dds.dart' as dds;import 'package:flutter_tools/src/application_package.dart';import 'package:flutter_tools/src/asset.dart';import 'package:flutter_tools/src/base/dds.dart';import 'package:flutter_tools/src/base/file_system.dart';import 'package:flutter_tools/src/build_info.dart';import 'package:flutter_tools/src/build_system/tools/scene_importer.dart';import 'package:flutter_tools/src/build_system/tools/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/device_port_forwarder.dart';import 'package:flutter_tools/src/project.dart';import 'package:flutter_tools/src/resident_runner.dart';import 'package:flutter_tools/src/run_cold.dart';import 'package:flutter_tools/src/run_hot.dart';import 'package:flutter_tools/src/vmservice.dart';import 'package:package_config/package_config.dart';import 'package:test/fake.dart';import 'package:vm_service/vm_service.dart' as vm_service;
import '../src/fake_vm_services.dart';
final vm_service.Event fakeUnpausedEvent = vm_service.Event( kind: vm_service.EventKind.kResume, timestamp: 0);
final vm_service.Event fakePausedEvent = vm_service.Event( kind: vm_service.EventKind.kPauseException, timestamp: 0);
final vm_service.Isolate fakeUnpausedIsolate = vm_service.Isolate( id: '1', pauseEvent: fakeUnpausedEvent, breakpoints: <vm_service.Breakpoint>[], extensionRPCs: <String>[], libraries: <vm_service.LibraryRef>[ vm_service.LibraryRef( id: '1', uri: 'file:///hello_world/main.dart', name: '', ), ], livePorts: 0, name: 'test', number: '1', pauseOnExit: false, runnable: true, startTime: 0, isSystemIsolate: false, isolateFlags: <vm_service.IsolateFlag>[],);
final vm_service.Isolate fakePausedIsolate = vm_service.Isolate( id: '1', pauseEvent: fakePausedEvent, breakpoints: <vm_service.Breakpoint>[ vm_service.Breakpoint( breakpointNumber: 123, id: 'test-breakpoint', location: vm_service.SourceLocation( tokenPos: 0, script: vm_service.ScriptRef(id: 'test-script', uri: 'foo.dart'), ), enabled: true, resolved: true, ), ], libraries: <vm_service.LibraryRef>[], livePorts: 0, name: 'test', number: '1', pauseOnExit: false, runnable: true, startTime: 0, isSystemIsolate: false, isolateFlags: <vm_service.IsolateFlag>[],);
final vm_service.VM fakeVM = vm_service.VM( isolates: <vm_service.IsolateRef>[fakeUnpausedIsolate], pid: 1, hostCPU: '', isolateGroups: <vm_service.IsolateGroupRef>[], targetCPU: '', startTime: 0, name: 'dart', architectureBits: 64, operatingSystem: '', version: '', systemIsolateGroups: <vm_service.IsolateGroupRef>[], systemIsolates: <vm_service.IsolateRef>[],);
final FlutterView fakeFlutterView = FlutterView( id: 'a', uiIsolate: fakeUnpausedIsolate,);
final FakeVmServiceRequest listViews = FakeVmServiceRequest( method: kListViewsMethod, jsonResponse: <String, Object>{ 'views': <Object>[ fakeFlutterView.toJson(), ], },);
const FakeVmServiceRequest renderFrameRasterStats = FakeVmServiceRequest( method: kRenderFrameWithRasterStatsMethod, args: <String, Object>{ 'viewId': 'a', 'isolateId': '1', }, error: FakeRPCError( code: RPCErrorCodes.kServerError, error: 'Raster status not supported on Impeller backend', ),);
const FakeVmServiceRequest setAssetBundlePath = FakeVmServiceRequest( method: '_flutter.setAssetBundlePath', args: <String, Object>{ 'viewId': 'a', 'assetDirectory': 'build/flutter_assets', 'isolateId': '1', });
const FakeVmServiceRequest evict = FakeVmServiceRequest( method: 'ext.flutter.evict', args: <String, Object>{ 'value': 'asset', 'isolateId': '1', });
const FakeVmServiceRequest evictShader = FakeVmServiceRequest( method: 'ext.ui.window.reinitializeShader', args: <String, Object>{ 'assetKey': 'foo.frag', 'isolateId': '1', });
final Uri testUri = Uri.parse('foo://bar');
// This implements [dds.DartDevelopmentService], not the [DartDevelopmentService]// interface from package:flutter_tools.class FakeDartDevelopmentService extends Fake implements dds.DartDevelopmentService { @override Future<void> get done => Future<void>.value();
@override Uri? get uri => null;}
class FakeDartDevelopmentServiceException implements dds.DartDevelopmentServiceException { FakeDartDevelopmentServiceException({this.message = defaultMessage});
@override final int errorCode = dds.DartDevelopmentServiceException.existingDdsInstanceError;
@override final String message; static const String defaultMessage = 'A DDS instance is already connected at http://localhost:8181';
@override Map<String, Object?> toJson() => <String, Object?>{ 'error_code': errorCode, 'message': message, };}
class TestFlutterDevice extends FlutterDevice { TestFlutterDevice(super.device, { Stream<Uri>? vmServiceUris }) : _vmServiceUris = vmServiceUris, super(buildInfo: BuildInfo.debug, developmentShaderCompiler: const FakeShaderCompiler());
final Stream<Uri>? _vmServiceUris;
@override Stream<Uri> get vmServiceUris => _vmServiceUris!;}
class ThrowingForwardingFileSystem extends ForwardingFileSystem { ThrowingForwardingFileSystem(super.delegate);
@override File file(dynamic path) { if (path == 'foo') { throw const FileSystemException(); } return delegate.file(path); }}
class FakeFlutterDevice extends Fake implements FlutterDevice { FakeVmServiceHost? Function()? vmServiceHost; Uri? testUri; UpdateFSReport report = UpdateFSReport( success: true, invalidatedSourcesCount: 1, ); Exception? reportError; Exception? runColdError; int runHotCode = 0; int runColdCode = 0;
@override ResidentCompiler? generator;
@override DevelopmentShaderCompiler get developmentShaderCompiler => const FakeShaderCompiler();
@override TargetPlatform targetPlatform = TargetPlatform.android;
@override Stream<Uri?> get vmServiceUris => Stream<Uri?>.value(testUri);
@override FlutterVmService? get vmService => vmServiceHost?.call()?.vmService;
DevFS? fakeDevFS;
@override DevFS? get devFS => fakeDevFS;
@override set devFS(DevFS? value) { }
@override Device? device;
@override Future<void> stopEchoingDeviceLog() async { }
@override Future<void> initLogReader() async { }
@override Future<Uri> setupDevFS(String fsName, Directory rootDirectory) async { return testUri!; }
@override Future<int> runHot({required HotRunner hotRunner, String? route}) async { return runHotCode; }
@override Future<int> runCold({required ColdRunner coldRunner, String? route}) async { if (runColdError != null) { throw runColdError!; } return runColdCode; }
@override Future<void> connect({ ReloadSources? reloadSources, Restart? restart, CompileExpression? compileExpression, GetSkSLMethod? getSkSLMethod, FlutterProject? flutterProject, PrintStructuredErrorLogMethod? printStructuredErrorLogMethod, int? hostVmServicePort, int? ddsPort, bool disableServiceAuthCodes = false, bool enableDds = true, bool cacheStartupProfile = false, required bool allowExistingDdsInstance, bool ipv6 = false, }) async { }
@override Future<UpdateFSReport> updateDevFS({ required Uri mainUri, String? target, AssetBundle? bundle, bool bundleFirstUpload = false, bool bundleDirty = false, bool fullRestart = false, String? projectRootPath, required String pathToReload, required String dillOutputPath, required List<Uri> invalidatedFiles, required PackageConfig packageConfig, }) async { if (reportError != null) { throw reportError!; } return report; }
@override Future<void> updateReloadStatus(bool wasReloadSuccessful) async { }}
class FakeDelegateFlutterDevice extends FlutterDevice { FakeDelegateFlutterDevice( super.device, BuildInfo buildInfo, ResidentCompiler residentCompiler, this.fakeDevFS, ) : super(buildInfo: buildInfo, generator: residentCompiler, developmentShaderCompiler: const FakeShaderCompiler());
@override Future<void> connect({ ReloadSources? reloadSources, Restart? restart, bool enableDds = true, bool cacheStartupProfile = false, bool disableServiceAuthCodes = false, bool ipv6 = false, CompileExpression? compileExpression, GetSkSLMethod? getSkSLMethod, FlutterProject? flutterProject, int? hostVmServicePort, int? ddsPort, PrintStructuredErrorLogMethod? printStructuredErrorLogMethod, bool allowExistingDdsInstance = false, }) async { }
final DevFS fakeDevFS;
@override DevFS? get devFS => fakeDevFS;
@override set devFS(DevFS? value) {}}
class FakeResidentCompiler extends Fake implements ResidentCompiler { CompilerOutput? nextOutput; bool didSuppressErrors = false; Uri? receivedNativeAssetsYaml; bool recompileCalled = false;
@override Future<CompilerOutput?> recompile( Uri mainUri, List<Uri>? invalidatedFiles, { required String outputPath, required PackageConfig packageConfig, String? projectRootPath, required FileSystem fs, bool suppressErrors = false, bool checkDartPluginRegistry = false, File? dartPluginRegistrant, Uri? nativeAssetsYaml, }) async { recompileCalled = true; receivedNativeAssetsYaml = nativeAssetsYaml; didSuppressErrors = suppressErrors; return nextOutput ?? const CompilerOutput('foo.dill', 0, <Uri>[]); }
@override void accept() { }
@override void reset() { }}
class FakeProjectFileInvalidator extends Fake implements ProjectFileInvalidator { @override Future<InvalidationResult> findInvalidated({ required DateTime? lastCompiled, required List<Uri> urisToMonitor, required String packagesPath, required PackageConfig packageConfig, bool asyncScanning = false, }) async { return InvalidationResult( packageConfig: packageConfig, uris: <Uri>[Uri.parse('file:///hello_world/main.dart'), ]); }}
class FakeDevice extends Fake implements Device { FakeDevice({ String sdkNameAndVersion = 'Android', TargetPlatform targetPlatform = TargetPlatform.android_arm, bool isLocalEmulator = false, this.supportsHotRestart = true, this.supportsScreenshot = true, this.supportsFlutterExit = true, }) : _isLocalEmulator = isLocalEmulator, _targetPlatform = targetPlatform, _sdkNameAndVersion = sdkNameAndVersion;
final bool _isLocalEmulator; final TargetPlatform _targetPlatform; final String _sdkNameAndVersion;
bool disposed = false; bool appStopped = false; bool failScreenshot = false;
@override bool supportsHotRestart;
@override bool supportsScreenshot;
@override bool supportsFlutterExit;
@override PlatformType get platformType => _targetPlatform == TargetPlatform.web_javascript ? PlatformType.web : PlatformType.android;
@override Future<String> get sdkNameAndVersion async => _sdkNameAndVersion;
@override Future<TargetPlatform> get targetPlatform async => _targetPlatform;
@override Future<bool> get isLocalEmulator async => _isLocalEmulator;
@override String get name => 'FakeDevice';
@override late DartDevelopmentService dds;
@override Future<void> dispose() async { disposed = true; }
@override Future<bool> stopApp(ApplicationPackage? app, {String? userIdentifier}) async { appStopped = true; return true; }
@override Future<void> takeScreenshot(File outputFile) async { if (failScreenshot) { throw Exception(); } outputFile.writeAsBytesSync(List<int>.generate(1024, (int i) => i)); }
@override FutureOr<DeviceLogReader> getLogReader({ ApplicationPackage? app, bool includePastLogs = false, }) => NoOpDeviceLogReader(name);
@override DevicePortForwarder portForwarder = const NoOpDevicePortForwarder();}
class FakeDevFS extends Fake implements DevFS { @override DateTime? lastCompiled = DateTime(2000);
@override PackageConfig? lastPackageConfig = PackageConfig.empty;
@override List<Uri> sources = <Uri>[];
@override Uri baseUri = Uri();
@override Future<void> destroy() async { }
@override Set<String> assetPathsToEvict = <String>{};
@override Set<String> shaderPathsToEvict = <String>{};
@override Set<String> scenePathsToEvict = <String>{};
@override bool didUpdateFontManifest = false;
UpdateFSReport nextUpdateReport = UpdateFSReport(success: true);
@override bool hasSetAssetDirectory = false;
@override Future<Uri> create() async { return Uri(); }
@override void resetLastCompiled() { lastCompiled = null; }
@override Future<UpdateFSReport> update({ required Uri mainUri, required ResidentCompiler generator, required bool trackWidgetCreation, required String pathToReload, required List<Uri> invalidatedFiles, required PackageConfig packageConfig, required String dillOutputPath, required DevelopmentShaderCompiler shaderCompiler, DevelopmentSceneImporter? sceneImporter, DevFSWriter? devFSWriter, String? target, AssetBundle? bundle, bool bundleFirstUpload = false, bool fullRestart = false, String? projectRootPath, File? dartPluginRegistrant, }) async { return nextUpdateReport; }}
class FakeShaderCompiler implements DevelopmentShaderCompiler { const FakeShaderCompiler();
@override void configureCompiler(TargetPlatform? platform) { }
@override Future<DevFSContent> recompileShader(DevFSContent inputShader) { throw UnimplementedError(); }}.gitattributes+1
NovelForge_Flutter_Development_Report.pdfAdded+3
flutter/packages/flutter_localizations/README.mdAdded+134
flutter/packages/flutter_test/analysis_options.yamlAdded+5
flutter/packages/flutter_test/dart_test.yamlAdded+5
flutter/packages/flutter_test/flutter_test.imlAdded+14
flutter/packages/flutter_test/pubspec.lockAdded+191
flutter/packages/flutter_test/pubspec.yamlAdded+56
flutter/packages/flutter_tools/README.mdAdded+121
flutter/packages/flutter_tools/analysis_options.yamlAdded+12
flutter/packages/flutter_tools/dart_test.yamlAdded+18
flutter/packages/flutter_tools/flutter_tools.imlAdded+21
flutter/packages/flutter_tools/pubspec.lockAdded+741
flutter/packages/flutter_tools/pubspec.yamlAdded+121
flutter/packages/flutter_tools/test/general.shard/android/android_gradle_builder_test.dartAdded+1937
flutter/packages/flutter_tools/test/general.shard/android/android_install_test.dartAdded+318
flutter/packages/flutter_tools/test/general.shard/android/android_project_migration_test.dartAdded+474
flutter/packages/flutter_tools/test/general.shard/devtools_launcher_test.dartAdded+152
flutter/packages/flutter_tools/test/general.shard/emulator_test.dartAdded+405
flutter/packages/flutter_tools/test/general.shard/fake_native_assets_build_runner.dartAdded+97
flutter/packages/flutter_tools/test/general.shard/fake_process_manager_test.dartAdded+323
flutter/packages/flutter_tools/test/general.shard/features_test.dartAdded+412
flutter/packages/flutter_tools/test/general.shard/flutter_manifest_assets_test.dartAdded+163
flutter/packages/flutter_tools/test/general.shard/flutter_manifest_assets_transformers_test.dartAdded+166
flutter/packages/flutter_tools/test/general.shard/flutter_manifest_test.dartAdded+1558
flutter/packages/flutter_tools/test/general.shard/flutter_platform_test.dartAdded+125
flutter/packages/flutter_tools/test/general.shard/flutter_project_metadata_test.dartAdded+202
flutter/packages/flutter_tools/test/general.shard/flutter_tester_device_test.dartAdded+300
flutter/packages/flutter_tools/test/general.shard/flutter_validator_test.dartAdded+647
flutter/packages/flutter_tools/test/general.shard/generate_localizations_test.dartAdded+2535
flutter/packages/flutter_tools/test/general.shard/github_template_test.dartAdded+277
flutter/packages/flutter_tools/test/general.shard/hot_shared.dartAdded+230
flutter/packages/flutter_tools/test/general.shard/hot_test.dartAdded+977
flutter/packages/flutter_tools/test/general.shard/html_utils_test.dartAdded+178
flutter/packages/flutter_tools/test/general.shard/integration_test_device_test.dartAdded+256
flutter/packages/flutter_tools/test/general.shard/license_collector_test.dartAdded+433
flutter/packages/flutter_tools/test/general.shard/mdns_discovery_test.dartAdded+1058
flutter/packages/flutter_tools/test/general.shard/message_parser_test.dartAdded+600
flutter/packages/flutter_tools/test/general.shard/persistent_tool_state_test.dartAdded+58
flutter/packages/flutter_tools/test/general.shard/plugin_parsing_test.dartAdded+423
flutter/packages/flutter_tools/test/general.shard/plugins_test.dartAdded+1954
flutter/packages/flutter_tools/test/general.shard/preview_device_test.dartAdded+208
flutter/packages/flutter_tools/test/general.shard/project_file_invalidator_test.dartAdded+198
flutter/packages/flutter_tools/test/general.shard/project_test.dartAdded+1727
flutter/packages/flutter_tools/test/general.shard/project_validator_result_test.dartAdded+99
flutter/packages/flutter_tools/test/general.shard/protocol_discovery_test.dartAdded+417
flutter/packages/flutter_tools/test/general.shard/pub_dependencies_project_validator_test.dartAdded+77
flutter/packages/flutter_tools/test/general.shard/resident_devtools_handler_test.dartAdded+501
flutter/packages/flutter_tools/test/general.shard/resident_runner_helpers.dartAdded+545
flutter/packages/flutter_tools/test/general.shard/resident_runner_test.dartAdded