diff --git a/.gitattributes b/.gitattributes index 6550f956ffe51f5b226edf6dcbfc667175608548..b7c8d65f8d3904f002404060d9211e409f040aeb 100644 --- a/.gitattributes +++ b/.gitattributes @@ -4,3 +4,4 @@ flutter/bin/cache/** filter=lfs diff=lfs merge=lfs -text novelforge_enhancement_report.pdf filter=lfs diff=lfs merge=lfs -text 001/NovelForge_Flutter_Development_Report.pdf filter=lfs diff=lfs merge=lfs -text +NovelForge_Flutter_Development_Report.pdf filter=lfs diff=lfs merge=lfs -text diff --git a/NovelForge_Flutter_Development_Report.pdf b/NovelForge_Flutter_Development_Report.pdf new file mode 100644 index 0000000000000000000000000000000000000000..c185a0f04b10933e9cec685f9e60e1a9a4c57a06 --- /dev/null +++ b/NovelForge_Flutter_Development_Report.pdf @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:ad0f73d3f651173322ce9271dcce70c29edb7da93893eccd5e16d932d129ed63 +size 512633 diff --git a/flutter/packages/flutter_localizations/README.md b/flutter/packages/flutter_localizations/README.md new file mode 100644 index 0000000000000000000000000000000000000000..96ae11036eb23e6a5109ddff6294aa8017eb9173 --- /dev/null +++ b/flutter/packages/flutter_localizations/README.md @@ -0,0 +1,134 @@ +# Flutter Framework localizations + +This package contains the localizations used by the Flutter framework +itself. + +See the [localization README](./lib/src/l10n/README.md) for more detailed +information about the localizations themselves. + +## Adding a new string to localizations + +If you (someone contributing to the Flutter framework) want to add a new +string to the `MaterialLocalizations`, `WidgetsLocalizations` or the +`CupertinoLocalizations` objects (e.g. because you've added a new widget +and 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 an +existing 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. diff --git a/flutter/packages/flutter_test/analysis_options.yaml b/flutter/packages/flutter_test/analysis_options.yaml new file mode 100644 index 0000000000000000000000000000000000000000..e61f982d45eb553b34c11630b746f0a798cd5b8d --- /dev/null +++ b/flutter/packages/flutter_test/analysis_options.yaml @@ -0,0 +1,5 @@ +include: ../analysis_options.yaml + +analyzer: + exclude: + - "test_fixes/**" diff --git a/flutter/packages/flutter_test/dart_test.yaml b/flutter/packages/flutter_test/dart_test.yaml new file mode 100644 index 0000000000000000000000000000000000000000..fb3b8a21d3fc1f619c6b87d1dc626a8a84c0945f --- /dev/null +++ b/flutter/packages/flutter_test/dart_test.yaml @@ -0,0 +1,5 @@ +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: false diff --git a/flutter/packages/flutter_test/flutter_test.iml b/flutter/packages/flutter_test/flutter_test.iml new file mode 100644 index 0000000000000000000000000000000000000000..b1df2810682090e7d4604cad4a47901a1a09cda6 --- /dev/null +++ b/flutter/packages/flutter_test/flutter_test.iml @@ -0,0 +1,14 @@ + + + + + + + + + + + + + + diff --git a/flutter/packages/flutter_test/pubspec.lock b/flutter/packages/flutter_test/pubspec.lock new file mode 100644 index 0000000000000000000000000000000000000000..98e0cdf5ae4e80484fb6b27510ddde24cae0f489 --- /dev/null +++ b/flutter/packages/flutter_test/pubspec.lock @@ -0,0 +1,191 @@ +# Generated by pub +# See https://dart.dev/tools/pub/glossary#lockfile +packages: + 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" diff --git a/flutter/packages/flutter_test/pubspec.yaml b/flutter/packages/flutter_test/pubspec.yaml new file mode 100644 index 0000000000000000000000000000000000000000..2fbfe812d230c62af15fa7e2596b6a4fc2e5b033 --- /dev/null +++ b/flutter/packages/flutter_test/pubspec.yaml @@ -0,0 +1,56 @@ +name: 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: 6913 diff --git a/flutter/packages/flutter_tools/README.md b/flutter/packages/flutter_tools/README.md new file mode 100644 index 0000000000000000000000000000000000000000..606eacfb3ad5b3fe14e7585e1d56cced4508eab7 --- /dev/null +++ b/flutter/packages/flutter_tools/README.md @@ -0,0 +1,121 @@ +# Flutter Tools + +This section of the Flutter repository contains the command line developer tools +for 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 by +invoking 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 be +tested](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` should +go in a file called `file_test.dart` in the subdirectory that matches +the behavior of the test. + +The `dart_test.yaml` file configures the timeout for these tests to be +15 minutes. The `test.dart` script that is used in CI overrides this +to two seconds for the `test/general.shard` directory, to catch +behaviour 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 engine +variant 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, this +can be provided by setting the `FLUTTER_LOCAL_ENGINE_SRC_PATH` environment +variable. This second variable is not necessary if the `flutter` and `engine` +checkouts are in adjacent directories. + +```shell +export FLUTTER_LOCAL_ENGINE=android_debug_unopt +export FLUTTER_LOCAL_ENGINE_HOST=host_debug_unopt +flutter 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 tests +in `test/general.shard`. Depending on your development computer, you +might want to limit concurrency. Generally it is easier to run these +on CI, or to manually verify the behavior you are changing instead of +running the test. + +The integration tests also require the `FLUTTER_ROOT` environment +variable to be set. The full invocation to run everything might +therefore 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 tests +alone 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 following +files: +```shell +$ rm ../../bin/cache/flutter_tools.stamp ../../bin/cache/flutter_tools.snapshot +``` diff --git a/flutter/packages/flutter_tools/analysis_options.yaml b/flutter/packages/flutter_tools/analysis_options.yaml new file mode 100644 index 0000000000000000000000000000000000000000..ad36811716d5ff044c644cfef66591c9e466dd45 --- /dev/null +++ b/flutter/packages/flutter_tools/analysis_options.yaml @@ -0,0 +1,12 @@ +include: ../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: true diff --git a/flutter/packages/flutter_tools/dart_test.yaml b/flutter/packages/flutter_tools/dart_test.yaml new file mode 100644 index 0000000000000000000000000000000000000000..f437c0fdb2c8a03d88c3208733baae39ddd5a4c6 --- /dev/null +++ b/flutter/packages/flutter_tools/dart_test.yaml @@ -0,0 +1,18 @@ +# 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: false diff --git a/flutter/packages/flutter_tools/flutter_tools.iml b/flutter/packages/flutter_tools/flutter_tools.iml new file mode 100644 index 0000000000000000000000000000000000000000..52d9dae1bbb611916d1d587b1b69f264bc6f632a --- /dev/null +++ b/flutter/packages/flutter_tools/flutter_tools.iml @@ -0,0 +1,21 @@ + + + + + + + + + + + + + + + + + + + + + diff --git a/flutter/packages/flutter_tools/pubspec.lock b/flutter/packages/flutter_tools/pubspec.lock new file mode 100644 index 0000000000000000000000000000000000000000..596cc0c8d8e9fb99530d0be2633ea29fcd2e95ee --- /dev/null +++ b/flutter/packages/flutter_tools/pubspec.lock @@ -0,0 +1,741 @@ +# Generated by pub +# See https://dart.dev/tools/pub/glossary#lockfile +packages: + _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" diff --git a/flutter/packages/flutter_tools/pubspec.yaml b/flutter/packages/flutter_tools/pubspec.yaml new file mode 100644 index 0000000000000000000000000000000000000000..a37d93f1c39c7cab0f368247a2944582e4cf6aef --- /dev/null +++ b/flutter/packages/flutter_tools/pubspec.yaml @@ -0,0 +1,121 @@ +name: flutter_tools +description: Tools for building Flutter applications +homepage: 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: a81b diff --git a/flutter/packages/flutter_tools/test/general.shard/android/android_gradle_builder_test.dart b/flutter/packages/flutter_tools/test/general.shard/android/android_gradle_builder_test.dart new file mode 100644 index 0000000000000000000000000000000000000000..dee0bd409454519198f9c4d7a8ac084d842591b2 --- /dev/null +++ b/flutter/packages/flutter_tools/test/general.shard/android/android_gradle_builder_test.dart @@ -0,0 +1,1937 @@ +// 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: [ + '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( + 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.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: { + 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: [ + '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: [], + ); + expect(processManager, hasNoRemainingExpectations); + }, overrides: { + 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: [ + '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( + 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: { + 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: [ + '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( + 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: { + 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 [ + '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('', [], '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 [], + ); + }, throwsProcessException()); + expect(processManager, hasNoRemainingExpectations); + }, overrides: { + 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: [ + '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: [ + '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( + 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: { + 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: { + 'HOME': '/home', + }, + ), + androidStudio: FakeAndroidStudio(), + ); + processManager.addCommand(const FakeCommand( + command: [ + '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.filled(100, 0))) + ..addFile(ArchiveFile('META-INF/CERT.RSA', 10, List.filled(10, 0))) + ..addFile(ArchiveFile('META-INF/CERT.SF', 10, List.filled(10, 0))) + ..addFile(ArchiveFile('lib/arm64-v8a/libapp.so', 50, List.filled(50, 0))) + ..addFile(ArchiveFile('lib/arm64-v8a/libflutter.so', 50, List.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.arm64_v8a], + ), + target: 'lib/main.dart', + isBuildingBundle: false, + configOnly: false, + localGradleErrors: [], + ); + + expect(testUsage.events, contains( + const TestUsageEvent( + 'code-size-analysis', + 'apk', + ), + )); + }, overrides: { + 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: [ + '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 [], + ); + + expect( + logger.statusText, + contains('Built build/app/outputs/flutter-apk/app-release.apk (0.0MB)'), + ); + expect(processManager, hasNoRemainingExpectations); + }, overrides: { + 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''' + + + + + + + + + + +'''); + + 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: [ + 'gradlew', + '-q', + 'printBuildVariants', + ], + stdout: ''' +BuildVariant: freeDebug +BuildVariant: paidDebug +BuildVariant: freeRelease +BuildVariant: paidRelease +BuildVariant: freeProfile +BuildVariant: paidProfile + ''', + )); + final List actual = await builder.getBuildVariants( + project: FlutterProject.fromDirectoryTest(fileSystem.currentDirectory), + ); + expect(actual, ['freeDebug', 'paidDebug', 'freeRelease', 'paidRelease', 'freeProfile', 'paidProfile']); + + expect( + analyticsTimingEventExists( + sentEvents: fakeAnalytics.sentEvents, + workflow: 'print', + variableName: 'android build variants', + ), + true, + ); + }, overrides: { + 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: [ + 'gradlew', + '-q', + 'printBuildVariants', + ], + stderr: ''' +Gradle Crashed + ''', + exitCode: 1, + )); + final List actual = await builder.getBuildVariants( + project: FlutterProject.fromDirectoryTest(fileSystem.currentDirectory), + ); + expect(actual, const []); + }, overrides: { + 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: [ + '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: { + 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: [ + '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: { + 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: [ + '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: { + 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: [ + '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: { + 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: [ + '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(''' + + + 1.0.0-73fd6b049a80bcea2db1f26c7cee434907cd188b + + + +'''); + 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 [], + ); + }, throwsToolExit()); + expect(processManager, hasNoRemainingExpectations); + }, overrides: { + 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: [ + '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(''' + + + 1.0.0-73fd6b049a80bcea2db1f26c7cee434907cd188b + + + +'''); + 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 [], + ); + }, throwsToolExit()); + expect(processManager, hasNoRemainingExpectations); + }, overrides: { + 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: [ + '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(''' + + + 1.0.0-73fd6b049a80bcea2db1f26c7cee434907cd188b + + + +'''); + 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 [], + ); + }, throwsToolExit()); + expect(processManager, hasNoRemainingExpectations); + }, overrides: { + 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: [ + '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(''' + + + 1.0.0-73fd6b049a80bcea2db1f26c7cee434907cd188b + + + +'''); + 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 [], + ); + }, throwsToolExit()); + expect(processManager, hasNoRemainingExpectations); + }, overrides: { + 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: [ + '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 [], + ); + }, throwsToolExit()); + expect(processManager, hasNoRemainingExpectations); + }, overrides: { + 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: [ + '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(''' + + + 1.0.0-73fd6b049a80bcea2db1f26c7cee434907cd188b + + + +'''); + 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: { + 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: [ + '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(''' + + + 1.0.0-73fd6b049a80bcea2db1f26c7cee434907cd188b + + + +'''); + 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: { + 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: [ + '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(''' + + + 1.0.0-73fd6b049a80bcea2db1f26c7cee434907cd188b + + + +'''); + 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: { + 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: [ + '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(''' + + + 1.0.0-73fd6b049a80bcea2db1f26c7cee434907cd188b + + + +'''); + 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: { + 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'; +} diff --git a/flutter/packages/flutter_tools/test/general.shard/android/android_install_test.dart b/flutter/packages/flutter_tools/test/general.shard/android/android_install_test.dart new file mode 100644 index 0000000000000000000000000000000000000000..21b653f53c23e832a66352218cad0406dd642a7a --- /dev/null +++ b/flutter/packages/flutter_tools/test/general.shard/android/android_install_test.dart @@ -0,0 +1,318 @@ +// 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: ['adb', 'version'], + stdout: 'Android Debug Bridge version 1.0.39', +); +const FakeCommand kAdbStartServerCommand = FakeCommand( + command: ['adb', 'start-server'] +); +const FakeCommand kInstallCommand = FakeCommand( + command: [ + 'adb', + '-s', + '1234', + 'install', + '-t', + '-r', + '--user', + '10', + 'app-debug.apk', + ], +); +const FakeCommand kStoreShaCommand = FakeCommand( + command: ['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([ + kAdbVersionCommand, + kAdbStartServerCommand, + const FakeCommand( + command: ['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([ + kAdbVersionCommand, + kAdbStartServerCommand, + const FakeCommand( + command: ['adb', '-s', '1234', 'shell', 'getprop'], + stdout: '[ro.build.version.sdk]: [16]', + ), + const FakeCommand( + command: ['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([ + kAdbVersionCommand, + kAdbStartServerCommand, + const FakeCommand( + command: ['adb', '-s', '1234', 'shell', 'getprop'], + ), + const FakeCommand( + command: ['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([ + kAdbVersionCommand, + kAdbStartServerCommand, + const FakeCommand( + command: ['adb', '-s', '1234', 'shell', 'getprop'], + ), + // This command is run before the user is checked and is allowed to fail. + const FakeCommand( + command: ['adb', '-s', '1234', 'shell', 'pm', 'list', 'packages', '--user', 'jane', 'app'], + stderr: 'Blah blah', + exitCode: 1, + ), + const FakeCommand( + command: [ + '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([ + kAdbVersionCommand, + kAdbStartServerCommand, + const FakeCommand( + command: ['adb', '-s', '1234', 'shell', 'getprop'], + stdout: '[ro.build.version.sdk]: [16]', + ), + const FakeCommand( + command: ['adb', '-s', '1234', 'shell', 'pm', 'list', 'packages', '--user', '10', 'app'], + stdout: 'package:app\n' + ), + const FakeCommand( + command: ['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([ + kAdbVersionCommand, + kAdbStartServerCommand, + const FakeCommand( + command: ['adb', '-s', '1234', 'shell', 'getprop'], + stdout: '[ro.build.version.sdk]: [16]', + ), + const FakeCommand( + command: ['adb', '-s', '1234', 'shell', 'pm', 'list', 'packages', '--user', '10', 'app'], + stdout: 'package:app\n' + ), + const FakeCommand( + command: ['adb', '-s', '1234', 'shell', 'cat', '/data/local/tmp/sky.app.sha1'], + stdout: 'different_example_sha', + ), + const FakeCommand( + command: ['adb', '-s', '1234', 'install', '-t', '-r', '--user', '10', 'app-debug.apk'], + exitCode: 1, + stderr: '[INSTALL_FAILED_INSUFFICIENT_STORAGE]', + ), + const FakeCommand(command: ['adb', '-s', '1234', 'uninstall', '--user', '10', 'app']), + kInstallCommand, + const FakeCommand(command: ['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([ + kAdbVersionCommand, + kAdbStartServerCommand, + const FakeCommand( + command: ['adb', '-s', '1234', 'shell', 'getprop'], + stdout: '[ro.build.version.sdk]: [16]', + ), + const FakeCommand( + command: ['adb', '-s', '1234', 'shell', 'pm', 'list', 'packages', '--user', '10', 'app'], + stdout: '\n' + ), + const FakeCommand( + command: ['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'; +} diff --git a/flutter/packages/flutter_tools/test/general.shard/android/android_project_migration_test.dart b/flutter/packages/flutter_tools/test/general.shard/android/android_project_migration_test.dart new file mode 100644 index 0000000000000000000000000000000000000000..2d28c6bd2d2f782573430665c70ebf49b715e650 --- /dev/null +++ b/flutter/packages/flutter_tools/test/general.shard/android/android_project_migration_test.dart @@ -0,0 +1,474 @@ +// 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_HOME +distributionPath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-6.6-all.zip +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists +'''; + +const String gradleWrapperToMigrate = r''' +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-6.7-all.zip +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists +'''; + +const String gradleWrapperToMigrateTo = r''' +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-7.6.1-all.zip +zipStoreBase=GRADLE_USER_HOME +zipStorePath=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?'); + } +} diff --git a/flutter/packages/flutter_tools/test/general.shard/devtools_launcher_test.dart b/flutter/packages/flutter_tools/test/general.shard/devtools_launcher_test.dart new file mode 100644 index 0000000000000000000000000000000000000000..94770357bea225d66bb5fd93fb33d347483ca3fd --- /dev/null +++ b/flutter/packages/flutter_tools/test/general.shard/devtools_launcher_test.dart @@ -0,0 +1,152 @@ +// 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 completer = Completer(); + final DevtoolsLauncher launcher = DevtoolsServerLauncher( + dartExecutable: 'dart', + logger: logger, + botDetector: const FakeBotDetector(false), + processManager: FakeProcessManager.list([ + FakeCommand( + command: const [ + '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 completer = Completer(); + final DevtoolsLauncher launcher = DevtoolsServerLauncher( + dartExecutable: 'dart', + logger: logger, + botDetector: const FakeBotDetector(false), + processManager: FakeProcessManager.list([ + FakeCommand( + command: const [ + '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([ + const FakeCommand( + command: [ + '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: ['--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([ + const FakeCommand( + command: [ + 'dart', + 'devtools', + '--no-launch-browser', + '--vm-uri=http://127.0.0.1:1234/abcdefg', + ], + exception: ProcessException('pub', []), + ), + ]), + ); + + 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 completer = Completer(); + final DevtoolsServerLauncher launcher = DevtoolsServerLauncher( + dartExecutable: 'dart', + logger: logger, + botDetector: const FakeBotDetector(true), + processManager: FakeProcessManager.list([ + FakeCommand( + command: const [ + '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()); + }); +} diff --git a/flutter/packages/flutter_tools/test/general.shard/emulator_test.dart b/flutter/packages/flutter_tools/test/general.shard/emulator_test.dart new file mode 100644 index 0000000000000000000000000000000000000000..1e54f5b77434e35ba946524e553306e74c4ef164 --- /dev/null +++ b/flutter/packages/flutter_tools/test/general.shard/emulator_test.dart @@ -0,0 +1,405 @@ +// 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 emulators = [ + 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: ['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([ + const FakeCommand( + command: ['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([ + const FakeCommand( + command: ['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'), [emulator1]); + expect(await testEmulatorManager.getEmulatorsMatching('Nexus_5X'), [emulator2]); + expect(await testEmulatorManager.getEmulatorsMatching('Nexus_5X_API_27_x86'), [emulator2]); + expect(await testEmulatorManager.getEmulatorsMatching('Nexus'), [emulator1, emulator2]); + expect(await testEmulatorManager.getEmulatorsMatching('iOS Simulator'), [emulator3]); + expect(await testEmulatorManager.getEmulatorsMatching('ios'), [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([ + const FakeCommand( + command: ['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([ + const FakeCommand( + command: ['emulator', '-list-avds'], + stdout: 'existing-avd-1', + ), + const FakeCommand( + command: ['avdmanager', 'list', 'device', '-c'], + stdout: 'test\ntest2\npixel\npixel-xl\n', + ), + kListEmulatorsCommand, + const FakeCommand( + command: [ + '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([ + const FakeCommand( + command: ['avdmanager', 'list', 'device', '-c'], + stdout: 'test\ntest2\npixel\npixel-xl\n', + ), + kListEmulatorsCommand, + const FakeCommand( + command: [ + '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([ + const FakeCommand( + command: ['avdmanager', 'list', 'device', '-c'], + stdout: 'test\ntest2\npixel\npixel-xl\n', + ), + kListEmulatorsCommand, + const FakeCommand( + command: [ + '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([ + const FakeCommand( + command: ['emulator', '-list-avds'], + stdout: 'existing-avd-1\nflutter_emulator', + ), + const FakeCommand( + command: ['avdmanager', 'list', 'device', '-c'], + stdout: 'test\ntest2\npixel\npixel-xl\n', + ), + kListEmulatorsCommand, + const FakeCommand( + command: [ + '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( + [ + const FakeCommand( + command: ['/usr/bin/xcode-select', '--print-path'], + stdout: '/fake/Xcode.app/Contents/Developer', + ), + const FakeCommand(command: [ + 'open', + '-n', + '-a', + '/fake/Xcode.app/Contents/Developer/Applications/Simulator.app', + ]), + const FakeCommand(command: [ + 'open', + '-a', + '/fake/Xcode.app/Contents/Developer/Applications/Simulator.app', + ]), + ], + ); + + const Emulator emulator = IOSEmulator('ios'); + await emulator.launch(); + expect(fakeProcessManager, hasNoRemainingExpectations); + }, overrides: { + 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 allEmulators; + + @override + Future> getAllAvailableEmulators() { + return Future>.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 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'; +} diff --git a/flutter/packages/flutter_tools/test/general.shard/fake_native_assets_build_runner.dart b/flutter/packages/flutter_tools/test/general.shard/fake_native_assets_build_runner.dart new file mode 100644 index 0000000000000000000000000000000000000000..db9365180b383914c60a00504bbe3673b477bcaf --- /dev/null +++ b/flutter/packages/flutter_tools/test/general.shard/fake_native_assets_build_runner.dart @@ -0,0 +1,97 @@ +// 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 [], + 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 packagesWithNativeAssetsResult; + final CCompilerConfig cCompilerConfigResult; + final CCompilerConfig ndkCCompilerConfigResult; + + int buildInvocations = 0; + int dryRunInvocations = 0; + int hasPackageConfigInvocations = 0; + int packagesWithNativeAssetsInvocations = 0; + + @override + Future 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 dryRun({ + required bool includeParentEnvironment, + required LinkModePreference linkModePreference, + required OS targetOS, + required Uri workingDirectory, + }) async { + dryRunInvocations++; + return dryRunResult; + } + + @override + Future hasPackageConfig() async { + hasPackageConfigInvocations++; + return hasPackageConfigResult; + } + + @override + Future> packagesWithNativeAssets() async { + packagesWithNativeAssetsInvocations++; + return packagesWithNativeAssetsResult; + } + + @override + Future get cCompilerConfig async => cCompilerConfigResult; + + @override + Future get ndkCCompilerConfig async => cCompilerConfigResult; +} + +final class FakeNativeAssetsBuilderResult + implements native_assets_builder.BuildResult { + const FakeNativeAssetsBuilderResult({ + this.assets = const [], + this.dependencies = const [], + this.success = true, + }); + + @override + final List assets; + + @override + final List dependencies; + + @override + final bool success; +} diff --git a/flutter/packages/flutter_tools/test/general.shard/fake_process_manager_test.dart b/flutter/packages/flutter_tools/test/general.shard/fake_process_manager_test.dart new file mode 100644 index 0000000000000000000000000000000000000000..bfa6478613c61ffa185d010b1b18cfdcfcff5dcb --- /dev/null +++ b/flutter/packages/flutter_tools/test/general.shard/fake_process_manager_test.dart @@ -0,0 +1,323 @@ +// 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 x) => x), 'stderr\u{FFFD}'.codeUnits); + expect((await process.stdout.toList()).expand((List x) => x), 'stdout\u{FFFD}'.codeUnits); + }); + + testWithoutContext('exits after specified delay (if no completer specified)', () { + final bool done = FakeAsync().run((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((FakeAsync time) { + final Completer completer = Completer(); + 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((FakeAsync time) { + final Completer completer = Completer(); + 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((FakeAsync time) { + final Completer completer = Completer(); + 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.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 stderr = []; + final List stdout = []; + 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.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: ['faketool'])); + + final Process process = await manager.start(['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: ['faketool'], + stderr: 'hello', + stdout: 'world', + outputFollowsExit: true, + )); + + final List stderrBytes = []; + final List stdoutBytes = []; + + // Start the process. + final Process process = await manager.start(['faketool']); + final StreamSubscription> stderrSubscription = process.stderr.listen((List chunk) { stderrBytes.addAll(chunk); }); + final StreamSubscription> stdoutSubscription = process.stdout.listen((List 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(>[ + 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: ['faketool'])); + + final ProcessResult result = await manager.run(['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: ['faketool'])); + + final ProcessResult result = await manager.run(['faketool']); + expect(result.exitCode, 0); + expect(result.stdout, isA()); + expect(result.stderr, isA()); + }); + + testWithoutContext('stderr, stdout are List if encoding is null', () async { + manager.addCommand(const FakeCommand(command: ['faketool'])); + + final ProcessResult result = await manager.run( + ['faketool'], + stderrEncoding: null, + stdoutEncoding: null, + ); + expect(result.exitCode, 0); + expect(result.stdout, isA>()); + expect(result.stderr, isA>()); + }); + + testWithoutContext('stderr, stdout are String if encoding is specified', () async { + manager.addCommand(const FakeCommand(command: ['faketool'])); + + final ProcessResult result = await manager.run( + ['faketool'], + stderrEncoding: utf8, + stdoutEncoding: utf8, + ); + expect(result.exitCode, 0); + expect(result.stdout, isA()); + expect(result.stderr, isA()); + }); + }); + + group('runSync', () { + testWithoutContext('can run a fake command', () { + manager.addCommand(const FakeCommand(command: ['faketool'])); + + final ProcessResult result = manager.runSync(['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: ['faketool'])); + + final ProcessResult result = manager.runSync(['faketool']); + expect(result.exitCode, 0); + expect(result.stdout, isA()); + expect(result.stderr, isA()); + }); + + testWithoutContext('stderr, stdout are List if encoding is null', () { + manager.addCommand(const FakeCommand(command: ['faketool'])); + + final ProcessResult result = manager.runSync( + ['faketool'], + stderrEncoding: null, + stdoutEncoding: null, + ); + expect(result.exitCode, 0); + expect(result.stdout, isA>()); + expect(result.stderr, isA>()); + }); + + testWithoutContext('stderr, stdout are String if encoding is specified', () { + manager.addCommand(const FakeCommand(command: ['faketool'])); + + final ProcessResult result = manager.runSync( + ['faketool'], + stderrEncoding: utf8, + stdoutEncoding: utf8, + ); + expect(result.exitCode, 0); + expect(result.stdout, isA()); + expect(result.stderr, isA()); + }); + }); + }); +} diff --git a/flutter/packages/flutter_tools/test/general.shard/features_test.dart b/flutter/packages/flutter_tools/test/general.shard/features_test.dart new file mode 100644 index 0000000000000000000000000000000000000000..07d870b0f536393ed73d095e9fe32aa50740a923 --- /dev/null +++ b/flutter/packages/flutter_tools/test/general.shard/features_test.dart @@ -0,0 +1,412 @@ +// 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: {}); + + 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 = {'FLUTTER_WEB': 'hello'}; + + expect(featureFlags.isWebEnabled, false); + + platform.environment = {'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 = {'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 = {'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 = {'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 = {'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 = {'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 = {'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 = {'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 = {'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 = {'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 = {'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 = {'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 = {'FLUTTER_WINDOWS': 'true'}; + + expect(featureFlags.isWindowsEnabled, true); + }); + + for (final Feature feature in [ + 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 ['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 = {'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); + }); + }); +} diff --git a/flutter/packages/flutter_tools/test/general.shard/flutter_manifest_assets_test.dart b/flutter/packages/flutter_tools/test/general.shard/flutter_manifest_assets_test.dart new file mode 100644 index 0000000000000000000000000000000000000000..b4557a49850edc898b9bfce94f5b24c016ff50e9 --- /dev/null +++ b/flutter/packages/flutter_tools/test/general.shard/flutter_manifest_assets_test.dart @@ -0,0 +1,163 @@ +// 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: test +dependencies: + flutter: + sdk: flutter +flutter: + 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: test +dependencies: + flutter: + sdk: flutter +flutter: + uses-material-design: true + assets: + - a/foo + - a/bar +'''; + + final FlutterManifest flutterManifest = FlutterManifest.createFromString( + manifest, + logger: logger, + )!; + + expect(flutterManifest.assets, [ + 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: test +dependencies: + flutter: + sdk: flutter +flutter: + 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: test +dependencies: + flutter: + sdk: flutter +flutter: + 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 assets = flutterManifest.assets; + + expect(assets, [ + 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: test +dependencies: + flutter: + sdk: flutter +flutter: + uses-material-design: true + assets: + - path: a/foo + flavors: + - apple + - strawberry +'''; + + final FlutterManifest flutterManifest = FlutterManifest.createFromString( + manifest, + logger: logger, + )!; + + expect(flutterManifest.assets, [ + AssetsEntry( + uri: Uri.parse('a/foo'), + flavors: const {'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: test +dependencies: + flutter: + sdk: flutter +flutter: + 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' + )); + }); + }); +} diff --git a/flutter/packages/flutter_tools/test/general.shard/flutter_manifest_assets_transformers_test.dart b/flutter/packages/flutter_tools/test/general.shard/flutter_manifest_assets_transformers_test.dart new file mode 100644 index 0000000000000000000000000000000000000000..228d0bbfc8168aaa92ec3b6412afba506b6edf7d --- /dev/null +++ b/flutter/packages/flutter_tools/test/general.shard/flutter_manifest_assets_transformers_test.dart @@ -0,0 +1,166 @@ +// 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: test +dependencies: + flutter: + sdk: flutter +flutter: + 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( + uri: Uri.parse('asset/hello.txt'), + transformers: const [ + AssetTransformerEntry(package: 'my_package', args: []) + ], + ), + ]); + + expect(logger.errorText, isEmpty); + }); + + testWithoutContext('parses an asset with a transformation that has args', () async { + final BufferLogger logger = BufferLogger.test(); + const String manifest = ''' +name: test +dependencies: + flutter: + sdk: flutter +flutter: + 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( + uri: Uri.parse('asset/hello.txt'), + transformers: const [ + AssetTransformerEntry( + package: 'my_package', + args: ['-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: test +dependencies: + flutter: + sdk: flutter +flutter: + 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: test +dependencies: + flutter: + sdk: flutter +flutter: + 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: test +dependencies: + flutter: + sdk: flutter +flutter: + 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: test +dependencies: + flutter: + sdk: flutter +flutter: + 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', + ); + }); + }); +} diff --git a/flutter/packages/flutter_tools/test/general.shard/flutter_manifest_test.dart b/flutter/packages/flutter_tools/test/general.shard/flutter_manifest_test.dart new file mode 100644 index 0000000000000000000000000000000000000000..dc048f5c8fecd7d46e006dff9d501f506def4db5 --- /dev/null +++ b/flutter/packages/flutter_tools/test/general.shard/flutter_manifest_test.dart @@ -0,0 +1,1558 @@ +// 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: test +dependencies: + 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: test +dependencies: + flutter: + sdk: flutter +flutter: + 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: test +dependencies: + flutter: + sdk: flutter +flutter: + 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: test +dependencies: + flutter: + sdk: flutter +flutter: + 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: test +dependencies: + flutter: + sdk: flutter +flutter: + generate: false +'''; + final FlutterManifest flutterManifest = FlutterManifest.createFromString( + manifest, + logger: logger, + )!; + + expect(flutterManifest.generateSyntheticPackage, false); + }); + + testWithoutContext('FlutterManifest has two assets', () async { + const String manifest = ''' +name: test +dependencies: + flutter: + sdk: flutter +flutter: + uses-material-design: true + assets: + - a/foo + - a/bar +'''; + + final FlutterManifest flutterManifest = FlutterManifest.createFromString( + manifest, + logger: logger, + )!; + + expect(flutterManifest.assets, [ + 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: test +dependencies: + flutter: + sdk: flutter +flutter: + 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: test +dependencies: + flutter: + sdk: flutter +flutter: + 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: { + 'family': 'foo', + 'fonts': [ + {'asset': 'a/bar'}, + ], + }, + fontAssets: [ + 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: test +dependencies: + flutter: + sdk: flutter +flutter: + 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: { + 'family': 'foo', + 'fonts': [ + {'asset': 'a/bar'}, + {'weight': 400, 'asset': 'a/bar'}, + ], + }, + fontAssets: [ + 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: test +dependencies: + flutter: + sdk: flutter +flutter: + 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: { + 'family': 'foo', + 'fonts': [ + {'asset': 'a/bar'}, + {'weight': 400, 'style': 'italic', 'asset': 'a/bar'}, + ], + }, + fontAssets: [ + 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: test +dependencies: + flutter: + sdk: flutter +flutter: + 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([ + matchesFont( + familyName: 'foo', + descriptor: { + 'family': 'foo', + 'fonts': [ + {'asset': 'a/bar'}, + {'weight': 400, 'style': 'italic', 'asset': 'a/bar'}, + ], + }, + fontAssets: [ + matchesFontAsset(assetUri: Uri.parse('a/bar')), + matchesFontAsset(assetUri: Uri.parse('a/bar'), weight: 400, style: 'italic'), + ], + ), + matchesFont( + familyName: 'bar', + descriptor: { + 'family': 'bar', + 'fonts': [ + {'asset': 'a/baz'}, + {'weight': 400, 'style': 'italic', 'asset': 'a/baz'}, + ], + }, + fontAssets: [ + 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: test +dependencies: + flutter: + sdk: flutter +flutter: + 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, [ + { + 'family': 'foo', + 'fonts': [ + {'asset': 'a/bar'}, + {'weight': 400, 'style': 'italic', 'asset': 'a/bar'}, + ], + }, + { + 'family': 'bar', + 'fonts': [ + {'asset': 'a/baz'}, + {'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: test +dependencies: + flutter: + sdk: flutter +flutter: + 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([ + matchesFont( + familyName: 'foo', + descriptor: { + 'family': 'foo', + 'fonts': [ + {'asset': 'a/bar'}, + {'weight': 400, 'style': 'italic', 'asset': 'a/bar'}, + ], + }, + fontAssets: [ + 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: test +dependencies: + flutter: + sdk: flutter +flutter: + 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([ + matchesFont( + familyName: 'foo', + descriptor: { + 'family': 'foo', + 'fonts': [ + {'asset': 'a/bar'}, + {'weight': 400, 'style': 'italic', 'asset': 'a/bar'}, + ], + }, + fontAssets: [ + 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: test +dependencies: + flutter: + sdk: flutter +flutter: + 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: test +dependencies: + flutter: + sdk: flutter +flutter: +'''; + + 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: test +flutter: + 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: test +flutter: + 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: test +flutter: + 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: test +flutter: + 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: test +flutter: + 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: test +version: 1.0.0+2 +dependencies: + flutter: + sdk: flutter +flutter: +'''; + + 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: test +version: 0.0.1 +dependencies: + flutter: + sdk: flutter +flutter: +'''; + + 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: test +version: 1.0.0-beta+exp.sha.5114f85 +dependencies: + flutter: + sdk: flutter +flutter: +'''; + + 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: test +version: 1.0.0+2 +dependencies: + flutter: + sdk: flutter +flutter: +'''; + + 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: test +version: +dependencies: + flutter: + sdk: flutter +flutter: +'''; + + final FlutterManifest? flutterManifest = FlutterManifest.createFromString( + manifest, + logger: logger, + ); + + expect(flutterManifest, matchesManifest()); + }); + + testWithoutContext('FlutterManifest parses no version clause', () { + const String manifest = ''' +name: test +dependencies: + flutter: + sdk: flutter +flutter: +'''; + + 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: test +dependencies: + flutter: + sdk: flutter +flutter: + 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: test +dependencies: + flutter: + sdk: flutter +flutter: + 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: test +dependencies: + flutter: + sdk: flutter +flutter: + 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: test +dependencies: + flutter: + sdk: flutter +flutter: + 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: test +dependencies: + flutter: + sdk: flutter +flutter: + 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: test +dependencies: + flutter: + sdk: flutter +flutter: + 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: test +dependencies: + flutter: + sdk: flutter +flutter: + 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: test +dependencies: + flutter: + sdk: flutter +flutter: + 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 assets = flutterManifest.assets; + + expect(assets, hasLength(3)); + expect(assets, [ + 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: test +dependencies: + flutter: + sdk: flutter +flutter: + - 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: test +dependencies: + flutter: + sdk: flutter +flutter: +'''; + 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: test +dependencies: + flutter: + sdk: flutter +flutter: +'''; + + 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: test +flutter: + 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: test +flutter: + 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: test +flutter: + plugin: + platforms: + some_platform: + pluginClass: SomeClass + ios: + pluginClass: SomeClass +'''; + + final FlutterManifest flutterManifest = FlutterManifest.createFromString( + manifest, + logger: logger, + )!; + + expect(flutterManifest.isPlugin, true); + final Map validSupportedPlatforms = flutterManifest.validSupportedPlatforms!; + expect(validSupportedPlatforms['ios'], + {'pluginClass': 'SomeClass'}); + expect(validSupportedPlatforms['some_platform'], + isNull); + }); + + testWithoutContext('FlutterManifest getSupportedPlatforms returns valid platforms.', () { + const String manifest = ''' +name: test +flutter: + 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 validSupportedPlatforms = flutterManifest.validSupportedPlatforms!; + expect(validSupportedPlatforms['ios'], {'pluginClass': 'SomeClass'}); + expect(validSupportedPlatforms['android'], { + 'pluginClass': 'SomeClass', + 'package': 'com.example', + }); + }); + + testWithoutContext('FlutterManifest validates a platform section that is a list ' + 'instead of a map', () { + const String manifest = ''' +name: test +flutter: + 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: test +flutter: + 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: test +dependencies: + flutter: + sdk: flutter +flutter: + 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: test +dependencies: + flutter: + sdk: flutter +flutter: + licenses: + - foo.txt +'''; + + final FlutterManifest flutterManifest = FlutterManifest.createFromString( + manifest, + logger: logger, + )!; + + expect(flutterManifest.additionalLicenses, ['foo.txt']); + }); + + testWithoutContext('FlutterManifest can validate incorrect licenses key', () async { + const String manifest = ''' +name: test +dependencies: + flutter: + sdk: flutter +flutter: + 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: test +dependencies: + flutter: + sdk: flutter +flutter: + 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: test +dependencies: + flutter: + sdk: flutter +flutter: + deferred-components: + - name: component1 + libraries: + - lib1 + assets: + - path/to/asset.jpg +'''; + + final FlutterManifest flutterManifest = FlutterManifest.createFromString( + manifest, + logger: logger, + )!; + + expect(flutterManifest, isNotNull); + final List 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: test +dependencies: + flutter: + sdk: flutter +flutter: + 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 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: test +dependencies: + flutter: + sdk: flutter +flutter: + 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: test +dependencies: + flutter: + sdk: flutter +flutter: + 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: test +dependencies: + flutter: + sdk: flutter +flutter: + 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: test +dependencies: + flutter: + sdk: flutter +flutter: + 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: test +dependencies: + flutter: + sdk: flutter +flutter: + 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: test +dependencies: + flutter: + sdk: flutter +flutter: + 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: test +dependencies: + flutter: + sdk: flutter +flutter: + 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: test +dependencies: + flutter: + sdk: flutter +flutter: + 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: test +dependencies: + flutter: + sdk: flutter +flutter: + 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: test +dependencies: + flutter: + sdk: flutter +flutter: + 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 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() + .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() + .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 descriptor, + required String familyName, + required List fontAssets, +}) { + return isA() + .having((Font font) => font.descriptor, 'descriptor', descriptor) + .having((Font font) => font.familyName, 'familyName', familyName) + .having((Font font) => font.fontAssets, 'fontAssets', containsAll(fontAssets)); +} diff --git a/flutter/packages/flutter_tools/test/general.shard/flutter_platform_test.dart b/flutter/packages/flutter_tools/test/general.shard/flutter_platform_test.dart new file mode 100644 index 0000000000000000000000000000000000000000..6f4b5f65e6be48b729f470c1049edd7b27cd39e2 --- /dev/null +++ b/flutter/packages/flutter_tools/test/general.shard/flutter_platform_test.dart @@ -0,0 +1,125 @@ +// 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: { + 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: { + 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 expectedPrecompiledDillFiles = {'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'); + }); + }); +} diff --git a/flutter/packages/flutter_tools/test/general.shard/flutter_project_metadata_test.dart b/flutter/packages/flutter_tools/test/general.shard/flutter_project_metadata_test.dart new file mode 100644 index 0000000000000000000000000000000000000000..6e2970faf8b900b25459765429c7c0d8e4dd08b3 --- /dev/null +++ b/flutter/packages/flutter_tools/test/general.shard/flutter_project_metadata_test.dart @@ -0,0 +1,202 @@ +// 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 MAP +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 String')); + }); + + testWithoutContext('version is populated when projectType is malformed', () { + metadataFile + ..createSync() + ..writeAsStringSync(''' +version: + revision: b59b226a49391949247e3d6122e34bb001049ae4 + channel: stable +project_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 MAP +project_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: stable +project_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: stable +project_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: { + FeatureFlags: () => TestFeatureFlags(isNativeAssetsEnabled: true), + }); +} diff --git a/flutter/packages/flutter_tools/test/general.shard/flutter_tester_device_test.dart b/flutter/packages/flutter_tools/test/general.shard/flutter_tester_device_test.dart new file mode 100644 index 0000000000000000000000000000000000000000..d3e035f4e7b3fcf065fe7b6ce8d012c806841dd9 --- /dev/null +++ b/flutter/packages/flutter_tools/test/general.shard/flutter_tester_device_test.dart @@ -0,0 +1,300 @@ +// 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: {}, + ); + processManager = FakeProcessManager.any(); + }); + + FlutterTesterTestDevice createDevice({ + List dartEntrypointArgs = const [], + 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: { + FileSystem: () => fileSystem, + ProcessManager: () => processManager, + }); + + group('The FLUTTER_TEST environment variable is passed to the test process', () { + setUp(() { + processManager = FakeProcessManager.list([]); + device = createDevice(); + + fileSystem + .file('.dart_tool/package_config.json') + ..createSync(recursive: true) + ..writeAsStringSync('{"configVersion":2,"packages":[]}'); + }); + + FakeCommand flutterTestCommand(String expectedFlutterTestValue) { + return FakeCommand(command: const [ + '/', + '--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: { + '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 = {'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 = {'FLUTTER_TEST': 'false'}; + processManager.addCommand(flutterTestCommand('false')); + + await device.start('example.dill'); + expect(processManager, hasNoRemainingExpectations); + }); + + testUsingContext('unchanged when set', () async { + platform.environment = {'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([ + const FakeCommand( + command: [ + '/', + '--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: ['--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([ + const FakeCommand( + command: [ + '/', + '--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 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 _ddsServiceUriCompleter = Completer(); + + Future ddsServiceUriFuture() => _ddsServiceUriCompleter.future; + + @override + Future 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 connectToVmServiceImpl( + Uri httpUri, { + CompileExpression? compileExpression, + required Logger logger, + }) async { + return FakeVmServiceHost(requests: [ + const FakeVmServiceRequest(method: '_serveObservatory'), + ]).vmService; + } + + @override + Future bind(InternetAddress? host, int port) async => FakeHttpServer(); + + @override + Future> get remoteChannel async => StreamChannelController().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; +} diff --git a/flutter/packages/flutter_tools/test/general.shard/flutter_validator_test.dart b/flutter/packages/flutter_tools/test/general.shard/flutter_validator_test.dart new file mode 100644 index 0000000000000000000000000000000000000000..f2cf86389a9198f098155957268ca5406cb8ee16 --- /dev/null +++ b/flutter/packages/flutter_tools/test/general.shard/flutter_validator_test.dart @@ -0,0 +1,647 @@ +// 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() + .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: {}, + ), + flutterVersion: () => flutterVersion, + devToolsVersion: () => '2.8.0', + userMessages: UserMessages(), + artifacts: artifacts, + fileSystem: fileSystem, + flutterRoot: () => '/sdk/flutter', + operatingSystemUtils: FakeOperatingSystemUtils(name: 'Linux'), + processManager: FakeProcessManager.list([ + const FakeCommand( + command: ['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.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: {}, + ), + 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([ + const FakeCommand( + command: ['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.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: {}, + ), + 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('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: { + '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('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: { + '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.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([ + 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([ + 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([ + 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([ + 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 {}, + ), + 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: { + '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().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: { + '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().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: { + '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: { + '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().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 ??= { + '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? 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'); + } +} diff --git a/flutter/packages/flutter_tools/test/general.shard/generate_localizations_test.dart b/flutter/packages/flutter_tools/test/general.shard/generate_localizations_test.dart new file mode 100644 index 0000000000000000000000000000000000000000..74e9964c6e65974269307e1a67666f031730b6ac --- /dev/null +++ b/flutter/packages/flutter_tools/test/general.shard/generate_localizations_test.dart @@ -0,0 +1,2535 @@ +// 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 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? 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().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().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().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().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().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().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().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().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({ + '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({ + '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({ + '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({ + 'en': singleMessageArbFileString, + 'en_CA_foo': singleMessageArbFileString, + }); + }, + throwsA(isA().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({ + '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({ + '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({ + '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({ + '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({ + '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( + { + '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 jsonResult = json.decode( + inputsAndOutputsList.readAsStringSync(), + ) as Map; + expect(jsonResult.containsKey('outputs'), isTrue); + final List outputList = jsonResult['outputs'] as List; + 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({ + '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(context, AppLocalizations);'), + ); + }, + ); + + testWithoutContext( + 'can generate non-nullable localizations class getter via static `of` method ', + () { + final LocalizationsGenerator generator = setupLocalizations({ + '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(context, AppLocalizations)!;'), + ); + }, + ); + + testWithoutContext('creates list of inputs and outputs when file path is specified', () { + setupLocalizations({ + '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 jsonResult = json.decode(inputsAndOutputsList.readAsStringSync()) as Map; + expect(jsonResult.containsKey('inputs'), isTrue); + final List inputList = jsonResult['inputs'] as List; + 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 outputList = jsonResult['outputs'] as List; + 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( + { + '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().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({ + 'en': singleMessageArbFileString, + 'es': singleEsMessageArbFileString, + }, headerFile: 'header.txt'); + }, + throwsA(isA().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: ['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: ['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 preferredSupportedLocale = ['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 preferredSupportedLocale = ['am', 'es']; + expect( + () { + LocalizationsGenerator( + fileSystem: fs, + inputPathString: defaultL10nPathString, + outputPathString: defaultL10nPathString, + templateArbFileName: defaultTemplateArbFileName, + outputFileString: defaultOutputFileString, + classNameString: defaultClassNameString, + preferredSupportedLocales: preferredSupportedLocale, + logger: logger, + ).loadResources(); + }, + throwsA(isA().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().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().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().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().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().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({ + '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({ + 'en': r''' +{ + "helloWorld": "Hello world!" +}''' + }); + expect(getGeneratedFileContent(), contains('/// No description provided for @helloWorld.')); + }); + + testWithoutContext('multiline descriptions are correctly formatted as comments', () { + setupLocalizations({ + '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( { + '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({ + '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({ + '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({ + '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 preferredSupportedLocales = ['zh']; + setupLocalizations({ + '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({ + '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({ + 'en': singleMessageArbFileString, + }, outputFileString: 'asdf'); + }, + throwsA(isA().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({ + 'en': singleMessageArbFileString, + }, outputFileString: '.g.dart'); + }, + throwsA(isA().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({ + '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({ + '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({ + '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({ + '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({ + '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({ + 'en': ''' +{ + "springBegins": "Spring begins on {springStartDate}", + "@springBegins": { + "placeholders": { + "springStartDate": { + "type": "DateTime", + "format": "asdf" + } + } + } +}''' + }); + }, + throwsA(isA().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({ + '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({ + '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({ + 'en': ''' +{ + "springBegins": "Spring begins on {springStartDate}", + "@springBegins": { + "description": "The first day of spring", + "placeholders": { + "springStartDate": { + "type": "DateTime" + } + } + } +}''' + }); + }, + throwsA(isA().having( + (L10nException e) => e.message, + 'message', + contains('the "format" attribute needs to be set'), + )), + ); + }); + }); + + group('NumberFormat tests', () { + testWithoutContext('imports package:intl', () { + setupLocalizations({ + '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({ + '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().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({ + 'en': singleMessageArbFileString, + 'es': singleEsMessageArbFileString, + }); + expect(getGeneratedFileContent(locale: 'es'), isNot(contains(intlImportDartCode))); + }); + + testWithoutContext('warnings are generated when plural parts are repeated', () { + setupLocalizations({ + '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({ + '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({ + '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({ + '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().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({ + '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({ + 'en': ''' +{ + "genderSelect": "{gender, select, female {She} male {He} other {they} }", + "@genderSelect": { + "placeholders": "Incorrectly a string, should be a map." + } +}''' + }); + }, + throwsA(isA().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({ + '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({ + '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({ + '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({ + '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({ + 'en': ''' +{ + "datetime": "{today, date, ::yMd}" +}''' + }); + expect(getGeneratedFileContent(locale: 'en'), contains('String datetime(DateTime today) {')); + }); + + testWithoutContext('should throw on invalid DateFormat', () { + try { + setupLocalizations({ + '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({ + '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({ + '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({ + '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({ + 'en': selectMessageArb, + 'es': selectMessageEsArb, + }); + expect(getGeneratedFileContent(locale: 'en'), contains(intlImportDartCode)); + expect(getGeneratedFileContent(locale: 'es'), contains(intlImportDartCode)); + }); + + testWithoutContext('check indentation on generated files', () { + setupLocalizations({ + '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 supportedLocales = ['), 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({ + '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({ + '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({ + '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({ + '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({ 'en': arbFileWithTrailingComma }); + }, + throwsA(isA().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( + { 'en': arbFileWithMissingResourceAttribute }, + areResourceAttributeRequired: true, + ); + }, + throwsA(isA().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({ 'en': nonAlphaNumericArbFile }), + throwsA(isA().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({ 'en': nonAlphaNumericArbFile }), + throwsA(isA().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({ 'en': nonAlphaNumericArbFile }), + throwsA(isA().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({ '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().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({ + '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()); + + 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({ + '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({ + '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({ '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({ '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( + { '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({ '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({ '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({ '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}) { + ''')); + }); +} diff --git a/flutter/packages/flutter_tools/test/general.shard/github_template_test.dart b/flutter/packages/flutter_tools/test/general.shard/github_template_test.dart new file mode 100644 index 0000000000000000000000000000000000000000..745bec9f15c29e232d7e360abddc2a1ac831757d --- /dev/null +++ b/flutter/packages/flutter_tools/test/general.shard/github_template_test.dart @@ -0,0 +1,277 @@ +// 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', ['path/to/something']) + ), + 'ProcessException: Command: cd, OS error code: 0', + ); + expect( + GitHubTemplateCreator.sanitizedCrashException( + const ProcessException('cd', ['path/to/something'], 'message') + ), + 'ProcessException: message Command: cd, OS error code: 0', + ); + expect( + GitHubTemplateCreator.sanitizedCrashException( + const ProcessException('cd', ['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. (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. (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: { + 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_app +version: 2.0.1+100 +flutter: + 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 Reproduce +1. ... +2. ... +3. ... + +## Logs +ArgumentError: 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 +### Plugins +camera-0.5.7+2 +device_info-0.4.1+4 + +'''; + + expect(actualBody, expectedBody); + }, overrides: { + FileSystem: () => fs, + ProcessManager: () => FakeProcessManager.any(), + }); + }); + }); +} + +class FakeError extends Error { + @override + StackTrace get stackTrace => StackTrace.fromString(''' +#0 _File.open. (dart:io/file_impl.dart:366:9) +#1 _rootRunUnary (dart:async/zone.dart:1141:38)'''); + + @override + String toString() => 'PII to ignore'; +} diff --git a/flutter/packages/flutter_tools/test/general.shard/hot_shared.dart b/flutter/packages/flutter_tools/test/general.shard/hot_shared.dart new file mode 100644 index 0000000000000000000000000000000000000000..30d2c5fc9b29aa3dd902dbedab25fdddf4344818 --- /dev/null +++ b/flutter/packages/flutter_tools/test/general.shard/hot_shared.dart @@ -0,0 +1,230 @@ +// 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 destroy() async { } + + @override + List sources = []; + + @override + DateTime? lastCompiled; + + @override + PackageConfig? lastPackageConfig; + + @override + Set assetPathsToEvict = {}; + + @override + Set shaderPathsToEvict= {}; + + @override + Set scenePathsToEvict= {}; + + @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 get targetPlatform async => _targetPlatform; + + @override + Future get sdkNameAndVersion async => 'Tester'; + + @override + Future get isLocalEmulator async => false; + + @override + String get name => 'Fake Device'; + + @override + Future stopApp( + ApplicationPackage? app, { + String? userIdentifier, + }) async { + return true; + } + + @override + Future dispose() async { + disposed = true; + } +} + +class FakeFlutterDevice extends Fake implements FlutterDevice { + FakeFlutterDevice(this.device); + + bool stoppedEchoingDeviceLog = false; + late Future Function() updateDevFSReportCallback; + + @override + final FakeDevice device; + + @override + Future stopEchoingDeviceLog() async { + stoppedEchoingDeviceLog = true; + } + + @override + DevFS? devFS = FakeDevFs(); + + @override + FlutterVmService get vmService => FakeFlutterVmService(); + + @override + ResidentCompiler? generator; + + @override + Future 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 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 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 setupHotRestart() async { + assert(successfulHotRestartSetup != null, 'setupHotRestart is not expected to be called in this test.'); + return successfulHotRestartSetup; + } + + @override + Future setupHotReload() async { + assert(successfulHotReloadSetup != null, 'setupHotReload is not expected to be called in this test.'); + return successfulHotReloadSetup; + } + + @override + void updateDevFSComplete() { + updateDevFSCompleteCalled = true; + } + + @override + Future 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> getFlutterViews({bool returnEarly = false, Duration delay = const Duration(milliseconds: 50)}) async { + return []; + } +} + +class FakeVmService extends Fake implements vm_service.VmService { + @override + Future getVM() async => FakeVm(); +} + +class FakeVm extends Fake implements vm_service.VM { + @override + List get isolates => []; +} + +class FakeShaderCompiler implements DevelopmentShaderCompiler { + const FakeShaderCompiler(); + + @override + void configureCompiler(TargetPlatform? platform) { } + + @override + Future recompileShader(DevFSContent inputShader) { + throw UnimplementedError(); + } +} diff --git a/flutter/packages/flutter_tools/test/general.shard/hot_test.dart b/flutter/packages/flutter_tools/test/general.shard/hot_test.dart new file mode 100644 index 0000000000000000000000000000000000000000..c357e144cd2297533b2efe8d5eba26342b24db28 --- /dev/null +++ b/flutter/packages/flutter_tools/test/general.shard/hot_test.dart @@ -0,0 +1,977 @@ +// 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({ + 'type': 'ReloadReport', + 'success': false, + 'details': {}, + })), false); + expect(HotRunner.validateReloadReport(vm_service.ReloadReport.parse({ + 'type': 'ReloadReport', + 'success': false, + 'details': { + 'notices': >[ + ], + }, + })), false); + expect(HotRunner.validateReloadReport(vm_service.ReloadReport.parse({ + 'type': 'ReloadReport', + 'success': false, + 'details': { + 'notices': { + 'message': 'error', + }, + }, + })), false); + expect(HotRunner.validateReloadReport(vm_service.ReloadReport.parse({ + 'type': 'ReloadReport', + 'success': false, + 'details': { + 'notices': >[], + }, + })), false); + expect(HotRunner.validateReloadReport(vm_service.ReloadReport.parse({ + 'type': 'ReloadReport', + 'success': false, + 'details': { + 'notices': >[ + {'message': false}, + ], + }, + })), false); + expect(HotRunner.validateReloadReport(vm_service.ReloadReport.parse({ + 'type': 'ReloadReport', + 'success': false, + 'details': { + 'notices': >[ + {'message': ['error']}, + ], + }, + })), false); + expect(HotRunner.validateReloadReport(vm_service.ReloadReport.parse({ + 'type': 'ReloadReport', + 'success': false, + 'details': { + 'notices': >[ + {'message': 'error'}, + {'message': ['error']}, + ], + }, + })), false); + expect(HotRunner.validateReloadReport(vm_service.ReloadReport.parse({ + 'type': 'ReloadReport', + 'success': false, + 'details': { + 'notices': >[ + {'message': 'error'}, + ], + }, + })), false); + expect(HotRunner.validateReloadReport(vm_service.ReloadReport.parse({ + '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 devices = [ + 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: { + 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 devices = [ + fakeFlutterDevice, + ]; + final OperationResult result = await HotRunner( + devices, + debuggingOptions: DebuggingOptions.disabled(BuildInfo.debug), + target: 'main.dart', + devtoolsHandler: createNoOpHandler, + reassembleHelper: ( + List flutterDevices, + Map> viewCache, + void Function(String message)? onSlow, + String reloadMessage, + ) async => ReassembleResult( + {null: null}, + false, + true, + ), + analytics: fakeAnalytics, + ).restart(); + expect(result.isOk, false); + expect(result.message, 'setupHotReload failed'); + expect(failingTestingConfig.updateDevFSCompleteCalled, false); + }, overrides: { + 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 devices = [ + 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: { + 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 devices = [ + 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: { + 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 devices = [ + 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: { + '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, [ + 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: { + 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 devices = [ + 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: { + '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 flutterDevices, + bool? pause, + Map 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 flutterDevices, + Map> viewCache, + void Function(String message)? onSlow, + String reloadMessage, + ) async => ReassembleResult( + {null: null}, + false, + true, + ), + ).restart(); + + expect(result.isOk, true); + expect(testUsage.events, [ + 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: { + 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 devices = [ + 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().having((Exception e) => e.toString(), 'message', 'Exception: updateDevFS failed'))); + expect(testingConfig.updateDevFSCompleteCalled, true); + }, overrides: { + 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 devices = [ + 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().having((Exception e) => e.toString(), 'message', 'Exception: updateDevFS failed'))); + expect(testingConfig.updateDevFSCompleteCalled, true); + }, overrides: { + 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 devices = [ + 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: { + 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 devices = [ + 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 devices = [ + 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('bar', fileSystem.currentDirectory.uri), + ], + dryRunResult: FakeNativeAssetsBuilderResult( + assets: [ + 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: { + 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 devices = [ + 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('bar', fileSystem.currentDirectory.uri), + ], + dryRunResult: FakeNativeAssetsBuilderResult( + assets: [ + 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: { + 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 destroy() async { } + + @override + List sources = []; + + @override + DateTime? lastCompiled; + + @override + PackageConfig? lastPackageConfig; + + @override + Set assetPathsToEvict = {}; + + @override + Set shaderPathsToEvict= {}; + + @override + Set scenePathsToEvict= {}; + + @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 get targetPlatform async => _targetPlatform; + + @override + Future get sdkNameAndVersion async => 'Tester'; + + @override + Future get isLocalEmulator async => false; + + @override + String get name => 'Fake Device'; + + @override + Future stopApp( + ApplicationPackage? app, { + String? userIdentifier, + }) async { + return true; + } + + @override + Future dispose() async { + disposed = true; + } +} + +class FakeFlutterDevice extends Fake implements FlutterDevice { + FakeFlutterDevice(this.device); + + bool stoppedEchoingDeviceLog = false; + late Future Function() updateDevFSReportCallback; + + @override + final FakeDevice device; + + @override + Future stopEchoingDeviceLog() async { + stoppedEchoingDeviceLog = true; + } + + @override + DevFS? devFS = FakeDevFs(); + + @override + FlutterVmService get vmService => FakeFlutterVmService(); + + @override + ResidentCompiler? generator; + + @override + Future 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 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 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 setupHotRestart() async { + assert(successfulHotRestartSetup != null, 'setupHotRestart is not expected to be called in this test.'); + return successfulHotRestartSetup; + } + + @override + Future setupHotReload() async { + assert(successfulHotReloadSetup != null, 'setupHotReload is not expected to be called in this test.'); + return successfulHotReloadSetup; + } + + @override + void updateDevFSComplete() { + updateDevFSCompleteCalled = true; + } + + @override + Future 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> getFlutterViews({bool returnEarly = false, Duration delay = const Duration(milliseconds: 50)}) async { + return []; + } +} + +class FakeVmService extends Fake implements vm_service.VmService { + @override + Future getVM() async => FakeVm(); +} + +class FakeVm extends Fake implements vm_service.VM { + @override + List get isolates => []; +} + +class FakeShaderCompiler implements DevelopmentShaderCompiler { + const FakeShaderCompiler(); + + @override + void configureCompiler( + TargetPlatform? platform, { + required ImpellerStatus impellerStatus, + }) { } + + @override + Future recompileShader(DevFSContent inputShader) { + throw UnimplementedError(); + } +} diff --git a/flutter/packages/flutter_tools/test/general.shard/html_utils_test.dart b/flutter/packages/flutter_tools/test/general.shard/html_utils_test.dart new file mode 100644 index 0000000000000000000000000000000000000000..83a5f0c1a6f62ca7c37732ead7b15787b9b62fe6 --- /dev/null +++ b/flutter/packages/flutter_tools/test/general.shard/html_utils_test.dart @@ -0,0 +1,178 @@ +// 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 = ''' + + + + + + + + + +
+ + + +'''; + +const String htmlSample2 = ''' + + + + + + + + + +
+ + + + + +'''; + +const String htmlSampleLegacyVar = ''' + + + + + + + + + +
+ + + + + +'''; + +String htmlSample2Replaced({ + required String baseHref, + required String serviceWorkerVersion, +}) => + ''' + + + + + + + + + +
+ + + + + +'''; + +const String htmlSample3 = ''' + + + + + + + + +
+ + + +'''; + +void main() { + test('can parse baseHref', () { + expect(IndexHtml('').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('').getBaseHref(), ''); + expect(IndexHtml(htmlSample3).getBaseHref(), ''); + }); + + test('throws on invalid baseHref', () { + expect(() => IndexHtml('').getBaseHref(), throwsToolExit()); + expect(() => IndexHtml('').getBaseHref(), throwsToolExit()); + expect(() => IndexHtml('').getBaseHref(), throwsToolExit()); + expect( + () => IndexHtml('').getBaseHref(), + throwsToolExit(), + ); + expect( + () => IndexHtml('').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'); + }); +} diff --git a/flutter/packages/flutter_tools/test/general.shard/integration_test_device_test.dart b/flutter/packages/flutter_tools/test/general.shard/integration_test_device_test.dart new file mode 100644 index 0000000000000000000000000000000000000000..c3cf3cbe16db4e8f5ac738274205168bf74eec3e --- /dev/null +++ b/flutter/packages/flutter_tools/test/general.shard/integration_test_device_test.dart @@ -0,0 +1,256 @@ +// 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: [], + libraries: [ + 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: [], + extensionRPCs: [kIntegrationTestMethod], +); + +final FlutterView fakeFlutterView = FlutterView( + id: 'a', + uiIsolate: isolate, +); + +final FakeVmServiceRequest listViewsRequest = FakeVmServiceRequest( + method: kListViewsMethod, + jsonResponse: { + 'views': [ + 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: [ + const FakeVmServiceRequest( + method: 'streamListen', + args: { + 'streamId': 'Isolate', + }, + ), + listViewsRequest, + FakeVmServiceRequest( + method: 'getIsolate', + jsonResponse: isolate.toJson(), + args: { + 'isolateId': '1', + }, + ), + const FakeVmServiceRequest( + method: 'streamCancel', + args: { + 'streamId': 'Isolate', + }, + ), + const FakeVmServiceRequest( + method: 'streamListen', + args: { + 'streamId': 'Extension', + }, + ), + ]); + }); + + testUsingContext('will not start when package missing', () async { + await expectLater( + testDevice.start('entrypointPath'), + throwsA( + isA().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: { + 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: { + 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())); + }, overrides: { + 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())); + }, overrides: { + 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 channel = await testDevice.start('entrypointPath'); + await fakeVmServiceHost.vmService.dispose(); + expect(await channel.stream.isEmpty, true); + }, overrides: { + 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 getPackageForPlatform( + TargetPlatform platform, { + BuildInfo? buildInfo, + File? applicationBinary, + }) async => FakeApplicationPackage(); +} + +class FakeApplicationPackage extends Fake implements ApplicationPackage { } diff --git a/flutter/packages/flutter_tools/test/general.shard/license_collector_test.dart b/flutter/packages/flutter_tools/test/general.shard/license_collector_test.dart new file mode 100644 index 0000000000000000000000000000000000000000..5bc1a3419e59e9d4593074d48d9127657ad3fa1d --- /dev/null +++ b/flutter/packages/flutter_tools/test/general.shard/license_collector_test.dart @@ -0,0 +1,433 @@ +// 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 copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, 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 THE +SOFTWARE. +'''; + +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( + { + 'configVersion': 2, + 'packages': [ + { + 'name': 'foo', + 'rootUri': 'file:///foo/', + 'packageUri': 'lib/', + 'languageVersion': '2.2', + }, + { + 'name': 'bar', + 'rootUri': 'file:///bar/', + 'packageUri': 'lib/', + 'languageVersion': '2.2', + }, + { + 'name': 'fizz', + 'rootUri': 'file:///fizz/', + 'packageUri': 'lib/', + 'languageVersion': '2.2', + }, + ], + } + )); + final PackageConfig packageConfig = await loadPackageConfig(packageConfigFile.absolute); + final LicenseResult result = licenseCollector.obtainLicenses(packageConfig, >{}); + + // 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 filePaths = result.dependencies.map((File file) => file.path); + expect(filePaths, unorderedEquals([ + '/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( + { + 'configVersion': 2, + 'packages': [ + { + 'name': 'foo', + 'rootUri': 'file:///foo/', + 'packageUri': 'lib/', + 'languageVersion': '2.2', + }, + { + 'name': 'bar', + 'rootUri': 'file:///bar/', + 'packageUri': 'lib/', + 'languageVersion': '2.2', + }, + ], + } + )); + final PackageConfig packageConfig = await loadPackageConfig(packageConfigFile.absolute); + final LicenseResult result = licenseCollector.obtainLicenses(packageConfig, >{ + 'foo': [fileSystem.file('foo.txt').absolute], + 'bar': [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 filePaths = result.dependencies.map((File file) => file.path); + expect(filePaths, unorderedEquals([ + '/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( + { + 'configVersion': 2, + 'packages': [ + { + 'name': 'foo', + 'rootUri': 'file:///foo/', + 'packageUri': 'lib/', + 'languageVersion': '2.2', + }, + ], + } + )); + final PackageConfig packageConfig = await loadPackageConfig(packageConfigFile.absolute); + + final LicenseResult licenseResult = licenseCollector.obtainLicenses(packageConfig, >{ + 'foo': [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, [ + '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([0xFFFE]); + + final File packageConfigFile = fileSystem.file('package_config.json') + ..writeAsStringSync(json.encode( + { + 'configVersion': 2, + 'packages': [ + { + 'name': 'foo', + 'rootUri': 'file:///foo/', + 'packageUri': 'lib/', + 'languageVersion': '2.2', + }, + ], + } + )); + final PackageConfig packageConfig = await loadPackageConfig(packageConfigFile.absolute); + + final LicenseResult licenseResult = licenseCollector.obtainLicenses(packageConfig, >{ + 'foo': [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'", + ); + }); +} diff --git a/flutter/packages/flutter_tools/test/general.shard/mdns_discovery_test.dart b/flutter/packages/flutter_tools/test/general.shard/mdns_discovery_test.dart new file mode 100644 index 0000000000000000000000000000000000000000..79aa29a9201da155c6dceaab1e7a45f71f4b86ef --- /dev/null +++ b/flutter/packages/flutter_tools/test/general.shard/mdns_discovery_test.dart @@ -0,0 +1,1058 @@ +// 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 => [], + ); + }); + + tearDown(() { + resetNetworkInterfaceLister(); + }); + + group('for attach', () { + late MDnsClient emptyClient; + + setUp(() { + emptyClient = FakeMDnsClient([], >{}); + }); + + testWithoutContext('Find result in preliminary client', () async { + final MDnsClient client = FakeMDnsClient( + [ + PtrResourceRecord('foo', future, domainName: 'bar'), + ], + >{ + 'bar': [ + 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('foo', future, domainName: 'bar'), + ], + >{ + 'bar': [ + 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('foo', future, domainName: 'bar'), + PtrResourceRecord('baz', future, domainName: 'fiz'), + ], + >{ + 'bar': [ + SrvResourceRecord('bar', future, port: 123, weight: 1, priority: 1, target: 'appId'), + ], + 'fiz': [ + 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('foo', future, domainName: 'bar'), + PtrResourceRecord('foo', future, domainName: 'bar'), + ], + >{ + 'bar': [ + 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('foo', future, domainName: 'bar'), + PtrResourceRecord('foo', future, domainName: 'bar (2)'), + ], + >{ + 'bar': [ + SrvResourceRecord('bar', future, port: 123, weight: 1, priority: 1, target: 'appId'), + ], + 'bar (2)': [ + 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('foo', future, domainName: 'bar'), + ], + >{ + 'bar': [ + 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('foo', future, domainName: 'bar'), + ], + >{ + 'bar': [ + SrvResourceRecord('bar', future, port: 123, weight: 1, priority: 1, target: 'appId'), + ], + }, + txtResponse: >{ + 'bar': [ + 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('foo', future, domainName: 'bar'), + PtrResourceRecord('baz', future, domainName: 'fiz'), + ], + >{ + 'bar': [ + SrvResourceRecord('bar', future, port: 123, weight: 1, priority: 1, target: 'appId'), + ], + 'fiz': [ + 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('foo', future, domainName: 'bar'), + PtrResourceRecord('baz', future, domainName: 'fiz'), + ], + >{ + 'bar': [ + SrvResourceRecord('bar', future, port: 1234, weight: 1, priority: 1, target: 'appId'), + SrvResourceRecord('bar', future, port: 123, weight: 1, priority: 1, target: 'appId'), + ], + 'fiz': [ + 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( + [], >{}, + 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('foo', future, domainName: 'bar'), + ], + >{ + 'bar': [ + 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('foo', future, domainName: 'bar'), + ], + >{ + 'bar': [ + SrvResourceRecord('bar', future, port: 1234, weight: 1, priority: 1, target: 'appId'), + ], + }, + ipResponse: >{ + 'appId': [ + IPAddressResourceRecord('Device IP', 0, address: InternetAddress.tryParse('111.111.111.111')!), + ], + }, + txtResponse: >{ + 'bar': [ + 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('foo', future, domainName: 'bar'), + ], + >{ + 'bar': [ + SrvResourceRecord('bar', future, port: 1234, weight: 1, priority: 1, target: 'appId'), + ], + }, + ipResponse: >{ + 'appId': [ + IPAddressResourceRecord('Device IP', 0, address: InternetAddress.tryParse('1111:1111:1111:1111:1111:1111:1111:1111')!), + ], + }, + txtResponse: >{ + 'bar': [ + 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('foo', future, domainName: 'srv-foo'), + PtrResourceRecord('bar', future, domainName: 'srv-bar'), + PtrResourceRecord('baz', future, domainName: 'srv-boo'), + ], + >{ + 'srv-foo': [ + SrvResourceRecord('srv-foo', future, port: 123, weight: 1, priority: 1, target: 'target-foo'), + ], + 'srv-bar': [ + SrvResourceRecord('srv-bar', future, port: 123, weight: 1, priority: 1, target: 'target-bar'), + ], + 'srv-baz': [ + 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('foo', future, domainName: 'srv-foo'), + ], + >{ + 'srv-foo': [ + 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([], >{}); + + 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([], >{}); + + 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([], >{}); + 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( + [], >{}, + 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('foo', future, domainName: 'bar'), + ], + >{ + 'bar': [ + 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('foo', future, domainName: 'bar'), + ], + >{ + 'bar': [ + SrvResourceRecord('bar', future, port: 1234, weight: 1, priority: 1, target: 'appId'), + ], + }, + ipResponse: >{ + 'appId': [ + IPAddressResourceRecord('Device IP', 0, address: InternetAddress.tryParse('111.111.111.111')!), + ], + }, + txtResponse: >{ + 'bar': [ + 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('foo', future, domainName: 'bar'), + ], + >{ + 'bar': [ + SrvResourceRecord('bar', future, port: 1234, weight: 1, priority: 1, target: 'appId'), + ], + }, + ipResponse: >{ + 'appId': [ + IPAddressResourceRecord('Device IP', 0, address: InternetAddress.tryParse('1111:1111:1111:1111:1111:1111:1111:1111')!), + ], + }, + txtResponse: >{ + 'bar': [ + 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('foo', future, domainName: 'srv-foo'), + PtrResourceRecord('bar', future, domainName: 'srv-bar'), + PtrResourceRecord('baz', future, domainName: 'srv-boo'), + ], + >{ + 'srv-foo': [ + SrvResourceRecord('srv-foo', future, port: 123, weight: 1, priority: 1, target: 'target-foo'), + ], + 'srv-bar': [ + SrvResourceRecord('srv-bar', future, port: 123, weight: 1, priority: 1, target: 'target-bar'), + ], + 'srv-baz': [ + 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('foo', future, domainName: 'srv-foo'), + PtrResourceRecord('bar', future, domainName: 'srv-bar'), + PtrResourceRecord('baz', future, domainName: 'srv-boo'), + ], + >{ + 'srv-bar': [ + 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('foo', future, domainName: 'srv-foo'), + PtrResourceRecord('bar', future, domainName: 'srv-bar'), + PtrResourceRecord('baz', future, domainName: 'srv-boo'), + ], + >{ + 'srv-foo': [ + 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( + [], + >{}, + ), + 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( + [], + >{}, + ), + 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('foo', future, domainName: 'srv-foo'), + PtrResourceRecord('bar', future, domainName: 'srv-bar'), + PtrResourceRecord('baz', future, domainName: 'srv-boo'), + ], + >{ + 'srv-foo': [ + SrvResourceRecord('srv-foo', future, port: 123, weight: 1, priority: 1, target: 'target-foo'), + ], + 'srv-bar': [ + SrvResourceRecord('srv-bar', future, port: 123, weight: 1, priority: 1, target: 'target-bar'), + ], + 'srv-baz': [ + 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('foo', future, domainName: 'srv-foo'), + PtrResourceRecord('bar', future, domainName: 'srv-bar'), + PtrResourceRecord('baz', future, domainName: 'srv-boo'), + ], + >{ + 'srv-foo': [ + SrvResourceRecord('srv-foo', future, port: 111, weight: 1, priority: 1, target: 'target-foo'), + ], + 'srv-bar': [ + 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('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('foo', future, domainName: 'srv-foo'), + ], + >{ + 'srv-foo': [ + SrvResourceRecord('srv-foo', future, port: 111, weight: 1, priority: 1, target: 'target-foo'), + ], + }, + ipResponse: >{ + 'target-foo': [ + 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('foo', future, domainName: 'srv-foo'), + ], + >{ + 'srv-foo': [ + SrvResourceRecord('srv-foo', future, port: 111, weight: 1, priority: 1, target: 'target-foo'), + ], + }, + txtResponse: >{ + 'srv-foo': [ + TxtResourceRecord('srv-foo', future, text: ''), + ], + }, + ipResponse: >{ + 'target-foo': [ + 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('foo', future, domainName: 'srv-foo'), + ], + >{ + 'srv-foo': [ + SrvResourceRecord('srv-foo', future, port: 111, weight: 1, priority: 1, target: 'target-foo'), + ], + }, + txtResponse: >{ + 'srv-foo': [ + TxtResourceRecord('srv-foo', future, text: 'authCode=xyz\n'), + ], + }, + ipResponse: >{ + 'target-foo': [ + 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 >{}, + this.ipResponse = const >{}, + this.osErrorOnStart = false, + }); + + final List ptrRecords; + final Map> srvResponse; + final Map> txtResponse; + final Map> ipResponse; + final bool osErrorOnStart; + + @override + Future start({ + InternetAddress? listenAddress, + NetworkInterfacesFactory? interfacesFactory, + int mDnsPort = 5353, + InternetAddress? mDnsAddress, + }) async { + if (osErrorOnStart) { + throw const OSError('Operation not supported on socket', 102); + } + } + + @override + Stream lookup( + ResourceRecordQuery query, { + Duration timeout = const Duration(seconds: 5), + }) { + if (T == PtrResourceRecord && query.fullyQualifiedName == MDnsVmServiceDiscovery.dartVmServiceName) { + return Stream.fromIterable(ptrRecords) as Stream; + } + if (T == SrvResourceRecord) { + final String key = query.fullyQualifiedName; + return Stream.fromIterable(srvResponse[key] ?? []) as Stream; + } + if (T == TxtResourceRecord) { + final String key = query.fullyQualifiedName; + return Stream.fromIterable(txtResponse[key] ?? []) as Stream; + } + if (T == IPAddressResourceRecord) { + final String key = query.fullyQualifiedName; + return Stream.fromIterable(ipResponse[key] ?? []) as Stream; + } + 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 get targetPlatform async => TargetPlatform.ios; + + @override + bool isSupported() => true; + + @override + bool isSupportedForProject(FlutterProject flutterProject) => true; + + @override + DevicePortForwarder get portForwarder => const NoOpDevicePortForwarder(); +} diff --git a/flutter/packages/flutter_tools/test/general.shard/message_parser_test.dart b/flutter/packages/flutter_tools/test/general.shard/message_parser_test.dart new file mode 100644 index 0000000000000000000000000000000000000000..3b716cd3c05aed087eeea7a067a219ad00233089 --- /dev/null +++ b/flutter/packages/flutter_tools/test/general.shard/message_parser_test.dart @@ -0,0 +1,600 @@ +// 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.openBrace(0), + Node.string(1, 'var'), + Node.closeBrace(4), + ], + ); + + final Node expected = Node( + ST.placeholderExpr, + 0, + expectedSymbolCount: 3, + children: [ + 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.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.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.string(1, 'var'), + Node.closeBrace(4), + ], + ); + expect(actual, isNot(equals(wrongChildrenCount))); + + final Node wrongChild = Node( + ST.placeholderExpr, + 0, + expectedSymbolCount: 3, + children: [ + Node.closeBrace(0), + Node.string(1, 'var'), + Node.closeBrace(4), + ], + ); + expect(actual, isNot(equals(wrongChild))); + }); + + testWithoutContext('lexer basic', () { + final List tokens1 = Parser( + 'helloWorld', + 'app_en.arb', + 'Hello {name}' + ).lexIntoTokens(); + expect(tokens1, equals([ + Node.string(0, 'Hello '), + Node.openBrace(6), + Node.identifier(7, 'name'), + Node.closeBrace(11), + ])); + + final List tokens2 = Parser( + 'plural', + 'app_en.arb', + 'There are {count} {count, plural, =1{cat} other{cats}}' + ).lexIntoTokens(); + expect(tokens2, equals([ + 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 tokens3 = Parser( + 'gender', + 'app_en.arb', + '{gender, select, male{he} female{she} other{they}}' + ).lexIntoTokens(); + expect(tokens3, equals([ + 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 tokens = Parser( + 'plural', + 'app_en.arb', + '{count, plural, =1{{gender, select, male{he} female{she}}} other{they}}' + ).lexIntoTokens(); + expect(tokens, equals([ + 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 tokens1 = Parser('escaping', 'app_en.arb', "''", useEscaping: true).lexIntoTokens(); + expect(tokens1, equals([Node.string(0, "'")])); + + final List tokens2 = Parser('escaping', 'app_en.arb', "'hello world { name }'", useEscaping: true).lexIntoTokens(); + expect(tokens2, equals([Node.string(0, 'hello world { name }')])); + + final List tokens3 = Parser('escaping', 'app_en.arb', "'{ escaped string }' { not escaped }", useEscaping: true).lexIntoTokens(); + expect(tokens3, equals([ + Node.string(0, '{ escaped string }'), + Node.string(20, ' '), + Node.openBrace(21), + Node.identifier(23, 'not'), + Node.identifier(27, 'escaped'), + Node.closeBrace(35), + ])); + + final List tokens4 = Parser('escaping', 'app_en.arb', "Flutter''s amazing!", useEscaping: true).lexIntoTokens(); + expect(tokens4, equals([ + Node.string(0, 'Flutter'), + Node.string(7, "'"), + Node.string(9, 's amazing!'), + ])); + + final List tokens5 = Parser('escaping', 'app_en.arb', "'Flutter''s amazing!'", useEscaping: true).lexIntoTokens(); + expect(tokens5, equals([ + Node(ST.string, 0, value: 'Flutter'), + Node(ST.string, 9, value: "'s amazing!"), + ])); + }); + + testWithoutContext('lexer identifier names can be "select" or "plural"', () { + final List 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 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 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 tokens = Parser( + 'syntax', + 'app_en.arb', + 'string { identifier { string { identifier } } }' + ).lexIntoTokens(); + expect(tokens, equals([ + 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().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().having( + (L10nException e) => e.message, + 'message', + contains(expectedError), + ))); + }); + + testWithoutContext('relaxed lexer', () { + final List tokens1 = Parser( + 'string', + 'app_en.arb', + '{ }', + placeholders: [], + ).lexIntoTokens(); + expect(tokens1, equals([ + Node(ST.string, 0, value: '{'), + Node(ST.string, 1, value: ' '), + Node(ST.string, 2, value: '}') + ])); + + final List tokens2 = Parser( + 'string', + 'app_en.arb', + '{ notAPlaceholder }', + placeholders: ['isAPlaceholder'], + ).lexIntoTokens(); + expect(tokens2, equals([ + Node(ST.string, 0, value: '{'), + Node(ST.string, 1, value: ' notAPlaceholder '), + Node(ST.string, 18, value: '}') + ])); + + final List tokens3 = Parser( + 'string', + 'app_en.arb', + '{ isAPlaceholder }', + placeholders: ['isAPlaceholder'], + ).lexIntoTokens(); + expect(tokens3, equals([ + 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 tokens = Parser( + 'string', + 'app_en.arb', + message, + placeholders: ['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(ST.string, 0, value: 'Hello '), + Node(ST.placeholderExpr, 6, children: [ + 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(ST.string, 0, value: 'Today is '), + Node(ST.argumentExpr, 9, children: [ + Node(ST.openBrace, 9, value: '{'), + Node(ST.identifier, 10, value: 'date'), + Node(ST.comma, 14, value: ','), + Node(ST.argType, 16, children: [ + 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(ST.string, 0, value: 'There are '), + Node(ST.placeholderExpr, 10, children: [ + 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(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(ST.pluralPart, 34, children: [ + Node(ST.equalSign, 34, value: '='), + Node(ST.number, 35, value: '1'), + Node(ST.openBrace, 36, value: '{'), + Node(ST.message, 37, children: [ + Node(ST.string, 37, value: 'cat') + ]), + Node(ST.closeBrace, 40, value: '}') + ]), + Node(ST.pluralPart, 42, children: [ + Node(ST.other, 42, value: 'other'), + Node(ST.openBrace, 47, value: '{'), + Node(ST.message, 48, children: [ + 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(ST.selectExpr, 0, children: [ + 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(ST.selectPart, 17, children: [ + Node(ST.identifier, 17, value: 'male'), + Node(ST.openBrace, 21, value: '{'), + Node(ST.message, 22, children: [ + Node(ST.string, 22, value: 'he'), + ]), + Node(ST.closeBrace, 24, value: '}'), + ]), + Node(ST.selectPart, 26, children: [ + Node(ST.identifier, 26, value: 'female'), + Node(ST.openBrace, 32, value: '{'), + Node(ST.message, 33, children: [ + Node(ST.string, 33, value: 'she'), + ]), + Node(ST.closeBrace, 36, value: '}'), + ]), + Node(ST.selectPart, 38, children: [ + Node(ST.other, 38, value: 'other'), + Node(ST.openBrace, 43, value: '{'), + Node(ST.message, 44, children: [ + 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(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(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(ST.pluralExpr, 0, children: [ + 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(ST.pluralPart, 16, children: [ + Node(ST.equalSign, 16, value: '='), + Node(ST.number, 17, value: '1'), + Node(ST.openBrace, 18, value: '{'), + Node(ST.message, 19, children: [ + Node(ST.selectExpr, 19, children: [ + 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(ST.selectPart, 36, children: [ + Node(ST.identifier, 36, value: 'male'), + Node(ST.openBrace, 40, value: '{'), + Node(ST.message, 41, children: [ + Node(ST.string, 41, value: 'he'), + ]), + Node(ST.closeBrace, 43, value: '}'), + ]), + Node(ST.selectPart, 45, children: [ + Node(ST.identifier, 45, value: 'female'), + Node(ST.openBrace, 51, value: '{'), + Node(ST.message, 52, children: [ + Node(ST.string, 52, value: 'she'), + ]), + Node(ST.closeBrace, 55, value: '}'), + ]), + Node(ST.selectPart, 57, children: [ + Node(ST.other, 57, value: 'other'), + Node(ST.openBrace, 62, value: '{'), + Node(ST.message, 63, children: [ + 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(ST.other, 71, value: 'other'), + Node(ST.openBrace, 76, value: '{'), + Node(ST.message, 77, children: [ + 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().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().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().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('}')); + }); +} diff --git a/flutter/packages/flutter_tools/test/general.shard/persistent_tool_state_test.dart b/flutter/packages/flutter_tools/test/general.shard/persistent_tool_state_test.dart new file mode 100644 index 0000000000000000000000000000000000000000..924b49e18cf2ecb31c72ff47f65136bea88d0186 --- /dev/null +++ b/flutter/packages/flutter_tools/test/general.shard/persistent_tool_state_test.dart @@ -0,0 +1,58 @@ +// 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'); + }); +} diff --git a/flutter/packages/flutter_tools/test/general.shard/plugin_parsing_test.dart b/flutter/packages/flutter_tools/test/general.shard/plugin_parsing_test.dart new file mode 100644 index 0000000000000000000000000000000000000000..2c534642f7b14dea9cc1c72fbd34f2871f636604 --- /dev/null +++ b/flutter/packages/flutter_tools/test/general.shard/plugin_parsing_test.dart @@ -0,0 +1,423 @@ +// 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 [], + 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 [], + 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 [], + 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 [], + 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 [], + 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 [], + fileSystem: fileSystem, + ); + + expect(plugin.platforms, {}); + expect(plugin.defaultPackagePlatforms, { + 'android': 'sample_package_android', + 'ios': 'sample_package_ios', + 'linux': 'sample_package_linux', + 'macos': 'sample_package_macos', + 'windows': 'sample_package_windows', + }); + expect(plugin.pluginDartClassPlatforms, {}); + }); + + 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 [], + fileSystem: fileSystem, + ); + + expect(plugin.pluginDartClassPlatforms, { + '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 [], + fileSystem: fileSystem, + ); + + final WindowsPlugin windowsPlugin = plugin.platforms[WindowsPlugin.kConfigKey]! as WindowsPlugin; + expect(windowsPlugin.supportedVariants, [ + 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 [], + 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 [], + fileSystem: fileSystem, + ); + + final WindowsPlugin windowsPlugin = plugin.platforms[WindowsPlugin.kConfigKey]! as WindowsPlugin; + expect(windowsPlugin.supportedVariants, [ + 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 [], + fileSystem: fileSystem, + ); + + final WindowsPlugin windowsPlugin = plugin.platforms[WindowsPlugin.kConfigKey]! as WindowsPlugin; + expect(windowsPlugin.supportedVariants, {}); + }); + + 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 [], + 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 [], + 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 [], + fileSystem: fileSystem, + ), + throwsToolExit(message: 'Invalid "android" plugin specification.'), + ); + }); +} diff --git a/flutter/packages/flutter_tools/test/general.shard/plugins_test.dart b/flutter/packages/flutter_tools/test/general.shard/plugins_test.dart new file mode 100644 index 0000000000000000000000000000000000000000..a1787c011638ea585c17289fe4e8b68ce346d08a --- /dev/null +++ b/flutter/packages/flutter_tools/test/general.shard/plugins_test.dart @@ -0,0 +1,1954 @@ +// 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 [ + 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 createFakePlugins(FileSystem fileSystem, List 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 directories = []; + 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, ['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 dependencies, + }) { + + final Directory pluginDirectory = fs.systemTempDirectory.createTempSync('flutter_plugin.'); + pluginDirectory + .childFile('pubspec.yaml') + .writeAsStringSync(''' +name: $name +flutter: + plugin: + androidPackage: plugin2 + pluginClass: UseNewEmbedding +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; + } + + Directory createPlugin({ + required String name, + required Map platforms, + List dependencies = const [], + }) { + + final Iterable platformSections = platforms.entries.map((MapEntry entry) => ''' + ${entry.key}: +${entry.value.indentedPubspecSection} +'''); + final Directory pluginDirectory = fs.systemTempDirectory.createTempSync('flutter_plugin.'); + pluginDirectory + .childFile('pubspec.yaml') + .writeAsStringSync(''' +name: $name +flutter: + 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: { + 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: { + FileSystem: () => fs, + ProcessManager: () => FakeProcessManager.any(), + }); + + testUsingContext('Refreshing the plugin list creates a sorted plugin directory when there are plugins', () async { + createFakePlugins(fs, [ + '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: { + 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 ['plugin-b', 'plugin-c', 'random-package']); + final Directory pluginB = createLegacyPluginWithDependencies(name: 'plugin-b', dependencies: const ['plugin-c']); + final Directory pluginC = createLegacyPluginWithDependencies(name: 'plugin-c', dependencies: const []); + 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 jsonContent = json.decode(pluginsString) as Map; + expect(jsonContent['info'], 'This is a generated file; do not edit or check into version control.'); + + final Map plugins = jsonContent['plugins'] as Map; + final List expectedPlugins = [ + { + 'name': 'plugin-a', + 'path': '${pluginA.path}/', + 'native_build': true, + 'dependencies': [ + 'plugin-b', + 'plugin-c', + ], + }, + { + 'name': 'plugin-b', + 'path': '${pluginB.path}/', + 'native_build': true, + 'dependencies': [ + 'plugin-c', + ], + }, + { + 'name': 'plugin-c', + 'path': '${pluginC.path}/', + 'native_build': true, + 'dependencies': [], + }, + ]; + expect(plugins['ios'], expectedPlugins); + expect(plugins['android'], expectedPlugins); + expect(plugins['macos'], []); + expect(plugins['windows'], []); + expect(plugins['linux'], []); + expect(plugins['web'], []); + + final List expectedDependencyGraph = [ + { + 'name': 'plugin-a', + 'dependencies': [ + 'plugin-b', + 'plugin-c', + ], + }, + { + 'name': 'plugin-b', + 'dependencies': [ + 'plugin-c', + ], + }, + { + 'name': 'plugin-c', + 'dependencies': [], + }, + ]; + + 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 expectedKeys = [ + 'info', + 'plugins', + 'dependencyGraph', + 'date_created', + 'version', + ]; + expect(jsonContent.keys, expectedKeys); + }, overrides: { + FileSystem: () => fs, + ProcessManager: () => FakeProcessManager.any(), + SystemClock: () => systemClock, + FlutterVersion: () => flutterVersion, + }); + + testUsingContext( + '.flutter-plugins-dependencies contains plugin platform info', () async { + createPlugin( + name: 'plugin-a', + platforms: const { + // 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 jsonContent = json.decode(pluginsString) as Map; + final Map? actualPlugins = jsonContent['plugins'] as Map?; + + final Map expectedPlugins = { + 'ios': >[ + { + 'name': 'plugin-a', + 'path': '/.tmp_rand0/flutter_plugin.rand0/', + 'shared_darwin_source': true, + 'native_build': true, + 'dependencies': [] + } + ], + 'android': >[ + { + 'name': 'plugin-a', + 'path': '/.tmp_rand0/flutter_plugin.rand0/', + 'native_build': true, + 'dependencies': [] + } + ], + 'macos': >[], + 'linux': >[], + 'windows': >[ + { + 'name': 'plugin-a', + 'path': '/.tmp_rand0/flutter_plugin.rand0/', + 'native_build': false, + 'dependencies': [] + } + ], + 'web': >[ + { + 'name': 'plugin-a', + 'path': '/.tmp_rand0/flutter_plugin.rand0/', + 'dependencies': [] + } + ] + }; + expect(actualPlugins, expectedPlugins); + }, overrides: { + 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: { + 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: { + 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: { + 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: { + 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: { + 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: { + 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: { + 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: { + 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: { + 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: { + 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: { + 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: { + 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: { + 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: { + 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: { + 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: { + 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: { + 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 [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: { + 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: { + 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: { + 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: { + 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: { + 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: { + 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: { + 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: { + 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: { + 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: { + 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: { + 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 $)')); + expect(contents, contains(r'list(APPEND PLUGIN_BUNDLED_LIBRARIES ${${plugin}_bundled_libraries})')); + }, overrides: { + FileSystem: () => fs, + ProcessManager: () => FakeProcessManager.any(), + }); + + testUsingContext('Generated Linux plugin files sorts by plugin name', () async { + createFakePlugins(fs, [ + '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 [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: { + 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: { + 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: { + 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: { + FileSystem: () => fs, + ProcessManager: () => FakeProcessManager.any(), + }); + + testUsingContext('Generated Windows plugin files sorts by plugin name', () async { + createFakePlugins(fs, [ + '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 [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: { + 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 [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: { + 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 ['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: { + 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: { + 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: { + 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 dummyFiles = [ + 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: { + 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 dummyFiles = [ + 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: { + 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 dummyFiles = [ + 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: { + 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 links = [ + 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: { + 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: [ + '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(['ios', 'android', 'linux'], 'PluginClass', 'some.android.package'); + expect(map['ios'], { + 'pluginClass' : 'PluginClass', + }); + expect(map['android'], { + 'pluginClass' : 'PluginClass', + 'package': 'some.android.package', + }); + expect(map['linux'], { + 'pluginClass' : 'PluginClass', + }); + }); + + testUsingContext('createPlatformsYamlMap should create empty map', () async { + final YamlMap map = Plugin.createPlatformsYamlMap([], '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 get dependencies => {}; +} + +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; + } +} diff --git a/flutter/packages/flutter_tools/test/general.shard/preview_device_test.dart b/flutter/packages/flutter_tools/test/general.shard/preview_device_test.dart new file mode 100644 index 0000000000000000000000000000000000000000..f65648f509a4c6af1be3bc825f7d01e21dc81aa3 --- /dev/null +++ b/flutter/packages/flutter_tools/test/general.shard/preview_device_test.dart @@ -0,0 +1,208 @@ +// 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 completer = Completer(); + final BufferLogger logger = BufferLogger.test(); + final PreviewDevice device = PreviewDevice( + artifacts: Artifacts.test(), + fileSystem: fs, + previewBinary: previewBinary, + processManager: FakeProcessManager.list([ + FakeCommand( + command: const [ + 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 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 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([1, 0, 0, 1]); + final PreviewDeviceDiscovery discovery = PreviewDeviceDiscovery( + artifacts: artifacts, + fileSystem: fs, + logger: BufferLogger.test(), + processManager: processManager, + platform: windowsPlatform, + featureFlags: featureFlags, + ); + + final List devices = await discovery.devices(); + + expect(devices, hasLength(1)); + final Device previewDevice = devices.first; + expect(previewDevice, isA()); + }); + + 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 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 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(); + } +} diff --git a/flutter/packages/flutter_tools/test/general.shard/project_file_invalidator_test.dart b/flutter/packages/flutter_tools/test/general.shard/project_file_invalidator_test.dart new file mode 100644 index 0000000000000000000000000000000000000000..35c12cabf6bc24ea021c0dcbeb816d7a8107500d --- /dev/null +++ b/flutter/packages/flutter_tools/test/general.shard/project_file_invalidator_test.dart @@ -0,0 +1,198 @@ +// 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 days +final DateTime inFuture = DateTime.now().add(const Duration(days: 100)); + +void main() { + for (final bool asyncScanning in [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: [], + 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: [], + 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.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({ + 'configVersion': 2, + 'packages': [], + })); + + final InvalidationResult invalidationResult = await projectFileInvalidator.findInvalidated( + lastCompiled: null, + urisToMonitor: [], + 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: [], + packagesPath: '.packages', + asyncScanning: asyncScanning, + packageConfig: packageConfig, + ); + expect(secondInvalidation.uris, unorderedEquals([ + 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: [], + 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: [], + 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: [ + '/root', + ], + ); + final ProjectFileInvalidator projectFileInvalidator = ProjectFileInvalidator( + fileSystem: multiRootFileSystem, + platform: FakePlatform(), + logger: BufferLogger.test(), + ); + + expect( + (await projectFileInvalidator.findInvalidated( + lastCompiled: inFuture, + urisToMonitor: [ + Uri.parse('file1'), + Uri.parse('file:///file2'), + Uri.parse('scheme:///file3'), + ], + packagesPath: '.packages', + asyncScanning: asyncScanning, + packageConfig: PackageConfig.empty, + )).uris, + isEmpty, + ); + }); + } +} diff --git a/flutter/packages/flutter_tools/test/general.shard/project_test.dart b/flutter/packages/flutter_tools/test/general.shard/project_test.dart new file mode 100644 index 0000000000000000000000000000000000000000..bea413c09a4c763bdd76c68ac60d0a59687f2f13 --- /dev/null +++ b/flutter/packages/flutter_tools/test/general.shard/project_test.dart @@ -0,0 +1,1727 @@ +// 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([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, + {'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 = ''; + 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 already indicates + // v1 embedding, as opposed to having . + + 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 already indicates + // v1 embedding, as opposed to having . + + await expectToolExitLater( + Future.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 `` 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 already indicates + // v1 embedding, as opposed to having . + + // 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 already indicates + // v1 embedding, as opposed to having . + + 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 already indicates + // v1 embedding, as opposed to having . + + 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 `` 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: { + 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: { + 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: { + 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: { + 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 versionInfo = jsonDecode(project.getVersionInfo()) as Map; + 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 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: { + 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 Function() testMethod) { + testUsingContext(description, testMethod, overrides: { + 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] = { + IosProject.kProductBundleIdKey: 'io.flutter.someProject', + IosProject.kTeamIdKey: 'ABC', + IosProject.kEntitlementFilePathKey: entitlementFilePath, + 'SUFFIX': 'suffix', + }; + xcodeProjectInterpreter.xcodeProjectInfo = XcodeProjectInfo([], [], ['Runner'], logger); + testPlistUtils.setProperty(PlistParser.kCFBundleIdentifierKey, r'$(PRODUCT_BUNDLE_IDENTIFIER).$(SUFFIX)'); + testPlistUtils.setProperty( + PlistParser.kAssociatedDomainsKey, + [ + '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 json = jsonDecode(outputFile.readAsStringSync()) as Map; + + expect( + json['associatedDomains'], + unorderedEquals( + [ + '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] = { + IosProject.kProductBundleIdKey: 'io.flutter.someProject', + IosProject.kTeamIdKey: 'ABC', + IosProject.kEntitlementFilePathKey: entitlementFilePath, + 'SUFFIX': 'suffix', + }; + xcodeProjectInterpreter.xcodeProjectInfo = XcodeProjectInfo([], [], ['Runner'], logger); + testPlistUtils.setProperty(PlistParser.kCFBundleIdentifierKey, r'$(PRODUCT_BUNDLE_IDENTIFIER).$(SUFFIX)'); + testPlistUtils.setProperty( + PlistParser.kAssociatedDomainsKey, + [ + '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 json = jsonDecode(outputFile.readAsStringSync()) as Map; + expect( + json['associatedDomains'], + unorderedEquals( + [ + '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] = { + IosProject.kProductBundleIdKey: 'io.flutter.someProject', + IosProject.kTeamIdKey: 'ABC', + }; + xcodeProjectInterpreter.xcodeProjectInfo = XcodeProjectInfo([], [], ['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 json = jsonDecode(outputFile.readAsStringSync()) as Map; + expect(json['teamIdentifier'], 'ABC'); + expect(json['bundleIdentifier'], 'io.flutter.someProject'); + expect(json['associatedDomains'], unorderedEquals([])); + }); + }); + + 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] = + { + IosProject.kProductBundleIdKey: 'io.flutter.someProject', + }; + xcodeProjectInterpreter.xcodeProjectInfo = XcodeProjectInfo([], [], ['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([], [], ['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] = { + IosProject.kProductBundleIdKey: 'io.flutter.someProject', + }; + xcodeProjectInterpreter.xcodeProjectInfo = XcodeProjectInfo([], [], ['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] = { + IosProject.kProductBundleIdKey: 'io.flutter.someProject', + 'SUFFIX': 'suffix', + }; + xcodeProjectInterpreter.xcodeProjectInfo = XcodeProjectInfo([], [], ['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([], [], ['free', 'paid'], logger); + + expect(await project.organizationNames, []); + }); + + testWithMocks('fails with no flavor and defined schemes', () async { + final FlutterProject project = await someProject(); + project.ios.xcodeProject.createSync(); + xcodeProjectInterpreter.xcodeProjectInfo = XcodeProjectInfo([], [], ['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] = { + IosProject.kProductBundleIdKey: 'io.flutter.someProject', + }; + xcodeProjectInterpreter.xcodeProjectInfo = XcodeProjectInfo([], [], ['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([], [], ['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([], [], ['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([], [], ['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([], [], ['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: { + 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] = { + 'FULL_PRODUCT_NAME': 'My App.app', + }; + mockXcodeProjectInterpreter.xcodeProjectInfo = XcodeProjectInfo([], [], ['Runner'], logger); + + expect(await project.ios.hostAppBundleName(null), 'My App.app'); + }, overrides: { + 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, ['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, ['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, ['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, ['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, ['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, ['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, + ['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(['WatchTarget'], [], [], logger); + expect( + await project.ios.containsWatchCompanion( + projectInfo: projectInfo, + buildInfo: BuildInfo.debug, + deviceId: '123', + ), + isFalse, + ); + }, overrides: { + 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] = { + IosProject.kProductBundleIdKey: 'io.flutter.someProject', + }; + mockXcodeProjectInterpreter.xcodeProjectInfo = XcodeProjectInfo(['Runner', 'WatchTarget'], [], ['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: { + 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: { + 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: { + 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: { + 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] = { + 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: { + 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] = { + IosProject.kProductBundleIdKey: 'io.flutter.someProject', + }; + + const XcodeProjectBuildContext watchBuildContext = XcodeProjectBuildContext( + scheme: 'WatchScheme', + deviceId: '123', + isWatch: true, + ); + mockXcodeProjectInterpreter.buildSettingsByBuildContext[watchBuildContext] = { + 'INFOPLIST_KEY_WKCompanionAppBundleIdentifier': 'io.flutter.someProject', + }; + + expect( + await project.ios.containsWatchCompanion( + projectInfo: mockXcodeProjectInterpreter.xcodeProjectInfo, + buildInfo: BuildInfo.debug, + deviceId: '123', + ), + isTrue, + ); + }, overrides: { + 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] = { + IosProject.kProductBundleIdKey: 'io.flutter.someProject', + }; + + const XcodeProjectBuildContext watchBuildContext = XcodeProjectBuildContext( + scheme: 'WatchScheme', + deviceId: '123', + isWatch: true, + ); + mockXcodeProjectInterpreter.buildSettingsByBuildContext[watchBuildContext] = { + 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: { + FileSystem: () => fs, + ProcessManager: () => FakeProcessManager.any(), + PlistParser: () => testPlistParser, + XcodeProjectInterpreter: () => mockXcodeProjectInterpreter, + FlutterProjectFactory: () => flutterProjectFactory, + }); + }); + }); +} + +Future 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 ?? ''); + return FlutterProject.fromDirectory(directory); +} + +Future 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_plugin +flutter: + plugin: + androidPackage: com.example + pluginClass: MyPlugin + iosPrefix: FLT +'''; + } else { + pluginPubSpec = ''' +name: my_plugin +flutter: + 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 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_module +flutter: + module: + androidPackage: com.example +'''); + return FlutterProject.fromDirectory(directory); +} + +/// Executes the [testMethod] in a context where the file system +/// is in memory. +@isTest +void _testInMemory( + String description, + Future 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: [], + 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({ + 'configVersion': 2, + 'packages': [ + { + 'name': 'flutter_template_images', + 'rootUri': dummyTemplateImagesDirectory.uri.toString(), + 'packageUri': 'lib/', + 'languageVersion': '2.6', + }, + ], + })); + + testUsingContext( + description, + testMethod, + overrides: { + 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: [], + ), + 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_HOME +distributionPath=wrapper/dists +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists +distributionUrl=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: hello +flutter: +'''; + +String get validPubspecWithDependencies => ''' +name: hello +flutter: + +dependencies: + plugin_a: + plugin_b: +'''; + + +String get invalidPubspec => ''' +name: hello +flutter: + 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> buildSettingsByBuildContext = >{}; + late XcodeProjectInfo xcodeProjectInfo; + + @override + Future> getBuildSettings(String projectPath, { + XcodeProjectBuildContext? buildContext, + Duration timeout = const Duration(minutes: 1), + }) async { + if (buildSettingsByBuildContext[buildContext] == null) { + return {}; + } + return buildSettingsByBuildContext[buildContext]!; + } + + @override + Future 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; +} diff --git a/flutter/packages/flutter_tools/test/general.shard/project_validator_result_test.dart b/flutter/packages/flutter_tools/test/general.shard/project_validator_result_test.dart new file mode 100644 index 0000000000000000000000000000000000000000..9920e3d7bde34bc2c24ae4b70e38ac892144ebd3 --- /dev/null +++ b/flutter/packages/flutter_tools/test/general.shard/project_validator_result_test.dart @@ -0,0 +1,99 @@ +// 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> 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 [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 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)'); + }); + }); +} diff --git a/flutter/packages/flutter_tools/test/general.shard/protocol_discovery_test.dart b/flutter/packages/flutter_tools/test/general.shard/protocol_discovery_test.dart new file mode 100644 index 0000000000000000000000000000000000000000..0bd89a3a033bb2887f3f3de893989b4ae34a4fb3 --- /dev/null +++ b/flutter/packages/flutter_tools/test/general.shard/protocol_discovery_test.dart @@ -0,0 +1,417 @@ +// 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 pendingUri = discoverer.uri; + logReader.addLine('The Dart VM service is listening on http12asdasdsd9999'); + await Future.delayed(const Duration(milliseconds: 10)); + logReader.addLine('The Dart VM service is listening on http://127.0.0.1:9999'); + + await Future.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.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.delayed(Duration.zero); + + expect(discoverer.uri, throwsA(isFormatException)); + }); + + testWithoutContext('discovers uri if logs not yet produced output', () async { + final Future 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 uriFuture = discoverer.uri; + await logReader.dispose(); + + expect(await uriFuture, isNull); + }); + + testWithoutContext('uri waits for correct log line', () async { + final Future 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 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 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 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 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> 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.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 discoveredUris = []; + 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 discoveredUris = []; + 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 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 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 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 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 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 forward(int devicePort, { int? hostPort }) async { + hostPort ??= 0; + if (hostPort == 0) { + return availablePort!; + } + return hostPort; + } + + @override + List get forwardedPorts => throw UnimplementedError(); + + @override + Future unforward(ForwardedPort forwardedPort) { + throw UnimplementedError(); + } + + @override + Future dispose() async {} +} diff --git a/flutter/packages/flutter_tools/test/general.shard/pub_dependencies_project_validator_test.dart b/flutter/packages/flutter_tools/test/general.shard/pub_dependencies_project_validator_test.dart new file mode 100644 index 0000000000000000000000000000000000000000..546e92d80a94a14e649ffb389963782c88fd0029 --- /dev/null +++ b/flutter/packages/flutter_tools/test/general.shard/pub_dependencies_project_validator_test.dart @@ -0,0 +1,77 @@ +// 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([ + const FakeCommand( + command: ['dart', 'pub', 'deps', '--json'], + stdout: '{"packages": [{"dependencies": ["abc"], "source": "hosted"}]}', + ), + ]); + final PubDependenciesProjectValidator validator = PubDependenciesProjectValidator(processManager); + + final List 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([ + const FakeCommand( + command: ['dart', 'pub', 'deps', '--json'], + stderr: 'command fail', + ), + ]); + final PubDependenciesProjectValidator validator = PubDependenciesProjectValidator(processManager); + + final List 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([ + const FakeCommand( + command: ['dart', 'pub', 'deps', '--json'], + stdout: '{"packages": [{"dependencies": ["dep1", "dep2"], "source": "other"}]}', + ), + ]); + final PubDependenciesProjectValidator validator = PubDependenciesProjectValidator(processManager); + + final List 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); + }); + }); +} diff --git a/flutter/packages/flutter_tools/test/general.shard/resident_devtools_handler_test.dart b/flutter/packages/flutter_tools/test/general.shard/resident_devtools_handler_test.dart new file mode 100644 index 0000000000000000000000000000000000000000..8e07a195760b3d6c3d58c356f123fa705ecb7787 --- /dev/null +++ b/flutter/packages/flutter_tools/test/general.shard/resident_devtools_handler_test.dart @@ -0,0 +1,501 @@ +// 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: [], + libraries: [ + 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: [], + extensionRPCs: ['ext.flutter.connectedVmServiceUri'], +); + +final FakeVmServiceRequest listViews = FakeVmServiceRequest( + method: kListViewsMethod, + jsonResponse: { + 'views': [ + 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: []); + + 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: []); + + 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: [], + ); + + 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: [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: [ + const FakeVmServiceRequest( + method: 'streamListen', + args: { + 'streamId': 'Isolate', + } + ), + listViews, + FakeVmServiceRequest( + method: 'getIsolate', + jsonResponse: isolate.toJson(), + args: { + 'isolateId': '1', + }, + ), + const FakeVmServiceRequest( + method: 'streamCancel', + args: { + 'streamId': 'Isolate', + }, + ), + listViews, + listViews, + const FakeVmServiceRequest( + method: 'ext.flutter.activeDevToolsServerAddress', + args: { + 'isolateId': '1', + 'value': 'http://localhost:8080', + }, + ), + const FakeVmServiceRequest( + method: 'ext.flutter.connectedVmServiceUri', + args: { + 'isolateId': '1', + 'value': 'http://localhost:1234', + }, + ), + ], httpAddress: Uri.parse('http://localhost:1234')); + + final FakeFlutterDevice device = FakeFlutterDevice() + ..vmService = fakeVmServiceHost.vmService; + + await handler.serveAndAnnounceDevTools( + flutterDevices: [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: [], httpAddress: Uri.parse('http://localhost:1234')); + + final FakeFlutterDevice device = FakeFlutterDevice() + ..vmService = fakeVmServiceHost.vmService; + + await handler.serveAndAnnounceDevTools( + flutterDevices: [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: [ + const FakeVmServiceRequest( + method: 'streamListen', + args: { + 'streamId': 'Isolate', + } + ), + listViews, + FakeVmServiceRequest( + method: 'getIsolate', + jsonResponse: isolate.toJson(), + args: { + 'isolateId': '1', + }, + ), + const FakeVmServiceRequest( + method: 'streamCancel', + args: { + 'streamId': 'Isolate', + }, + ), + const FakeVmServiceRequest( + method: 'ext.flutter.activeDevToolsServerAddress', + args: { + 'value': 'http://localhost:8080', + }, + ), + const FakeVmServiceRequest( + method: 'ext.flutter.connectedVmServiceUri', + args: { + '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: [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: [ + const FakeVmServiceRequest( + method: 'streamListen', + args: { + 'streamId': 'Isolate', + }, + ), + const FakeVmServiceRequest( + method: kListViewsMethod, + error: FakeRPCError(code: RPCErrorCodes.kServiceDisappeared), + ), + const FakeVmServiceRequest( + method: 'streamCancel', + args: { + 'streamId': 'Isolate', + }, + error: FakeRPCError(code: RPCErrorCodes.kServiceDisappeared), + ), + ], httpAddress: Uri.parse('http://localhost:1234')); + + final FakeFlutterDevice device = FakeFlutterDevice() + ..vmService = fakeVmServiceHost.vmService; + + await handler.serveAndAnnounceDevTools( + flutterDevices: [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: [ + const FakeVmServiceRequest( + method: 'streamListen', + args: { + 'streamId': 'Isolate', + }, + ), + listViews, + FakeVmServiceRequest( + method: 'getIsolate', + jsonResponse: isolate.toJson(), + args: { + 'isolateId': '1', + }, + ), + const FakeVmServiceRequest( + method: 'streamCancel', + args: { + 'streamId': 'Isolate', + }, + ), + listViews, + listViews, + const FakeVmServiceRequest( + method: 'ext.flutter.activeDevToolsServerAddress', + args: { + 'isolateId': '1', + 'value': 'http://localhost:8080', + }, + ), + const FakeVmServiceRequest( + method: 'ext.flutter.connectedVmServiceUri', + args: { + 'isolateId': '1', + 'value': 'http://localhost:1234', + }, + ), + ], httpAddress: Uri.parse('http://localhost:1234')); + + final FakeVmServiceHost vmServiceHostThatDisappears = FakeVmServiceHost(requests: [ + const FakeVmServiceRequest( + method: 'streamListen', + args: { + 'streamId': 'Isolate', + }, + ), + const FakeVmServiceRequest( + method: kListViewsMethod, + error: FakeRPCError(code: RPCErrorCodes.kServiceDisappeared), + ), + const FakeVmServiceRequest( + method: 'streamCancel', + args: { + 'streamId': 'Isolate', + }, + error: FakeRPCError(code: RPCErrorCodes.kServiceDisappeared), + ), + ], httpAddress: Uri.parse('http://localhost:5678')); + + await handler.serveAndAnnounceDevTools( + flutterDevices: [ + 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: []); + 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: []); + expect(handler.launchedInBrowser, isFalse); + expect(handler.activeDevToolsServer, null); + }); + + testWithoutContext('launchDevToolsInBrowser launches after _devToolsLauncher.ready completes', () async { + final Completer completer = Completer(); + 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: []), isTrue); + expect(handler.launchedInBrowser, isFalse); + + completer.complete(); + // Await a short delay to give DevTools time to launch. + await Future.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: []), 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 serve() async => null; + + @override + Future get ready => readyCompleter.future; + + Completer readyCompleter = Completer()..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 startDartDevelopmentService( + Uri observatoryUri, { + required Logger logger, + int? hostPort, + bool? ipv6, + bool? disableServiceAuthCodes, + bool cacheStartupProfile = false, + }) async { + started = true; + } + + @override + Future shutdown() async { + disposed = true; + } + + @override + void setExternalDevToolsUri(Uri uri) {} +} diff --git a/flutter/packages/flutter_tools/test/general.shard/resident_runner_helpers.dart b/flutter/packages/flutter_tools/test/general.shard/resident_runner_helpers.dart new file mode 100644 index 0000000000000000000000000000000000000000..c6da20415e3781e69ab4f295bc517cb17aef31ce --- /dev/null +++ b/flutter/packages/flutter_tools/test/general.shard/resident_runner_helpers.dart @@ -0,0 +1,545 @@ +// 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: [], + extensionRPCs: [], + libraries: [ + 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: [], +); + +final vm_service.Isolate fakePausedIsolate = vm_service.Isolate( + id: '1', + pauseEvent: fakePausedEvent, + breakpoints: [ + 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: [], + livePorts: 0, + name: 'test', + number: '1', + pauseOnExit: false, + runnable: true, + startTime: 0, + isSystemIsolate: false, + isolateFlags: [], +); + +final vm_service.VM fakeVM = vm_service.VM( + isolates: [fakeUnpausedIsolate], + pid: 1, + hostCPU: '', + isolateGroups: [], + targetCPU: '', + startTime: 0, + name: 'dart', + architectureBits: 64, + operatingSystem: '', + version: '', + systemIsolateGroups: [], + systemIsolates: [], +); + +final FlutterView fakeFlutterView = FlutterView( + id: 'a', + uiIsolate: fakeUnpausedIsolate, +); + +final FakeVmServiceRequest listViews = FakeVmServiceRequest( + method: kListViewsMethod, + jsonResponse: { + 'views': [ + fakeFlutterView.toJson(), + ], + }, +); + +const FakeVmServiceRequest renderFrameRasterStats = FakeVmServiceRequest( + method: kRenderFrameWithRasterStatsMethod, + args: { + '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: { + 'viewId': 'a', + 'assetDirectory': 'build/flutter_assets', + 'isolateId': '1', + } +); + +const FakeVmServiceRequest evict = FakeVmServiceRequest( + method: 'ext.flutter.evict', + args: { + 'value': 'asset', + 'isolateId': '1', + } +); + +const FakeVmServiceRequest evictShader = FakeVmServiceRequest( + method: 'ext.ui.window.reinitializeShader', + args: { + '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 get done => Future.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 toJson() => { + 'error_code': errorCode, + 'message': message, + }; +} + +class TestFlutterDevice extends FlutterDevice { + TestFlutterDevice(super.device, { Stream? vmServiceUris }) + : _vmServiceUris = vmServiceUris, super(buildInfo: BuildInfo.debug, developmentShaderCompiler: const FakeShaderCompiler()); + + final Stream? _vmServiceUris; + + @override + Stream 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 get vmServiceUris => Stream.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 stopEchoingDeviceLog() async { } + + @override + Future initLogReader() async { } + + @override + Future setupDevFS(String fsName, Directory rootDirectory) async { + return testUri!; + } + + @override + Future runHot({required HotRunner hotRunner, String? route}) async { + return runHotCode; + } + + @override + Future runCold({required ColdRunner coldRunner, String? route}) async { + if (runColdError != null) { + throw runColdError!; + } + return runColdCode; + } + + @override + Future 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 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 invalidatedFiles, + required PackageConfig packageConfig, + }) async { + if (reportError != null) { + throw reportError!; + } + return report; + } + + @override + Future 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 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 recompile( + Uri mainUri, + List? 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, []); + } + + @override + void accept() { } + + @override + void reset() { } +} + +class FakeProjectFileInvalidator extends Fake implements ProjectFileInvalidator { + @override + Future findInvalidated({ + required DateTime? lastCompiled, + required List urisToMonitor, + required String packagesPath, + required PackageConfig packageConfig, + bool asyncScanning = false, + }) async { + return InvalidationResult( + packageConfig: packageConfig, + uris: [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 get sdkNameAndVersion async => _sdkNameAndVersion; + + @override + Future get targetPlatform async => _targetPlatform; + + @override + Future get isLocalEmulator async => _isLocalEmulator; + + @override + String get name => 'FakeDevice'; + + @override + late DartDevelopmentService dds; + + @override + Future dispose() async { + disposed = true; + } + + @override + Future stopApp(ApplicationPackage? app, {String? userIdentifier}) async { + appStopped = true; + return true; + } + + @override + Future takeScreenshot(File outputFile) async { + if (failScreenshot) { + throw Exception(); + } + outputFile.writeAsBytesSync(List.generate(1024, (int i) => i)); + } + + @override + FutureOr 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 sources = []; + + @override + Uri baseUri = Uri(); + + @override + Future destroy() async { } + + @override + Set assetPathsToEvict = {}; + + @override + Set shaderPathsToEvict = {}; + + @override + Set scenePathsToEvict = {}; + + @override + bool didUpdateFontManifest = false; + + UpdateFSReport nextUpdateReport = UpdateFSReport(success: true); + + @override + bool hasSetAssetDirectory = false; + + @override + Future create() async { + return Uri(); + } + + @override + void resetLastCompiled() { + lastCompiled = null; + } + + @override + Future update({ + required Uri mainUri, + required ResidentCompiler generator, + required bool trackWidgetCreation, + required String pathToReload, + required List 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 recompileShader(DevFSContent inputShader) { + throw UnimplementedError(); + } +} diff --git a/flutter/packages/flutter_tools/test/general.shard/resident_runner_test.dart b/flutter/packages/flutter_tools/test/general.shard/resident_runner_test.dart new file mode 100644 index 0000000000000000000000000000000000000000..7fe3f1777d31cc36d6c70a6016f1895b3c2468b3 --- /dev/null +++ b/flutter/packages/flutter_tools/test/general.shard/resident_runner_test.dart @@ -0,0 +1,2939 @@ +// 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:file/memory.dart'; +import 'package:file_testing/file_testing.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/command_help.dart'; +import 'package:flutter_tools/src/base/common.dart'; +import 'package:flutter_tools/src/base/dds.dart'; +import 'package:flutter_tools/src/base/file_system.dart'; +import 'package:flutter_tools/src/base/io.dart' as io; +import 'package:flutter_tools/src/base/logger.dart'; +import 'package:flutter_tools/src/base/platform.dart'; +import 'package:flutter_tools/src/build_info.dart'; +import 'package:flutter_tools/src/build_system/build_system.dart'; +import 'package:flutter_tools/src/build_system/targets/scene_importer.dart'; +import 'package:flutter_tools/src/build_system/targets/shader_compiler.dart'; +import 'package:flutter_tools/src/compile.dart'; +import 'package:flutter_tools/src/convert.dart'; +import 'package:flutter_tools/src/devfs.dart'; +import 'package:flutter_tools/src/device.dart'; +import 'package:flutter_tools/src/device_port_forwarder.dart'; +import 'package:flutter_tools/src/features.dart'; +import 'package:flutter_tools/src/globals.dart' as globals; +import 'package:flutter_tools/src/project.dart'; +import 'package:flutter_tools/src/reporting/reporting.dart'; +import 'package:flutter_tools/src/resident_devtools_handler.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/version.dart'; +import 'package:flutter_tools/src/vmservice.dart'; +import 'package:native_assets_cli/native_assets_cli.dart' + hide BuildMode, Target; +import 'package:native_assets_cli/native_assets_cli.dart' as native_assets_cli; +import 'package:package_config/package_config.dart'; +import 'package:test/fake.dart'; +import 'package:unified_analytics/src/enums.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/fake_vm_services.dart'; +import '../src/fakes.dart'; +import '../src/testbed.dart'; +import 'fake_native_assets_build_runner.dart'; + +final vm_service.Event fakeUnpausedEvent = vm_service.Event( + kind: vm_service.EventKind.kResume, + 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: [], + extensionRPCs: [], + libraries: [ + 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: [], +); + +final vm_service.Isolate fakePausedIsolate = vm_service.Isolate( + id: '1', + pauseEvent: fakePausedEvent, + breakpoints: [ + 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: [], + livePorts: 0, + name: 'test', + number: '1', + pauseOnExit: false, + runnable: true, + startTime: 0, + isSystemIsolate: false, + isolateFlags: [], +); + +final vm_service.VM fakeVM = vm_service.VM( + isolates: [fakeUnpausedIsolate], + pid: 1, + hostCPU: '', + isolateGroups: [], + targetCPU: '', + startTime: 0, + name: 'dart', + architectureBits: 64, + operatingSystem: '', + version: '', + systemIsolateGroups: [], + systemIsolates: [], +); + +final FlutterView fakeFlutterView = FlutterView( + id: 'a', + uiIsolate: fakeUnpausedIsolate, +); + +final FakeVmServiceRequest listViews = FakeVmServiceRequest( + method: kListViewsMethod, + jsonResponse: { + 'views': [ + fakeFlutterView.toJson(), + ], + }, +); + +const FakeVmServiceRequest setAssetBundlePath = FakeVmServiceRequest( + method: '_flutter.setAssetBundlePath', + args: { + 'viewId': 'a', + 'assetDirectory': 'build/flutter_assets', + 'isolateId': '1', + } +); + +const FakeVmServiceRequest evict = FakeVmServiceRequest( + method: 'ext.flutter.evict', + args: { + 'value': 'asset', + 'isolateId': '1', + } +); + +const FakeVmServiceRequest evictShader = FakeVmServiceRequest( + method: 'ext.ui.window.reinitializeShader', + args: { + 'assetKey': 'foo.frag', + 'isolateId': '1', + } +); + +final Uri testUri = Uri.parse('foo://bar'); + +void main() { + late Testbed testbed; + late FakeFlutterDevice flutterDevice; + late FakeDevFS devFS; + late ResidentRunner residentRunner; + late FakeDevice device; + late FakeAnalytics fakeAnalytics; + FakeVmServiceHost? fakeVmServiceHost; + + setUp(() { + testbed = Testbed(setup: () { + fakeAnalytics = getInitializedFakeAnalyticsInstance( + fs: globals.fs, + fakeFlutterVersion: FakeFlutterVersion(), + ); + + globals.fs.file('.packages') + .writeAsStringSync('\n'); + globals.fs.file(globals.fs.path.join('build', 'app.dill')) + ..createSync(recursive: true) + ..writeAsStringSync('ABC'); + residentRunner = HotRunner( + [ + flutterDevice, + ], + stayResident: false, + debuggingOptions: DebuggingOptions.enabled(BuildInfo.debug), + target: 'main.dart', + devtoolsHandler: createNoOpHandler, + analytics: fakeAnalytics, + ); + }); + device = FakeDevice(); + devFS = FakeDevFS(); + flutterDevice = FakeFlutterDevice() + ..testUri = testUri + ..vmServiceHost = (() => fakeVmServiceHost) + ..device = device + .._devFS = devFS; + }); + + testUsingContext('ResidentRunner can attach to device successfully', () => testbed.run(() async { + fakeVmServiceHost = FakeVmServiceHost(requests: [ + listViews, + listViews, + ]); + final Completer futureConnectionInfo = Completer.sync(); + final Completer futureAppStart = Completer.sync(); + final Future result = residentRunner.attach( + appStartedCompleter: futureAppStart, + connectionInfoCompleter: futureConnectionInfo, + enableDevTools: true, + ); + final Future connectionInfo = futureConnectionInfo.future; + + expect(await result, 0); + expect(futureConnectionInfo.isCompleted, true); + expect((await connectionInfo).baseUri, 'foo://bar'); + expect(futureAppStart.isCompleted, true); + expect(fakeVmServiceHost?.hasRemainingExpectations, false); + })); + + testUsingContext('ResidentRunner suppresses errors for the initial compilation', () => testbed.run(() async { + globals.fs.file(globals.fs.path.join('lib', 'main.dart')) + .createSync(recursive: true); + fakeVmServiceHost = FakeVmServiceHost(requests: [ + listViews, + listViews, + ]); + final FakeResidentCompiler residentCompiler = FakeResidentCompiler() + ..nextOutput = const CompilerOutput('foo', 0 ,[]); + residentRunner = HotRunner( + [ + flutterDevice, + ], + stayResident: false, + debuggingOptions: DebuggingOptions.enabled(BuildInfo.debug), + target: 'main.dart', + devtoolsHandler: createNoOpHandler, + analytics: fakeAnalytics, + ); + flutterDevice.generator = residentCompiler; + + expect(await residentRunner.run(enableDevTools: true), 0); + expect(residentCompiler.didSuppressErrors, true); + expect(fakeVmServiceHost?.hasRemainingExpectations, false); + })); + + // Regression test for https://github.com/flutter/flutter/issues/60613 + testUsingContext('ResidentRunner calls appFailedToStart if initial compilation fails', () => testbed.run(() async { + globals.fs.file(globals.fs.path.join('lib', 'main.dart')) + .createSync(recursive: true); + fakeVmServiceHost = FakeVmServiceHost(requests: []); + final FakeResidentCompiler residentCompiler = FakeResidentCompiler() + ..nextOutput = const CompilerOutput('foo', 1 ,[]); + residentRunner = HotRunner( + [ + flutterDevice, + ], + stayResident: false, + debuggingOptions: DebuggingOptions.enabled(BuildInfo.debug), + target: 'main.dart', + devtoolsHandler: createNoOpHandler, + analytics: fakeAnalytics, + ); + flutterDevice.generator = residentCompiler; + + expect(await residentRunner.run(), 1); + // Completing this future ensures that the daemon can exit correctly. + expect(await residentRunner.waitForAppToFinish(), 1); + })); + + // Regression test for https://github.com/flutter/flutter/issues/60613 + testUsingContext('ResidentRunner calls appFailedToStart if initial compilation fails - cold mode', () => testbed.run(() async { + globals.fs.file(globals.fs.path.join('lib', 'main.dart')) + .createSync(recursive: true); + fakeVmServiceHost = FakeVmServiceHost(requests: []); + residentRunner = ColdRunner( + [ + flutterDevice, + ], + stayResident: false, + debuggingOptions: DebuggingOptions.enabled(BuildInfo.release), + target: 'main.dart', + devtoolsHandler: createNoOpHandler, + ); + flutterDevice.runColdCode = 1; + + expect(await residentRunner.run(), 1); + // Completing this future ensures that the daemon can exit correctly. + expect(await residentRunner.waitForAppToFinish(), 1); + })); + + // Regression test for https://github.com/flutter/flutter/issues/60613 + testUsingContext('ResidentRunner calls appFailedToStart if exception is thrown - cold mode', () => testbed.run(() async { + globals.fs.file(globals.fs.path.join('lib', 'main.dart')) + .createSync(recursive: true); + fakeVmServiceHost = FakeVmServiceHost(requests: []); + residentRunner = ColdRunner( + [ + flutterDevice, + ], + stayResident: false, + debuggingOptions: DebuggingOptions.enabled(BuildInfo.release), + target: 'main.dart', + devtoolsHandler: createNoOpHandler, + ); + flutterDevice.runColdError = Exception('BAD STUFF'); + + + expect(await residentRunner.run(), 1); + // Completing this future ensures that the daemon can exit correctly. + expect(await residentRunner.waitForAppToFinish(), 1); + })); + + testUsingContext('ResidentRunner does not suppressErrors if running with an applicationBinary', () => testbed.run(() async { + globals.fs.file(globals.fs.path.join('lib', 'main.dart')) + .createSync(recursive: true); + fakeVmServiceHost = FakeVmServiceHost(requests: [ + listViews, + listViews, + ]); + final FakeResidentCompiler residentCompiler = FakeResidentCompiler() + ..nextOutput = const CompilerOutput('foo', 0 ,[]); + residentRunner = HotRunner( + [ + flutterDevice, + ], + applicationBinary: globals.fs.file('app-debug.apk'), + stayResident: false, + debuggingOptions: DebuggingOptions.enabled(BuildInfo.debug), + target: 'main.dart', + devtoolsHandler: createNoOpHandler, + analytics: fakeAnalytics, + ); + flutterDevice.generator = residentCompiler; + + expect(await residentRunner.run(enableDevTools: true), 0); + expect(residentCompiler.didSuppressErrors, false); + expect(fakeVmServiceHost?.hasRemainingExpectations, false); + })); + + testUsingContext('ResidentRunner can attach to device successfully with --fast-start', () => testbed.run(() async { + fakeVmServiceHost = FakeVmServiceHost(requests: [ + listViews, + listViews, + listViews, + FakeVmServiceRequest( + method: 'getIsolate', + args: { + 'isolateId': fakeUnpausedIsolate.id, + }, + jsonResponse: fakeUnpausedIsolate.toJson(), + ), + FakeVmServiceRequest( + method: 'getVM', + jsonResponse: vm_service.VM.parse({})!.toJson(), + ), + listViews, + const FakeVmServiceRequest( + method: 'streamListen', + args: { + 'streamId': 'Isolate', + } + ), + FakeVmServiceRequest( + method: kRunInViewMethod, + args: { + 'viewId': fakeFlutterView.id, + 'mainScript': 'main.dart.dill', + 'assetDirectory': 'build/flutter_assets', + } + ), + FakeVmServiceStreamResponse( + streamId: 'Isolate', + event: vm_service.Event( + timestamp: 0, + kind: vm_service.EventKind.kIsolateRunnable, + ) + ), + ]); + residentRunner = HotRunner( + [ + flutterDevice, + ], + stayResident: false, + debuggingOptions: DebuggingOptions.enabled( + BuildInfo.debug, + fastStart: true, + startPaused: true, + ), + target: 'main.dart', + devtoolsHandler: createNoOpHandler, + analytics: fakeAnalytics, + ); + final Completer futureConnectionInfo = Completer.sync(); + final Completer futureAppStart = Completer.sync(); + final Future result = residentRunner.attach( + appStartedCompleter: futureAppStart, + connectionInfoCompleter: futureConnectionInfo, + enableDevTools: true, + ); + final Future connectionInfo = futureConnectionInfo.future; + + expect(await result, 0); + expect(futureConnectionInfo.isCompleted, true); + expect((await connectionInfo).baseUri, 'foo://bar'); + expect(futureAppStart.isCompleted, true); + expect(fakeVmServiceHost?.hasRemainingExpectations, false); + })); + + testUsingContext('ResidentRunner can handle an RPC exception from hot reload', () => testbed.run(() async { + fakeVmServiceHost = FakeVmServiceHost(requests: [ + listViews, + listViews, + listViews, + ]); + final Completer futureConnectionInfo = Completer.sync(); + final Completer futureAppStart = Completer.sync(); + unawaited(residentRunner.attach( + appStartedCompleter: futureAppStart, + connectionInfoCompleter: futureConnectionInfo, + enableDevTools: true, + )); + await futureAppStart.future; + flutterDevice.reportError = vm_service.RPCError('something bad happened', 666, ''); + + final OperationResult result = await residentRunner.restart(); + expect(result.fatal, true); + expect(result.code, 1); + expect((globals.flutterUsage as TestUsage).events, contains( + TestUsageEvent('hot', 'exception', parameters: CustomDimensions( + hotEventTargetPlatform: getNameForTargetPlatform(TargetPlatform.android_arm), + hotEventSdkName: 'Android', + hotEventEmulator: false, + hotEventFullRestart: false, + )), + )); + expect(fakeAnalytics.sentEvents, contains( + Event.hotRunnerInfo( + label: 'exception', + targetPlatform: getNameForTargetPlatform(TargetPlatform.android_arm), + sdkName: 'Android', + emulator: false, + fullRestart: false, + ), + )); + expect(fakeVmServiceHost?.hasRemainingExpectations, false); + }, overrides: { + Usage: () => TestUsage(), + })); + + testUsingContext('ResidentRunner can handle an RPC exception from debugFrameJankMetrics', () => testbed.run(() async { + fakeVmServiceHost = FakeVmServiceHost(requests: [ + listViews, + listViews, + listViews, + renderFrameRasterStats, + ]); + final Completer futureConnectionInfo = Completer.sync(); + final Completer futureAppStart = Completer.sync(); + unawaited(residentRunner.attach( + appStartedCompleter: futureAppStart, + connectionInfoCompleter: futureConnectionInfo, + enableDevTools: true, + )); + await futureAppStart.future; + + final bool result = await residentRunner.debugFrameJankMetrics(); + expect(result, true); + expect((globals.flutterUsage as TestUsage).events, isEmpty); + expect(fakeAnalytics.sentEvents, isEmpty); + expect(fakeVmServiceHost?.hasRemainingExpectations, false); + expect((globals.logger as BufferLogger).warningText, contains('Unable to get jank metrics for Impeller renderer')); + }, overrides: { + Usage: () => TestUsage(), + })); + + testUsingContext('ResidentRunner fails its operation if the device initialization is not complete', () => testbed.run(() async { + fakeVmServiceHost = FakeVmServiceHost(requests: [ + listViews, + listViews, + ]); + final Completer futureConnectionInfo = Completer.sync(); + final Completer futureAppStart = Completer.sync(); + unawaited(residentRunner.attach( + appStartedCompleter: futureAppStart, + connectionInfoCompleter: futureConnectionInfo, + )); + await futureAppStart.future; + flutterDevice._devFS = null; + + final OperationResult result = await residentRunner.restart(); + expect(result.fatal, false); + expect(result.code, 1); + expect(result.message, contains('Device initialization has not completed.')); + expect(fakeVmServiceHost?.hasRemainingExpectations, false); + })); + + testUsingContext('ResidentRunner can handle an reload-barred exception from hot reload', () => testbed.run(() async { + fakeVmServiceHost = FakeVmServiceHost(requests: [ + listViews, + listViews, + listViews, + ]); + final Completer futureConnectionInfo = Completer.sync(); + final Completer futureAppStart = Completer.sync(); + unawaited(residentRunner.attach( + appStartedCompleter: futureAppStart, + connectionInfoCompleter: futureConnectionInfo, + enableDevTools: true, + )); + await futureAppStart.future; + flutterDevice.reportError = vm_service.RPCError('something bad happened', kIsolateReloadBarred, ''); + + final OperationResult result = await residentRunner.restart(); + expect(result.fatal, true); + expect(result.code, kIsolateReloadBarred); + expect(result.message, contains('Unable to hot reload application due to an unrecoverable error')); + + expect((globals.flutterUsage as TestUsage).events, contains( + TestUsageEvent('hot', 'reload-barred', parameters: CustomDimensions( + hotEventTargetPlatform: getNameForTargetPlatform(TargetPlatform.android_arm), + hotEventSdkName: 'Android', + hotEventEmulator: false, + hotEventFullRestart: false, + )), + )); + expect(fakeAnalytics.sentEvents, contains( + Event.hotRunnerInfo( + label: 'reload-barred', + targetPlatform: getNameForTargetPlatform(TargetPlatform.android_arm), + sdkName: 'Android', + emulator: false, + fullRestart: false, + ) + )); + expect(fakeVmServiceHost?.hasRemainingExpectations, false); + }, overrides: { + Usage: () => TestUsage(), + })); + + testUsingContext('ResidentRunner reports hot reload event with null safety analytics', () => testbed.run(() async { + fakeVmServiceHost = FakeVmServiceHost(requests: [ + listViews, + listViews, + listViews, + ]); + residentRunner = HotRunner( + [ + flutterDevice, + ], + stayResident: false, + target: 'main.dart', + debuggingOptions: DebuggingOptions.enabled(const BuildInfo( + BuildMode.debug, '', treeShakeIcons: false, extraFrontEndOptions: [ + '--enable-experiment=non-nullable', + ], + )), + devtoolsHandler: createNoOpHandler, + analytics: fakeAnalytics, + ); + final Completer futureConnectionInfo = Completer.sync(); + final Completer futureAppStart = Completer.sync(); + unawaited(residentRunner.attach( + appStartedCompleter: futureAppStart, + connectionInfoCompleter: futureConnectionInfo, + enableDevTools: true, + )); + await futureAppStart.future; + flutterDevice.reportError = vm_service.RPCError('something bad happened', 666, ''); + + final OperationResult result = await residentRunner.restart(); + expect(result.fatal, true); + expect(result.code, 1); + + expect((globals.flutterUsage as TestUsage).events, contains( + TestUsageEvent('hot', 'exception', parameters: CustomDimensions( + hotEventTargetPlatform: getNameForTargetPlatform(TargetPlatform.android_arm), + hotEventSdkName: 'Android', + hotEventEmulator: false, + hotEventFullRestart: false, + )), + )); + expect(fakeAnalytics.sentEvents, contains( + Event.hotRunnerInfo( + label: 'exception', + targetPlatform: getNameForTargetPlatform(TargetPlatform.android_arm), + sdkName: 'Android', + emulator: false, + fullRestart: false, + ) + )); + expect(fakeVmServiceHost?.hasRemainingExpectations, false); + }, overrides: { + Usage: () => TestUsage(), + })); + + testUsingContext('ResidentRunner does not reload sources if no sources changed', () => testbed.run(() async { + fakeVmServiceHost = FakeVmServiceHost(requests: [ + listViews, + listViews, + listViews, + FakeVmServiceRequest( + method: 'getIsolatePauseEvent', + args: { + 'isolateId': '1', + }, + jsonResponse: fakeUnpausedEvent.toJson(), + ), + FakeVmServiceRequest( + method: 'ext.flutter.reassemble', + args: { + 'isolateId': fakeUnpausedIsolate.id, + }, + ), + ]); + residentRunner = HotRunner( + [ + flutterDevice, + ], + stayResident: false, + debuggingOptions: DebuggingOptions.enabled(BuildInfo.debug), + target: 'main.dart', + devtoolsHandler: createNoOpHandler, + analytics: fakeAnalytics, + ); + final Completer futureConnectionInfo = Completer.sync(); + final Completer futureAppStart = Completer.sync(); + unawaited(residentRunner.attach( + appStartedCompleter: futureAppStart, + connectionInfoCompleter: futureConnectionInfo, + enableDevTools: true, + )); + await futureAppStart.future; + flutterDevice.report = UpdateFSReport(success: true); + + final OperationResult result = await residentRunner.restart(); + + expect(result.code, 0); + expect(fakeVmServiceHost?.hasRemainingExpectations, false); + })); + + testUsingContext('ResidentRunner reports error with missing entrypoint file', () => testbed.run(() async { + fakeVmServiceHost = FakeVmServiceHost(requests: [ + listViews, + listViews, + listViews, + FakeVmServiceRequest( + method: 'getVM', + jsonResponse: vm_service.VM.parse({ + 'isolates': [ + fakeUnpausedIsolate.toJson(), + ], + })!.toJson(), + ), + const FakeVmServiceRequest( + method: kReloadSourcesServiceName, + args: { + 'isolateId': '1', + 'pause': false, + 'rootLibUri': 'main.dart.incremental.dill', + }, + jsonResponse: { + 'type': 'ReloadReport', + 'success': true, + 'details': { + 'loadedLibraryCount': 1, + }, + }, + ), + FakeVmServiceRequest( + method: 'getIsolatePauseEvent', + args: { + 'isolateId': '1', + }, + jsonResponse: fakeUnpausedEvent.toJson(), + ), + FakeVmServiceRequest( + method: 'ext.flutter.reassemble', + args: { + 'isolateId': fakeUnpausedIsolate.id, + }, + ), + ]); + final Completer futureConnectionInfo = Completer.sync(); + final Completer futureAppStart = Completer.sync(); + unawaited(residentRunner.attach( + appStartedCompleter: futureAppStart, + connectionInfoCompleter: futureConnectionInfo, + enableDevTools: true, + )); + await futureAppStart.future; + flutterDevice.report = UpdateFSReport(success: true, invalidatedSourcesCount: 1); + + final OperationResult result = await residentRunner.restart(); + + expect(globals.fs.file(globals.fs.path.join('lib', 'main.dart')), isNot(exists)); + expect(testLogger.errorText, contains('The entrypoint file (i.e. the file with main())')); + expect(result.fatal, false); + expect(result.code, 0); + })); + + testUsingContext('ResidentRunner resets compilation time on reload reject', () => testbed.run(() async { + fakeVmServiceHost = FakeVmServiceHost(requests: [ + listViews, + listViews, + listViews, + FakeVmServiceRequest( + method: 'getVM', + jsonResponse: vm_service.VM.parse({ + 'isolates': [ + fakeUnpausedIsolate.toJson(), + ], + })!.toJson(), + ), + const FakeVmServiceRequest( + method: kReloadSourcesServiceName, + args: { + 'isolateId': '1', + 'pause': false, + 'rootLibUri': 'main.dart.incremental.dill', + }, + jsonResponse: { + 'type': 'ReloadReport', + 'success': false, + 'notices': [ + { + 'message': 'Failed to hot reload', + }, + ], + 'details': {}, + }, + ), + listViews, + FakeVmServiceRequest( + method: 'getIsolate', + args: { + 'isolateId': '1', + }, + jsonResponse: fakeUnpausedIsolate.toJson(), + ), + FakeVmServiceRequest( + method: 'ext.flutter.reassemble', + args: { + 'isolateId': fakeUnpausedIsolate.id, + }, + ), + ]); + final Completer futureConnectionInfo = Completer.sync(); + final Completer futureAppStart = Completer.sync(); + unawaited(residentRunner.attach( + appStartedCompleter: futureAppStart, + connectionInfoCompleter: futureConnectionInfo, + enableDevTools: true, + )); + await futureAppStart.future; + flutterDevice.report = UpdateFSReport(success: true, invalidatedSourcesCount: 1); + + final OperationResult result = await residentRunner.restart(); + + expect(result.fatal, false); + expect(result.message, contains('Reload rejected: Failed to hot reload')); // contains error message from reload report. + expect(result.code, 1); + expect(devFS.lastCompiled, null); + })); + + testUsingContext('ResidentRunner can send target platform to analytics from hot reload', () => testbed.run(() async { + fakeVmServiceHost = FakeVmServiceHost(requests: [ + listViews, + listViews, + listViews, + FakeVmServiceRequest( + method: 'getVM', + jsonResponse: vm_service.VM.parse({ + 'isolates': [ + fakeUnpausedIsolate.toJson(), + ], + })!.toJson(), + ), + const FakeVmServiceRequest( + method: kReloadSourcesServiceName, + args: { + 'isolateId': '1', + 'pause': false, + 'rootLibUri': 'main.dart.incremental.dill', + }, + jsonResponse: { + 'type': 'ReloadReport', + 'success': true, + 'details': { + 'loadedLibraryCount': 1, + }, + }, + ), + FakeVmServiceRequest( + method: 'getIsolatePauseEvent', + args: { + 'isolateId': '1', + }, + jsonResponse: fakeUnpausedEvent.toJson(), + ), + FakeVmServiceRequest( + method: 'ext.flutter.reassemble', + args: { + 'isolateId': fakeUnpausedIsolate.id, + }, + ), + ]); + final Completer futureConnectionInfo = Completer.sync(); + final Completer futureAppStart = Completer.sync(); + unawaited(residentRunner.attach( + appStartedCompleter: futureAppStart, + connectionInfoCompleter: futureConnectionInfo, + enableDevTools: true, + )); + await futureAppStart.future; + + final OperationResult result = await residentRunner.restart(); + expect(result.fatal, false); + expect(result.code, 0); + + final TestUsageEvent event = (globals.flutterUsage as TestUsage).events.first; + expect(event.category, 'hot'); + expect(event.parameter, 'reload'); + expect(event.parameters?.hotEventTargetPlatform, getNameForTargetPlatform(TargetPlatform.android_arm)); + + final Event newEvent = fakeAnalytics.sentEvents.first; + expect(newEvent.eventName.label, 'hot_runner_info'); + expect(newEvent.eventData['label'], 'reload'); + expect(newEvent.eventData['targetPlatform'], getNameForTargetPlatform(TargetPlatform.android_arm)); + + }, overrides: { + Usage: () => TestUsage(), + })); + + testUsingContext('ResidentRunner reports hot reload time details', () => testbed.run(() async { + fakeVmServiceHost = FakeVmServiceHost(requests: [ + listViews, + FakeVmServiceRequest( + method: 'getVM', + jsonResponse: fakeVM.toJson(), + ), + listViews, + listViews, + FakeVmServiceRequest( + method: 'getVM', + jsonResponse: fakeVM.toJson(), + ), + const FakeVmServiceRequest( + method: kReloadSourcesServiceName, + args: { + 'isolateId': '1', + 'pause': false, + 'rootLibUri': 'main.dart.incremental.dill', + }, + jsonResponse: { + 'type': 'ReloadReport', + 'success': true, + 'details': { + 'loadedLibraryCount': 1, + 'finalLibraryCount': 42, + }, + }, + ), + FakeVmServiceRequest( + method: 'getIsolatePauseEvent', + args: { + 'isolateId': '1', + }, + jsonResponse: fakeUnpausedEvent.toJson(), + ), + FakeVmServiceRequest( + method: 'ext.flutter.reassemble', + args: { + 'isolateId': fakeUnpausedIsolate.id, + }, + ), + ]); + final FakeDelegateFlutterDevice flutterDevice = FakeDelegateFlutterDevice( + device, + BuildInfo.debug, + FakeResidentCompiler(), + devFS, + )..vmService = fakeVmServiceHost!.vmService; + residentRunner = HotRunner( + [ + flutterDevice, + ], + stayResident: false, + debuggingOptions: DebuggingOptions.enabled(BuildInfo.debug), + target: 'main.dart', + devtoolsHandler: createNoOpHandler, + analytics: fakeAnalytics, + ); + devFS.nextUpdateReport = UpdateFSReport( + success: true, + invalidatedSourcesCount: 1, + ); + + final Completer futureConnectionInfo = Completer.sync(); + final Completer futureAppStart = Completer.sync(); + unawaited(residentRunner.attach( + appStartedCompleter: futureAppStart, + connectionInfoCompleter: futureConnectionInfo, + enableDevTools: true, + )); + + await futureAppStart.future; + await residentRunner.restart(); + + // The actual test: Expect to have compile, reload and reassemble times. + expect( + testLogger.statusText, + contains(RegExp(r'Reloaded 1 of 42 libraries in \d+ms ' + r'\(compile: \d+ ms, reload: \d+ ms, reassemble: \d+ ms\)\.'))); + }, overrides: { + FileSystem: () => MemoryFileSystem.test(), + Platform: () => FakePlatform(), + ProjectFileInvalidator: () => FakeProjectFileInvalidator(), + Usage: () => TestUsage(), + })); + + testUsingContext('ResidentRunner can send target platform to analytics from full restart', () => testbed.run(() async { + fakeVmServiceHost = FakeVmServiceHost(requests: [ + listViews, + listViews, + listViews, + FakeVmServiceRequest( + method: 'getIsolate', + args: { + 'isolateId': fakeUnpausedIsolate.id, + }, + jsonResponse: fakeUnpausedIsolate.toJson(), + ), + FakeVmServiceRequest( + method: 'getVM', + jsonResponse: vm_service.VM.parse({})!.toJson(), + ), + listViews, + const FakeVmServiceRequest( + method: 'streamListen', + args: { + 'streamId': 'Isolate', + }, + ), + FakeVmServiceRequest( + method: kRunInViewMethod, + args: { + 'viewId': fakeFlutterView.id, + 'mainScript': 'main.dart.dill', + 'assetDirectory': 'build/flutter_assets', + }, + ), + FakeVmServiceStreamResponse( + streamId: 'Isolate', + event: vm_service.Event( + timestamp: 0, + kind: vm_service.EventKind.kIsolateRunnable, + ) + ), + ]); + final Completer futureConnectionInfo = Completer.sync(); + final Completer futureAppStart = Completer.sync(); + unawaited(residentRunner.attach( + appStartedCompleter: futureAppStart, + connectionInfoCompleter: futureConnectionInfo, + enableDevTools: true, + )); + + final OperationResult result = await residentRunner.restart(fullRestart: true); + expect(result.fatal, false); + expect(result.code, 0); + + final TestUsageEvent event = (globals.flutterUsage as TestUsage).events.first; + expect(event.category, 'hot'); + expect(event.parameter, 'restart'); + expect(event.parameters?.hotEventTargetPlatform, getNameForTargetPlatform(TargetPlatform.android_arm)); + expect(fakeVmServiceHost?.hasRemainingExpectations, false); + + // Parse out the event of interest since we may have timing events with + // the new analytics package + final List newEventList = fakeAnalytics.sentEvents.where((Event e) => e.eventName == DashEvent.hotRunnerInfo).toList(); + expect(newEventList, hasLength(1)); + final Event newEvent = newEventList.first; + expect(newEvent.eventName.label, 'hot_runner_info'); + expect(newEvent.eventData['label'], 'restart'); + expect(newEvent.eventData['targetPlatform'], getNameForTargetPlatform(TargetPlatform.android_arm)); + + }, overrides: { + Usage: () => TestUsage(), + })); + + testUsingContext('ResidentRunner can remove breakpoints and exception-pause-mode from paused isolate during hot restart', () => testbed.run(() async { + fakeVmServiceHost = FakeVmServiceHost(requests: [ + listViews, + listViews, + listViews, + FakeVmServiceRequest( + method: 'getIsolate', + args: { + 'isolateId': fakeUnpausedIsolate.id, + }, + jsonResponse: fakePausedIsolate.toJson(), + ), + FakeVmServiceRequest( + method: 'getVM', + jsonResponse: vm_service.VM.parse({})!.toJson(), + ), + const FakeVmServiceRequest( + method: 'setIsolatePauseMode', + args: { + 'isolateId': '1', + 'exceptionPauseMode': 'None', + } + ), + const FakeVmServiceRequest( + method: 'removeBreakpoint', + args: { + 'isolateId': '1', + 'breakpointId': 'test-breakpoint', + } + ), + const FakeVmServiceRequest( + method: 'resume', + args: { + 'isolateId': '1', + } + ), + listViews, + const FakeVmServiceRequest( + method: 'streamListen', + args: { + 'streamId': 'Isolate', + }, + ), + FakeVmServiceRequest( + method: kRunInViewMethod, + args: { + 'viewId': fakeFlutterView.id, + 'mainScript': 'main.dart.dill', + 'assetDirectory': 'build/flutter_assets', + }, + ), + FakeVmServiceStreamResponse( + streamId: 'Isolate', + event: vm_service.Event( + timestamp: 0, + kind: vm_service.EventKind.kIsolateRunnable, + ), + ), + ]); + final Completer futureConnectionInfo = Completer.sync(); + final Completer futureAppStart = Completer.sync(); + unawaited(residentRunner.attach( + appStartedCompleter: futureAppStart, + connectionInfoCompleter: futureConnectionInfo, + enableDevTools: true, + )); + + final OperationResult result = await residentRunner.restart(fullRestart: true); + + expect(result.isOk, true); + expect(fakeVmServiceHost?.hasRemainingExpectations, false); + })); + + testUsingContext('ResidentRunner will alternative the name of the dill file uploaded for a hot restart', () => testbed.run(() async { + fakeVmServiceHost = FakeVmServiceHost(requests: [ + listViews, + listViews, + listViews, + FakeVmServiceRequest( + method: 'getIsolate', + args: { + 'isolateId': fakeUnpausedIsolate.id, + }, + jsonResponse: fakeUnpausedIsolate.toJson(), + ), + FakeVmServiceRequest( + method: 'getVM', + jsonResponse: vm_service.VM.parse({})!.toJson(), + ), + listViews, + const FakeVmServiceRequest( + method: 'streamListen', + args: { + 'streamId': 'Isolate', + }, + ), + FakeVmServiceRequest( + method: kRunInViewMethod, + args: { + 'viewId': fakeFlutterView.id, + 'mainScript': 'main.dart.dill', + 'assetDirectory': 'build/flutter_assets', + }, + ), + FakeVmServiceStreamResponse( + streamId: 'Isolate', + event: vm_service.Event( + timestamp: 0, + kind: vm_service.EventKind.kIsolateRunnable, + ), + ), + listViews, + FakeVmServiceRequest( + method: 'getIsolate', + args: { + 'isolateId': fakeUnpausedIsolate.id, + }, + jsonResponse: fakeUnpausedIsolate.toJson(), + ), + FakeVmServiceRequest( + method: 'getVM', + jsonResponse: vm_service.VM.parse({})!.toJson(), + ), + listViews, + const FakeVmServiceRequest( + method: 'streamListen', + args: { + 'streamId': 'Isolate', + }, + ), + FakeVmServiceRequest( + method: kRunInViewMethod, + args: { + 'viewId': fakeFlutterView.id, + 'mainScript': 'main.dart.swap.dill', + 'assetDirectory': 'build/flutter_assets', + }, + ), + FakeVmServiceStreamResponse( + streamId: 'Isolate', + event: vm_service.Event( + timestamp: 0, + kind: vm_service.EventKind.kIsolateRunnable, + ), + ), + listViews, + FakeVmServiceRequest( + method: 'getIsolate', + args: { + 'isolateId': fakeUnpausedIsolate.id, + }, + jsonResponse: fakeUnpausedIsolate.toJson(), + ), + FakeVmServiceRequest( + method: 'getVM', + jsonResponse: vm_service.VM.parse({})!.toJson(), + ), + listViews, + const FakeVmServiceRequest( + method: 'streamListen', + args: { + 'streamId': 'Isolate', + }, + ), + FakeVmServiceRequest( + method: kRunInViewMethod, + args: { + 'viewId': fakeFlutterView.id, + 'mainScript': 'main.dart.dill', + 'assetDirectory': 'build/flutter_assets', + }, + ), + FakeVmServiceStreamResponse( + streamId: 'Isolate', + event: vm_service.Event( + timestamp: 0, + kind: vm_service.EventKind.kIsolateRunnable, + ), + ), + ]); + final Completer futureConnectionInfo = Completer.sync(); + final Completer futureAppStart = Completer.sync(); + unawaited(residentRunner.attach( + appStartedCompleter: futureAppStart, + connectionInfoCompleter: futureConnectionInfo, + enableDevTools: true, + )); + + await residentRunner.restart(fullRestart: true); + await residentRunner.restart(fullRestart: true); + await residentRunner.restart(fullRestart: true); + + expect(fakeVmServiceHost?.hasRemainingExpectations, false); + })); + + testUsingContext('ResidentRunner Can handle an RPC exception from hot restart', () => testbed.run(() async { + fakeVmServiceHost = FakeVmServiceHost(requests: [ + listViews, + listViews, + ]); + final Completer futureConnectionInfo = Completer.sync(); + final Completer futureAppStart = Completer.sync(); + unawaited(residentRunner.attach( + appStartedCompleter: futureAppStart, + connectionInfoCompleter: futureConnectionInfo, + enableDevTools: true, + )); + await futureAppStart.future; + flutterDevice.reportError = vm_service.RPCError('something bad happened', 666, ''); + + final OperationResult result = await residentRunner.restart(fullRestart: true); + expect(result.fatal, true); + expect(result.code, 1); + + expect((globals.flutterUsage as TestUsage).events, contains( + TestUsageEvent('hot', 'exception', parameters: CustomDimensions( + hotEventTargetPlatform: getNameForTargetPlatform(TargetPlatform.android_arm), + hotEventSdkName: 'Android', + hotEventEmulator: false, + hotEventFullRestart: true, + )), + )); + expect(fakeAnalytics.sentEvents, contains( + Event.hotRunnerInfo( + label: 'exception', + targetPlatform: getNameForTargetPlatform(TargetPlatform.android_arm), + sdkName: 'Android', + emulator: false, + fullRestart: true, + ), + )); + expect(fakeVmServiceHost?.hasRemainingExpectations, false); + }, overrides: { + Usage: () => TestUsage(), + })); + + testUsingContext('ResidentRunner uses temp directory when there is no output dill path', () => testbed.run(() { + fakeVmServiceHost = FakeVmServiceHost(requests: []); + expect(residentRunner.artifactDirectory.path, contains('flutter_tool.')); + + final ResidentRunner otherRunner = HotRunner( + [ + flutterDevice, + ], + stayResident: false, + debuggingOptions: DebuggingOptions.enabled(BuildInfo.debug), + dillOutputPath: globals.fs.path.join('foobar', 'app.dill'), + target: 'main.dart', + devtoolsHandler: createNoOpHandler, + analytics: fakeAnalytics, + ); + expect(otherRunner.artifactDirectory.path, contains('foobar')); + })); + + testUsingContext('ResidentRunner deletes artifact directory on preExit', () => testbed.run(() async { + fakeVmServiceHost = FakeVmServiceHost(requests: []); + residentRunner.artifactDirectory.childFile('app.dill').createSync(); + await residentRunner.preExit(); + + expect(residentRunner.artifactDirectory, isNot(exists)); + })); + + testUsingContext('ResidentRunner can run source generation', () => testbed.run(() async { + final File arbFile = globals.fs.file(globals.fs.path.join('lib', 'l10n', 'app_en.arb')) + ..createSync(recursive: true); + arbFile.writeAsStringSync(''' +{ + "helloWorld": "Hello, World!", + "@helloWorld": { + "description": "Sample description" + } +}'''); + globals.fs.file('l10n.yaml').createSync(); + globals.fs.file('pubspec.yaml').writeAsStringSync('flutter:\n generate: true\n'); + + // Create necessary files for [DartPluginRegistrantTarget] + final File packageConfig = globals.fs.directory('.dart_tool') + .childFile('package_config.json'); + packageConfig.createSync(recursive: true); + packageConfig.writeAsStringSync(''' +{ + "configVersion": 2, + "packages": [ + { + "name": "path_provider_linux", + "rootUri": "../../../path_provider_linux", + "packageUri": "lib/", + "languageVersion": "2.12" + } + ] +} +'''); + // Start from an empty dart_plugin_registrant.dart file. + globals.fs.directory('.dart_tool').childDirectory('flutter_build').childFile('dart_plugin_registrant.dart').createSync(recursive: true); + + await residentRunner.runSourceGenerators(); + + expect(testLogger.errorText, isEmpty); + expect(testLogger.statusText, isEmpty); + })); + + testUsingContext('generated main uses correct target', () => testbed.run(() async { + final File arbFile = globals.fs.file(globals.fs.path.join('lib', 'l10n', 'app_en.arb')) + ..createSync(recursive: true); + arbFile.writeAsStringSync(''' +{ + "helloWorld": "Hello, World!", + "@helloWorld": { + "description": "Sample description" + } +}'''); + globals.fs.file('l10n.yaml').createSync(); + globals.fs.file('pubspec.yaml').writeAsStringSync(''' +flutter: + generate: true + +dependencies: + flutter: + sdk: flutter + path_provider_linux: 1.0.0 +'''); + + // Create necessary files for [DartPluginRegistrantTarget], including a + // plugin that will trigger generation. + final File packageConfig = globals.fs.directory('.dart_tool') + .childFile('package_config.json'); + packageConfig.createSync(recursive: true); + packageConfig.writeAsStringSync(''' +{ + "configVersion": 2, + "packages": [ + { + "name": "path_provider_linux", + "rootUri": "../path_provider_linux", + "packageUri": "lib/", + "languageVersion": "2.12" + } + ] +} +'''); + globals.fs.file('.packages').writeAsStringSync(''' +path_provider_linux:/path_provider_linux/lib/ +'''); + final Directory fakePluginDir = globals.fs.directory('path_provider_linux'); + final File pluginPubspec = fakePluginDir.childFile('pubspec.yaml'); + pluginPubspec.createSync(recursive: true); + pluginPubspec.writeAsStringSync(''' +name: path_provider_linux + +flutter: + plugin: + implements: path_provider + platforms: + linux: + dartPluginClass: PathProviderLinux +'''); + + residentRunner = HotRunner( + [ + flutterDevice, + ], + stayResident: false, + debuggingOptions: DebuggingOptions.enabled(BuildInfo.debug), + target: 'custom_main.dart', + devtoolsHandler: createNoOpHandler, + analytics: fakeAnalytics, + ); + await residentRunner.runSourceGenerators(); + + final File generatedMain = globals.fs.directory('.dart_tool') + .childDirectory('flutter_build') + .childFile('dart_plugin_registrant.dart'); + + expect(generatedMain.existsSync(), isTrue); + expect(testLogger.errorText, isEmpty); + expect(testLogger.statusText, isEmpty); + })); + + testUsingContext('ResidentRunner can run source generation - generation fails', () => testbed.run(() async { + // Intentionally define arb file with wrong name. generate_localizations defaults + // to app_en.arb. + final File arbFile = globals.fs.file(globals.fs.path.join('lib', 'l10n', 'foo.arb')) + ..createSync(recursive: true); + arbFile.writeAsStringSync(''' +{ + "helloWorld": "Hello, World!", + "@helloWorld": { + "description": "Sample description" + } +}'''); + globals.fs.file('l10n.yaml').createSync(); + globals.fs.file('pubspec.yaml').writeAsStringSync('flutter:\n generate: true\n'); + + await residentRunner.runSourceGenerators(); + + expect(testLogger.errorText, contains('Error')); + expect(testLogger.statusText, isEmpty); + })); + + testUsingContext('ResidentRunner generates files when l10n.yaml exists', () => testbed.run(() async { + globals.fs.file(globals.fs.path.join('lib', 'main.dart')) + .createSync(recursive: true); + final File arbFile = globals.fs.file(globals.fs.path.join('lib', 'l10n', 'app_en.arb')) + ..createSync(recursive: true); + arbFile.writeAsStringSync(''' +{ + "helloWorld": "Hello, World!", + "@helloWorld": { + "description": "Sample description" + } +}'''); + globals.fs.file('l10n.yaml').createSync(); + globals.fs.file('pubspec.yaml').writeAsStringSync('flutter:\n generate: true\n'); + + fakeVmServiceHost = FakeVmServiceHost(requests: []); + final FakeResidentCompiler residentCompiler = FakeResidentCompiler() + ..nextOutput = const CompilerOutput('foo', 1 ,[]); + residentRunner = HotRunner( + [ + flutterDevice, + ], + stayResident: false, + debuggingOptions: DebuggingOptions.enabled(BuildInfo.debug), + target: 'main.dart', + devtoolsHandler: createNoOpHandler, + analytics: fakeAnalytics, + ); + flutterDevice.generator = residentCompiler; + + await residentRunner.run(); + + final File generatedLocalizationsFile = globals.fs.directory('.dart_tool') + .childDirectory('flutter_gen') + .childDirectory('gen_l10n') + .childFile('app_localizations.dart'); + expect(generatedLocalizationsFile.existsSync(), isTrue); + + // Completing this future ensures that the daemon can exit correctly. + expect(await residentRunner.waitForAppToFinish(), 1); + })); + + testUsingContext('ResidentRunner printHelpDetails hot runner', () => testbed.run(() { + fakeVmServiceHost = FakeVmServiceHost(requests: []); + + residentRunner.printHelp(details: true); + + final CommandHelp commandHelp = residentRunner.commandHelp; + + // supports service protocol + expect(residentRunner.supportsServiceProtocol, true); + // isRunningDebug + expect(residentRunner.isRunningDebug, true); + // does support SkSL + expect(residentRunner.supportsWriteSkSL, true); + // commands + expect(testLogger.statusText, equals( + [ + 'Flutter run key commands.', + commandHelp.r, + commandHelp.R, + commandHelp.v, + commandHelp.s, + commandHelp.w, + commandHelp.t, + commandHelp.L, + commandHelp.f, + commandHelp.S, + commandHelp.U, + commandHelp.i, + commandHelp.p, + commandHelp.I, + commandHelp.o, + commandHelp.b, + commandHelp.P, + commandHelp.a, + commandHelp.M, + commandHelp.g, + commandHelp.j, + commandHelp.hWithDetails, + commandHelp.c, + commandHelp.q, + '', + 'A Dart VM Service on FakeDevice is available at: null', + '', + ].join('\n') + )); + })); + + testUsingContext('ResidentRunner printHelp hot runner', () => testbed.run(() { + fakeVmServiceHost = FakeVmServiceHost(requests: []); + + residentRunner.printHelp(details: false); + + final CommandHelp commandHelp = residentRunner.commandHelp; + + // supports service protocol + expect(residentRunner.supportsServiceProtocol, true); + // isRunningDebug + expect(residentRunner.isRunningDebug, true); + // does support SkSL + expect(residentRunner.supportsWriteSkSL, true); + // commands + expect(testLogger.statusText, equals( + [ + 'Flutter run key commands.', + commandHelp.r, + commandHelp.R, + commandHelp.hWithoutDetails, + commandHelp.c, + commandHelp.q, + '', + 'A Dart VM Service on FakeDevice is available at: null', + '', + ].join('\n') + )); + })); + + testUsingContext('ResidentRunner printHelpDetails cold runner', () => testbed.run(() { + fakeVmServiceHost = null; + residentRunner = ColdRunner( + [ + flutterDevice, + ], + stayResident: false, + debuggingOptions: DebuggingOptions.disabled(BuildInfo.release), + target: 'main.dart', + devtoolsHandler: createNoOpHandler, + ); + residentRunner.printHelp(details: true); + + final CommandHelp commandHelp = residentRunner.commandHelp; + + // does not supports service protocol + expect(residentRunner.supportsServiceProtocol, false); + // isRunningDebug + expect(residentRunner.isRunningDebug, false); + // does support SkSL + expect(residentRunner.supportsWriteSkSL, false); + // commands + expect(testLogger.statusText, equals( + [ + 'Flutter run key commands.', + commandHelp.v, + commandHelp.s, + commandHelp.hWithDetails, + commandHelp.c, + commandHelp.q, + '', + ].join('\n') + )); + })); + + testUsingContext('ResidentRunner printHelp cold runner', () => testbed.run(() { + fakeVmServiceHost = null; + residentRunner = ColdRunner( + [ + flutterDevice, + ], + stayResident: false, + debuggingOptions: DebuggingOptions.disabled(BuildInfo.release), + target: 'main.dart', + devtoolsHandler: createNoOpHandler, + ); + residentRunner.printHelp(details: false); + + final CommandHelp commandHelp = residentRunner.commandHelp; + + // does not supports service protocol + expect(residentRunner.supportsServiceProtocol, false); + // isRunningDebug + expect(residentRunner.isRunningDebug, false); + // does support SkSL + expect(residentRunner.supportsWriteSkSL, false); + // commands + expect(testLogger.statusText, equals( + [ + 'Flutter run key commands.', + commandHelp.hWithoutDetails, + commandHelp.c, + commandHelp.q, + '', + ].join('\n') + )); + })); + + testUsingContext('ResidentRunner handles writeSkSL returning no data', () => testbed.run(() async { + fakeVmServiceHost = FakeVmServiceHost(requests: [ + listViews, + FakeVmServiceRequest( + method: kGetSkSLsMethod, + args: { + 'viewId': fakeFlutterView.id, + }, + jsonResponse: { + 'SkSLs': {}, + } + ), + ]); + await residentRunner.writeSkSL(); + + expect(testLogger.statusText, contains('No data was received')); + expect(fakeVmServiceHost?.hasRemainingExpectations, false); + })); + + testUsingContext('ResidentRunner can write SkSL data to a unique file with engine revision, platform, and device name', () => testbed.run(() async { + fakeVmServiceHost = FakeVmServiceHost(requests: [ + listViews, + FakeVmServiceRequest( + method: kGetSkSLsMethod, + args: { + 'viewId': fakeFlutterView.id, + }, + jsonResponse: { + 'SkSLs': { + 'A': 'B', + }, + }, + ), + ]); + await residentRunner.writeSkSL(); + + expect(testLogger.statusText, contains('flutter_01.sksl.json')); + expect(globals.fs.file('flutter_01.sksl.json'), exists); + expect(json.decode(globals.fs.file('flutter_01.sksl.json').readAsStringSync()), { + 'platform': 'android', + 'name': 'FakeDevice', + 'engineRevision': 'abcdefg', + 'data': {'A': 'B'}, + }); + expect(fakeVmServiceHost?.hasRemainingExpectations, false); + }, overrides: { + FileSystemUtils: () => FileSystemUtils( + fileSystem: globals.fs, + platform: globals.platform, + ), + FlutterVersion: () => FakeFlutterVersion(engineRevision: 'abcdefg'), + })); + + testUsingContext('ResidentRunner ignores DevtoolsLauncher when attaching with enableDevTools: false - cold mode', () => testbed.run(() async { + fakeVmServiceHost = FakeVmServiceHost(requests: [ + listViews, + listViews, + ]); + residentRunner = ColdRunner( + [ + flutterDevice, + ], + stayResident: false, + debuggingOptions: DebuggingOptions.enabled(BuildInfo.profile, vmserviceOutFile: 'foo'), + target: 'main.dart', + devtoolsHandler: createNoOpHandler, + ); + + final Future result = residentRunner.attach(); + expect(await result, 0); + })); + + testUsingContext('FlutterDevice can exit from a release mode isolate with no VmService', () => testbed.run(() async { + final TestFlutterDevice flutterDevice = TestFlutterDevice( + device, + ); + + await flutterDevice.exitApps(); + + expect(device.appStopped, true); + })); + + testUsingContext('FlutterDevice will exit an un-paused isolate using stopApp', () => testbed.run(() async { + fakeVmServiceHost = FakeVmServiceHost(requests: []); + final TestFlutterDevice flutterDevice = TestFlutterDevice( + device, + ); + flutterDevice.vmService = fakeVmServiceHost!.vmService; + + final Future exitFuture = flutterDevice.exitApps(); + + await expectLater(exitFuture, completes); + expect(device.appStopped, true); + expect(fakeVmServiceHost?.hasRemainingExpectations, false); + })); + + testUsingContext('HotRunner writes vm service file when providing debugging option', () => testbed.run(() async { + fakeVmServiceHost = FakeVmServiceHost(requests: [ + listViews, + listViews, + ], wsAddress: testUri); + globals.fs.file(globals.fs.path.join('lib', 'main.dart')).createSync(recursive: true); + residentRunner = HotRunner( + [ + flutterDevice, + ], + stayResident: false, + debuggingOptions: DebuggingOptions.enabled(BuildInfo.debug, vmserviceOutFile: 'foo'), + target: 'main.dart', + devtoolsHandler: createNoOpHandler, + analytics: fakeAnalytics, + ); + + await residentRunner.run(enableDevTools: true); + + expect(fakeVmServiceHost?.hasRemainingExpectations, false); + expect(await globals.fs.file('foo').readAsString(), testUri.toString()); + })); + + testUsingContext('HotRunner copies compiled app.dill to cache during startup', () => testbed.run(() async { + fakeVmServiceHost = FakeVmServiceHost(requests: [ + listViews, + listViews, + ], wsAddress: testUri); + globals.fs.file(globals.fs.path.join('lib', 'main.dart')).createSync(recursive: true); + residentRunner = HotRunner( + [ + flutterDevice, + ], + stayResident: false, + debuggingOptions: DebuggingOptions.enabled( + const BuildInfo( + BuildMode.debug, + null, + treeShakeIcons: false, + ) + ), + target: 'main.dart', + devtoolsHandler: createNoOpHandler, + analytics: fakeAnalytics, + ); + residentRunner.artifactDirectory.childFile('app.dill').writeAsStringSync('ABC'); + + await residentRunner.run(enableDevTools: true); + + expect(await globals.fs.file(globals.fs.path.join('build', 'cache.dill')).readAsString(), 'ABC'); + })); + + testUsingContext('HotRunner copies compiled app.dill to cache during startup with dart defines', () => testbed.run(() async { + fakeVmServiceHost = FakeVmServiceHost(requests: [ + listViews, + listViews, + ], wsAddress: testUri); + globals.fs.file(globals.fs.path.join('lib', 'main.dart')).createSync(recursive: true); + residentRunner = HotRunner( + [ + flutterDevice, + ], + stayResident: false, + debuggingOptions: DebuggingOptions.enabled( + const BuildInfo( + BuildMode.debug, + '', + treeShakeIcons: false, + dartDefines: ['a', 'b'], + ) + ), + target: 'main.dart', + devtoolsHandler: createNoOpHandler, + analytics: fakeAnalytics, + ); + residentRunner.artifactDirectory.childFile('app.dill').writeAsStringSync('ABC'); + + await residentRunner.run(enableDevTools: true); + + expect(await globals.fs.file(globals.fs.path.join( + 'build', '187ef4436122d1cc2f40dc2b92f0eba0.cache.dill')).readAsString(), 'ABC'); + })); + + testUsingContext('HotRunner copies compiled app.dill to cache during startup with null safety', () => testbed.run(() async { + fakeVmServiceHost = FakeVmServiceHost(requests: [ + listViews, + listViews, + ], wsAddress: testUri); + globals.fs.file(globals.fs.path.join('lib', 'main.dart')).createSync(recursive: true); + residentRunner = HotRunner( + [ + flutterDevice, + ], + stayResident: false, + debuggingOptions: DebuggingOptions.enabled( + const BuildInfo( + BuildMode.debug, + '', + treeShakeIcons: false, + extraFrontEndOptions: ['--enable-experiment=non-nullable'] + ) + ), + target: 'main.dart', + devtoolsHandler: createNoOpHandler, + analytics: fakeAnalytics, + ); + residentRunner.artifactDirectory.childFile('app.dill').writeAsStringSync('ABC'); + + await residentRunner.run(enableDevTools: true); + + expect(await globals.fs.file(globals.fs.path.join( + 'build', 'cache.dill')).readAsString(), 'ABC'); + })); + + testUsingContext('HotRunner copies compiled app.dill to cache during startup with track-widget-creation', () => testbed.run(() async { + fakeVmServiceHost = FakeVmServiceHost(requests: [ + listViews, + listViews, + ], wsAddress: testUri); + globals.fs.file(globals.fs.path.join('lib', 'main.dart')).createSync(recursive: true); + residentRunner = HotRunner( + [ + flutterDevice, + ], + stayResident: false, + debuggingOptions: DebuggingOptions.enabled(BuildInfo.debug), + target: 'main.dart', + devtoolsHandler: createNoOpHandler, + analytics: fakeAnalytics, + ); + residentRunner.artifactDirectory.childFile('app.dill').writeAsStringSync('ABC'); + + await residentRunner.run(enableDevTools: true); + + expect(await globals.fs.file(globals.fs.path.join( + 'build', 'cache.dill.track.dill')).readAsString(), 'ABC'); + })); + + testUsingContext('HotRunner does not copy app.dill if a dillOutputPath is given', () => testbed.run(() async { + fakeVmServiceHost = FakeVmServiceHost(requests: [ + listViews, + listViews, + ], wsAddress: testUri); + globals.fs.file(globals.fs.path.join('lib', 'main.dart')).createSync(recursive: true); + residentRunner = HotRunner( + [ + flutterDevice, + ], + stayResident: false, + dillOutputPath: 'test', + debuggingOptions: DebuggingOptions.enabled(BuildInfo.debug), + target: 'main.dart', + devtoolsHandler: createNoOpHandler, + analytics: fakeAnalytics, + ); + residentRunner.artifactDirectory.childFile('app.dill').writeAsStringSync('ABC'); + + await residentRunner.run(enableDevTools: true); + + expect(globals.fs.file(globals.fs.path.join('build', 'cache.dill')), isNot(exists)); + })); + + testUsingContext('HotRunner copies compiled app.dill to cache during startup with --track-widget-creation', () => testbed.run(() async { + fakeVmServiceHost = FakeVmServiceHost(requests: [ + listViews, + listViews, + ], wsAddress: testUri); + globals.fs.file(globals.fs.path.join('lib', 'main.dart')).createSync(recursive: true); + residentRunner = HotRunner( + [ + flutterDevice, + ], + stayResident: false, + debuggingOptions: DebuggingOptions.enabled(const BuildInfo( + BuildMode.debug, + '', + treeShakeIcons: false, + trackWidgetCreation: true, + )), + target: 'main.dart', + devtoolsHandler: createNoOpHandler, + analytics: fakeAnalytics, + ); + residentRunner.artifactDirectory.childFile('app.dill').writeAsStringSync('ABC'); + + await residentRunner.run(enableDevTools: true); + + expect(await globals.fs.file(globals.fs.path.join('build', 'cache.dill.track.dill')).readAsString(), 'ABC'); + })); + + testUsingContext('HotRunner calls device dispose', () => testbed.run(() async { + fakeVmServiceHost = FakeVmServiceHost(requests: [ + listViews, + listViews, + ], wsAddress: testUri); + globals.fs.file(globals.fs.path.join('lib', 'main.dart')).createSync(recursive: true); + residentRunner = HotRunner( + [ + flutterDevice, + ], + stayResident: false, + debuggingOptions: DebuggingOptions.enabled(BuildInfo.debug), + target: 'main.dart', + devtoolsHandler: createNoOpHandler, + analytics: fakeAnalytics, + ); + + await residentRunner.run(); + expect(device.disposed, true); + })); + + testUsingContext('HotRunner handles failure to write vmservice file', () => testbed.run(() async { + fakeVmServiceHost = FakeVmServiceHost(requests: [ + listViews, + listViews, + ]); + globals.fs.file(globals.fs.path.join('lib', 'main.dart')).createSync(recursive: true); + residentRunner = HotRunner( + [ + flutterDevice, + ], + stayResident: false, + debuggingOptions: DebuggingOptions.enabled(BuildInfo.debug, vmserviceOutFile: 'foo'), + target: 'main.dart', + devtoolsHandler: createNoOpHandler, + analytics: fakeAnalytics, + ); + + await residentRunner.run(enableDevTools: true); + + expect(testLogger.errorText, contains('Failed to write vmservice-out-file at foo')); + expect(fakeVmServiceHost?.hasRemainingExpectations, false); + }, overrides: { + FileSystem: () => ThrowingForwardingFileSystem(MemoryFileSystem.test()), + })); + + testUsingContext('ColdRunner writes vm service file when providing debugging option', () => testbed.run(() async { + fakeVmServiceHost = FakeVmServiceHost(requests: [ + listViews, + ], wsAddress: testUri); + globals.fs.file(globals.fs.path.join('lib', 'main.dart')).createSync(recursive: true); + residentRunner = ColdRunner( + [ + flutterDevice, + ], + stayResident: false, + debuggingOptions: DebuggingOptions.enabled(BuildInfo.profile, vmserviceOutFile: 'foo'), + target: 'main.dart', + devtoolsHandler: createNoOpHandler, + ); + + await residentRunner.run(enableDevTools: true); + + expect(await globals.fs.file('foo').readAsString(), testUri.toString()); + expect(fakeVmServiceHost?.hasRemainingExpectations, false); + })); + + testUsingContext('FlutterDevice uses dartdevc configuration when targeting web', () async { + fakeVmServiceHost = FakeVmServiceHost(requests: []); + final FakeDevice device = FakeDevice(targetPlatform: TargetPlatform.web_javascript); + final DefaultResidentCompiler? residentCompiler = (await FlutterDevice.create( + device, + buildInfo: const BuildInfo( + BuildMode.debug, + '', + treeShakeIcons: false, + nullSafetyMode: NullSafetyMode.unsound, + ), + target: null, + platform: FakePlatform(), + )).generator as DefaultResidentCompiler?; + + expect(residentCompiler!.initializeFromDill, + globals.fs.path.join(getBuildDirectory(), 'fbbe6a61fb7a1de317d381f8df4814e5.cache.dill')); + expect(residentCompiler.librariesSpec, + globals.fs.file(globals.artifacts!.getHostArtifact(HostArtifact.flutterWebLibrariesJson)) + .uri.toString()); + expect(residentCompiler.targetModel, TargetModel.dartdevc); + expect(residentCompiler.sdkRoot, + '${globals.artifacts!.getHostArtifact(HostArtifact.flutterWebSdk).path}/'); + expect(residentCompiler.platformDill, 'file:///HostArtifact.webPlatformKernelFolder/ddc_outline.dill'); + }, overrides: { + Artifacts: () => Artifacts.test(), + FileSystem: () => MemoryFileSystem.test(), + ProcessManager: () => FakeProcessManager.any(), + }); + + testUsingContext('FlutterDevice uses dartdevc configuration when targeting web with null-safety autodetected', () async { + fakeVmServiceHost = FakeVmServiceHost(requests: []); + final FakeDevice device = FakeDevice(targetPlatform: TargetPlatform.web_javascript); + + final DefaultResidentCompiler? residentCompiler = (await FlutterDevice.create( + device, + buildInfo: const BuildInfo( + BuildMode.debug, + '', + treeShakeIcons: false, + extraFrontEndOptions: ['--enable-experiment=non-nullable'], + ), + target: null, + platform: FakePlatform(), + )).generator as DefaultResidentCompiler?; + + expect(residentCompiler!.initializeFromDill, + globals.fs.path.join(getBuildDirectory(), '80b1a4cf4e7b90e1ab5f72022a0bc624.cache.dill')); + expect(residentCompiler.librariesSpec, + globals.fs.file(globals.artifacts!.getHostArtifact(HostArtifact.flutterWebLibrariesJson)) + .uri.toString()); + expect(residentCompiler.targetModel, TargetModel.dartdevc); + expect(residentCompiler.sdkRoot, + '${globals.artifacts!.getHostArtifact(HostArtifact.flutterWebSdk).path}/'); + expect(residentCompiler.platformDill, 'file:///HostArtifact.webPlatformKernelFolder/ddc_outline_sound.dill'); + }, overrides: { + Artifacts: () => Artifacts.test(), + FileSystem: () => MemoryFileSystem.test(), + ProcessManager: () => FakeProcessManager.any(), + }); + + testUsingContext('FlutterDevice passes alternative-invalidation-strategy flag', () async { + fakeVmServiceHost = FakeVmServiceHost(requests: []); + final FakeDevice device = FakeDevice(); + + + final DefaultResidentCompiler? residentCompiler = (await FlutterDevice.create( + device, + buildInfo: const BuildInfo( + BuildMode.debug, + '', + treeShakeIcons: false, + extraFrontEndOptions: [], + ), + target: null, platform: FakePlatform(), + )).generator as DefaultResidentCompiler?; + + expect(residentCompiler!.extraFrontEndOptions, + contains('--enable-experiment=alternative-invalidation-strategy')); + }, overrides: { + Artifacts: () => Artifacts.test(), + FileSystem: () => MemoryFileSystem.test(), + ProcessManager: () => FakeProcessManager.any(), + }); + + testUsingContext('FlutterDevice passes initializeFromDill parameter if specified', () async { + fakeVmServiceHost = FakeVmServiceHost(requests: []); + final FakeDevice device = FakeDevice(); + + final DefaultResidentCompiler? residentCompiler = (await FlutterDevice.create( + device, + buildInfo: const BuildInfo( + BuildMode.debug, + '', + treeShakeIcons: false, + extraFrontEndOptions: [], + initializeFromDill: '/foo/bar.dill', + ), + target: null, platform: FakePlatform(), + )).generator as DefaultResidentCompiler?; + + expect(residentCompiler!.initializeFromDill, '/foo/bar.dill'); + expect(residentCompiler.assumeInitializeFromDillUpToDate, false); + }, overrides: { + Artifacts: () => Artifacts.test(), + FileSystem: () => MemoryFileSystem.test(), + ProcessManager: () => FakeProcessManager.any(), + }); + + testUsingContext('FlutterDevice passes assumeInitializeFromDillUpToDate parameter if specified', () async { + fakeVmServiceHost = FakeVmServiceHost(requests: []); + final FakeDevice device = FakeDevice(); + + final DefaultResidentCompiler? residentCompiler = (await FlutterDevice.create( + device, + buildInfo: const BuildInfo( + BuildMode.debug, + '', + treeShakeIcons: false, + extraFrontEndOptions: [], + assumeInitializeFromDillUpToDate: true, + ), + target: null, platform: FakePlatform(), + )).generator as DefaultResidentCompiler?; + + expect(residentCompiler!.assumeInitializeFromDillUpToDate, true); + }, overrides: { + Artifacts: () => Artifacts.test(), + FileSystem: () => MemoryFileSystem.test(), + ProcessManager: () => FakeProcessManager.any(), + }); + + testUsingContext('FlutterDevice passes frontendServerStarterPath parameter if specified', () async { + fakeVmServiceHost = FakeVmServiceHost(requests: []); + final FakeDevice device = FakeDevice(); + + final DefaultResidentCompiler? residentCompiler = (await FlutterDevice.create( + device, + buildInfo: const BuildInfo( + BuildMode.debug, + '', + treeShakeIcons: false, + frontendServerStarterPath: '/foo/bar/frontend_server_starter.dart', + ), + target: null, platform: FakePlatform(), + )).generator as DefaultResidentCompiler?; + + expect(residentCompiler!.frontendServerStarterPath, '/foo/bar/frontend_server_starter.dart'); + }, overrides: { + Artifacts: () => Artifacts.test(), + FileSystem: () => MemoryFileSystem.test(), + ProcessManager: () => FakeProcessManager.any(), + }); + + testUsingContext('Handle existing VM service clients DDS error', () => testbed.run(() async { + fakeVmServiceHost = FakeVmServiceHost(requests: []); + final FakeDevice device = FakeDevice() + ..dds = DartDevelopmentService(); + ddsLauncherCallback = (Uri uri, {bool enableAuthCodes = true, bool ipv6 = false, Uri? serviceUri, List cachedUserTags = const [], dds.UriConverter? uriConverter}) { + expect(uri, Uri(scheme: 'foo', host: 'bar')); + expect(enableAuthCodes, isTrue); + expect(ipv6, isFalse); + expect(serviceUri, Uri(scheme: 'http', host: '127.0.0.1', port: 0)); + expect(cachedUserTags, isEmpty); + expect(uriConverter, isNull); + throw FakeDartDevelopmentServiceException(message: + 'Existing VM service clients prevent DDS from taking control.', + ); + }; + final TestFlutterDevice flutterDevice = TestFlutterDevice( + device, + vmServiceUris: Stream.value(testUri), + ); + bool caught = false; + final Completerdone = Completer(); + runZonedGuarded(() { + flutterDevice.connect(allowExistingDdsInstance: true).then((_) => done.complete()); + }, (Object e, StackTrace st) { + expect(e, isA()); + expect((e as ToolExit).message, + contains('Existing VM service clients prevent DDS from taking control.', + )); + done.complete(); + caught = true; + }); + await done.future; + if (!caught) { + fail('Expected ToolExit to be thrown.'); + } + }, overrides: { + VMServiceConnector: () => (Uri httpUri, { + ReloadSources? reloadSources, + Restart? restart, + CompileExpression? compileExpression, + GetSkSLMethod? getSkSLMethod, + FlutterProject? flutterProject, + PrintStructuredErrorLogMethod? printStructuredErrorLogMethod, + io.CompressionOptions? compression, + Device? device, + required Logger logger, + }) async => FakeVmServiceHost(requests: []).vmService, + })); + + testUsingContext('Uses existing DDS URI from exception field', () => testbed.run(() async { + fakeVmServiceHost = FakeVmServiceHost(requests: []); + final FakeDevice device = FakeDevice() + ..dds = DartDevelopmentService(); + ddsLauncherCallback = (Uri uri, {bool enableAuthCodes = true, bool ipv6 = false, Uri? serviceUri, List cachedUserTags = const [], dds.UriConverter? uriConverter}) { + throw dds.DartDevelopmentServiceException.existingDdsInstance( + 'Existing DDS at http://localhost/existingDdsInMessage.', + ddsUri: Uri.parse('http://localhost/existingDdsInField'), + ); + }; + final TestFlutterDevice flutterDevice = TestFlutterDevice( + device, + vmServiceUris: Stream.value(testUri), + ); + final Completer done = Completer(); + await runZonedGuarded( + () => flutterDevice.connect(allowExistingDdsInstance: true).then((_) => done.complete()), + (_, __) => done.complete(), + ); + await done.future; + expect(device.dds.uri, Uri.parse('http://localhost/existingDdsInField')); + }, overrides: { + VMServiceConnector: () => (Uri httpUri, { + ReloadSources? reloadSources, + Restart? restart, + CompileExpression? compileExpression, + GetSkSLMethod? getSkSLMethod, + FlutterProject? flutterProject, + PrintStructuredErrorLogMethod? printStructuredErrorLogMethod, + io.CompressionOptions? compression, + Device? device, + required Logger logger, + }) async => FakeVmServiceHost(requests: []).vmService, + })); + + testUsingContext('Falls back to existing DDS URI from exception message', () => testbed.run(() async { + fakeVmServiceHost = FakeVmServiceHost(requests: []); + final FakeDevice device = FakeDevice() + ..dds = DartDevelopmentService(); + ddsLauncherCallback = (Uri uri, {bool enableAuthCodes = true, bool ipv6 = false, Uri? serviceUri, List cachedUserTags = const [], dds.UriConverter? uriConverter}) { + throw dds.DartDevelopmentServiceException.existingDdsInstance( + 'Existing DDS at http://localhost/existingDdsInMessage.', + ); + }; + final TestFlutterDevice flutterDevice = TestFlutterDevice( + device, + vmServiceUris: Stream.value(testUri), + ); + final Completerdone = Completer(); + await runZonedGuarded( + () => flutterDevice.connect(allowExistingDdsInstance: true).then((_) => done.complete()), + (_, __) => done.complete(), + ); + await done.future; + expect(device.dds.uri, Uri.parse('http://localhost/existingDdsInMessage')); + }, overrides: { + VMServiceConnector: () => (Uri httpUri, { + ReloadSources? reloadSources, + Restart? restart, + CompileExpression? compileExpression, + GetSkSLMethod? getSkSLMethod, + FlutterProject? flutterProject, + PrintStructuredErrorLogMethod? printStructuredErrorLogMethod, + io.CompressionOptions? compression, + Device? device, + required Logger logger, + }) async => FakeVmServiceHost(requests: []).vmService, + })); + + testUsingContext('Host VM service ipv6 defaults', () => testbed.run(() async { + fakeVmServiceHost = FakeVmServiceHost(requests: []); + final FakeDevice device = FakeDevice() + ..dds = DartDevelopmentService(); + final Completerdone = Completer(); + ddsLauncherCallback = (Uri uri, {bool enableAuthCodes = true, bool ipv6 = false, Uri? serviceUri, List cachedUserTags = const [], dds.UriConverter? uriConverter}) async { + expect(uri, Uri(scheme: 'foo', host: 'bar')); + expect(enableAuthCodes, isFalse); + expect(ipv6, isTrue); + expect(serviceUri, Uri(scheme: 'http', host: '::1', port: 0)); + expect(cachedUserTags, isEmpty); + expect(uriConverter, isNull); + done.complete(); + return FakeDartDevelopmentService(); + }; + final TestFlutterDevice flutterDevice = TestFlutterDevice( + device, + vmServiceUris: Stream.value(testUri), + ); + await flutterDevice.connect(allowExistingDdsInstance: true, ipv6: true, disableServiceAuthCodes: true); + await done.future; + }, overrides: { + VMServiceConnector: () => (Uri httpUri, { + ReloadSources? reloadSources, + Restart? restart, + CompileExpression? compileExpression, + GetSkSLMethod? getSkSLMethod, + FlutterProject? flutterProject, + PrintStructuredErrorLogMethod? printStructuredErrorLogMethod, + io.CompressionOptions? compression, + Device? device, + required Logger logger, + }) async => FakeVmServiceHost(requests: []).vmService, + })); + + testUsingContext('Context includes URI converter', () => testbed.run(() async { + fakeVmServiceHost = FakeVmServiceHost(requests: []); + final FakeDevice device = FakeDevice() + ..dds = DartDevelopmentService(); + final Completerdone = Completer(); + ddsLauncherCallback = ( + Uri uri, { + bool enableAuthCodes = false, + bool ipv6 = false, + Uri? serviceUri, + List cachedUserTags = const [], + dds.UriConverter? uriConverter, + }) async { + expect(uri, Uri(scheme: 'foo', host: 'bar')); + expect(enableAuthCodes, isFalse); + expect(ipv6, isTrue); + expect(serviceUri, Uri(scheme: 'http', host: '::1', port: 0)); + expect(cachedUserTags, isEmpty); + expect(uriConverter, isNotNull); + done.complete(); + return FakeDartDevelopmentService(); + }; + final TestFlutterDevice flutterDevice = TestFlutterDevice( + device, + vmServiceUris: Stream.value(testUri), + ); + await flutterDevice.connect(allowExistingDdsInstance: true, ipv6: true, disableServiceAuthCodes: true); + await done.future; + }, overrides: { + VMServiceConnector: () => (Uri httpUri, { + ReloadSources? reloadSources, + Restart? restart, + CompileExpression? compileExpression, + GetSkSLMethod? getSkSLMethod, + FlutterProject? flutterProject, + PrintStructuredErrorLogMethod? printStructuredErrorLogMethod, + io.CompressionOptions compression = io.CompressionOptions.compressionDefault, + Device? device, + required Logger logger, + }) async => FakeVmServiceHost(requests: []).vmService, + dds.UriConverter: () => (String uri) => 'test', + })); + + testUsingContext('Failed DDS start outputs error message', () => testbed.run(() async { + // See https://github.com/flutter/flutter/issues/72385 for context. + final FakeDevice device = FakeDevice() + ..dds = DartDevelopmentService(); + ddsLauncherCallback = ( + Uri uri, { + bool enableAuthCodes = false, + bool ipv6 = false, + Uri? serviceUri, + List cachedUserTags = const [], + dds.UriConverter? uriConverter, + }) { + expect(uri, Uri(scheme: 'foo', host: 'bar')); + expect(enableAuthCodes, isTrue); + expect(ipv6, isFalse); + expect(serviceUri, Uri(scheme: 'http', host: '127.0.0.1', port: 0)); + expect(cachedUserTags, isEmpty); + expect(uriConverter, isNull); + throw FakeDartDevelopmentServiceException(message: 'No URI'); + }; + final TestFlutterDevice flutterDevice = TestFlutterDevice( + device, + vmServiceUris: Stream.value(testUri), + ); + bool caught = false; + final Completerdone = Completer(); + runZonedGuarded(() { + flutterDevice.connect(allowExistingDdsInstance: true).then((_) => done.complete()); + }, (Object e, StackTrace st) { + expect(e, isA()); + expect((e as StateError).message, contains('No URI')); + expect(testLogger.errorText, contains( + 'DDS has failed to start and there is not an existing DDS instance', + )); + done.complete(); + caught = true; + }); + await done.future; + if (!caught) { + fail('Expected a StateError to be thrown.'); + } + }, overrides: { + VMServiceConnector: () => (Uri httpUri, { + ReloadSources? reloadSources, + Restart? restart, + CompileExpression? compileExpression, + GetSkSLMethod? getSkSLMethod, + FlutterProject? flutterProject, + PrintStructuredErrorLogMethod? printStructuredErrorLogMethod, + io.CompressionOptions compression = io.CompressionOptions.compressionDefault, + Device? device, + required Logger logger, + }) async => FakeVmServiceHost(requests: []).vmService, + })); + + testUsingContext('nextPlatform moves through expected platforms', () { + expect(nextPlatform('android'), 'iOS'); + expect(nextPlatform('iOS'), 'windows'); + expect(nextPlatform('windows'), 'macOS'); + expect(nextPlatform('macOS'), 'linux'); + expect(nextPlatform('linux'), 'fuchsia'); + expect(nextPlatform('fuchsia'), 'android'); + expect(() => nextPlatform('unknown'), throwsAssertionError); + }); + + testUsingContext('cleanupAtFinish shuts down resident devtools handler', () => testbed.run(() async { + residentRunner = HotRunner( + [ + flutterDevice, + ], + stayResident: false, + debuggingOptions: DebuggingOptions.enabled(BuildInfo.debug, vmserviceOutFile: 'foo'), + target: 'main.dart', + devtoolsHandler: createNoOpHandler, + analytics: fakeAnalytics, + ); + await residentRunner.cleanupAtFinish(); + + expect((residentRunner.residentDevtoolsHandler! as NoOpDevtoolsHandler).wasShutdown, true); + })); + + testUsingContext('HotRunner sets asset directory when first evict assets', () => testbed.run(() async { + fakeVmServiceHost = FakeVmServiceHost(requests: [ + listViews, + setAssetBundlePath, + evict, + ]); + residentRunner = HotRunner( + [ + flutterDevice, + ], + stayResident: false, + debuggingOptions: DebuggingOptions.enabled(BuildInfo.debug), + target: 'main.dart', + devtoolsHandler: createNoOpHandler, + analytics: fakeAnalytics, + ); + + (flutterDevice.devFS! as FakeDevFS).assetPathsToEvict = {'asset'}; + + expect(flutterDevice.devFS!.hasSetAssetDirectory, isFalse); + await (residentRunner as HotRunner).evictDirtyAssets(); + expect(flutterDevice.devFS!.hasSetAssetDirectory, isTrue); + expect(fakeVmServiceHost!.hasRemainingExpectations, isFalse); + })); + + testUsingContext('HotRunner sets asset directory when first evict shaders', () => testbed.run(() async { + fakeVmServiceHost = FakeVmServiceHost(requests: [ + listViews, + setAssetBundlePath, + evictShader, + ]); + residentRunner = HotRunner( + [ + flutterDevice, + ], + stayResident: false, + debuggingOptions: DebuggingOptions.enabled(BuildInfo.debug), + target: 'main.dart', + devtoolsHandler: createNoOpHandler, + analytics: fakeAnalytics, + ); + + (flutterDevice.devFS! as FakeDevFS).shaderPathsToEvict = {'foo.frag'}; + + expect(flutterDevice.devFS!.hasSetAssetDirectory, false); + await (residentRunner as HotRunner).evictDirtyAssets(); + expect(flutterDevice.devFS!.hasSetAssetDirectory, true); + expect(fakeVmServiceHost!.hasRemainingExpectations, false); + })); + + testUsingContext('HotRunner does not sets asset directory when no assets to evict', () => testbed.run(() async { + fakeVmServiceHost = FakeVmServiceHost(requests: [ + ]); + residentRunner = HotRunner( + [ + flutterDevice, + ], + stayResident: false, + debuggingOptions: DebuggingOptions.enabled(BuildInfo.debug), + target: 'main.dart', + devtoolsHandler: createNoOpHandler, + analytics: fakeAnalytics, + ); + + expect(flutterDevice.devFS!.hasSetAssetDirectory, false); + await (residentRunner as HotRunner).evictDirtyAssets(); + expect(flutterDevice.devFS!.hasSetAssetDirectory, false); + expect(fakeVmServiceHost!.hasRemainingExpectations, false); + })); + + testUsingContext('HotRunner does not set asset directory if it has been set before', () => testbed.run(() async { + fakeVmServiceHost = FakeVmServiceHost(requests: [ + listViews, + evict, + ]); + residentRunner = HotRunner( + [ + flutterDevice, + ], + stayResident: false, + debuggingOptions: DebuggingOptions.enabled(BuildInfo.debug), + target: 'main.dart', + devtoolsHandler: createNoOpHandler, + analytics: fakeAnalytics, + ); + + (flutterDevice.devFS! as FakeDevFS).assetPathsToEvict = {'asset'}; + flutterDevice.devFS!.hasSetAssetDirectory = true; + + await (residentRunner as HotRunner).evictDirtyAssets(); + expect(flutterDevice.devFS!.hasSetAssetDirectory, true); + expect(fakeVmServiceHost!.hasRemainingExpectations, false); + })); + + testUsingContext( + 'native assets', + () => testbed.run(() async { + final FileSystem fileSystem = globals.fs; + final Environment environment = Environment.test( + fileSystem.currentDirectory, + inputs: {}, + artifacts: Artifacts.test(), + processManager: FakeProcessManager.empty(), + fileSystem: fileSystem, + logger: BufferLogger.test(), + ); + final Uri projectUri = environment.projectDir.uri; + + final FakeDevice device = FakeDevice( + targetPlatform: TargetPlatform.darwin, + sdkNameAndVersion: 'Macos', + ); + final FakeFlutterDevice flutterDevice = FakeFlutterDevice() + ..testUri = testUri + ..vmServiceHost = (() => fakeVmServiceHost) + ..device = device + .._devFS = devFS + ..targetPlatform = TargetPlatform.darwin; + + fakeVmServiceHost = FakeVmServiceHost(requests: [ + listViews, + listViews, + ]); + globals.fs + .file(globals.fs.path.join('lib', 'main.dart')) + .createSync(recursive: true); + final FakeNativeAssetsBuildRunner buildRunner = FakeNativeAssetsBuildRunner( + packagesWithNativeAssetsResult: [ + Package('bar', projectUri), + ], + dryRunResult: FakeNativeAssetsBuilderResult( + assets: [ + Asset( + id: 'package:bar/bar.dart', + linkMode: LinkMode.dynamic, + target: native_assets_cli.Target.macOSArm64, + path: AssetAbsolutePath(Uri.file('bar.dylib')), + ), + ], + ), + ); + residentRunner = HotRunner( + [ + flutterDevice, + ], + stayResident: false, + debuggingOptions: DebuggingOptions.enabled(const BuildInfo( + BuildMode.debug, + '', + treeShakeIcons: false, + trackWidgetCreation: true, + )), + target: 'main.dart', + devtoolsHandler: createNoOpHandler, + buildRunner: buildRunner, + analytics: fakeAnalytics, + ); + + final int? result = await residentRunner.run(); + expect(result, 0); + + expect(buildRunner.buildInvocations, 0); + expect(buildRunner.dryRunInvocations, 1); + expect(buildRunner.hasPackageConfigInvocations, 1); + expect(buildRunner.packagesWithNativeAssetsInvocations, 1); + }), + overrides: { + ProcessManager: () => FakeProcessManager.any(), + FeatureFlags: () => TestFeatureFlags(isNativeAssetsEnabled: true, isMacOSEnabled: true), + }); +} + +// This implements [dds.DartDevelopmentService], not the [DartDevelopmentService] +// interface from package:flutter_tools. +class FakeDartDevelopmentService extends Fake implements dds.DartDevelopmentService { + @override + Future get done => Future.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'; +} + +class TestFlutterDevice extends FlutterDevice { + TestFlutterDevice(super.device, { Stream? vmServiceUris }) + : _vmServiceUris = vmServiceUris, super(buildInfo: BuildInfo.debug, developmentShaderCompiler: const FakeShaderCompiler()); + + final Stream? _vmServiceUris; + + @override + Stream 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 get vmServiceUris => Stream.value(testUri); + + @override + FlutterVmService? get vmService => vmServiceHost?.call()?.vmService; + + DevFS? _devFS; + + @override + DevFS? get devFS => _devFS; + + @override + set devFS(DevFS? value) { } + + @override + Device? device; + + @override + Future stopEchoingDeviceLog() async { } + + @override + Future initLogReader() async { } + + @override + Future setupDevFS(String fsName, Directory rootDirectory) async { + return testUri!; + } + + @override + Future runHot({required HotRunner hotRunner, String? route}) async { + return runHotCode; + } + + @override + Future runCold({required ColdRunner coldRunner, String? route}) async { + if (runColdError != null) { + throw runColdError!; + } + return runColdCode; + } + + @override + Future 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 updateDevFS({ + required Uri mainUri, + String? target, + AssetBundle? bundle, + DateTime? firstBuildTime, + bool bundleFirstUpload = false, + bool bundleDirty = false, + bool fullRestart = false, + String? projectRootPath, + required String pathToReload, + required String dillOutputPath, + required List invalidatedFiles, + required PackageConfig packageConfig, + }) async { + if (reportError != null) { + throw reportError!; + } + return report; + } + + @override + Future 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 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; + + @override + Future recompile( + Uri mainUri, + List? invalidatedFiles, { + required String outputPath, + required PackageConfig packageConfig, + String? projectRootPath, + required FileSystem fs, + bool suppressErrors = false, + bool checkDartPluginRegistry = false, + File? dartPluginRegistrant, + Uri? nativeAssetsYaml, + }) async { + didSuppressErrors = suppressErrors; + return nextOutput ?? const CompilerOutput('foo.dill', 0, []); + } + + @override + void accept() { } + + @override + void reset() { } +} + +class FakeProjectFileInvalidator extends Fake implements ProjectFileInvalidator { + @override + Future findInvalidated({ + required DateTime? lastCompiled, + required List urisToMonitor, + required String packagesPath, + required PackageConfig packageConfig, + bool asyncScanning = false, + }) async { + return InvalidationResult( + packageConfig: packageConfig, + uris: [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 get sdkNameAndVersion async => _sdkNameAndVersion; + + @override + Future get targetPlatform async => _targetPlatform; + + @override + Future get isLocalEmulator async => _isLocalEmulator; + + @override + String get name => 'FakeDevice'; + + @override + late DartDevelopmentService dds; + + @override + Future dispose() async { + disposed = true; + } + + @override + Future stopApp(ApplicationPackage? app, {String? userIdentifier}) async { + appStopped = true; + return true; + } + + @override + Future takeScreenshot(File outputFile) async { + if (failScreenshot) { + throw Exception(); + } + outputFile.writeAsBytesSync(List.generate(1024, (int i) => i)); + } + + @override + FutureOr 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 sources = []; + + @override + Uri baseUri = Uri(); + + @override + Future destroy() async { } + + @override + Set assetPathsToEvict = {}; + + @override + Set shaderPathsToEvict = {}; + + @override + Set scenePathsToEvict = {}; + + @override + bool didUpdateFontManifest = false; + + UpdateFSReport nextUpdateReport = UpdateFSReport(success: true); + + @override + bool hasSetAssetDirectory = false; + + @override + Future create() async { + return Uri(); + } + + @override + void resetLastCompiled() { + lastCompiled = null; + } + + @override + Future update({ + required Uri mainUri, + required ResidentCompiler generator, + required bool trackWidgetCreation, + required String pathToReload, + required List invalidatedFiles, + required PackageConfig packageConfig, + required String dillOutputPath, + required DevelopmentShaderCompiler shaderCompiler, + DevelopmentSceneImporter? sceneImporter, + DevFSWriter? devFSWriter, + String? target, + AssetBundle? bundle, + DateTime? firstBuildTime, + bool bundleFirstUpload = false, + bool fullRestart = false, + String? projectRootPath, + File? dartPluginRegistrant, + }) async { + return nextUpdateReport; + } +} + +class FakeShaderCompiler implements DevelopmentShaderCompiler { + const FakeShaderCompiler(); + + @override + void configureCompiler( + TargetPlatform? platform, { + required ImpellerStatus impellerStatus, + }) { } + + @override + Future recompileShader(DevFSContent inputShader) { + throw UnimplementedError(); + } +} + +const FakeVmServiceRequest renderFrameRasterStats = FakeVmServiceRequest( + method: kRenderFrameWithRasterStatsMethod, + args: { + 'viewId': 'a', + 'isolateId': '1', + }, + error: FakeRPCError( + code: RPCErrorCodes.kServerError, + error: 'Raster status not supported on Impeller backend', + ), +); diff --git a/flutter/packages/flutter_tools/test/general.shard/resident_web_runner_cold_test.dart b/flutter/packages/flutter_tools/test/general.shard/resident_web_runner_cold_test.dart new file mode 100644 index 0000000000000000000000000000000000000000..a777028be3cbb17ae3a2538acad2a8d423cdac25 --- /dev/null +++ b/flutter/packages/flutter_tools/test/general.shard/resident_web_runner_cold_test.dart @@ -0,0 +1,248 @@ +// 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/base/file_system.dart'; +import 'package:flutter_tools/src/base/logger.dart'; +import 'package:flutter_tools/src/base/time.dart'; +import 'package:flutter_tools/src/build_info.dart'; +import 'package:flutter_tools/src/build_system/build_system.dart'; +import 'package:flutter_tools/src/devfs.dart'; +import 'package:flutter_tools/src/device.dart'; +import 'package:flutter_tools/src/isolated/devfs_web.dart'; +import 'package:flutter_tools/src/isolated/resident_web_runner.dart'; +import 'package:flutter_tools/src/project.dart'; +import 'package:flutter_tools/src/reporting/reporting.dart'; +import 'package:flutter_tools/src/resident_runner.dart'; +import 'package:flutter_tools/src/vmservice.dart'; +import 'package:test/fake.dart'; + +import '../src/common.dart'; +import '../src/context.dart'; +import '../src/fakes.dart'; +import '../src/test_build_system.dart'; + +void main() { + late FakeFlutterDevice mockFlutterDevice; + late FakeWebDevFS mockWebDevFS; + late FileSystem fileSystem; + + setUp(() { + fileSystem = MemoryFileSystem.test(); + mockWebDevFS = FakeWebDevFS(); + final FakeWebDevice mockWebDevice = FakeWebDevice(); + mockFlutterDevice = FakeFlutterDevice(mockWebDevice); + mockFlutterDevice._devFS = mockWebDevFS; + + fileSystem.file('.packages').writeAsStringSync('\n'); + fileSystem.file('pubspec.yaml').createSync(); + fileSystem.file(fileSystem.path.join('lib', 'main.dart')).createSync(recursive: true); + fileSystem.file(fileSystem.path.join('web', 'index.html')).createSync(recursive: true); + }); + + testUsingContext('Can successfully run and connect without vmservice', () async { + final FlutterProject project = FlutterProject.fromDirectoryTest(fileSystem.currentDirectory); + final ResidentWebRunner residentWebRunner = ResidentWebRunner( + mockFlutterDevice, + flutterProject: project, + debuggingOptions: DebuggingOptions.disabled(BuildInfo.release), + ipv6: true, + fileSystem: fileSystem, + logger: BufferLogger.test(), + systemClock: SystemClock.fixed(DateTime(0, 0, 0)), + usage: TestUsage(), + analytics: getInitializedFakeAnalyticsInstance( + fs: fileSystem, + fakeFlutterVersion: FakeFlutterVersion(), + ), + ); + + final Completer connectionInfoCompleter = Completer(); + unawaited(residentWebRunner.run( + connectionInfoCompleter: connectionInfoCompleter, + )); + final DebugConnectionInfo debugConnectionInfo = await connectionInfoCompleter.future; + + expect(debugConnectionInfo.wsUri, null); + }, overrides: { + BuildSystem: () => TestBuildSystem.all(BuildResult(success: true)), + FileSystem: () => fileSystem, + ProcessManager: () => FakeProcessManager.any(), + }); + + // Regression test for https://github.com/flutter/flutter/issues/60613 + testUsingContext('ResidentWebRunner calls appFailedToStart if initial compilation fails', () async { + final FlutterProject project = FlutterProject.fromDirectoryTest(fileSystem.currentDirectory); + final ResidentWebRunner residentWebRunner = ResidentWebRunner( + mockFlutterDevice, + flutterProject: project, + debuggingOptions: DebuggingOptions.disabled(BuildInfo.release), + ipv6: true, + fileSystem: fileSystem, + logger: BufferLogger.test(), + systemClock: SystemClock.fixed(DateTime(0, 0, 0)), + usage: TestUsage(), + analytics: getInitializedFakeAnalyticsInstance( + fs: fileSystem, + fakeFlutterVersion: FakeFlutterVersion(), + ), + ); + + expect(() => residentWebRunner.run(), throwsToolExit()); + expect(await residentWebRunner.waitForAppToFinish(), 1); + }, overrides: { + BuildSystem: () => TestBuildSystem.all(BuildResult(success: false)), + FileSystem: () => fileSystem, + ProcessManager: () => FakeProcessManager.any(), + }); + + // Regression test for https://github.com/flutter/flutter/issues/60613 + testUsingContext('ResidentWebRunner calls appFailedToStart if error is thrown during startup', () async { + final FlutterProject project = FlutterProject.fromDirectoryTest(fileSystem.currentDirectory); + final ResidentWebRunner residentWebRunner = ResidentWebRunner( + mockFlutterDevice, + flutterProject: project, + debuggingOptions: DebuggingOptions.disabled(BuildInfo.release), + ipv6: true, + fileSystem: fileSystem, + logger: BufferLogger.test(), + systemClock: SystemClock.fixed(DateTime(0, 0, 0)), + usage: TestUsage(), + analytics: getInitializedFakeAnalyticsInstance( + fs: fileSystem, + fakeFlutterVersion: FakeFlutterVersion(), + ), + ); + + expect(() async => residentWebRunner.run(), throwsException); + expect(await residentWebRunner.waitForAppToFinish(), 1); + }, overrides: { + BuildSystem: () => TestBuildSystem.error(Exception('foo')), + FileSystem: () => fileSystem, + ProcessManager: () => FakeProcessManager.any(), + }); + + testUsingContext('Can full restart after attaching', () async { + final FlutterProject project = FlutterProject.fromDirectoryTest(fileSystem.currentDirectory); + final ResidentWebRunner residentWebRunner = ResidentWebRunner( + mockFlutterDevice, + flutterProject: project, + debuggingOptions: DebuggingOptions.disabled(BuildInfo.release), + ipv6: true, + fileSystem: fileSystem, + logger: BufferLogger.test(), + systemClock: SystemClock.fixed(DateTime(0, 0, 0)), + usage: TestUsage(), + analytics: getInitializedFakeAnalyticsInstance( + fs: fileSystem, + fakeFlutterVersion: FakeFlutterVersion(), + ), + ); + final Completer connectionInfoCompleter = Completer(); + unawaited(residentWebRunner.run( + connectionInfoCompleter: connectionInfoCompleter, + )); + await connectionInfoCompleter.future; + final OperationResult result = await residentWebRunner.restart(fullRestart: true); + + expect(result.code, 0); + }, overrides: { + BuildSystem: () => TestBuildSystem.all(BuildResult(success: true)), + FileSystem: () => fileSystem, + ProcessManager: () => FakeProcessManager.any(), + }); + + testUsingContext('Fails on compilation errors in hot restart', () async { + final FlutterProject project = FlutterProject.fromDirectoryTest(fileSystem.currentDirectory); + final ResidentWebRunner residentWebRunner = ResidentWebRunner( + mockFlutterDevice, + flutterProject: project, + debuggingOptions: DebuggingOptions.disabled(BuildInfo.release), + ipv6: true, + fileSystem: fileSystem, + logger: BufferLogger.test(), + systemClock: SystemClock.fixed(DateTime(0, 0, 0)), + usage: TestUsage(), + analytics: getInitializedFakeAnalyticsInstance( + fs: fileSystem, + fakeFlutterVersion: FakeFlutterVersion(), + ), + ); + final Completer connectionInfoCompleter = Completer(); + unawaited(residentWebRunner.run( + connectionInfoCompleter: connectionInfoCompleter, + )); + await connectionInfoCompleter.future; + final OperationResult result = await residentWebRunner.restart(fullRestart: true); + + expect(result.code, 1); + expect(result.message, contains('Failed to recompile application.')); + }, overrides: { + BuildSystem: () => TestBuildSystem.list([ + BuildResult(success: true), + BuildResult(success: false), + ]), + FileSystem: () => fileSystem, + ProcessManager: () => FakeProcessManager.any(), + }); +} + +class FakeWebDevFS extends Fake implements WebDevFS { + @override + List get sources => []; + + @override + Future create() async { + return Uri.base; + } +} + +class FakeWebDevice extends Fake implements Device { + @override + String get name => 'web'; + + @override + Future stopApp( + ApplicationPackage? app, { + String? userIdentifier, + }) async { + return true; + } + + @override + Future startApp( + ApplicationPackage? package, { + String? mainPath, + String? route, + DebuggingOptions? debuggingOptions, + Map? platformArgs, + bool prebuiltApplication = false, + bool ipv6 = false, + String? userIdentifier, + }) async { + return LaunchResult.succeeded(); + } +} + +class FakeFlutterDevice extends Fake implements FlutterDevice { + FakeFlutterDevice(this.device); + + @override + final FakeWebDevice device; + + + DevFS? _devFS; + + @override + DevFS? get devFS => _devFS; + + @override + set devFS(DevFS? value) { } + + @override + FlutterVmService? vmService; +} diff --git a/flutter/packages/flutter_tools/test/general.shard/resident_web_runner_test.dart b/flutter/packages/flutter_tools/test/general.shard/resident_web_runner_test.dart new file mode 100644 index 0000000000000000000000000000000000000000..d29dff7444db082a3e43a7cf474e3bcae437547c --- /dev/null +++ b/flutter/packages/flutter_tools/test/general.shard/resident_web_runner_test.dart @@ -0,0 +1,1768 @@ +// Copyright 2014 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +import 'dart:async'; +import 'dart:convert'; +import 'dart:io'; + +import 'package:dwds/dwds.dart'; +import 'package:file/memory.dart'; +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/base/logger.dart'; +import 'package:flutter_tools/src/base/platform.dart'; +import 'package:flutter_tools/src/base/time.dart'; +import 'package:flutter_tools/src/build_info.dart'; +import 'package:flutter_tools/src/build_system/targets/scene_importer.dart'; +import 'package:flutter_tools/src/build_system/targets/shader_compiler.dart'; +import 'package:flutter_tools/src/compile.dart'; +import 'package:flutter_tools/src/devfs.dart'; +import 'package:flutter_tools/src/device.dart'; +import 'package:flutter_tools/src/globals.dart' as globals; +import 'package:flutter_tools/src/isolated/devfs_web.dart'; +import 'package:flutter_tools/src/isolated/resident_web_runner.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/vmservice.dart'; +import 'package:flutter_tools/src/web/chrome.dart'; +import 'package:flutter_tools/src/web/web_device.dart'; +import 'package:package_config/package_config.dart'; +import 'package:package_config/package_config_types.dart'; +import 'package:test/fake.dart'; +import 'package:unified_analytics/unified_analytics.dart'; +import 'package:vm_service/vm_service.dart' as vm_service; +import 'package:webkit_inspection_protocol/webkit_inspection_protocol.dart'; + +import '../src/common.dart'; +import '../src/context.dart'; +import '../src/fake_process_manager.dart'; +import '../src/fake_vm_services.dart'; +import '../src/fakes.dart' as test_fakes; + +const List kAttachLogExpectations = + [ + FakeVmServiceRequest( + method: 'streamListen', + args: { + 'streamId': 'Stdout', + }, + ), + FakeVmServiceRequest( + method: 'streamListen', + args: { + 'streamId': 'Stderr', + }, + ), +]; + +const List kAttachIsolateExpectations = + [ + FakeVmServiceRequest(method: 'streamListen', args: { + 'streamId': 'Isolate', + }), + FakeVmServiceRequest(method: 'registerService', args: { + 'service': kReloadSourcesServiceName, + 'alias': kFlutterToolAlias, + }), + FakeVmServiceRequest(method: 'registerService', args: { + 'service': kFlutterVersionServiceName, + 'alias': kFlutterToolAlias, + }), + FakeVmServiceRequest(method: 'registerService', args: { + 'service': kFlutterMemoryInfoServiceName, + 'alias': kFlutterToolAlias, + }), + FakeVmServiceRequest( + method: 'streamListen', + args: { + 'streamId': 'Extension', + }, + ), +]; + +const List kAttachExpectations = [ + ...kAttachLogExpectations, + ...kAttachIsolateExpectations, +]; + +void main() { + late FakeDebugConnection debugConnection; + late FakeChromeDevice chromeDevice; + late FakeAppConnection appConnection; + late FakeFlutterDevice flutterDevice; + late FakeWebDevFS webDevFS; + late FakeResidentCompiler residentCompiler; + late FakeChromeConnection chromeConnection; + late FakeChromeTab chromeTab; + late FakeWebServerDevice webServerDevice; + late FakeDevice mockDevice; + late FakeVmServiceHost fakeVmServiceHost; + late FileSystem fileSystem; + late ProcessManager processManager; + late TestUsage testUsage; + late FakeAnalytics fakeAnalytics; + + setUp(() { + testUsage = TestUsage(); + fileSystem = MemoryFileSystem.test(); + processManager = FakeProcessManager.any(); + debugConnection = FakeDebugConnection(); + mockDevice = FakeDevice(); + appConnection = FakeAppConnection(); + webDevFS = FakeWebDevFS(); + residentCompiler = FakeResidentCompiler(); + chromeDevice = FakeChromeDevice(); + chromeConnection = FakeChromeConnection(); + chromeTab = FakeChromeTab('index.html'); + webServerDevice = FakeWebServerDevice(); + flutterDevice = FakeFlutterDevice() + .._devFS = webDevFS + ..device = mockDevice + ..generator = residentCompiler; + fileSystem.file('.packages').writeAsStringSync('\n'); + fakeAnalytics = getInitializedFakeAnalyticsInstance( + fs: fileSystem, + fakeFlutterVersion: test_fakes.FakeFlutterVersion(), + ); + }); + + void setupMocks() { + fileSystem.file('pubspec.yaml').createSync(); + fileSystem.file('lib/main.dart').createSync(recursive: true); + fileSystem.file('web/index.html').createSync(recursive: true); + webDevFS.report = UpdateFSReport(success: true); + debugConnection.fakeVmServiceHost = () => fakeVmServiceHost; + webDevFS.result = ConnectionResult( + appConnection, + debugConnection, + debugConnection.vmService, + ); + debugConnection.uri = 'ws://127.0.0.1/abcd/'; + chromeConnection.tabs.add(chromeTab); + } + + testUsingContext( + 'runner with web server device does not support debugging without --start-paused', + () { + final ResidentRunner residentWebRunner = setUpResidentRunner(flutterDevice); + flutterDevice.device = WebServerDevice( + logger: BufferLogger.test(), + ); + fakeVmServiceHost = FakeVmServiceHost(requests: []); + final ResidentRunner profileResidentWebRunner = ResidentWebRunner( + flutterDevice, + flutterProject: + FlutterProject.fromDirectoryTest(fileSystem.currentDirectory), + debuggingOptions: DebuggingOptions.enabled(BuildInfo.debug), + ipv6: true, + fileSystem: fileSystem, + logger: BufferLogger.test(), + usage: globals.flutterUsage, + analytics: globals.analytics, + systemClock: globals.systemClock, + ); + + expect(profileResidentWebRunner.debuggingEnabled, false); + + flutterDevice.device = chromeDevice; + + expect(residentWebRunner.debuggingEnabled, true); + expect(fakeVmServiceHost.hasRemainingExpectations, false); + }, overrides: { + FileSystem: () => fileSystem, + ProcessManager: () => processManager, + }); + + testUsingContext( + 'runner with web server device supports debugging with --start-paused', + () { + fakeVmServiceHost = FakeVmServiceHost(requests: []); + setupMocks(); + flutterDevice.device = WebServerDevice( + logger: BufferLogger.test(), + ); + final ResidentRunner profileResidentWebRunner = ResidentWebRunner( + flutterDevice, + flutterProject: + FlutterProject.fromDirectoryTest(fileSystem.currentDirectory), + debuggingOptions: + DebuggingOptions.enabled(BuildInfo.debug, startPaused: true), + ipv6: true, + fileSystem: fileSystem, + logger: BufferLogger.test(), + usage: globals.flutterUsage, + analytics: globals.analytics, + systemClock: globals.systemClock, + ); + + expect(profileResidentWebRunner.uri, webDevFS.baseUri); + expect(profileResidentWebRunner.debuggingEnabled, true); + }, overrides: { + FileSystem: () => fileSystem, + ProcessManager: () => processManager, + }); + testUsingContext('profile does not supportsServiceProtocol', () { + final ResidentRunner residentWebRunner = ResidentWebRunner( + flutterDevice, + flutterProject: + FlutterProject.fromDirectoryTest(fileSystem.currentDirectory), + debuggingOptions: DebuggingOptions.enabled(BuildInfo.debug), + ipv6: true, + fileSystem: fileSystem, + logger: BufferLogger.test(), + usage: globals.flutterUsage, + analytics: globals.analytics, + systemClock: globals.systemClock, + ); + fakeVmServiceHost = FakeVmServiceHost(requests: []); + flutterDevice.device = chromeDevice; + final ResidentRunner profileResidentWebRunner = ResidentWebRunner( + flutterDevice, + flutterProject: + FlutterProject.fromDirectoryTest(fileSystem.currentDirectory), + debuggingOptions: DebuggingOptions.enabled(BuildInfo.profile), + ipv6: true, + fileSystem: fileSystem, + logger: BufferLogger.test(), + usage: globals.flutterUsage, + analytics: globals.analytics, + systemClock: globals.systemClock, + ); + + expect(profileResidentWebRunner.supportsServiceProtocol, false); + expect(residentWebRunner.supportsServiceProtocol, true); + }, overrides: { + FileSystem: () => fileSystem, + ProcessManager: () => processManager, + }); + + testUsingContext('Can successfully run and connect to vmservice', () async { + final BufferLogger logger = BufferLogger.test(); + final ResidentRunner residentWebRunner = + setUpResidentRunner(flutterDevice, logger: logger); + fakeVmServiceHost = + FakeVmServiceHost(requests: kAttachExpectations.toList()); + setupMocks(); + + final Completer connectionInfoCompleter = + Completer(); + unawaited(residentWebRunner.run( + connectionInfoCompleter: connectionInfoCompleter, + )); + final DebugConnectionInfo debugConnectionInfo = + await connectionInfoCompleter.future; + + expect(appConnection.ranMain, true); + expect(logger.statusText, + contains('Debug service listening on ws://127.0.0.1/abcd/')); + expect(debugConnectionInfo.wsUri.toString(), 'ws://127.0.0.1/abcd/'); + }, overrides: { + FileSystem: () => fileSystem, + ProcessManager: () => processManager, + }); + + testUsingContext('WebRunner copies compiled app.dill to cache during startup', + () async { + final DebuggingOptions debuggingOptions = DebuggingOptions.enabled( + const BuildInfo(BuildMode.debug, null, treeShakeIcons: false), + ); + final ResidentRunner residentWebRunner = + setUpResidentRunner(flutterDevice, debuggingOptions: debuggingOptions); + fakeVmServiceHost = + FakeVmServiceHost(requests: kAttachExpectations.toList()); + setupMocks(); + + residentWebRunner.artifactDirectory + .childFile('app.dill') + .writeAsStringSync('ABC'); + final Completer connectionInfoCompleter = + Completer(); + unawaited(residentWebRunner.run( + connectionInfoCompleter: connectionInfoCompleter, + )); + await connectionInfoCompleter.future; + + expect( + await fileSystem + .file(fileSystem.path.join('build', 'cache.dill')) + .readAsString(), + 'ABC'); + }, overrides: { + FileSystem: () => fileSystem, + ProcessManager: () => processManager, + }); + + testUsingContext( + 'WebRunner copies compiled app.dill to cache during startup with track-widget-creation', + () async { + final ResidentRunner residentWebRunner = setUpResidentRunner(flutterDevice); + fakeVmServiceHost = + FakeVmServiceHost(requests: kAttachExpectations.toList()); + setupMocks(); + + residentWebRunner.artifactDirectory + .childFile('app.dill') + .writeAsStringSync('ABC'); + final Completer connectionInfoCompleter = + Completer(); + unawaited(residentWebRunner.run( + connectionInfoCompleter: connectionInfoCompleter, + )); + await connectionInfoCompleter.future; + + expect( + await fileSystem + .file(fileSystem.path.join('build', 'cache.dill.track.dill')) + .readAsString(), + 'ABC'); + }, overrides: { + FileSystem: () => fileSystem, + ProcessManager: () => processManager, + }); + + // Regression test for https://github.com/flutter/flutter/issues/60613 + testUsingContext( + 'ResidentWebRunner calls appFailedToStart if initial compilation fails', + () async { + fakeVmServiceHost = + FakeVmServiceHost(requests: kAttachExpectations.toList()); + setupMocks(); + final ResidentRunner residentWebRunner = setUpResidentRunner(flutterDevice); + fileSystem + .file(globals.fs.path.join('lib', 'main.dart')) + .createSync(recursive: true); + webDevFS.report = UpdateFSReport(); + + expect(await residentWebRunner.run(), 1); + // Completing this future ensures that the daemon can exit correctly. + expect(await residentWebRunner.waitForAppToFinish(), 1); + }, overrides: { + FileSystem: () => fileSystem, + ProcessManager: () => processManager, + }); + + testUsingContext( + 'Can successfully run without an index.html including status warning', + () async { + final BufferLogger logger = BufferLogger.test(); + fakeVmServiceHost = + FakeVmServiceHost(requests: kAttachExpectations.toList()); + setupMocks(); + fileSystem.directory('web').deleteSync(recursive: true); + final ResidentWebRunner residentWebRunner = ResidentWebRunner( + flutterDevice, + flutterProject: + FlutterProject.fromDirectoryTest(fileSystem.currentDirectory), + debuggingOptions: DebuggingOptions.enabled(BuildInfo.debug), + ipv6: true, + stayResident: false, + fileSystem: fileSystem, + logger: logger, + usage: globals.flutterUsage, + analytics: globals.analytics, + systemClock: globals.systemClock, + ); + + expect(await residentWebRunner.run(), 0); + expect(logger.statusText, + contains('This application is not configured to build on the web')); + }, overrides: { + FileSystem: () => fileSystem, + ProcessManager: () => processManager, + }); + + testUsingContext('Can successfully run and disconnect with --no-resident', + () async { + fakeVmServiceHost = + FakeVmServiceHost(requests: kAttachExpectations.toList()); + setupMocks(); + final ResidentRunner residentWebRunner = ResidentWebRunner( + flutterDevice, + flutterProject: + FlutterProject.fromDirectoryTest(fileSystem.currentDirectory), + debuggingOptions: DebuggingOptions.enabled(BuildInfo.debug), + ipv6: true, + stayResident: false, + fileSystem: fileSystem, + logger: BufferLogger.test(), + usage: globals.flutterUsage, + analytics: globals.analytics, + systemClock: globals.systemClock, + ); + + expect(await residentWebRunner.run(), 0); + }, overrides: { + FileSystem: () => fileSystem, + ProcessManager: () => processManager, + }); + + testUsingContext('Listens to stdout and stderr streams before running main', + () async { + final BufferLogger logger = BufferLogger.test(); + final ResidentRunner residentWebRunner = + setUpResidentRunner(flutterDevice, logger: logger); + fakeVmServiceHost = FakeVmServiceHost(requests: [ + ...kAttachLogExpectations, + FakeVmServiceStreamResponse( + streamId: 'Stdout', + event: vm_service.Event( + timestamp: 0, + kind: vm_service.EventStreams.kStdout, + bytes: base64.encode(utf8.encode('THIS MESSAGE IS IMPORTANT'))), + ), + FakeVmServiceStreamResponse( + streamId: 'Stderr', + event: vm_service.Event( + timestamp: 0, + kind: vm_service.EventStreams.kStderr, + bytes: base64.encode(utf8.encode('SO IS THIS'))), + ), + ...kAttachIsolateExpectations, + ]); + setupMocks(); + final Completer connectionInfoCompleter = + Completer(); + unawaited(residentWebRunner.run( + connectionInfoCompleter: connectionInfoCompleter, + )); + await connectionInfoCompleter.future; + + expect(logger.statusText, contains('THIS MESSAGE IS IMPORTANT')); + expect(logger.statusText, contains('SO IS THIS')); + }, overrides: { + FileSystem: () => fileSystem, + ProcessManager: () => processManager, + }); + + testUsingContext('Listens to extension events with structured errors', + () async { + final ResidentRunner residentWebRunner = + setUpResidentRunner(flutterDevice, logger: testLogger); + final List requests = [ + ...kAttachExpectations, + // This is the first error message of a session. + FakeVmServiceStreamResponse( + streamId: 'Extension', + event: vm_service.Event( + timestamp: 0, + extensionKind: 'Flutter.Error', + extensionData: vm_service.ExtensionData.parse({ + 'errorsSinceReload': 0, + 'renderedErrorText': 'first', + }), + kind: vm_service.EventStreams.kExtension, + ), + ), + // This is the second error message of a session. + FakeVmServiceStreamResponse( + streamId: 'Extension', + event: vm_service.Event( + timestamp: 0, + extensionKind: 'Flutter.Error', + extensionData: vm_service.ExtensionData.parse({ + 'errorsSinceReload': 1, + 'renderedErrorText': 'second', + }), + kind: vm_service.EventStreams.kExtension, + ), + ), + // This is not Flutter.Error kind data, so it should not be logged, even though it has a renderedErrorText field. + FakeVmServiceStreamResponse( + streamId: 'Extension', + event: vm_service.Event( + timestamp: 0, + extensionKind: 'Other', + extensionData: vm_service.ExtensionData.parse({ + 'errorsSinceReload': 2, + 'renderedErrorText': 'not an error', + }), + kind: vm_service.EventStreams.kExtension, + ), + ), + // This is the third error message of a session. + FakeVmServiceStreamResponse( + streamId: 'Extension', + event: vm_service.Event( + timestamp: 0, + extensionKind: 'Flutter.Error', + extensionData: vm_service.ExtensionData.parse({ + 'errorsSinceReload': 2, + 'renderedErrorText': 'third', + }), + kind: vm_service.EventStreams.kExtension, + ), + ), + // This is bogus error data. + FakeVmServiceStreamResponse( + streamId: 'Extension', + event: vm_service.Event( + timestamp: 0, + extensionKind: 'Flutter.Error', + extensionData: vm_service.ExtensionData.parse({ + 'other': 'bad stuff', + }), + kind: vm_service.EventStreams.kExtension, + ), + ), + // Empty error text should not break anything. + FakeVmServiceStreamResponse( + streamId: 'Extension', + event: vm_service.Event( + timestamp: 0, + extensionKind: 'Flutter.Error', + extensionData: vm_service.ExtensionData.parse({ + 'test': 'data', + 'renderedErrorText': '', + }), + kind: vm_service.EventStreams.kExtension, + ), + ), + // Messages without errorsSinceReload should act as if errorsSinceReload: 0 + FakeVmServiceStreamResponse( + streamId: 'Extension', + event: vm_service.Event( + timestamp: 0, + extensionKind: 'Flutter.Error', + extensionData: vm_service.ExtensionData.parse({ + 'test': 'data', + 'renderedErrorText': 'error text', + }), + kind: vm_service.EventStreams.kExtension, + ), + ), + // When adding things here, make sure the last one is supposed to output something + // to the statusLog, otherwise you won't be able to distinguish the absence of output + // due to it passing the test from absence due to it not running the test. + ]; + // We use requests below, so make a copy of it here (FakeVmServiceHost will + // clear its copy internally, which would affect our pumping below). + fakeVmServiceHost = FakeVmServiceHost(requests: requests.toList()); + + setupMocks(); + final Completer connectionInfoCompleter = + Completer(); + unawaited(residentWebRunner.run( + connectionInfoCompleter: connectionInfoCompleter, + )); + await connectionInfoCompleter.future; + assert(requests.length > 5, 'requests was modified'); + for (final Object _ in requests) { + // pump the task queue once for each message + await null; + } + + expect(testLogger.statusText, + 'Launching lib/main.dart on FakeDevice in debug mode...\n' + 'Waiting for connection from debug service on FakeDevice...\n' + 'Debug service listening on ws://127.0.0.1/abcd/\n' + '\n' + 'first\n' + '\n' + 'second\n' + 'third\n' + '\n' + '\n' // the empty message + '\n' + '\n' + 'error text\n' + '\n' + ); + + expect(testLogger.errorText, + 'Received an invalid Flutter.Error message from app: {other: bad stuff}\n' + ); + }, overrides: { + FileSystem: () => fileSystem, + ProcessManager: () => processManager, + }); + + testUsingContext('Does not run main with --start-paused', () async { + final ResidentRunner residentWebRunner = ResidentWebRunner( + flutterDevice, + flutterProject: + FlutterProject.fromDirectoryTest(fileSystem.currentDirectory), + debuggingOptions: + DebuggingOptions.enabled(BuildInfo.debug, startPaused: true), + ipv6: true, + fileSystem: fileSystem, + logger: BufferLogger.test(), + usage: globals.flutterUsage, + analytics: globals.analytics, + systemClock: globals.systemClock, + ); + fakeVmServiceHost = + FakeVmServiceHost(requests: kAttachExpectations.toList()); + setupMocks(); + final Completer connectionInfoCompleter = + Completer(); + + unawaited(residentWebRunner.run( + connectionInfoCompleter: connectionInfoCompleter, + )); + await connectionInfoCompleter.future; + + expect(appConnection.ranMain, false); + }, overrides: { + FileSystem: () => fileSystem, + ProcessManager: () => processManager, + }); + + testUsingContext('Can hot reload after attaching', () async { + final BufferLogger logger = BufferLogger.test(); + final ResidentRunner residentWebRunner = setUpResidentRunner( + flutterDevice, + logger: logger, + systemClock: SystemClock.fixed(DateTime(2001)), + ); + fakeVmServiceHost = FakeVmServiceHost(requests: [ + ...kAttachExpectations, + const FakeVmServiceRequest( + method: kHotRestartServiceName, + jsonResponse: { + 'type': 'Success', + }), + const FakeVmServiceRequest( + method: 'streamListen', + args: { + 'streamId': 'Isolate', + }, + ), + ]); + setupMocks(); + final TestChromiumLauncher chromiumLauncher = TestChromiumLauncher(); + final FakeProcess process = FakeProcess(); + final Chromium chrome = + Chromium(1, chromeConnection, chromiumLauncher: chromiumLauncher, process: process, logger: logger); + chromiumLauncher.setInstance(chrome); + + flutterDevice.device = GoogleChromeDevice( + fileSystem: fileSystem, + chromiumLauncher: chromiumLauncher, + logger: BufferLogger.test(), + platform: FakePlatform(), + processManager: FakeProcessManager.any(), + ); + webDevFS.report = UpdateFSReport(success: true); + + final Completer connectionInfoCompleter = + Completer(); + unawaited(residentWebRunner.run( + connectionInfoCompleter: connectionInfoCompleter, + )); + final DebugConnectionInfo debugConnectionInfo = + await connectionInfoCompleter.future; + + expect(debugConnectionInfo, isNotNull); + + final OperationResult result = await residentWebRunner.restart(); + + expect(logger.statusText, contains('Restarted application in')); + expect(result.code, 0); + expect(webDevFS.mainUri.toString(), contains('entrypoint.dart')); + + // ensure that analytics are sent. + expect(testUsage.events, [ + TestUsageEvent('hot', 'restart', + parameters: CustomDimensions.fromMap({ + 'cd27': 'web-javascript', + 'cd28': '', + 'cd29': 'false', + 'cd30': 'true', + 'cd13': '0', + 'cd48': 'false' + })), + ]); + expect( + fakeAnalytics.sentEvents, + contains( + Event.hotRunnerInfo( + label: 'restart', + targetPlatform: 'web-javascript', + sdkName: '', + emulator: false, + fullRestart: true, + overallTimeInMs: 0, + ), + ), + ); + expect(testUsage.timings, const [ + TestTimingEvent('hot', 'web-incremental-restart', Duration.zero), + ]); + expect(fakeAnalytics.sentEvents, contains( + Event.timing( + workflow: 'hot', + variableName: 'web-incremental-restart', + elapsedMilliseconds: 0, + ), + )); + }, overrides: { + Usage: () => testUsage, + Analytics: () => fakeAnalytics, + FileSystem: () => fileSystem, + ProcessManager: () => processManager, + }); + + testUsingContext('Can hot restart after attaching', () async { + final BufferLogger logger = BufferLogger.test(); + final ResidentRunner residentWebRunner = setUpResidentRunner( + flutterDevice, + logger: logger, + systemClock: SystemClock.fixed(DateTime(2001)), + ); + fakeVmServiceHost = FakeVmServiceHost(requests: [ + ...kAttachExpectations, + const FakeVmServiceRequest( + method: kHotRestartServiceName, + jsonResponse: { + 'type': 'Success', + }), + ]); + setupMocks(); + final TestChromiumLauncher chromiumLauncher = TestChromiumLauncher(); + final FakeProcess process = FakeProcess(); + final Chromium chrome = + Chromium(1, chromeConnection, chromiumLauncher: chromiumLauncher, process: process, logger: logger); + chromiumLauncher.setInstance(chrome); + + flutterDevice.device = GoogleChromeDevice( + fileSystem: fileSystem, + chromiumLauncher: chromiumLauncher, + logger: BufferLogger.test(), + platform: FakePlatform(), + processManager: FakeProcessManager.any(), + ); + webDevFS.report = UpdateFSReport(success: true); + + final Completer connectionInfoCompleter = + Completer(); + unawaited(residentWebRunner.run( + connectionInfoCompleter: connectionInfoCompleter, + )); + await connectionInfoCompleter.future; + final OperationResult result = + await residentWebRunner.restart(fullRestart: true); + + // Ensure that generated entrypoint is generated correctly. + expect(webDevFS.mainUri, isNotNull); + final String entrypointContents = + fileSystem.file(webDevFS.mainUri).readAsStringSync(); + expect(entrypointContents, contains('// Flutter web bootstrap script')); + expect(entrypointContents, contains("import 'dart:ui_web' as ui_web;")); + expect(entrypointContents, contains('await ui_web.bootstrapEngine(')); + + expect(logger.statusText, contains('Restarted application in')); + expect(result.code, 0); + + // ensure that analytics are sent. + expect(testUsage.events, [ + TestUsageEvent('hot', 'restart', + parameters: CustomDimensions.fromMap({ + 'cd27': 'web-javascript', + 'cd28': '', + 'cd29': 'false', + 'cd30': 'true', + 'cd13': '0', + 'cd48': 'false' + })), + ]); + expect( + fakeAnalytics.sentEvents, + contains( + Event.hotRunnerInfo( + label: 'restart', + targetPlatform: 'web-javascript', + sdkName: '', + emulator: false, + fullRestart: true, + overallTimeInMs: 0, + ), + ), + ); + expect(testUsage.timings, const [ + TestTimingEvent('hot', 'web-incremental-restart', Duration.zero), + ]); + expect(fakeAnalytics.sentEvents, contains( + Event.timing( + workflow: 'hot', + variableName: 'web-incremental-restart', + elapsedMilliseconds: 0, + ), + )); + }, overrides: { + Usage: () => testUsage, + Analytics: () => fakeAnalytics, + FileSystem: () => fileSystem, + ProcessManager: () => processManager, + }); + + testUsingContext('Can hot restart after attaching with web-server device', + () async { + final BufferLogger logger = BufferLogger.test(); + final ResidentRunner residentWebRunner = setUpResidentRunner( + flutterDevice, + logger: logger, + systemClock: SystemClock.fixed(DateTime(2001)), + ); + fakeVmServiceHost = FakeVmServiceHost(requests: kAttachExpectations); + setupMocks(); + flutterDevice.device = webServerDevice; + webDevFS.report = UpdateFSReport(success: true); + + final Completer connectionInfoCompleter = + Completer(); + unawaited(residentWebRunner.run( + connectionInfoCompleter: connectionInfoCompleter, + )); + await connectionInfoCompleter.future; + final OperationResult result = + await residentWebRunner.restart(fullRestart: true); + + expect(logger.statusText, contains('Restarted application in')); + expect(result.code, 0); + + // web-server device does not send restart analytics + expect(testUsage.events, isEmpty); + expect(fakeAnalytics.sentEvents, isEmpty); + expect(testUsage.timings, isEmpty); + }, overrides: { + Usage: () => testUsage, + Analytics: () => fakeAnalytics, + FileSystem: () => fileSystem, + ProcessManager: () => processManager, + }); + + testUsingContext('web resident runner is debuggable', () { + final ResidentRunner residentWebRunner = setUpResidentRunner(flutterDevice); + fakeVmServiceHost = + FakeVmServiceHost(requests: kAttachExpectations.toList()); + + expect(residentWebRunner.debuggingEnabled, true); + }, overrides: { + FileSystem: () => fileSystem, + ProcessManager: () => processManager, + }); + + testUsingContext('Exits when initial compile fails', () async { + final ResidentRunner residentWebRunner = setUpResidentRunner(flutterDevice); + fakeVmServiceHost = FakeVmServiceHost(requests: []); + setupMocks(); + webDevFS.report = UpdateFSReport(); + + final Completer connectionInfoCompleter = + Completer(); + unawaited(residentWebRunner.run( + connectionInfoCompleter: connectionInfoCompleter, + )); + + expect(await residentWebRunner.run(), 1); + expect(testUsage.events, isEmpty); + expect(fakeAnalytics.sentEvents, isEmpty); + expect(testUsage.timings, isEmpty); + }, overrides: { + Usage: () => testUsage, + Analytics: () => fakeAnalytics, + FileSystem: () => fileSystem, + ProcessManager: () => processManager, + }); + + testUsingContext( + 'Faithfully displays stdout messages with leading/trailing spaces', + () async { + final BufferLogger logger = BufferLogger.test(); + final ResidentRunner residentWebRunner = + setUpResidentRunner(flutterDevice, logger: logger); + fakeVmServiceHost = FakeVmServiceHost(requests: [ + ...kAttachLogExpectations, + FakeVmServiceStreamResponse( + streamId: 'Stdout', + event: vm_service.Event( + timestamp: 0, + kind: vm_service.EventStreams.kStdout, + bytes: base64.encode( + utf8.encode( + ' This is a message with 4 leading and trailing spaces '), + ), + ), + ), + ...kAttachIsolateExpectations, + ]); + setupMocks(); + final Completer connectionInfoCompleter = + Completer(); + unawaited(residentWebRunner.run( + connectionInfoCompleter: connectionInfoCompleter, + )); + await connectionInfoCompleter.future; + + expect( + logger.statusText, + contains( + ' This is a message with 4 leading and trailing spaces ')); + expect(fakeVmServiceHost.hasRemainingExpectations, false); + }, overrides: { + FileSystem: () => fileSystem, + ProcessManager: () => processManager, + }); + + testUsingContext('Fails on compilation errors in hot restart', () async { + final ResidentRunner residentWebRunner = setUpResidentRunner(flutterDevice); + fakeVmServiceHost = + FakeVmServiceHost(requests: kAttachExpectations.toList()); + setupMocks(); + final Completer connectionInfoCompleter = + Completer(); + unawaited(residentWebRunner.run( + connectionInfoCompleter: connectionInfoCompleter, + )); + await connectionInfoCompleter.future; + webDevFS.report = UpdateFSReport(); + + final OperationResult result = + await residentWebRunner.restart(fullRestart: true); + + expect(result.code, 1); + expect(result.message, contains('Failed to recompile application.')); + expect(testUsage.events, isEmpty); + expect(fakeAnalytics.sentEvents, isEmpty); + expect(testUsage.timings, isEmpty); + }, overrides: { + Usage: () => testUsage, + Analytics: () => fakeAnalytics, + FileSystem: () => fileSystem, + ProcessManager: () => processManager, + }); + + testUsingContext( + 'Fails non-fatally on vmservice response error for hot restart', + () async { + final ResidentRunner residentWebRunner = setUpResidentRunner(flutterDevice); + fakeVmServiceHost = FakeVmServiceHost(requests: [ + ...kAttachExpectations, + const FakeVmServiceRequest( + method: kHotRestartServiceName, + jsonResponse: { + 'type': 'Failed', + }, + ), + ]); + setupMocks(); + final Completer connectionInfoCompleter = + Completer(); + unawaited(residentWebRunner.run( + connectionInfoCompleter: connectionInfoCompleter, + )); + await connectionInfoCompleter.future; + + final OperationResult result = await residentWebRunner.restart(); + + expect(result.code, 0); + }, overrides: { + FileSystem: () => fileSystem, + ProcessManager: () => processManager, + }); + + testUsingContext('Fails fatally on Vm Service error response', () async { + final ResidentRunner residentWebRunner = setUpResidentRunner(flutterDevice); + fakeVmServiceHost = FakeVmServiceHost(requests: [ + ...kAttachExpectations, + const FakeVmServiceRequest( + method: kHotRestartServiceName, + // Failed response, + error: FakeRPCError(code: RPCErrorCodes.kInternalError), + ), + ]); + setupMocks(); + final Completer connectionInfoCompleter = + Completer(); + unawaited(residentWebRunner.run( + connectionInfoCompleter: connectionInfoCompleter, + )); + await connectionInfoCompleter.future; + final OperationResult result = await residentWebRunner.restart(); + + expect(result.code, 1); + expect(result.message, contains(RPCErrorCodes.kInternalError.toString())); + }, overrides: { + FileSystem: () => fileSystem, + ProcessManager: () => processManager, + }); + + testUsingContext('printHelp without details shows hot restart help message', + () async { + final BufferLogger logger = BufferLogger.test(); + final ResidentRunner residentWebRunner = + setUpResidentRunner(flutterDevice, logger: logger); + fakeVmServiceHost = FakeVmServiceHost(requests: []); + residentWebRunner.printHelp(details: false); + + expect(logger.statusText, contains('To hot restart changes')); + }, overrides: { + FileSystem: () => fileSystem, + ProcessManager: () => processManager, + }); + + testUsingContext('cleanup of resources is safe to call multiple times', + () async { + final ResidentRunner residentWebRunner = setUpResidentRunner(flutterDevice); + mockDevice.dds = DartDevelopmentService(); + fakeVmServiceHost = FakeVmServiceHost(requests: [ + ...kAttachExpectations, + ]); + setupMocks(); + final Completer connectionInfoCompleter = + Completer(); + unawaited(residentWebRunner.run( + connectionInfoCompleter: connectionInfoCompleter, + )); + await connectionInfoCompleter.future; + + await residentWebRunner.exit(); + await residentWebRunner.exit(); + + expect(debugConnection.didClose, false); + expect(fakeVmServiceHost.hasRemainingExpectations, false); + }, overrides: { + FileSystem: () => fileSystem, + ProcessManager: () => processManager, + }); + + testUsingContext('cleans up Chrome if tab is closed', () async { + final ResidentRunner residentWebRunner = setUpResidentRunner(flutterDevice); + fakeVmServiceHost = FakeVmServiceHost(requests: [ + ...kAttachExpectations, + ]); + setupMocks(); + final Completer connectionInfoCompleter = + Completer(); + final Future result = residentWebRunner.run( + connectionInfoCompleter: connectionInfoCompleter, + ); + await connectionInfoCompleter.future; + debugConnection.completer.complete(); + + await result; + expect(fakeVmServiceHost.hasRemainingExpectations, false); + }, overrides: { + FileSystem: () => fileSystem, + ProcessManager: () => processManager, + }); + + testUsingContext('Prints target and device name on run', () async { + final BufferLogger logger = BufferLogger.test(); + final ResidentRunner residentWebRunner = + setUpResidentRunner(flutterDevice, logger: logger); + fakeVmServiceHost = FakeVmServiceHost(requests: [ + ...kAttachExpectations, + ]); + setupMocks(); + mockDevice.name = 'Chromez'; + final Completer connectionInfoCompleter = + Completer(); + unawaited(residentWebRunner.run( + connectionInfoCompleter: connectionInfoCompleter, + )); + await connectionInfoCompleter.future; + + expect( + logger.statusText, + contains( + 'Launching ${fileSystem.path.join('lib', 'main.dart')} on ' + 'Chromez in debug mode', + )); + expect(fakeVmServiceHost.hasRemainingExpectations, false); + }, overrides: { + FileSystem: () => fileSystem, + ProcessManager: () => processManager, + }); + + testUsingContext('Sends launched app.webLaunchUrl event for Chrome device', + () async { + final BufferLogger logger = BufferLogger.test(); + fakeVmServiceHost = FakeVmServiceHost(requests: [ + ...kAttachLogExpectations, + ...kAttachIsolateExpectations, + ]); + setupMocks(); + final FakeChromeConnection chromeConnection = FakeChromeConnection(); + final TestChromiumLauncher chromiumLauncher = TestChromiumLauncher(); + final FakeProcess process = FakeProcess(); + final Chromium chrome = + Chromium(1, chromeConnection, chromiumLauncher: chromiumLauncher, process: process, logger: logger); + chromiumLauncher.setInstance(chrome); + + flutterDevice.device = GoogleChromeDevice( + fileSystem: fileSystem, + chromiumLauncher: chromiumLauncher, + logger: logger, + platform: FakePlatform(), + processManager: FakeProcessManager.any(), + ); + webDevFS.baseUri = Uri.parse('http://localhost:8765/app/'); + + final FakeChromeTab chromeTab = FakeChromeTab('index.html'); + chromeConnection.tabs.add(chromeTab); + + final ResidentWebRunner runner = ResidentWebRunner( + flutterDevice, + flutterProject: + FlutterProject.fromDirectoryTest(fileSystem.currentDirectory), + debuggingOptions: DebuggingOptions.enabled(BuildInfo.debug), + ipv6: true, + fileSystem: fileSystem, + logger: logger, + usage: globals.flutterUsage, + analytics: globals.analytics, + systemClock: globals.systemClock, + ); + + final Completer connectionInfoCompleter = + Completer(); + unawaited(runner.run( + connectionInfoCompleter: connectionInfoCompleter, + )); + await connectionInfoCompleter.future; + + // Ensure we got the URL and that it was already launched. + expect( + logger.eventText, + contains(json.encode( + { + 'name': 'app.webLaunchUrl', + 'args': { + 'url': 'http://localhost:8765/app/', + 'launched': true, + }, + }, + ))); + expect(fakeVmServiceHost.hasRemainingExpectations, false); + }, overrides: { + FileSystem: () => fileSystem, + ProcessManager: () => processManager, + }); + + testUsingContext( + 'Sends unlaunched app.webLaunchUrl event for Web Server device', + () async { + final BufferLogger logger = BufferLogger.test(); + fakeVmServiceHost = FakeVmServiceHost(requests: []); + setupMocks(); + flutterDevice.device = WebServerDevice( + logger: logger, + ); + webDevFS.baseUri = Uri.parse('http://localhost:8765/app/'); + + final ResidentWebRunner runner = ResidentWebRunner( + flutterDevice, + flutterProject: + FlutterProject.fromDirectoryTest(fileSystem.currentDirectory), + debuggingOptions: DebuggingOptions.enabled(BuildInfo.debug), + ipv6: true, + fileSystem: fileSystem, + logger: logger, + usage: globals.flutterUsage, + analytics: globals.analytics, + systemClock: globals.systemClock, + ); + + final Completer connectionInfoCompleter = + Completer(); + unawaited(runner.run( + connectionInfoCompleter: connectionInfoCompleter, + )); + await connectionInfoCompleter.future; + + // Ensure we got the URL and that it was not already launched. + expect( + logger.eventText, + contains(json.encode( + { + 'name': 'app.webLaunchUrl', + 'args': { + 'url': 'http://localhost:8765/app/', + 'launched': false, + }, + }, + ))); + expect(fakeVmServiceHost.hasRemainingExpectations, false); + }, overrides: { + FileSystem: () => fileSystem, + ProcessManager: () => processManager, + }); + + testUsingContext('ResidentWebRunner generates files when l10n.yaml exists', () async { + fakeVmServiceHost = + FakeVmServiceHost(requests: kAttachExpectations.toList()); + setupMocks(); + final ResidentRunner residentWebRunner = ResidentWebRunner( + flutterDevice, + flutterProject: + FlutterProject.fromDirectoryTest(fileSystem.currentDirectory), + debuggingOptions: DebuggingOptions.enabled(BuildInfo.debug), + ipv6: true, + stayResident: false, + fileSystem: fileSystem, + logger: BufferLogger.test(), + usage: globals.flutterUsage, + analytics: globals.analytics, + systemClock: globals.systemClock, + ); + + // Create necessary files. + globals.fs.file(globals.fs.path.join('lib', 'main.dart')) + .createSync(recursive: true); + globals.fs.file(globals.fs.path.join('lib', 'l10n', 'app_en.arb')) + ..createSync(recursive: true) + ..writeAsStringSync(''' +{ + "helloWorld": "Hello, World!", + "@helloWorld": { + "description": "Sample description" + } +}'''); + globals.fs.file('l10n.yaml').createSync(); + globals.fs.file('pubspec.yaml').writeAsStringSync(''' +flutter: + generate: true +'''); + globals.fs.directory('.dart_tool') + .childFile('package_config.json') + ..createSync(recursive: true) + ..writeAsStringSync(''' +{ + "configVersion": 2, + "packages": [ + { + "name": "path_provider_linux", + "rootUri": "../../../path_provider_linux", + "packageUri": "lib/", + "languageVersion": "2.12" + } + ] +} +'''); + expect(await residentWebRunner.run(), 0); + final File generatedLocalizationsFile = globals.fs.directory('.dart_tool') + .childDirectory('flutter_gen') + .childDirectory('gen_l10n') + .childFile('app_localizations.dart'); + expect(generatedLocalizationsFile.existsSync(), isTrue); + // Completing this future ensures that the daemon can exit correctly. + expect(fakeVmServiceHost.hasRemainingExpectations, false); + }, overrides: { + FileSystem: () => fileSystem, + ProcessManager: () => processManager, + }); + + // While this file should be ignored on web, generating it here will cause a + // perf regression in hot restart. + testUsingContext('Does not generate dart_plugin_registrant.dart', () async { + // Create necessary files for [DartPluginRegistrantTarget] + final File packageConfig = + globals.fs.directory('.dart_tool').childFile('package_config.json'); + packageConfig.createSync(recursive: true); + packageConfig.writeAsStringSync(''' +{ + "configVersion": 2, + "packages": [ + { + "name": "path_provider_linux", + "rootUri": "../../../path_provider_linux", + "packageUri": "lib/", + "languageVersion": "2.12" + } + ] +} +'''); + // Start with a dart_plugin_registrant.dart file. + globals.fs + .directory('.dart_tool') + .childDirectory('flutter_build') + .childFile('dart_plugin_registrant.dart') + .createSync(recursive: true); + + final FlutterProject project = + FlutterProject.fromDirectoryTest(fileSystem.currentDirectory); + + final ResidentRunner residentWebRunner = setUpResidentRunner(flutterDevice); + await residentWebRunner.runSourceGenerators(); + + // dart_plugin_registrant.dart should be untouched, indicating that its + // generation didn't run. If it had run, the file would have been removed as + // there are no plugins in the project. + expect(project.dartPluginRegistrant.existsSync(), true); + expect(project.dartPluginRegistrant.readAsStringSync(), ''); + }, overrides: { + FileSystem: () => fileSystem, + ProcessManager: () => processManager, + }); + + testUsingContext('Successfully turns WebSocketException into ToolExit', + () async { + final BufferLogger logger = BufferLogger.test(); + final ResidentRunner residentWebRunner = + setUpResidentRunner(flutterDevice, logger: logger); + fakeVmServiceHost = FakeVmServiceHost(requests: []); + setupMocks(); + webDevFS.exception = const WebSocketException(); + + await expectLater(residentWebRunner.run, throwsToolExit()); + expect(logger.errorText, contains('WebSocketException')); + expect(fakeVmServiceHost.hasRemainingExpectations, false); + }, overrides: { + FileSystem: () => fileSystem, + ProcessManager: () => processManager, + }); + + testUsingContext('Successfully turns AppConnectionException into ToolExit', + () async { + final ResidentRunner residentWebRunner = setUpResidentRunner(flutterDevice); + fakeVmServiceHost = FakeVmServiceHost(requests: []); + setupMocks(); + webDevFS.exception = AppConnectionException(''); + + await expectLater(residentWebRunner.run, throwsToolExit()); + expect(fakeVmServiceHost.hasRemainingExpectations, false); + }, overrides: { + FileSystem: () => fileSystem, + ProcessManager: () => processManager, + }); + + testUsingContext('Successfully turns ChromeDebugError into ToolExit', + () async { + final ResidentRunner residentWebRunner = setUpResidentRunner(flutterDevice); + fakeVmServiceHost = FakeVmServiceHost(requests: []); + setupMocks(); + + webDevFS.exception = ChromeDebugException({ + 'text': 'error', + }); + + await expectLater(residentWebRunner.run, throwsToolExit()); + expect(fakeVmServiceHost.hasRemainingExpectations, false); + }, overrides: { + FileSystem: () => fileSystem, + ProcessManager: () => processManager, + }); + + testUsingContext('Rethrows unknown Exception type from dwds', () async { + final ResidentRunner residentWebRunner = setUpResidentRunner(flutterDevice); + fakeVmServiceHost = FakeVmServiceHost(requests: []); + setupMocks(); + webDevFS.exception = Exception(); + + await expectLater(residentWebRunner.run, throwsException); + expect(fakeVmServiceHost.hasRemainingExpectations, false); + }, overrides: { + FileSystem: () => fileSystem, + ProcessManager: () => processManager, + }); + + testUsingContext('Rethrows unknown Error type from dwds tooling', () async { + final BufferLogger logger = BufferLogger.test(); + final ResidentRunner residentWebRunner = + setUpResidentRunner(flutterDevice, logger: logger); + fakeVmServiceHost = FakeVmServiceHost(requests: []); + setupMocks(); + webDevFS.exception = StateError(''); + + await expectLater(residentWebRunner.run, throwsStateError); + expect(fakeVmServiceHost.hasRemainingExpectations, false); + }, overrides: { + FileSystem: () => fileSystem, + ProcessManager: () => processManager, + }); + + testUsingContext('throws when port is an integer outside the valid TCP range', () async { + final BufferLogger logger = BufferLogger.test(); + + DebuggingOptions debuggingOptions = DebuggingOptions.enabled(BuildInfo.debug, port: '65536'); + ResidentRunner residentWebRunner = + setUpResidentRunner(flutterDevice, logger: logger, debuggingOptions: debuggingOptions); + await expectToolExitLater(residentWebRunner.run(), matches('Invalid port: 65536.*')); + + debuggingOptions = DebuggingOptions.enabled(BuildInfo.debug, port: '-1'); + residentWebRunner = + setUpResidentRunner(flutterDevice, logger: logger, debuggingOptions: debuggingOptions); + await expectToolExitLater(residentWebRunner.run(), matches('Invalid port: -1.*')); + }, overrides: { + FileSystem: () => fileSystem, + ProcessManager: () => processManager, + }); +} + +ResidentRunner setUpResidentRunner( + FlutterDevice flutterDevice, { + Logger? logger, + SystemClock? systemClock, + DebuggingOptions? debuggingOptions, +}) { + return ResidentWebRunner( + flutterDevice, + flutterProject: + FlutterProject.fromDirectoryTest(globals.fs.currentDirectory), + debuggingOptions: + debuggingOptions ?? DebuggingOptions.enabled(BuildInfo.debug), + ipv6: true, + usage: globals.flutterUsage, + analytics: globals.analytics, + systemClock: systemClock ?? SystemClock.fixed(DateTime.now()), + fileSystem: globals.fs, + logger: logger ?? BufferLogger.test(), + devtoolsHandler: createNoOpHandler, + ); +} + +class FakeWebServerDevice extends FakeDevice implements WebServerDevice {} + +class FakeDevice extends Fake implements Device { + @override + String name = 'FakeDevice'; + + int count = 0; + + @override + Future get sdkNameAndVersion async => 'SDK Name and Version'; + + @override + late DartDevelopmentService dds; + + @override + Future startApp( + ApplicationPackage? package, { + String? mainPath, + String? route, + DebuggingOptions? debuggingOptions, + Map? platformArgs, + bool prebuiltApplication = false, + bool ipv6 = false, + String? userIdentifier, + }) async { + return LaunchResult.succeeded(); + } + + @override + Future stopApp( + ApplicationPackage? app, { + String? userIdentifier, + }) async { + if (count > 0) { + throw StateError('stopApp called more than once.'); + } + count += 1; + return true; + } +} + +class FakeDebugConnection extends Fake implements DebugConnection { + late FakeVmServiceHost Function() fakeVmServiceHost; + + @override + vm_service.VmService get vmService => + fakeVmServiceHost.call().vmService.service; + + @override + late String uri; + + final Completer completer = Completer(); + bool didClose = false; + + @override + Future get onDone => completer.future; + + @override + Future close() async { + didClose = true; + } +} + +class FakeAppConnection extends Fake implements AppConnection { + bool ranMain = false; + + @override + void runMain() { + ranMain = true; + } +} +class FakeChromeDevice extends Fake implements ChromiumDevice {} + +class FakeWipDebugger extends Fake implements WipDebugger {} + +class FakeResidentCompiler extends Fake implements ResidentCompiler { + @override + Future recompile( + Uri mainUri, + List? invalidatedFiles, { + required String outputPath, + required PackageConfig packageConfig, + required FileSystem fs, + String? projectRootPath, + bool suppressErrors = false, + bool checkDartPluginRegistry = false, + File? dartPluginRegistrant, + Uri? nativeAssetsYaml, + }) async { + return const CompilerOutput('foo.dill', 0, []); + } + + @override + void accept() {} + + @override + void reset() {} + + @override + Future reject() async { + return const CompilerOutput('foo.dill', 0, []); + } + + @override + void addFileSystemRoot(String root) {} +} + +class FakeWebDevFS extends Fake implements WebDevFS { + Object? exception; + ConnectionResult? result; + late UpdateFSReport report; + + Uri? mainUri; + + @override + List sources = []; + + @override + Uri baseUri = Uri.parse('http://localhost:12345'); + + @override + DateTime? lastCompiled = DateTime.now(); + + @override + PackageConfig? lastPackageConfig = PackageConfig.empty; + + @override + Future create() async { + return baseUri; + } + + @override + Future update({ + required Uri mainUri, + required ResidentCompiler generator, + required bool trackWidgetCreation, + required String pathToReload, + required List invalidatedFiles, + required PackageConfig packageConfig, + required String dillOutputPath, + required DevelopmentShaderCompiler shaderCompiler, + DevelopmentSceneImporter? sceneImporter, + DevFSWriter? devFSWriter, + String? target, + AssetBundle? bundle, + DateTime? firstBuildTime, + bool bundleFirstUpload = false, + bool fullRestart = false, + String? projectRootPath, + File? dartPluginRegistrant, + }) async { + this.mainUri = mainUri; + return report; + } + + @override + Future connect(bool useDebugExtension, {VmServiceFactory vmServiceFactory = createVmServiceDelegate}) async { + if (exception != null) { + assert(exception is Exception || exception is Error); + // ignore: only_throw_errors, exception is either Error or Exception here. + throw exception!; + } + return result; + } +} + +class FakeChromeConnection extends Fake implements ChromeConnection { + final List tabs = []; + + @override + Future getTab(bool Function(ChromeTab tab) accept, + {Duration? retryFor}) async { + return tabs.firstWhere(accept); + } + + @override + Future> getTabs({Duration? retryFor}) async { + return tabs; + } +} + +class FakeChromeTab extends Fake implements ChromeTab { + FakeChromeTab(this.url); + + @override + final String url; + final FakeWipConnection connection = FakeWipConnection(); + + @override + Future connect({Function? onError}) async { + return connection; + } +} + +class FakeWipConnection extends Fake implements WipConnection { + @override + final WipDebugger debugger = FakeWipDebugger(); +} + +/// A test implementation of the [ChromiumLauncher] that launches a fixed instance. +class TestChromiumLauncher implements ChromiumLauncher { + TestChromiumLauncher(); + + bool _hasInstance = false; + void setInstance(Chromium chromium) { + _hasInstance = true; + currentCompleter.complete(chromium); + } + + @override + Completer currentCompleter = Completer(); + + @override + bool canFindExecutable() { + return true; + } + + @override + Future get connectedInstance => currentCompleter.future; + + @override + String findExecutable() { + return 'chrome'; + } + + @override + bool get hasChromeInstance => _hasInstance; + + @override + Future launch( + String url, { + bool headless = false, + int? debugPort, + bool skipCheck = false, + Directory? cacheDir, + List webBrowserFlags = const [], + }) async { + return currentCompleter.future; + } + + @override + Future connect(Chromium chrome, bool skipCheck) { + return currentCompleter.future; + } +} + +class FakeFlutterDevice extends Fake implements FlutterDevice { + Uri? testUri; + UpdateFSReport report = UpdateFSReport( + success: true, + invalidatedSourcesCount: 1, + ); + Exception? reportError; + + @override + ResidentCompiler? generator; + + @override + Stream get vmServiceUris => Stream.value(testUri); + + @override + DevelopmentShaderCompiler get developmentShaderCompiler => const FakeShaderCompiler(); + + @override + FlutterVmService? vmService; + + DevFS? _devFS; + + @override + DevFS? get devFS => _devFS; + + @override + set devFS(DevFS? value) {} + + @override + Device? device; + + @override + Future stopEchoingDeviceLog() async {} + + @override + Future initLogReader() async {} + + @override + Future setupDevFS(String fsName, Directory rootDirectory) async { + return testUri; + } + + @override + Future exitApps( + {Duration timeoutDelay = const Duration(seconds: 10)}) async {} + + @override + Future 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 updateDevFS({ + Uri? mainUri, + String? target, + AssetBundle? bundle, + DateTime? firstBuildTime, + bool bundleFirstUpload = false, + bool bundleDirty = false, + bool fullRestart = false, + String? projectRootPath, + String? pathToReload, + String? dillOutputPath, + List? invalidatedFiles, + PackageConfig? packageConfig, + File? dartPluginRegistrant, + }) async { + if (reportError != null) { + throw reportError!; + } + return report; + } + + @override + Future updateReloadStatus(bool wasReloadSuccessful) async {} +} + +class FakeShaderCompiler implements DevelopmentShaderCompiler { + const FakeShaderCompiler(); + + @override + void configureCompiler( + TargetPlatform? platform, { + required ImpellerStatus impellerStatus, + }) { } + + @override + Future recompileShader(DevFSContent inputShader) { + throw UnimplementedError(); + } +} diff --git a/flutter/packages/flutter_tools/test/general.shard/run_hot_test.dart b/flutter/packages/flutter_tools/test/general.shard/run_hot_test.dart new file mode 100644 index 0000000000000000000000000000000000000000..9c149257e10c043a63797eefcfa00fb7b385f4d1 --- /dev/null +++ b/flutter/packages/flutter_tools/test/general.shard/run_hot_test.dart @@ -0,0 +1,67 @@ +// 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/devfs.dart'; +import 'package:flutter_tools/src/reporting/reporting.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:test/fake.dart'; +import 'package:unified_analytics/unified_analytics.dart'; +import 'package:vm_service/vm_service.dart' as vm_service; + +//import '../src/context.dart'; +import '../src/common.dart'; + +void main() { + testWithoutContext('defaultReloadSourcesHelper() handles empty DeviceReloadReports)', () { + defaultReloadSourcesHelper( + _FakeHotRunner(), + [_FakeFlutterDevice()], + false, + const {}, + 'android', + 'flutter-sdk', + false, + 'test-reason', + TestUsage(), + NoOpAnalytics(), + ); + }); +} + +class _FakeHotRunner extends Fake implements HotRunner {} + +class _FakeDevFS extends Fake implements DevFS { + @override + final Uri? baseUri = Uri(); + + @override + void resetLastCompiled() {} +} + +class _FakeFlutterDevice extends Fake implements FlutterDevice { + @override + final DevFS? devFS = _FakeDevFS(); + + @override + final FlutterVmService? vmService = _FakeFlutterVmService(); +} + +class _FakeFlutterVmService extends Fake implements FlutterVmService { + @override + final vm_service.VmService service = _FakeVmService(); +} + +class _FakeVmService extends Fake implements vm_service.VmService { + @override + Future<_FakeVm> getVM() async => _FakeVm(); +} + +class _FakeVm extends Fake implements vm_service.VM { + final List _isolates = []; + + @override + List? get isolates => _isolates; +} diff --git a/flutter/packages/flutter_tools/test/general.shard/template_test.dart b/flutter/packages/flutter_tools/test/general.shard/template_test.dart new file mode 100644 index 0000000000000000000000000000000000000000..fa4bf6823df30fa87f9b3b1e99763a6d38e12b9e --- /dev/null +++ b/flutter/packages/flutter_tools/test/general.shard/template_test.dart @@ -0,0 +1,222 @@ +// 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:typed_data'; + +import 'package:file/memory.dart'; +import 'package:file_testing/file_testing.dart'; +import 'package:flutter_tools/src/base/file_system.dart'; +import 'package:flutter_tools/src/base/logger.dart'; +import 'package:flutter_tools/src/base/template.dart'; +import 'package:flutter_tools/src/cache.dart'; +import 'package:flutter_tools/src/globals.dart' as globals; +import 'package:flutter_tools/src/template.dart'; +import '../src/common.dart'; +import '../src/context.dart'; + +void main() { + testWithoutContext('Template constructor throws ToolExit when source directory is missing', () { + final FileExceptionHandler handler = FileExceptionHandler(); + final MemoryFileSystem fileSystem = MemoryFileSystem.test(opHandle: handler.opHandle); + + expect(() => Template( + fileSystem.directory('doesNotExist'), + fileSystem.currentDirectory, + fileSystem: fileSystem, + logger: BufferLogger.test(), + templateRenderer: FakeTemplateRenderer(), + ), throwsToolExit()); + }); + + testWithoutContext('Template.render throws ToolExit when FileSystem exception is raised', () { + final FileExceptionHandler handler = FileExceptionHandler(); + final MemoryFileSystem fileSystem = MemoryFileSystem.test(opHandle: handler.opHandle); + final Template template = Template( + fileSystem.directory('examples')..createSync(recursive: true), + fileSystem.currentDirectory, + fileSystem: fileSystem, + logger: BufferLogger.test(), + templateRenderer: FakeTemplateRenderer(), + ); + final Directory directory = fileSystem.directory('foo'); + handler.addError(directory, FileSystemOp.create, const FileSystemException()); + + expect(() => template.render(directory, {}), + throwsToolExit()); + }); + + group('template image directory', () { + final Map overrides = { + FileSystem: () => MemoryFileSystem.test(), + ProcessManager: () => FakeProcessManager.any(), + }; + const TemplatePathProvider templatePathProvider = TemplatePathProvider(); + + testUsingContext('templatePathProvider.imageDirectory returns parent template directory if passed null name', () async { + final String packageConfigPath = globals.fs.path.join( + Cache.flutterRoot!, + 'packages', + 'flutter_tools', + '.dart_tool', + 'package_config.json', + ); + + globals.fs.file(packageConfigPath) + ..createSync(recursive: true) + ..writeAsStringSync(''' +{ + "configVersion": 2, + "packages": [ + { + "name": "flutter_template_images", + "rootUri": "/flutter_template_images", + "packageUri": "lib/", + "languageVersion": "2.12" + } + ] +} +'''); + expect( + (await templatePathProvider.imageDirectory(null, globals.fs, globals.logger)).path, + globals.fs.path.absolute( + 'flutter_template_images', + 'templates', + ), + ); + }, overrides: overrides); + + testUsingContext('templatePathProvider.imageDirectory returns the directory containing the `name` template directory', () async { + final String packageConfigPath = globals.fs.path.join( + Cache.flutterRoot!, + 'packages', + 'flutter_tools', + '.dart_tool', + 'package_config.json', + ); + globals.fs.file(packageConfigPath) + ..createSync(recursive: true) + ..writeAsStringSync(''' +{ + "configVersion": 2, + "packages": [ + { + "name": "flutter_template_images", + "rootUri": "/flutter_template_images", + "packageUri": "lib/", + "languageVersion": "2.12" + } + ] +} +'''); + expect( + (await templatePathProvider.imageDirectory('app_shared', globals.fs, globals.logger)).path, + globals.fs.path.absolute( + 'flutter_template_images', + 'templates', + 'app_shared', + ), + ); + }, overrides: overrides); + }); + + group('renders template', () { + late Directory destination; + const String imageName = 'some_image.png'; + late File sourceImage; + late BufferLogger logger; + late Template template; + + setUp(() { + final MemoryFileSystem fileSystem = MemoryFileSystem.test(); + final Directory templateDir = fileSystem.directory('templates'); + final Directory imageSourceDir = fileSystem.directory('template_images'); + destination = fileSystem.directory('target'); + templateDir.childFile('$imageName.img.tmpl').createSync(recursive: true); + sourceImage = imageSourceDir.childFile(imageName); + sourceImage.createSync(recursive: true); + sourceImage.writeAsStringSync("Ceci n'est pas une pipe"); + + logger = BufferLogger.test(); + template = Template( + templateDir, + imageSourceDir, + fileSystem: fileSystem, + logger: logger, + templateRenderer: FakeTemplateRenderer(), + ); + }); + + testWithoutContext('overwrites .img.tmpl files with files from the image source', () { + expect(template.render(destination, {}), 1); + + final File destinationImage = destination.childFile(imageName); + final Uint8List sourceImageBytes = sourceImage.readAsBytesSync(); + expect(destinationImage, exists); + expect(destinationImage.readAsBytesSync(), equals(sourceImageBytes)); + + expect(logger.errorText, isEmpty); + expect(logger.statusText, contains('${destinationImage.path} (created)')); + logger.clear(); + + // Run it again to overwrite (returns 1 file updated). + expect(template.render(destination, {}), 1); + + expect(destinationImage.readAsBytesSync(), equals(sourceImageBytes)); + expect(logger.errorText, isEmpty); + expect(logger.statusText, contains('${destinationImage.path} (overwritten)')); + }); + + testWithoutContext('does not overwrite .img.tmpl files with files from the image source', () { + expect(template.render(destination, {}), 1); + + final File destinationImage = destination.childFile(imageName); + expect(destinationImage, exists); + + expect(logger.errorText, isEmpty); + expect(logger.statusText, contains('${destinationImage.path} (created)')); + logger.clear(); + + // Run it again, do not overwrite (returns 0 files updated). + expect(template.render(destination, {}, overwriteExisting: false), 0); + + expect(destinationImage, exists); + expect(logger.errorText, isEmpty); + expect(logger.statusText, isEmpty); + }); + + testWithoutContext('can suppress file printing', () { + template.render(destination, {}, printStatusWhenWriting: false); + + final File destinationImage = destination.childFile(imageName); + expect(destinationImage, exists); + + expect(logger.errorText, isEmpty); + expect(logger.statusText, isEmpty); + }); + }); + + testWithoutContext('escapeYamlString', () { + expect(escapeYamlString(''), r'""'); + expect(escapeYamlString('\x00\n\r\t\b'), r'"\0\n\r\t\x08"'); + expect(escapeYamlString('test'), r'"test"'); + expect(escapeYamlString('test\n test'), r'"test\n test"'); + expect(escapeYamlString('\x00\x01\x02\x0c\x19\xab'), r'"\0\x01\x02\x0c\x19«"'); + expect(escapeYamlString('"'), r'"\""'); + expect(escapeYamlString(r'\'), r'"\\"'); + expect(escapeYamlString('[user branch]'), r'"[user branch]"'); + expect(escapeYamlString('main'), r'"main"'); + expect(escapeYamlString('TEST_BRANCH'), r'"TEST_BRANCH"'); + expect(escapeYamlString(' '), r'" "'); + expect(escapeYamlString(' \n '), r'" \n "'); + expect(escapeYamlString('""'), r'"\"\""'); + expect(escapeYamlString('"\x01\u{0263A}\u{1F642}'), r'"\"\x01☺🙂"'); + }); +} + +class FakeTemplateRenderer extends TemplateRenderer { + @override + String renderString(String template, dynamic context, {bool htmlEscapeValues = false}) { + return ''; + } +} diff --git a/flutter/packages/flutter_tools/test/general.shard/terminal_handler_test.dart b/flutter/packages/flutter_tools/test/general.shard/terminal_handler_test.dart new file mode 100644 index 0000000000000000000000000000000000000000..99a61417df66cc73056bbadc48839f3dae3cdf6e --- /dev/null +++ b/flutter/packages/flutter_tools/test/general.shard/terminal_handler_test.dart @@ -0,0 +1,1487 @@ +// 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/file.dart'; +import 'package:file/memory.dart'; +import 'package:file_testing/file_testing.dart'; +import 'package:flutter_tools/src/base/io.dart'; +import 'package:flutter_tools/src/base/logger.dart'; +import 'package:flutter_tools/src/base/signals.dart'; +import 'package:flutter_tools/src/base/terminal.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/convert.dart'; +import 'package:flutter_tools/src/devfs.dart'; +import 'package:flutter_tools/src/device.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_vm_services.dart'; + +final vm_service.Isolate fakeUnpausedIsolate = vm_service.Isolate( + id: '1', + pauseEvent: vm_service.Event( + kind: vm_service.EventKind.kResume, + timestamp: 0 + ), + breakpoints: [], + extensionRPCs: [], + libraries: [ + 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: [], +); + +final FlutterView fakeFlutterView = FlutterView( + id: 'a', + uiIsolate: fakeUnpausedIsolate, +); + +final FakeVmServiceRequest listViews = FakeVmServiceRequest( + method: kListViewsMethod, + jsonResponse: { + 'views': [ + fakeFlutterView.toJson(), + ], + }, +); + +void main() { + testWithoutContext('keyboard input handling single help character', () async { + final TestRunner testRunner = TestRunner(); + final Logger logger = BufferLogger.test(); + final Signals signals = Signals.test(); + final Terminal terminal = Terminal.test(); + final MemoryFileSystem fs = MemoryFileSystem.test(); + final ProcessInfo processInfo = ProcessInfo.test(fs); + final TerminalHandler terminalHandler = TerminalHandler( + testRunner, + logger: logger, + signals: signals, + terminal: terminal, + processInfo: processInfo, + reportReady: false, + ); + + expect(testRunner.hasHelpBeenPrinted, false); + await terminalHandler.processTerminalInput('h'); + expect(testRunner.hasHelpBeenPrinted, true); + }); + + testWithoutContext('keyboard input handling help character surrounded with newlines', () async { + final TestRunner testRunner = TestRunner(); + final Logger logger = BufferLogger.test(); + final Signals signals = Signals.test(); + final Terminal terminal = Terminal.test(); + final MemoryFileSystem fs = MemoryFileSystem.test(); + final ProcessInfo processInfo = ProcessInfo.test(fs); + final TerminalHandler terminalHandler = TerminalHandler( + testRunner, + logger: logger, + signals: signals, + terminal: terminal, + processInfo: processInfo, + reportReady: false, + ); + + expect(testRunner.hasHelpBeenPrinted, false); + await terminalHandler.processTerminalInput('\nh\n'); + expect(testRunner.hasHelpBeenPrinted, true); + }); + + group('keycode verification, brought to you by the letter', () { + testWithoutContext('a, can handle trailing newlines', () async { + final TerminalHandler terminalHandler = setUpTerminalHandler([], supportsServiceProtocol: false); + await terminalHandler.processTerminalInput('a\n'); + + expect(terminalHandler.lastReceivedCommand, 'a'); + }); + + testWithoutContext('n, can handle trailing only newlines', () async { + final TerminalHandler terminalHandler = setUpTerminalHandler([]); + await terminalHandler.processTerminalInput('\n\n'); + + expect(terminalHandler.lastReceivedCommand, ''); + }); + + testWithoutContext('a - debugToggleProfileWidgetBuilds', () async { + final TerminalHandler terminalHandler = setUpTerminalHandler([ + listViews, + const FakeVmServiceRequest( + method: 'ext.flutter.profileWidgetBuilds', + args: { + 'isolateId': '1', + }, + jsonResponse: { + 'enabled': 'false', + }, + ), + const FakeVmServiceRequest( + method: 'ext.flutter.profileWidgetBuilds', + args: { + 'isolateId': '1', + 'enabled': 'true', + }, + jsonResponse: { + 'enabled': 'true', + }, + ), + ]); + + await terminalHandler.processTerminalInput('a'); + }); + + testWithoutContext('a - debugToggleProfileWidgetBuilds with web target', () async { + final TerminalHandler terminalHandler = setUpTerminalHandler([ + listViews, + const FakeVmServiceRequest( + method: 'ext.flutter.profileWidgetBuilds', + args: { + 'isolateId': '1', + }, + jsonResponse: { + 'enabled': 'false', + }, + ), + const FakeVmServiceRequest( + method: 'ext.flutter.profileWidgetBuilds', + args: { + 'isolateId': '1', + 'enabled': 'true', + }, + jsonResponse: { + 'enabled': 'true', + }, + ), + ], web: true); + + await terminalHandler.processTerminalInput('a'); + }); + + testWithoutContext('j unsupported jank metrics for web', () async { + final TerminalHandler terminalHandler = setUpTerminalHandler([], web: true); + await terminalHandler.processTerminalInput('j'); + expect(terminalHandler.logger.warningText.contains('Unable to get jank metrics for web'), true); + }); + + testWithoutContext('a - debugToggleProfileWidgetBuilds without service protocol is skipped', () async { + final TerminalHandler terminalHandler = setUpTerminalHandler([], supportsServiceProtocol: false); + + await terminalHandler.processTerminalInput('a'); + }); + + testWithoutContext('b - debugToggleBrightness', () async { + final TerminalHandler terminalHandler = setUpTerminalHandler([ + listViews, + const FakeVmServiceRequest( + method: 'ext.flutter.brightnessOverride', + args: { + 'isolateId': '1', + }, + jsonResponse: { + 'value': 'Brightness.light', + } + ), + listViews, + const FakeVmServiceRequest( + method: 'ext.flutter.brightnessOverride', + args: { + 'isolateId': '1', + 'value': 'Brightness.dark', + }, + jsonResponse: { + 'value': 'Brightness.dark', + } + ), + ]); + await terminalHandler.processTerminalInput('b'); + + expect(terminalHandler.logger.statusText, contains('Changed brightness to Brightness.dark')); + }); + + testWithoutContext('b - debugToggleBrightness with web target', () async { + final TerminalHandler terminalHandler = setUpTerminalHandler([ + listViews, + const FakeVmServiceRequest( + method: 'ext.flutter.brightnessOverride', + args: { + 'isolateId': '1', + }, + jsonResponse: { + 'value': 'Brightness.light', + } + ), + listViews, + const FakeVmServiceRequest( + method: 'ext.flutter.brightnessOverride', + args: { + 'isolateId': '1', + 'value': 'Brightness.dark', + }, + jsonResponse: { + 'value': 'Brightness.dark', + } + ), + ], web: true); + await terminalHandler.processTerminalInput('b'); + + expect(terminalHandler.logger.statusText, contains('Changed brightness to Brightness.dark')); + }); + + testWithoutContext('b - debugToggleBrightness without service protocol is skipped', () async { + final TerminalHandler terminalHandler = setUpTerminalHandler([], supportsServiceProtocol: false); + + await terminalHandler.processTerminalInput('b'); + }); + + testWithoutContext('d,D - detach', () async { + final TerminalHandler terminalHandler = setUpTerminalHandler([]); + final FakeResidentRunner runner = terminalHandler.residentRunner as FakeResidentRunner; + await terminalHandler.processTerminalInput('d'); + + expect(runner.calledDetach, true); + runner.calledDetach = false; + + await terminalHandler.processTerminalInput('D'); + + expect(runner.calledDetach, true); + }); + + testWithoutContext('h,H,? - printHelp', () async { + final TerminalHandler terminalHandler = setUpTerminalHandler([]); + final FakeResidentRunner runner = terminalHandler.residentRunner as FakeResidentRunner; + await terminalHandler.processTerminalInput('h'); + + expect(runner.calledPrintWithDetails, true); + runner.calledPrintWithDetails = false; + + await terminalHandler.processTerminalInput('H'); + + expect(runner.calledPrintWithDetails, true); + runner.calledPrintWithDetails = false; + + await terminalHandler.processTerminalInput('?'); + + expect(runner.calledPrintWithDetails, true); + }); + + testWithoutContext('i - debugToggleWidgetInspector', () async { + final TerminalHandler terminalHandler = setUpTerminalHandler([ + listViews, + const FakeVmServiceRequest( + method: 'ext.flutter.inspector.show', + args: { + 'isolateId': '1', + }, + ), + ]); + + await terminalHandler.processTerminalInput('i'); + }); + + testWithoutContext('i - debugToggleWidgetInspector with web target', () async { + final TerminalHandler terminalHandler = setUpTerminalHandler([ + listViews, + const FakeVmServiceRequest( + method: 'ext.flutter.inspector.show', + args: { + 'isolateId': '1', + }, + ), + ], web: true); + + await terminalHandler.processTerminalInput('i'); + }); + + testWithoutContext('i - debugToggleWidgetInspector without service protocol is skipped', () async { + final TerminalHandler terminalHandler = setUpTerminalHandler([], supportsServiceProtocol: false); + + await terminalHandler.processTerminalInput('i'); + }); + + testWithoutContext('I - debugToggleInvertOversizedImages', () async { + final TerminalHandler terminalHandler = setUpTerminalHandler([ + listViews, + const FakeVmServiceRequest( + method: 'ext.flutter.invertOversizedImages', + args: { + 'isolateId': '1', + }, + ), + ]); + await terminalHandler.processTerminalInput('I'); + }); + + testWithoutContext('I - debugToggleInvertOversizedImages with web target', () async { + final TerminalHandler terminalHandler = setUpTerminalHandler([ + listViews, + const FakeVmServiceRequest( + method: 'ext.flutter.invertOversizedImages', + args: { + 'isolateId': '1', + }, + ), + ], web: true); + await terminalHandler.processTerminalInput('I'); + }); + + testWithoutContext('I - debugToggleInvertOversizedImages without service protocol is skipped', () async { + final TerminalHandler terminalHandler = setUpTerminalHandler([], supportsServiceProtocol: false); + await terminalHandler.processTerminalInput('I'); + }); + + testWithoutContext('I - debugToggleInvertOversizedImages in profile mode is skipped', () async { + final TerminalHandler terminalHandler = setUpTerminalHandler([], buildMode: BuildMode.profile); + await terminalHandler.processTerminalInput('I'); + }); + + testWithoutContext('L - debugDumpLayerTree', () async { + final TerminalHandler terminalHandler = setUpTerminalHandler([ + listViews, + const FakeVmServiceRequest( + method: 'ext.flutter.debugDumpLayerTree', + args: { + 'isolateId': '1', + }, + jsonResponse: { + 'data': 'LAYER TREE', + } + ), + ]); + await terminalHandler.processTerminalInput('L'); + + expect(terminalHandler.logger.statusText, contains('LAYER TREE')); + }); + + testWithoutContext('L - debugDumpLayerTree with web target', () async { + final TerminalHandler terminalHandler = setUpTerminalHandler([ + listViews, + const FakeVmServiceRequest( + method: 'ext.flutter.debugDumpLayerTree', + args: { + 'isolateId': '1', + }, + jsonResponse: { + 'data': 'LAYER TREE', + } + ), + ], web: true); + await terminalHandler.processTerminalInput('L'); + + expect(terminalHandler.logger.statusText, contains('LAYER TREE')); + }); + + testWithoutContext('L - debugDumpLayerTree with service protocol and profile mode is skipped', () async { + final TerminalHandler terminalHandler = setUpTerminalHandler([], buildMode: BuildMode.profile); + await terminalHandler.processTerminalInput('L'); + }); + + testWithoutContext('L - debugDumpLayerTree without service protocol is skipped', () async { + final TerminalHandler terminalHandler = setUpTerminalHandler([], supportsServiceProtocol: false); + await terminalHandler.processTerminalInput('L'); + }); + + testWithoutContext('f - debugDumpFocusTree', () async { + final TerminalHandler terminalHandler = setUpTerminalHandler([ + listViews, + const FakeVmServiceRequest( + method: 'ext.flutter.debugDumpFocusTree', + args: { + 'isolateId': '1', + }, + jsonResponse: { + 'data': 'FOCUS TREE', + } + ), + ]); + await terminalHandler.processTerminalInput('f'); + + expect(terminalHandler.logger.statusText, contains('FOCUS TREE')); + }); + + testWithoutContext('f - debugDumpLayerTree with web target', () async { + final TerminalHandler terminalHandler = setUpTerminalHandler([ + listViews, + const FakeVmServiceRequest( + method: 'ext.flutter.debugDumpFocusTree', + args: { + 'isolateId': '1', + }, + jsonResponse: { + 'data': 'FOCUS TREE', + } + ), + ], web: true); + await terminalHandler.processTerminalInput('f'); + + expect(terminalHandler.logger.statusText, contains('FOCUS TREE')); + }); + + testWithoutContext('f - debugDumpFocusTree with service protocol and profile mode is skipped', () async { + final TerminalHandler terminalHandler = setUpTerminalHandler([], buildMode: BuildMode.profile); + await terminalHandler.processTerminalInput('f'); + }); + + testWithoutContext('f - debugDumpFocusTree without service protocol is skipped', () async { + final TerminalHandler terminalHandler = setUpTerminalHandler([], supportsServiceProtocol: false); + await terminalHandler.processTerminalInput('f'); + }); + + testWithoutContext('o,O - debugTogglePlatform', () async { + final TerminalHandler terminalHandler = setUpTerminalHandler([ + // Request 1. + listViews, + const FakeVmServiceRequest( + method: 'ext.flutter.platformOverride', + args: { + 'isolateId': '1', + }, + jsonResponse: { + 'value': 'iOS', + }, + ), + listViews, + const FakeVmServiceRequest( + method: 'ext.flutter.platformOverride', + args: { + 'isolateId': '1', + 'value': 'windows', + }, + jsonResponse: { + 'value': 'windows', + }, + ), + // Request 2. + listViews, + const FakeVmServiceRequest( + method: 'ext.flutter.platformOverride', + args: { + 'isolateId': '1', + }, + jsonResponse: { + 'value': 'android', + }, + ), + listViews, + const FakeVmServiceRequest( + method: 'ext.flutter.platformOverride', + args: { + 'isolateId': '1', + 'value': 'iOS', + }, + jsonResponse: { + 'value': 'iOS', + }, + ), + ]); + await terminalHandler.processTerminalInput('o'); + await terminalHandler.processTerminalInput('O'); + + expect(terminalHandler.logger.statusText, contains('Switched operating system to windows')); + expect(terminalHandler.logger.statusText, contains('Switched operating system to iOS')); + }); + + testWithoutContext('o,O - debugTogglePlatform with web target', () async { + final TerminalHandler terminalHandler = setUpTerminalHandler([ + // Request 1. + listViews, + const FakeVmServiceRequest( + method: 'ext.flutter.platformOverride', + args: { + 'isolateId': '1', + }, + jsonResponse: { + 'value': 'iOS', + }, + ), + listViews, + const FakeVmServiceRequest( + method: 'ext.flutter.platformOverride', + args: { + 'isolateId': '1', + 'value': 'windows', + }, + jsonResponse: { + 'value': 'windows', + }, + ), + // Request 2. + listViews, + const FakeVmServiceRequest( + method: 'ext.flutter.platformOverride', + args: { + 'isolateId': '1', + }, + jsonResponse: { + 'value': 'android', + }, + ), + listViews, + const FakeVmServiceRequest( + method: 'ext.flutter.platformOverride', + args: { + 'isolateId': '1', + 'value': 'iOS', + }, + jsonResponse: { + 'value': 'iOS', + }, + ), + ], web: true); + await terminalHandler.processTerminalInput('o'); + await terminalHandler.processTerminalInput('O'); + + expect(terminalHandler.logger.statusText, contains('Switched operating system to windows')); + expect(terminalHandler.logger.statusText, contains('Switched operating system to iOS')); + }); + + testWithoutContext('o,O - debugTogglePlatform without service protocol is skipped', () async { + final TerminalHandler terminalHandler = setUpTerminalHandler([], supportsServiceProtocol: false); + await terminalHandler.processTerminalInput('o'); + await terminalHandler.processTerminalInput('O'); + }); + + testWithoutContext('p - debugToggleDebugPaintSizeEnabled', () async { + final TerminalHandler terminalHandler = setUpTerminalHandler([ + listViews, + const FakeVmServiceRequest( + method: 'ext.flutter.debugPaint', + args: { + 'isolateId': '1', + }, + ), + ]); + await terminalHandler.processTerminalInput('p'); + }); + + testWithoutContext('p - debugToggleDebugPaintSizeEnabled with web target', () async { + final TerminalHandler terminalHandler = setUpTerminalHandler([ + listViews, + const FakeVmServiceRequest( + method: 'ext.flutter.debugPaint', + args: { + 'isolateId': '1', + }, + ), + ], web: true); + await terminalHandler.processTerminalInput('p'); + }); + + testWithoutContext('p - debugToggleDebugPaintSizeEnabled without service protocol is skipped', () async { + final TerminalHandler terminalHandler = setUpTerminalHandler([], supportsServiceProtocol: false); + await terminalHandler.processTerminalInput('p'); + }); + + testWithoutContext('P - debugTogglePerformanceOverlayOverride', () async { + final TerminalHandler terminalHandler = setUpTerminalHandler([ + listViews, + const FakeVmServiceRequest( + method: 'ext.flutter.showPerformanceOverlay', + args: { + 'isolateId': '1', + }, + ), + ]); + await terminalHandler.processTerminalInput('P'); + }); + + testWithoutContext('P - debugTogglePerformanceOverlayOverride with web target is skipped ', () async { + final TerminalHandler terminalHandler = setUpTerminalHandler([], web: true); + await terminalHandler.processTerminalInput('P'); + }); + + testWithoutContext('P - debugTogglePerformanceOverlayOverride without service protocol is skipped ', () async { + final TerminalHandler terminalHandler = setUpTerminalHandler([], supportsServiceProtocol: false); + await terminalHandler.processTerminalInput('P'); + }); + + testWithoutContext('S - debugDumpSemanticsTreeInTraversalOrder', () async { + final TerminalHandler terminalHandler = setUpTerminalHandler([ + listViews, + const FakeVmServiceRequest( + method: 'ext.flutter.debugDumpSemanticsTreeInTraversalOrder', + args: { + 'isolateId': '1', + }, + jsonResponse: { + 'data': 'SEMANTICS DATA', + }, + ), + ]); + await terminalHandler.processTerminalInput('S'); + + expect(terminalHandler.logger.statusText, contains('SEMANTICS DATA')); + }); + + testWithoutContext('S - debugDumpSemanticsTreeInTraversalOrder with web target', () async { + final TerminalHandler terminalHandler = setUpTerminalHandler([ + listViews, + const FakeVmServiceRequest( + method: 'ext.flutter.debugDumpSemanticsTreeInTraversalOrder', + args: { + 'isolateId': '1', + }, + jsonResponse: { + 'data': 'SEMANTICS DATA', + }, + ), + ], web: true); + await terminalHandler.processTerminalInput('S'); + + expect(terminalHandler.logger.statusText, contains('SEMANTICS DATA')); + }); + + testWithoutContext('S - debugDumpSemanticsTreeInTraversalOrder without service protocol is skipped', () async { + final TerminalHandler terminalHandler = setUpTerminalHandler([], supportsServiceProtocol: false); + await terminalHandler.processTerminalInput('S'); + }); + + testWithoutContext('U - debugDumpSemanticsTreeInInverseHitTestOrder', () async { + final TerminalHandler terminalHandler = setUpTerminalHandler([ + listViews, + const FakeVmServiceRequest( + method: 'ext.flutter.debugDumpSemanticsTreeInInverseHitTestOrder', + args: { + 'isolateId': '1', + }, + jsonResponse: { + 'data': 'SEMANTICS DATA', + }, + ), + ]); + await terminalHandler.processTerminalInput('U'); + + expect(terminalHandler.logger.statusText, contains('SEMANTICS DATA')); + }); + + testWithoutContext('U - debugDumpSemanticsTreeInInverseHitTestOrder with web target', () async { + final TerminalHandler terminalHandler = setUpTerminalHandler([ + listViews, + const FakeVmServiceRequest( + method: 'ext.flutter.debugDumpSemanticsTreeInInverseHitTestOrder', + args: { + 'isolateId': '1', + }, + jsonResponse: { + 'data': 'SEMANTICS DATA', + }, + ), + ], web: true); + await terminalHandler.processTerminalInput('U'); + + expect(terminalHandler.logger.statusText, contains('SEMANTICS DATA')); + }); + + testWithoutContext('U - debugDumpSemanticsTreeInInverseHitTestOrder without service protocol is skipped', () async { + final TerminalHandler terminalHandler = setUpTerminalHandler([], supportsServiceProtocol: false); + await terminalHandler.processTerminalInput('U'); + }); + + testWithoutContext('t,T - debugDumpRenderTree', () async { + final TerminalHandler terminalHandler = setUpTerminalHandler([ + listViews, + const FakeVmServiceRequest( + method: 'ext.flutter.debugDumpRenderTree', + args: { + 'isolateId': '1', + }, + jsonResponse: { + 'data': 'RENDER DATA 1', + }, + ), + // Request 2. + listViews, + const FakeVmServiceRequest( + method: 'ext.flutter.debugDumpRenderTree', + args: { + 'isolateId': '1', + }, + jsonResponse: { + 'data': 'RENDER DATA 2', + }, + ), + ]); + await terminalHandler.processTerminalInput('t'); + await terminalHandler.processTerminalInput('T'); + + expect(terminalHandler.logger.statusText, contains('RENDER DATA 1')); + expect(terminalHandler.logger.statusText, contains('RENDER DATA 2')); + }); + + testWithoutContext('t,T - debugDumpRenderTree with web target', () async { + final TerminalHandler terminalHandler = setUpTerminalHandler([ + listViews, + const FakeVmServiceRequest( + method: 'ext.flutter.debugDumpRenderTree', + args: { + 'isolateId': '1', + }, + jsonResponse: { + 'data': 'RENDER DATA 1', + }, + ), + // Request 2. + listViews, + const FakeVmServiceRequest( + method: 'ext.flutter.debugDumpRenderTree', + args: { + 'isolateId': '1', + }, + jsonResponse: { + 'data': 'RENDER DATA 2', + }, + ), + ], web: true); + await terminalHandler.processTerminalInput('t'); + await terminalHandler.processTerminalInput('T'); + + expect(terminalHandler.logger.statusText, contains('RENDER DATA 1')); + expect(terminalHandler.logger.statusText, contains('RENDER DATA 2')); + }); + + testWithoutContext('t,T - debugDumpRenderTree without service protocol is skipped', () async { + final TerminalHandler terminalHandler = setUpTerminalHandler([], supportsServiceProtocol: false); + await terminalHandler.processTerminalInput('t'); + await terminalHandler.processTerminalInput('T'); + }); + + testWithoutContext('w,W - debugDumpApp', () async { + final TerminalHandler terminalHandler = setUpTerminalHandler([ + listViews, + const FakeVmServiceRequest( + method: 'ext.flutter.debugDumpApp', + args: { + 'isolateId': '1', + }, + jsonResponse: { + 'data': 'WIDGET DATA 1', + }, + ), + // Request 2. + listViews, + const FakeVmServiceRequest( + method: 'ext.flutter.debugDumpApp', + args: { + 'isolateId': '1', + }, + jsonResponse: { + 'data': 'WIDGET DATA 2', + }, + ), + ]); + await terminalHandler.processTerminalInput('w'); + await terminalHandler.processTerminalInput('W'); + + expect(terminalHandler.logger.statusText, contains('WIDGET DATA 1')); + expect(terminalHandler.logger.statusText, contains('WIDGET DATA 2')); + }); + + testWithoutContext('w,W - debugDumpApp with web target', () async { + final TerminalHandler terminalHandler = setUpTerminalHandler([ + listViews, + const FakeVmServiceRequest( + method: 'ext.flutter.debugDumpApp', + args: { + 'isolateId': '1', + }, + jsonResponse: { + 'data': 'WIDGET DATA 1', + }, + ), + // Request 2. + listViews, + const FakeVmServiceRequest( + method: 'ext.flutter.debugDumpApp', + args: { + 'isolateId': '1', + }, + jsonResponse: { + 'data': 'WIDGET DATA 2', + }, + ), + ], web: true); + await terminalHandler.processTerminalInput('w'); + await terminalHandler.processTerminalInput('W'); + + expect(terminalHandler.logger.statusText, contains('WIDGET DATA 1')); + expect(terminalHandler.logger.statusText, contains('WIDGET DATA 2')); + }); + + testWithoutContext('v - launchDevToolsInBrowser', () async { + final TerminalHandler terminalHandler = setUpTerminalHandler([]); + final FakeResidentRunner runner = terminalHandler.residentRunner as FakeResidentRunner; + final FakeResidentDevtoolsHandler devtoolsHandler = runner.residentDevtoolsHandler as FakeResidentDevtoolsHandler; + + expect(devtoolsHandler.calledLaunchDevToolsInBrowser, isFalse); + await terminalHandler.processTerminalInput('v'); + expect(devtoolsHandler.calledLaunchDevToolsInBrowser, isTrue); + }); + + testWithoutContext('w,W - debugDumpApp without service protocol is skipped', () async { + final TerminalHandler terminalHandler = setUpTerminalHandler([], supportsServiceProtocol: false); + await terminalHandler.processTerminalInput('w'); + await terminalHandler.processTerminalInput('W'); + }); + + testWithoutContext('z,Z - debugToggleDebugCheckElevationsEnabled', () async { + final TerminalHandler terminalHandler = setUpTerminalHandler([ + listViews, + const FakeVmServiceRequest( + method: 'ext.flutter.debugCheckElevationsEnabled', + args: { + 'isolateId': '1', + }, + ), + // Request 2. + listViews, + const FakeVmServiceRequest( + method: 'ext.flutter.debugCheckElevationsEnabled', + args: { + 'isolateId': '1', + }, + ), + ]); + await terminalHandler.processTerminalInput('z'); + await terminalHandler.processTerminalInput('Z'); + }); + + testWithoutContext('z,Z - debugToggleDebugCheckElevationsEnabled with web target', () async { + final TerminalHandler terminalHandler = setUpTerminalHandler([ + listViews, + const FakeVmServiceRequest( + method: 'ext.flutter.debugCheckElevationsEnabled', + args: { + 'isolateId': '1', + }, + ), + // Request 2. + listViews, + const FakeVmServiceRequest( + method: 'ext.flutter.debugCheckElevationsEnabled', + args: { + 'isolateId': '1', + }, + ), + ], web: true); + await terminalHandler.processTerminalInput('z'); + await terminalHandler.processTerminalInput('Z'); + }); + + testWithoutContext('z,Z - debugToggleDebugCheckElevationsEnabled without service protocol is skipped', () async { + final TerminalHandler terminalHandler = setUpTerminalHandler([], supportsServiceProtocol: false); + await terminalHandler.processTerminalInput('z'); + await terminalHandler.processTerminalInput('Z'); + }); + + testWithoutContext('q,Q - exit', () async { + final TerminalHandler terminalHandler = setUpTerminalHandler([]); + final FakeResidentRunner runner = terminalHandler.residentRunner as FakeResidentRunner; + await terminalHandler.processTerminalInput('q'); + + expect(runner.calledExit, true); + runner.calledExit = false; + + await terminalHandler.processTerminalInput('Q'); + + expect(runner.calledExit, true); + }); + + testWithoutContext('r - hotReload unsupported', () async { + final TerminalHandler terminalHandler = setUpTerminalHandler([], supportsHotReload: false); + await terminalHandler.processTerminalInput('r'); + }); + + testWithoutContext('R - hotRestart unsupported', () async { + final TerminalHandler terminalHandler = setUpTerminalHandler([], supportsRestart: false); + await terminalHandler.processTerminalInput('R'); + }); + + testWithoutContext('r - hotReload', () async { + final TerminalHandler terminalHandler = setUpTerminalHandler([]); + final FakeResidentRunner runner = terminalHandler.residentRunner as FakeResidentRunner; + + await terminalHandler.processTerminalInput('r'); + + expect(runner.calledReload, true); + expect(runner.calledRestart, false); + }); + + testWithoutContext('R - hotRestart', () async { + final TerminalHandler terminalHandler = setUpTerminalHandler([]); + final FakeResidentRunner runner = terminalHandler.residentRunner as FakeResidentRunner; + + await terminalHandler.processTerminalInput('R'); + + expect(runner.calledReload, false); + expect(runner.calledRestart, true); + }); + + testWithoutContext('r - hotReload with non-fatal error', () async { + final TerminalHandler terminalHandler = setUpTerminalHandler([], reloadExitCode: 1); + final FakeResidentRunner runner = terminalHandler.residentRunner as FakeResidentRunner; + + await terminalHandler.processTerminalInput('r'); + + expect(runner.calledReload, true); + expect(runner.calledRestart, false); + expect(terminalHandler.logger.statusText, contains('Try again after fixing the above error(s).')); + }); + + testWithoutContext('R - hotRestart with non-fatal error', () async { + final TerminalHandler terminalHandler = setUpTerminalHandler([], reloadExitCode: 1); + final FakeResidentRunner runner = terminalHandler.residentRunner as FakeResidentRunner; + + await terminalHandler.processTerminalInput('R'); + + expect(runner.calledReload, false); + expect(runner.calledRestart, true); + expect(terminalHandler.logger.statusText, contains('Try again after fixing the above error(s).')); + }); + + testWithoutContext('r - hotReload with fatal error', () async { + final TerminalHandler terminalHandler = setUpTerminalHandler([], reloadExitCode: 1, fatalReloadError: true); + final FakeResidentRunner runner = terminalHandler.residentRunner as FakeResidentRunner; + + await expectLater(() => terminalHandler.processTerminalInput('r'), throwsToolExit()); + + expect(runner.calledReload, true); + expect(runner.calledRestart, false); + }); + + testWithoutContext('R - hotRestart with fatal error', () async { + final TerminalHandler terminalHandler = setUpTerminalHandler([], reloadExitCode: 1, fatalReloadError: true); + final FakeResidentRunner runner = terminalHandler.residentRunner as FakeResidentRunner; + + await expectLater(() => terminalHandler.processTerminalInput('R'), throwsToolExit()); + + expect(runner.calledReload, false); + expect(runner.calledRestart, true); + }); + }); + + testWithoutContext('ResidentRunner clears the screen when it should', () async { + final TerminalHandler terminalHandler = setUpTerminalHandler([], reloadExitCode: 1, fatalReloadError: true); + const String message = 'This should be cleared'; + + expect(terminalHandler.logger.statusText, equals('')); + terminalHandler.logger.printStatus(message); + expect(terminalHandler.logger.statusText, equals('$message\n')); // printStatus makes a newline + + await terminalHandler.processTerminalInput('c'); + expect(terminalHandler.logger.statusText, equals('')); + }); + + testWithoutContext('s, can take screenshot on debug device that supports screenshot', () async { + final BufferLogger logger = BufferLogger.test(); + final TerminalHandler terminalHandler = setUpTerminalHandler([ + listViews, + FakeVmServiceRequest( + method: 'ext.flutter.debugAllowBanner', + args: { + 'isolateId': fakeUnpausedIsolate.id, + 'enabled': 'false', + }, + ), + FakeVmServiceRequest( + method: 'ext.flutter.debugAllowBanner', + args: { + 'isolateId': fakeUnpausedIsolate.id, + 'enabled': 'true', + }, + ), + ], logger: logger, supportsScreenshot: true); + + await terminalHandler.processTerminalInput('s'); + + expect(logger.statusText, contains('Screenshot written to flutter_01.png (0kB)')); + }); + + testWithoutContext('s, will not take screenshot on non-web device without screenshot tooling support', () async { + final BufferLogger logger = BufferLogger.test(); + final FileSystem fileSystem = MemoryFileSystem.test(); + final TerminalHandler terminalHandler = setUpTerminalHandler([], logger: logger, fileSystem: fileSystem); + + await terminalHandler.processTerminalInput('s'); + + expect(logger.statusText, isNot(contains('Screenshot written to'))); + }); + + testWithoutContext('s, can take screenshot on debug web device that does not support screenshot', () async { + final BufferLogger logger = BufferLogger.test(); + final FileSystem fileSystem = MemoryFileSystem.test(); + final TerminalHandler terminalHandler = setUpTerminalHandler([ + listViews, + FakeVmServiceRequest( + method: 'ext.flutter.debugAllowBanner', + args: { + 'isolateId': fakeUnpausedIsolate.id, + 'enabled': 'false', + }, + ), + FakeVmServiceRequest( + method: 'ext.dwds.screenshot', + args: {}, + jsonResponse: { + 'data': base64.encode([1, 2, 3, 4]), + }, + ), + FakeVmServiceRequest( + method: 'ext.flutter.debugAllowBanner', + args: { + 'isolateId': fakeUnpausedIsolate.id, + 'enabled': 'true', + }, + ), + ], logger: logger, web: true, fileSystem: fileSystem); + + await terminalHandler.processTerminalInput('s'); + + expect(logger.statusText, contains('Screenshot written to flutter_01.png (0kB)')); + expect(fileSystem.currentDirectory.childFile('flutter_01.png').readAsBytesSync(), [1, 2, 3, 4]); + }); + + testWithoutContext('s, can take screenshot on device that does not support service protocol', () async { + final BufferLogger logger = BufferLogger.test(); + final FileSystem fileSystem = MemoryFileSystem.test(); + final TerminalHandler terminalHandler = setUpTerminalHandler( + [], + logger: logger, + supportsScreenshot: true, + supportsServiceProtocol: false, + fileSystem: fileSystem, + ); + + await terminalHandler.processTerminalInput('s'); + + expect(logger.statusText, contains('Screenshot written to flutter_01.png (0kB)')); + expect(fileSystem.currentDirectory.childFile('flutter_01.png').readAsBytesSync(), [1, 2, 3, 4]); + }); + + testWithoutContext('s, does not take a screenshot on a device that does not support screenshot or the service protocol', () async { + final BufferLogger logger = BufferLogger.test(); + final FileSystem fileSystem = MemoryFileSystem.test(); + final TerminalHandler terminalHandler = setUpTerminalHandler( + [], + logger: logger, + supportsServiceProtocol: false, + fileSystem: fileSystem, + ); + + await terminalHandler.processTerminalInput('s'); + + expect(logger.statusText, '\n'); + expect(fileSystem.currentDirectory.childFile('flutter_01.png'), isNot(exists)); + }); + + testWithoutContext('s, does not take a screenshot on a web device that does not support screenshot or the service protocol', () async { + final BufferLogger logger = BufferLogger.test(); + final FileSystem fileSystem = MemoryFileSystem.test(); + final TerminalHandler terminalHandler = setUpTerminalHandler( + [], + logger: logger, + supportsServiceProtocol: false, + web: true, + fileSystem: fileSystem, + ); + + await terminalHandler.processTerminalInput('s'); + + expect(logger.statusText, '\n'); + expect(fileSystem.currentDirectory.childFile('flutter_01.png'), isNot(exists)); + }); + + testWithoutContext('s, bails taking screenshot on debug device if dwds.screenshot throws RpcError, restoring banner', () async { + final BufferLogger logger = BufferLogger.test(); + final FileSystem fileSystem = MemoryFileSystem.test(); + final TerminalHandler terminalHandler = setUpTerminalHandler( + [ + listViews, + FakeVmServiceRequest( + method: 'ext.flutter.debugAllowBanner', + args: { + 'isolateId': fakeUnpausedIsolate.id, + 'enabled': 'false', + }, + ), + const FakeVmServiceRequest( + method: 'ext.dwds.screenshot', + // Failed response, + error: FakeRPCError(code: RPCErrorCodes.kInternalError), + ), + FakeVmServiceRequest( + method: 'ext.flutter.debugAllowBanner', + args: { + 'isolateId': fakeUnpausedIsolate.id, + 'enabled': 'true', + }, + ), + ], + logger: logger, + web: true, + fileSystem: fileSystem, + ); + + await terminalHandler.processTerminalInput('s'); + + expect(logger.errorText, contains('Error')); + }); + + testWithoutContext('s, bails taking screenshot on debug device if debugAllowBanner during second request', () async { + final BufferLogger logger = BufferLogger.test(); + final FileSystem fileSystem = MemoryFileSystem.test(); + final TerminalHandler terminalHandler = setUpTerminalHandler( + [ + listViews, + FakeVmServiceRequest( + method: 'ext.flutter.debugAllowBanner', + args: { + 'isolateId': fakeUnpausedIsolate.id, + 'enabled': 'false', + }, + ), + FakeVmServiceRequest( + method: 'ext.flutter.debugAllowBanner', + args: { + 'isolateId': fakeUnpausedIsolate.id, + 'enabled': 'true', + }, + // Failed response, + error: const FakeRPCError(code: RPCErrorCodes.kInternalError), + ), + ], + logger: logger, + supportsScreenshot: true, + fileSystem: fileSystem, + ); + + await terminalHandler.processTerminalInput('s'); + + expect(logger.errorText, contains('Error')); + }); + + testWithoutContext('pidfile creation', () { + final BufferLogger testLogger = BufferLogger.test(); + final Signals signals = _TestSignals(Signals.defaultExitSignals); + final Terminal terminal = Terminal.test(); + final MemoryFileSystem fs = MemoryFileSystem.test(); + final ProcessInfo processInfo = ProcessInfo.test(fs); + final FakeResidentRunner residentRunner = FakeResidentRunner( + FlutterDevice( + FakeDevice(), + buildInfo: BuildInfo.debug, + generator: FakeResidentCompiler(), + developmentShaderCompiler: const FakeShaderCompiler(), + ), + testLogger, + fs, + ); + residentRunner + ..supportsRestart = true + ..supportsServiceProtocol = true + ..stayResident = true; + + const String filename = 'test.pid'; + final TerminalHandler terminalHandler = TerminalHandler( + residentRunner, + logger: testLogger, + signals: signals, + terminal: terminal, + processInfo: processInfo, + reportReady: false, + pidFile: filename, + ); + + expect(fs.file(filename), isNot(exists)); + terminalHandler.setupTerminal(); + terminalHandler.registerSignalHandlers(); + expect(fs.file(filename), exists); + terminalHandler.stop(); + expect(fs.file(filename), isNot(exists)); + }); +} + +class FakeResidentRunner extends ResidentHandlers { + FakeResidentRunner(FlutterDevice device, this.logger, this.fileSystem) : flutterDevices = [device]; + + bool calledDetach = false; + bool calledPrint = false; + bool calledExit = false; + bool calledPrintWithDetails = false; + bool calledReload = false; + bool calledRestart = false; + int reloadExitCode = 0; + bool fatalReloadError = false; + + @override + final Logger logger; + + @override + final FileSystem fileSystem; + + @override + final List flutterDevices; + + @override + bool canHotReload = true; + + @override + bool hotMode = true; + + @override + bool isRunningDebug = true; + + @override + bool isRunningProfile = false; + + @override + bool isRunningRelease = false; + + @override + bool stayResident = true; + + @override + bool supportsRestart = true; + + @override + bool supportsServiceProtocol = true; + + @override + bool supportsWriteSkSL = true; + + @override + Future cleanupAfterSignal() async { } + + @override + Future detach() async { + calledDetach = true; + } + + @override + Future exit() async { + calledExit = true; + } + + @override + void printHelp({required bool details}) { + if (details) { + calledPrintWithDetails = true; + } else { + calledPrint = true; + } + } + + @override + Future runSourceGenerators() async { } + + @override + Future restart({bool fullRestart = false, bool pause = false, String? reason}) async { + if (fullRestart && !supportsRestart) { + throw StateError('illegal restart'); + } + if (!fullRestart && !canHotReload) { + throw StateError('illegal reload'); + } + if (fullRestart) { + calledRestart = true; + } else { + calledReload = true; + } + return OperationResult(reloadExitCode, '', fatal: fatalReloadError); + } + + @override + ResidentDevtoolsHandler get residentDevtoolsHandler => _residentDevtoolsHandler; + final ResidentDevtoolsHandler _residentDevtoolsHandler = FakeResidentDevtoolsHandler(); +} + +class FakeResidentDevtoolsHandler extends Fake implements ResidentDevtoolsHandler { + bool calledLaunchDevToolsInBrowser = false; + + @override + bool launchDevToolsInBrowser({List? flutterDevices}) { + return calledLaunchDevToolsInBrowser = true; + } +} + +class FakeDevice extends Fake implements Device { + @override + bool isSupported() => true; + + @override + bool supportsScreenshot = false; + + @override + String get name => 'Fake Device'; + + @override + Future takeScreenshot(File file) async { + if (!supportsScreenshot) { + throw StateError('illegal screenshot attempt'); + } + file.writeAsBytesSync([1, 2, 3, 4]); + } + +} + +TerminalHandler setUpTerminalHandler(List requests, { + bool supportsRestart = true, + bool supportsServiceProtocol = true, + bool supportsHotReload = true, + bool web = false, + bool fatalReloadError = false, + bool supportsScreenshot = false, + int reloadExitCode = 0, + BuildMode buildMode = BuildMode.debug, + Logger? logger, + FileSystem? fileSystem, +}) { + final Logger testLogger = logger ?? BufferLogger.test(); + final Signals signals = Signals.test(); + final Terminal terminal = Terminal.test(); + final FileSystem localFileSystem = fileSystem ?? MemoryFileSystem.test(); + final ProcessInfo processInfo = ProcessInfo.test(MemoryFileSystem.test()); + final FlutterDevice device = FlutterDevice( + FakeDevice()..supportsScreenshot = supportsScreenshot, + buildInfo: BuildInfo(buildMode, '', treeShakeIcons: false), + generator: FakeResidentCompiler(), + developmentShaderCompiler: const FakeShaderCompiler(), + targetPlatform: web + ? TargetPlatform.web_javascript + : TargetPlatform.android_arm, + ); + device.vmService = FakeVmServiceHost(requests: requests).vmService; + final FakeResidentRunner residentRunner = FakeResidentRunner(device, testLogger, localFileSystem) + ..supportsServiceProtocol = supportsServiceProtocol + ..supportsRestart = supportsRestart + ..canHotReload = supportsHotReload + ..fatalReloadError = fatalReloadError + ..reloadExitCode = reloadExitCode; + + switch (buildMode) { + case BuildMode.debug: + residentRunner + ..isRunningDebug = true + ..isRunningProfile = false + ..isRunningRelease = false; + case BuildMode.profile: + residentRunner + ..isRunningDebug = false + ..isRunningProfile = true + ..isRunningRelease = false; + case BuildMode.release: + residentRunner + ..isRunningDebug = false + ..isRunningProfile = false + ..isRunningRelease = true; + case _: + // NOOP + } + return TerminalHandler( + residentRunner, + logger: testLogger, + signals: signals, + terminal: terminal, + processInfo: processInfo, + reportReady: false, + ); +} + +class FakeResidentCompiler extends Fake implements ResidentCompiler { } + +class TestRunner extends Fake implements ResidentRunner { + bool hasHelpBeenPrinted = false; + + @override + Future cleanupAfterSignal() async { } + + @override + Future cleanupAtFinish() async { } + + @override + void printHelp({ bool? details }) { + hasHelpBeenPrinted = true; + } + + @override + Future run({ + Completer? connectionInfoCompleter, + Completer? appStartedCompleter, + bool enableDevTools = false, + String? route, + }) async => null; + + @override + Future attach({ + Completer? connectionInfoCompleter, + Completer? appStartedCompleter, + bool allowExistingDdsInstance = false, + bool enableDevTools = false, + bool needsFullRestart = true, + }) async => null; +} + +class _TestSignals implements Signals { + _TestSignals(this.exitSignals); + + final List exitSignals; + + final Map> _handlersTable = + >{}; + + @override + Object addHandler(ProcessSignal signal, SignalHandler handler) { + final Object token = Object(); + _handlersTable.putIfAbsent(signal, () => {})[token] = handler; + return token; + } + + @override + Future removeHandler(ProcessSignal signal, Object token) async { + if (!_handlersTable.containsKey(signal)) { + return false; + } + if (!_handlersTable[signal]!.containsKey(token)) { + return false; + } + _handlersTable[signal]!.remove(token); + return true; + } + + @override + Stream get errors => _errors.stream; + final StreamController _errors = StreamController(); +} + +class FakeShaderCompiler implements DevelopmentShaderCompiler { + const FakeShaderCompiler(); + + @override + void configureCompiler( + TargetPlatform? platform, { + required ImpellerStatus impellerStatus, + }) { } + + @override + Future recompileShader(DevFSContent inputShader) { + throw UnimplementedError(); + } +} diff --git a/flutter/packages/flutter_tools/test/general.shard/testbed_test.dart b/flutter/packages/flutter_tools/test/general.shard/testbed_test.dart new file mode 100644 index 0000000000000000000000000000000000000000..135bb54a780294fcf5ed2c333143287bcb8e2614 --- /dev/null +++ b/flutter/packages/flutter_tools/test/general.shard/testbed_test.dart @@ -0,0 +1,104 @@ +// Copyright 2014 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +import 'dart:async'; +import 'dart:io'; + +import 'package:file/file.dart'; +import 'package:file/memory.dart'; +import 'package:flutter_tools/src/base/context.dart'; +import 'package:flutter_tools/src/base/error_handling_io.dart'; +import 'package:flutter_tools/src/base/file_system.dart'; +import 'package:flutter_tools/src/base/process.dart'; +import 'package:flutter_tools/src/globals.dart' as globals; + +import '../src/common.dart'; +import '../src/testbed.dart'; + +void main() { + group('Testbed', () { + + test('Can provide default interfaces', () async { + final Testbed testbed = Testbed(); + + late FileSystem localFileSystem; + await testbed.run(() { + localFileSystem = globals.fs; + }); + + expect(localFileSystem, isA()); + expect((localFileSystem as ErrorHandlingFileSystem).fileSystem, + isA()); + }); + + test('Can provide setup interfaces', () async { + final Testbed testbed = Testbed(overrides: { + A: () => A(), + }); + + A? instance; + await testbed.run(() { + instance = context.get(); + }); + + expect(instance, isA()); + }); + + test('Can provide local overrides', () async { + final Testbed testbed = Testbed(overrides: { + A: () => A(), + }); + + A? instance; + await testbed.run(() { + instance = context.get(); + }, overrides: { + A: () => B(), + }); + + expect(instance, isA()); + }); + + test('provides a mocked http client', () async { + final Testbed testbed = Testbed(); + await testbed.run(() async { + final HttpClient client = HttpClient(); + final HttpClientRequest request = await client.getUrl(Uri.parse('http://foo.dev')); + final HttpClientResponse response = await request.close(); + + expect(response.statusCode, HttpStatus.ok); + expect(response.contentLength, 0); + }); + }); + + test('Throws StateError if Timer is left pending', () async { + final Testbed testbed = Testbed(); + + expect(testbed.run(() async { + Timer.periodic(const Duration(seconds: 1), (Timer timer) { }); + }), throwsStateError); + }); + + test("Doesn't throw a StateError if Timer is left cleaned up", () async { + final Testbed testbed = Testbed(); + + await testbed.run(() async { + final Timer timer = Timer.periodic(const Duration(seconds: 1), (Timer timer) { }); + timer.cancel(); + }); + }); + + test('Throws if ProcessUtils is injected',() { + final Testbed testbed = Testbed(overrides: { + ProcessUtils: () => null, + }); + + expect(() => testbed.run(() {}), throwsStateError); + }); + }); +} + +class A { } + +class B extends A { } diff --git a/flutter/packages/flutter_tools/test/general.shard/time_test.dart b/flutter/packages/flutter_tools/test/general.shard/time_test.dart new file mode 100644 index 0000000000000000000000000000000000000000..e1d707bc707b63221dff27df114f6924222ecde9 --- /dev/null +++ b/flutter/packages/flutter_tools/test/general.shard/time_test.dart @@ -0,0 +1,39 @@ +// 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/time.dart'; + +import '../src/common.dart'; + +void main() { + group(SystemClock, () { + test('can set a fixed time', () { + final SystemClock clock = SystemClock.fixed(DateTime(1991, 8, 23)); + expect(clock.now(), DateTime(1991, 8, 23)); + }); + + test('can find a time ago', () { + final SystemClock clock = SystemClock.fixed(DateTime(1991, 8, 23)); + expect(clock.ago(const Duration(days: 10)), DateTime(1991, 8, 13)); + }); + }); + + group('formatting', () { + test('can round-trip formatted time', () { + final DateTime time = DateTime(1991, 7, 31); + expect(time.isUtc, isFalse); + // formatDateTime() adds a timezone offset to DateTime.toString(). + final String formattedTime = formatDateTime(time); + // If a date time string has a timezone offset, DateTime.tryParse() + // converts the parsed time to UTC. + final DateTime? parsedTime = DateTime.tryParse(formattedTime); + expect(parsedTime, isNotNull); + expect(parsedTime!.isUtc, isTrue); + // Convert the parsed time (which should be utc) to the local timezone and + // compare against the original time which is in the local timezone. They + // should be the same. + expect(parsedTime.toLocal(), equals(time)); + }); + }); +} diff --git a/flutter/packages/flutter_tools/test/general.shard/tracing_test.dart b/flutter/packages/flutter_tools/test/general.shard/tracing_test.dart new file mode 100644 index 0000000000000000000000000000000000000000..e7719b26e6394b80405288e6690efb84e5ba8b6f --- /dev/null +++ b/flutter/packages/flutter_tools/test/general.shard/tracing_test.dart @@ -0,0 +1,397 @@ +// 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:file/memory.dart'; +import 'package:file_testing/file_testing.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/tracing.dart'; +import 'package:flutter_tools/src/vmservice.dart'; +import 'package:vm_service/vm_service.dart' as vm_service; + +import '../src/common.dart'; +import '../src/fake_vm_services.dart'; + +final vm_service.Isolate fakeUnpausedIsolate = vm_service.Isolate( + id: '1', + pauseEvent: vm_service.Event( + kind: vm_service.EventKind.kResume, + timestamp: 0 + ), + breakpoints: [], + libraries: [ + 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: [], +); + +final FlutterView fakeFlutterView = FlutterView( + id: 'a', + uiIsolate: fakeUnpausedIsolate, +); + +final FakeVmServiceRequest listViews = FakeVmServiceRequest( + method: kListViewsMethod, + jsonResponse: { + 'views': [ + fakeFlutterView.toJson(), + ], + }, +); + +final List vmServiceSetup = [ + const FakeVmServiceRequest( + method: 'streamListen', + args: { + 'streamId': vm_service.EventKind.kExtension, + } + ), + listViews, + // Satisfies didAwaitFirstFrame + const FakeVmServiceRequest( + method: 'ext.flutter.didSendFirstFrameRasterizedEvent', + args: { + 'isolateId': '1', + }, + jsonResponse: { + 'enabled': 'true', + }, + ), +]; + +void main() { + testWithoutContext('Can trace application startup', () async { + final BufferLogger logger = BufferLogger.test(); + final FileSystem fileSystem = MemoryFileSystem.test(); + final FakeVmServiceHost fakeVmServiceHost = FakeVmServiceHost(requests: [ + ...vmServiceSetup, + FakeVmServiceRequest( + method: 'getVMTimeline', + jsonResponse: vm_service.Timeline( + timeExtentMicros: 4, + timeOriginMicros: 0, + traceEvents: [ + vm_service.TimelineEvent.parse({ + 'name': kFlutterEngineMainEnterEventName, + 'ts': 0, + })!, + vm_service.TimelineEvent.parse({ + 'name': kFrameworkInitEventName, + 'ts': 1, + })!, + vm_service.TimelineEvent.parse({ + 'name': kFirstFrameBuiltEventName, + 'ts': 2, + })!, + vm_service.TimelineEvent.parse({ + 'name': kFirstFrameRasterizedEventName, + 'ts': 3, + })!, + ], + ).toJson(), + ), + const FakeVmServiceRequest( + method: 'setVMTimelineFlags', + args: { + 'recordedStreams': [], + }, + ), + ]); + + // Validate that old tracing data is deleted. + final File outFile = fileSystem.currentDirectory.childFile('start_up_info.json') + ..writeAsStringSync('stale'); + + await downloadStartupTrace(fakeVmServiceHost.vmService, + output: fileSystem.currentDirectory, + logger: logger, + ); + + expect(outFile, exists); + expect(json.decode(outFile.readAsStringSync()), { + 'engineEnterTimestampMicros': 0, + 'timeToFrameworkInitMicros': 1, + 'timeToFirstFrameRasterizedMicros': 3, + 'timeToFirstFrameMicros': 2, + 'timeAfterFrameworkInitMicros': 1, + }); + }); + + testWithoutContext('throws tool exit if the vmservice disconnects', () async { + final BufferLogger logger = BufferLogger.test(); + final FileSystem fileSystem = MemoryFileSystem.test(); + final FakeVmServiceHost fakeVmServiceHost = FakeVmServiceHost(requests: [ + ...vmServiceSetup, + const FakeVmServiceRequest( + method: 'getVMTimeline', + error: FakeRPCError(code: RPCErrorCodes.kServiceDisappeared), + ), + const FakeVmServiceRequest( + method: 'setVMTimelineFlags', + args: { + 'recordedStreams': [], + }, + ), + ]); + + await expectLater(() async => downloadStartupTrace(fakeVmServiceHost.vmService, + output: fileSystem.currentDirectory, + logger: logger, + ), throwsToolExit(message: 'The device disconnected before the timeline could be retrieved.')); + }); + + testWithoutContext('throws tool exit if timeline is missing the engine start event', () async { + final BufferLogger logger = BufferLogger.test(); + final FileSystem fileSystem = MemoryFileSystem.test(); + final FakeVmServiceHost fakeVmServiceHost = FakeVmServiceHost(requests: [ + ...vmServiceSetup, + FakeVmServiceRequest( + method: 'getVMTimeline', + jsonResponse: vm_service.Timeline( + timeExtentMicros: 4, + timeOriginMicros: 0, + traceEvents: [], + ).toJson(), + ), + const FakeVmServiceRequest( + method: 'setVMTimelineFlags', + args: { + 'recordedStreams': [], + }, + ), + ]); + + await expectLater(() async => downloadStartupTrace(fakeVmServiceHost.vmService, + output: fileSystem.currentDirectory, + logger: logger, + ), throwsToolExit(message: 'Engine start event is missing in the timeline')); + }); + + testWithoutContext('prints when first frame is taking a long time', () async { + final BufferLogger logger = BufferLogger.test(); + final FileSystem fileSystem = MemoryFileSystem.test(); + final Completer completer = Completer(); + await FakeAsync().run((FakeAsync time) { + final Map extensionData = { + 'test': 'data', + 'renderedErrorText': 'error text', + }; + final FakeVmServiceHost fakeVmServiceHost = FakeVmServiceHost(requests: [ + const FakeVmServiceRequest( + method: 'streamListen', + args: { + 'streamId': vm_service.EventKind.kExtension, + } + ), + const FakeVmServiceRequest( + method: kListViewsMethod, + jsonResponse: { + 'views': [ + { + 'id': '1', + // No isolate, no views. + 'isolate': null, + } + ], + }, + ), + FakeVmServiceStreamResponse( + streamId: 'Extension', + event: vm_service.Event( + timestamp: 0, + extensionKind: 'Flutter.Error', + extensionData: vm_service.ExtensionData.parse(extensionData), + kind: vm_service.EventStreams.kExtension, + ), + ), + ]); + unawaited(downloadStartupTrace(fakeVmServiceHost.vmService, + output: fileSystem.currentDirectory, + logger: logger, + )); + time.elapse(const Duration(seconds: 11)); + time.flushMicrotasks(); + completer.complete(); + return completer.future; + }); + expect(logger.statusText, contains('First frame is taking longer than expected')); + expect(logger.traceText, contains('View ID: 1')); + expect(logger.traceText, contains('No isolate ID associated with the view')); + expect(logger.traceText, contains('Flutter.Error: [ExtensionData {test: data, renderedErrorText: error text}]')); + }); + + testWithoutContext('throws tool exit if first frame events are missing', () async { + final BufferLogger logger = BufferLogger.test(); + final FileSystem fileSystem = MemoryFileSystem.test(); + final FakeVmServiceHost fakeVmServiceHost = FakeVmServiceHost(requests: [ + ...vmServiceSetup, + FakeVmServiceRequest( + method: 'getVMTimeline', + jsonResponse: vm_service.Timeline( + timeExtentMicros: 4, + timeOriginMicros: 0, + traceEvents: [ + vm_service.TimelineEvent.parse({ + 'name': kFlutterEngineMainEnterEventName, + 'ts': 0, + })!, + vm_service.TimelineEvent.parse({ + 'name': kFrameworkInitEventName, + 'ts': 1, + })!, + ], + ).toJson(), + ), + const FakeVmServiceRequest( + method: 'setVMTimelineFlags', + args: { + 'recordedStreams': [], + }, + ), + ]); + + await expectLater(() async => downloadStartupTrace(fakeVmServiceHost.vmService, + output: fileSystem.currentDirectory, + logger: logger, + ), throwsToolExit(message: 'First frame events are missing in the timeline')); + }); + + testWithoutContext('Can trace application startup without awaiting for first frame', () async { + final BufferLogger logger = BufferLogger.test(); + final FileSystem fileSystem = MemoryFileSystem.test(); + final FakeVmServiceHost fakeVmServiceHost = FakeVmServiceHost(requests: [ + FakeVmServiceRequest( + method: 'getVMTimeline', + jsonResponse: vm_service.Timeline( + timeExtentMicros: 4, + timeOriginMicros: 0, + traceEvents: [ + vm_service.TimelineEvent.parse({ + 'name': kFlutterEngineMainEnterEventName, + 'ts': 0, + })!, + vm_service.TimelineEvent.parse({ + 'name': kFrameworkInitEventName, + 'ts': 1, + })!, + ], + ).toJson(), + ), + const FakeVmServiceRequest( + method: 'setVMTimelineFlags', + args: { + 'recordedStreams': [], + }, + ), + ]); + + final File outFile = fileSystem.currentDirectory.childFile('start_up_info.json'); + + await downloadStartupTrace(fakeVmServiceHost.vmService, + output: fileSystem.currentDirectory, + logger: logger, + awaitFirstFrame: false, + ); + + expect(outFile, exists); + expect(json.decode(outFile.readAsStringSync()), { + 'engineEnterTimestampMicros': 0, + 'timeToFrameworkInitMicros': 1, + }); + }); + + testWithoutContext('downloadStartupTrace also downloads the timeline', () async { + final BufferLogger logger = BufferLogger.test(); + final FileSystem fileSystem = MemoryFileSystem.test(); + final FakeVmServiceHost fakeVmServiceHost = FakeVmServiceHost(requests: [ + ...vmServiceSetup, + FakeVmServiceRequest( + method: 'getVMTimeline', + jsonResponse: vm_service.Timeline( + timeExtentMicros: 4, + timeOriginMicros: 0, + traceEvents: [ + vm_service.TimelineEvent.parse({ + 'name': kFlutterEngineMainEnterEventName, + 'ts': 0, + })!, + vm_service.TimelineEvent.parse({ + 'name': kFrameworkInitEventName, + 'ts': 1, + })!, + vm_service.TimelineEvent.parse({ + 'name': kFirstFrameBuiltEventName, + 'ts': 2, + })!, + vm_service.TimelineEvent.parse({ + 'name': kFirstFrameRasterizedEventName, + 'ts': 3, + })!, + ], + ).toJson(), + ), + const FakeVmServiceRequest( + method: 'setVMTimelineFlags', + args: { + 'recordedStreams': [], + }, + ), + ]); + + // Validate that old tracing data is deleted. + final File timelineFile = fileSystem.currentDirectory.childFile('start_up_timeline.json') + ..writeAsStringSync('stale'); + + await downloadStartupTrace(fakeVmServiceHost.vmService, + output: fileSystem.currentDirectory, + logger: logger, + ); + + final Map expectedTimeline = { + 'type': 'Timeline', + 'traceEvents': [ + { + 'name': 'FlutterEngineMainEnter', + 'ts': 0, + 'type': 'TimelineEvent', + }, + { + 'name': 'Framework initialization', + 'ts': 1, + 'type': 'TimelineEvent', + }, + { + 'name': 'Widgets built first useful frame', + 'ts': 2, + 'type': 'TimelineEvent', + }, + { + 'name': 'Rasterized first useful frame', + 'ts': 3, + 'type': 'TimelineEvent', + }, + ], + 'timeOriginMicros': 0, + 'timeExtentMicros': 4, + }; + + expect(timelineFile, exists); + expect(json.decode(timelineFile.readAsStringSync()), expectedTimeline); + }); +} diff --git a/flutter/packages/flutter_tools/test/general.shard/unified_analytics_test.dart b/flutter/packages/flutter_tools/test/general.shard/unified_analytics_test.dart new file mode 100644 index 0000000000000000000000000000000000000000..fd51697cbfb3f8f00acb1f1f8b5a6a0ce726d8f2 --- /dev/null +++ b/flutter/packages/flutter_tools/test/general.shard/unified_analytics_test.dart @@ -0,0 +1,171 @@ +// 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/config.dart'; +import 'package:flutter_tools/src/base/file_system.dart'; +import 'package:flutter_tools/src/reporting/unified_analytics.dart'; +import 'package:unified_analytics/unified_analytics.dart'; + +import '../src/common.dart'; +import '../src/fakes.dart'; + +void main() { + const String userBranch = 'abc123'; + const String clientIde = 'VSCode'; + + late FileSystem fs; + late Config config; + late FakeAnalytics analyticsOverride; + + setUp(() { + fs = MemoryFileSystem.test(); + config = Config.test(); + + analyticsOverride = getInitializedFakeAnalyticsInstance( + fs: fs, + fakeFlutterVersion: FakeFlutterVersion( + branch: userBranch, + ), + clientIde: clientIde, + ); + }); + + group('Unit testing util:', () { + test('getEnabledFeatures is null', () { + final String? enabledFeatures = getEnabledFeatures(config); + expect(enabledFeatures, isNull); + }); + + testWithoutContext('getEnabledFeatures not null', () { + config.setValue('cli-animations', true); + config.setValue('enable-flutter-preview', true); + + final String? enabledFeatures = getEnabledFeatures(config); + expect(enabledFeatures, isNotNull); + expect(enabledFeatures!.split(','), unorderedEquals(['enable-flutter-preview', 'cli-animations'])); + }); + }); + + group('Unit testing getAnalytics', () { + testWithoutContext('Successfully creates the instance for standard branch', + () { + final Analytics analytics = getAnalytics( + runningOnBot: false, + flutterVersion: FakeFlutterVersion(), + environment: const {}, + analyticsOverride: analyticsOverride, + clientIde: clientIde, + config: config, + ); + + expect(analytics.clientId, isNot(NoOpAnalytics.staticClientId), + reason: 'The CLIENT ID should be a randomly generated id'); + expect(analytics, isNot(isA())); + }); + + testWithoutContext('NoOp instance for user branch', () { + final Analytics analytics = getAnalytics( + runningOnBot: false, + flutterVersion: FakeFlutterVersion( + branch: userBranch, + frameworkRevision: '3.14.0-14.0.pre.370', + ), + environment: const {}, + analyticsOverride: analyticsOverride, + clientIde: clientIde, + config: config, + ); + + expect( + analytics.clientId, + NoOpAnalytics.staticClientId, + reason: 'The client ID should match the NoOp client id', + ); + expect(analytics, isA()); + }); + + testWithoutContext('NoOp instance for unknown branch', () { + final Analytics analytics = getAnalytics( + runningOnBot: false, + flutterVersion: FakeFlutterVersion( + frameworkRevision: 'unknown', + ), + environment: const {}, + analyticsOverride: analyticsOverride, + clientIde: clientIde, + config: config, + ); + + expect( + analytics.clientId, + NoOpAnalytics.staticClientId, + reason: 'The client ID should match the NoOp client id', + ); + expect(analytics, isA()); + }); + + testWithoutContext('NoOp instance when running on bots', () { + final Analytics analytics = getAnalytics( + runningOnBot: true, + flutterVersion: FakeFlutterVersion(), + environment: const {}, + analyticsOverride: analyticsOverride, + clientIde: clientIde, + config: config, + ); + + expect( + analytics.clientId, + NoOpAnalytics.staticClientId, + reason: 'The client ID should match the NoOp client id', + ); + expect(analytics, isA()); + }); + + testWithoutContext('NoOp instance when suppressing via env variable', () { + final Analytics analytics = getAnalytics( + runningOnBot: false, + flutterVersion: FakeFlutterVersion(), + environment: const {'FLUTTER_SUPPRESS_ANALYTICS': 'true'}, + analyticsOverride: analyticsOverride, + clientIde: clientIde, + config: config, + ); + + expect( + analytics.clientId, + NoOpAnalytics.staticClientId, + reason: 'The client ID should match the NoOp client id', + ); + expect(analytics, isA()); + }); + + testWithoutContext('Suppression prevents events from being sent', () { + expect(analyticsOverride.okToSend, true); + analyticsOverride.send(Event.surveyShown(surveyId: 'surveyId')); + expect(analyticsOverride.sentEvents, hasLength(1)); + + analyticsOverride.suppressTelemetry(); + expect(analyticsOverride.okToSend, false); + analyticsOverride.send(Event.surveyShown(surveyId: 'surveyId')); + + expect(analyticsOverride.sentEvents, hasLength(1)); + }); + + testWithoutContext('Client IDE is passed and found in events', () { + final Analytics analytics = getAnalytics( + runningOnBot: false, + flutterVersion: FakeFlutterVersion(), + environment: const {}, + analyticsOverride: analyticsOverride, + clientIde: clientIde, + config: config, + ); + analytics as FakeAnalytics; + + expect(analytics.userProperty.clientIde, 'VSCode'); + }); + }); +} diff --git a/flutter/packages/flutter_tools/test/general.shard/update_packages_test.dart b/flutter/packages/flutter_tools/test/general.shard/update_packages_test.dart new file mode 100644 index 0000000000000000000000000000000000000000..899131f1723c46a8e1469380ca9a3c40c683dd9c --- /dev/null +++ b/flutter/packages/flutter_tools/test/general.shard/update_packages_test.dart @@ -0,0 +1,216 @@ +// Copyright 2014 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +import 'package:file/memory.dart'; +import 'package:file_testing/file_testing.dart'; +import 'package:flutter_tools/src/base/file_system.dart'; +import 'package:flutter_tools/src/base/logger.dart'; +import 'package:flutter_tools/src/commands/update_packages.dart'; +import 'package:flutter_tools/src/update_packages_pins.dart'; + +import '../src/common.dart'; + +// An example pubspec.yaml from flutter, not necessary for it to be up to date. +const String kFlutterPubspecYaml = r''' +name: flutter +description: A framework for writing Flutter applications +homepage: http://flutter.dev + +environment: + sdk: '>=3.2.0-0 <4.0.0' + +dependencies: + # To update these, use "flutter update-packages --force-upgrade". + collection: 1.14.11 + meta: 1.1.8 + typed_data: 1.1.6 + vector_math: 2.0.8 + + sky_engine: + sdk: flutter + + gallery: + git: + url: https://github.com/flutter/gallery.git + ref: d00362e6bdd0f9b30bba337c358b9e4a6e4ca950 + +dev_dependencies: + flutter_test: + sdk: flutter + flutter_goldens: + sdk: flutter + + archive: 2.0.11 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" + +# PUBSPEC CHECKSUM: 1437 +'''; + +const String kExtraPubspecYaml = r''' +name: nodeps +description: A dummy pubspec with no dependencies +homepage: http://flutter.dev + +environment: + sdk: '>=3.2.0-0 <4.0.0' +'''; + +const String kInvalidGitPubspec = ''' +name: flutter +description: A framework for writing Flutter applications +homepage: http://flutter.dev + +environment: + sdk: '>=3.2.0-0 <4.0.0' + +dependencies: + # To update these, use "flutter update-packages --force-upgrade". + collection: 1.14.11 + meta: 1.1.8 + typed_data: 1.1.6 + vector_math: 2.0.8 + + sky_engine: + sdk: flutter + + gallery: + git: +'''; + +void main() { + late FileSystem fileSystem; + late Directory flutterSdk; + late Directory flutter; + + setUp(() { + fileSystem = MemoryFileSystem.test(); + // Setup simplified Flutter SDK. + flutterSdk = fileSystem.directory('flutter')..createSync(); + // Create version file + flutterSdk.childFile('version').writeAsStringSync('1.2.3'); + // Create a pubspec file + flutter = flutterSdk.childDirectory('packages').childDirectory('flutter') + ..createSync(recursive: true); + flutter.childFile('pubspec.yaml').writeAsStringSync(kFlutterPubspecYaml); + }); + + testWithoutContext('kManuallyPinnedDependencies pins are actually pins', () { + expect( + kManuallyPinnedDependencies.values, + isNot(contains(anyOf('any', startsWith('^'), startsWith('>'), startsWith('<')))), + reason: 'Version pins in kManuallyPinnedDependencies must be specific pins, not ranges.', + ); + }); + + testWithoutContext( + 'createTemporaryFlutterSdk creates an unpinned flutter SDK', () { + // A stray extra package should not cause a crash. + final Directory extra = flutterSdk + .childDirectory('packages') + .childDirectory('extra') + ..createSync(recursive: true); + extra.childFile('pubspec.yaml').writeAsStringSync(kExtraPubspecYaml); + + // Create already parsed pubspecs. + final PubspecYaml flutterPubspec = PubspecYaml(flutter); + + final PubspecDependency gitDependency = flutterPubspec.dependencies + .firstWhere((PubspecDependency dep) => dep.kind == DependencyKind.git); + expect( + gitDependency.lockLine, + ''' + git: + url: https://github.com/flutter/gallery.git + ref: d00362e6bdd0f9b30bba337c358b9e4a6e4ca950 +''', + ); + final BufferLogger bufferLogger = BufferLogger.test(); + final Directory result = createTemporaryFlutterSdk( + bufferLogger, + fileSystem, + flutterSdk, + [flutterPubspec], + fileSystem.systemTempDirectory, + ); + + expect(result, exists); + + // We get a warning about the unexpected package. + expect( + bufferLogger.warningText, + contains("Unexpected package 'extra' found in packages directory"), + ); + + // The version file exists. + expect(result.childFile('version'), exists); + expect(result.childFile('version').readAsStringSync(), '1.2.3'); + + // The sky_engine package exists + expect(fileSystem.directory('${result.path}/bin/cache/pkg/sky_engine'), exists); + + // The flutter pubspec exists + final File pubspecFile = fileSystem.file('${result.path}/packages/flutter/pubspec.yaml'); + expect(pubspecFile, exists); + + // The flutter pubspec contains `any` dependencies. + final PubspecYaml outputPubspec = PubspecYaml(pubspecFile.parent); + expect(outputPubspec.name, 'flutter'); + expect(outputPubspec.dependencies.first.name, 'collection'); + expect(outputPubspec.dependencies.first.version, 'any'); + }); + + testWithoutContext('Throws a StateError on a malformed git: reference', () { + // Create an invalid pubspec file. + flutter.childFile('pubspec.yaml').writeAsStringSync(kInvalidGitPubspec); + + expect( + () => PubspecYaml(flutter), + throwsStateError, + ); + }); + + testWithoutContext('PubspecYaml Loads dependencies', () async { + final PubspecYaml pubspecYaml = PubspecYaml(flutter); + expect( + pubspecYaml.allDependencies + .map((PubspecDependency dependency) => '${dependency.name}: ${dependency.version}') + .toSet(), + equals({ + 'collection: 1.14.11', + 'meta: 1.1.8', + 'typed_data: 1.1.6', + 'vector_math: 2.0.8', + 'sky_engine: ', + 'gallery: ', + 'flutter_test: ', + 'flutter_goldens: ', + 'archive: 2.0.11', + })); + expect( + pubspecYaml.allExplicitDependencies + .map((PubspecDependency dependency) => '${dependency.name}: ${dependency.version}') + .toSet(), + equals({ + 'collection: 1.14.11', + 'meta: 1.1.8', + 'typed_data: 1.1.6', + 'vector_math: 2.0.8', + 'sky_engine: ', + 'gallery: ', + 'flutter_test: ', + 'flutter_goldens: ', + })); + expect( + pubspecYaml.dependencies + .map((PubspecDependency dependency) => '${dependency.name}: ${dependency.version}') + .toSet(), + equals({ + 'collection: 1.14.11', + 'meta: 1.1.8', + 'typed_data: 1.1.6', + 'vector_math: 2.0.8', + 'sky_engine: ', + 'gallery: ', + })); + }); +} diff --git a/flutter/packages/flutter_tools/test/general.shard/utils_test.dart b/flutter/packages/flutter_tools/test/general.shard/utils_test.dart new file mode 100644 index 0000000000000000000000000000000000000000..3fa94cb1c77b43201a9d8812f829f6d683643ec9 --- /dev/null +++ b/flutter/packages/flutter_tools/test/general.shard/utils_test.dart @@ -0,0 +1,409 @@ +// 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/terminal.dart'; +import 'package:flutter_tools/src/base/utils.dart'; +import 'package:flutter_tools/src/base/version.dart'; + +import '../src/common.dart'; + +void main() { + group('SettingsFile', () { + testWithoutContext('parse', () { + final SettingsFile file = SettingsFile.parse(''' +# ignore comment +foo=bar +baz=qux +'''); + expect(file.values['foo'], 'bar'); + expect(file.values['baz'], 'qux'); + expect(file.values, hasLength(2)); + }); + }); + + group('Version', () { + testWithoutContext('can parse and compare', () { + expect(Version(0, null, null).toString(), equals('0')); + expect(const Version.withText(1, 2, 3, 'versionText').toString(), 'versionText'); + + final Version v1 = Version.parse('1')!; + expect(v1.major, equals(1)); + expect(v1.minor, equals(0)); + expect(v1.patch, equals(0)); + + expect(v1, greaterThan(Version(0, 0, 0))); + + final Version v2 = Version.parse('1.2')!; + expect(v2.major, equals(1)); + expect(v2.minor, equals(2)); + expect(v2.patch, equals(0)); + + final Version v3 = Version.parse('1.2.3')!; + expect(v3.major, equals(1)); + expect(v3.minor, equals(2)); + expect(v3.patch, equals(3)); + + final Version v4 = Version.parse('1.12')!; + expect(v4, greaterThan(v2)); + + expect(v3, greaterThan(v2)); + expect(v2, greaterThan(v1)); + + final Version v5 = Version(1, 2, 0, text: 'foo'); + expect(v5, equals(v2)); + + expect(Version.parse('Preview2.2'), isNull); + }); + + group('isWithinVersionRange', () { + test('unknown not included', () { + expect(isWithinVersionRange('unknown', min: '1.0.0', max: '1.1.3'), + isFalse); + }); + + test('pre java 8 format included', () { + expect(isWithinVersionRange('1.0.0_201', min: '1.0.0', max: '1.1.3'), + isTrue); + }); + + test('min included by default', () { + expect( + isWithinVersionRange('1.0.0', min: '1.0.0', max: '1.1.3'), isTrue); + }); + + test('max included by default', () { + expect( + isWithinVersionRange('1.1.3', min: '1.0.0', max: '1.1.3'), isTrue); + }); + + test('inclusive min excluded', () { + expect( + isWithinVersionRange('1.0.0', + min: '1.0.0', max: '1.1.3', inclusiveMin: false), + isFalse); + }); + + test('inclusive max excluded', () { + expect( + isWithinVersionRange('1.1.3', + min: '1.0.0', max: '1.1.3', inclusiveMax: false), + isFalse); + }); + + test('lower value excluded', () { + expect( + isWithinVersionRange('0.1.0', min: '1.0.0', max: '1.1.3'), isFalse); + }); + + test('higher value excluded', () { + expect( + isWithinVersionRange('1.1.4', min: '1.0.0', max: '1.1.3'), isFalse); + }); + + test('middle value included', () { + expect( + isWithinVersionRange('1.1.0', min: '1.0.0', max: '1.1.3'), isTrue); + }); + }); + }); + + group('Misc', () { + testWithoutContext('snakeCase', () async { + expect(snakeCase('abc'), equals('abc')); + expect(snakeCase('abC'), equals('ab_c')); + expect(snakeCase('aBc'), equals('a_bc')); + expect(snakeCase('aBC'), equals('a_b_c')); + expect(snakeCase('Abc'), equals('abc')); + expect(snakeCase('AbC'), equals('ab_c')); + expect(snakeCase('ABc'), equals('a_bc')); + expect(snakeCase('ABC'), equals('a_b_c')); + }); + + testWithoutContext('kebabCase', () async { + expect(kebabCase('abc'), equals('abc')); + expect(kebabCase('abC'), equals('ab-c')); + expect(kebabCase('aBc'), equals('a-bc')); + expect(kebabCase('aBC'), equals('a-b-c')); + expect(kebabCase('Abc'), equals('abc')); + expect(kebabCase('AbC'), equals('ab-c')); + expect(kebabCase('ABc'), equals('a-bc')); + expect(kebabCase('ABC'), equals('a-b-c')); + }); + + testWithoutContext('sentenceCase', () async { + expect(sentenceCase('abc'), equals('Abc')); + expect(sentenceCase('ab_c'), equals('Ab_c')); + expect(sentenceCase('a b c'), equals('A b c')); + expect(sentenceCase('a B c'), equals('A B c')); + expect(sentenceCase('Abc'), equals('Abc')); + expect(sentenceCase('ab_c'), equals('Ab_c')); + expect(sentenceCase('a_bc'), equals('A_bc')); + expect(sentenceCase('a_b_c'), equals('A_b_c')); + }); + + testWithoutContext('snakeCaseToTitleCase', () async { + expect(snakeCaseToTitleCase('abc'), equals('Abc')); + expect(snakeCaseToTitleCase('ab_c'), equals('Ab C')); + expect(snakeCaseToTitleCase('a_b_c'), equals('A B C')); + expect(snakeCaseToTitleCase('a_B_c'), equals('A B C')); + expect(snakeCaseToTitleCase('Abc'), equals('Abc')); + expect(snakeCaseToTitleCase('ab_c'), equals('Ab C')); + expect(snakeCaseToTitleCase('a_bc'), equals('A Bc')); + expect(snakeCaseToTitleCase('a_b_c'), equals('A B C')); + }); + }); + + group('text wrapping', () { + const int lineLength = 40; + const String longLine = 'This is a long line that needs to be wrapped.'; + final String longLineWithNewlines = 'This is a long line with newlines that\n' + 'needs to be wrapped.\n\n' + '${'0123456789' * 5}'; + final String longAnsiLineWithNewlines = '${AnsiTerminal.red}This${AnsiTerminal.resetAll} is a long line with newlines that\n' + 'needs to be wrapped.\n\n' + '${AnsiTerminal.green}0123456789${AnsiTerminal.resetAll}' + '${'0123456789' * 3}' + '${AnsiTerminal.green}0123456789${AnsiTerminal.resetAll}'; + const String onlyAnsiSequences = '${AnsiTerminal.red}${AnsiTerminal.resetAll}'; + final String indentedLongLineWithNewlines = ' This is an indented long line with newlines that\n' + 'needs to be wrapped.\n\tAnd preserves tabs.\n \n ' + '${'0123456789' * 5}'; + const String shortLine = 'Short line.'; + const String indentedLongLine = ' This is an indented long line that needs to be ' + 'wrapped and indentation preserved.'; + testWithoutContext('does not wrap by default in tests', () { + expect(wrapText(longLine, columnWidth: 80, shouldWrap: true), equals(longLine)); + }); + + testWithoutContext('can override wrap preference if preference is off', () { + expect(wrapText(longLine, columnWidth: lineLength, shouldWrap: true), equals(''' +This is a long line that needs to be +wrapped.''')); + }); + + testWithoutContext('can override wrap preference if preference is on', () { + expect(wrapText(longLine, shouldWrap: false, columnWidth: 80), equals(longLine)); + }); + + testWithoutContext('does not wrap at all if not told to wrap', () { + expect(wrapText(longLine, columnWidth: 80, shouldWrap: false), equals(longLine)); + }); + + testWithoutContext('does not wrap short lines.', () { + expect(wrapText(shortLine, columnWidth: lineLength, shouldWrap: true), equals(shortLine)); + }); + + testWithoutContext('able to wrap long lines', () { + expect(wrapText(longLine, columnWidth: lineLength, shouldWrap: true), equals(''' +This is a long line that needs to be +wrapped.''')); + }); + + testWithoutContext('able to handle dynamically changing terminal column size', () { + expect(wrapText(longLine, columnWidth: 20, shouldWrap: true), equals(''' +This is a long line +that needs to be +wrapped.''')); + + expect(wrapText(longLine, columnWidth: lineLength, shouldWrap: true), equals(''' +This is a long line that needs to be +wrapped.''')); + }); + + testWithoutContext('wrap long lines with no whitespace', () { + expect(wrapText('0123456789' * 5, columnWidth: lineLength, shouldWrap: true), equals(''' +0123456789012345678901234567890123456789 +0123456789''')); + }); + + testWithoutContext('refuses to wrap to a column smaller than 10 characters', () { + expect(wrapText('$longLine ${'0123456789' * 4}', columnWidth: 1, shouldWrap: true), equals(''' +This is a +long line +that needs +to be +wrapped. +0123456789 +0123456789 +0123456789 +0123456789''')); + }); + testWithoutContext('preserves indentation', () { + expect(wrapText(indentedLongLine, columnWidth: lineLength, shouldWrap: true), equals(''' + This is an indented long line that + needs to be wrapped and indentation + preserved.''')); + }); + + testWithoutContext('preserves indentation and stripping trailing whitespace', () { + expect(wrapText('$indentedLongLine ', columnWidth: lineLength, shouldWrap: true), equals(''' + This is an indented long line that + needs to be wrapped and indentation + preserved.''')); + }); + + testWithoutContext('wraps text with newlines', () { + expect(wrapText(longLineWithNewlines, columnWidth: lineLength, shouldWrap: true), equals(''' +This is a long line with newlines that +needs to be wrapped. + +0123456789012345678901234567890123456789 +0123456789''')); + }); + + testWithoutContext('wraps text with ANSI sequences embedded', () { + expect(wrapText(longAnsiLineWithNewlines, columnWidth: lineLength, shouldWrap: true), equals(''' +${AnsiTerminal.red}This${AnsiTerminal.resetAll} is a long line with newlines that +needs to be wrapped. + +${AnsiTerminal.green}0123456789${AnsiTerminal.resetAll}012345678901234567890123456789 +${AnsiTerminal.green}0123456789${AnsiTerminal.resetAll}''')); + }); + + testWithoutContext('wraps text with only ANSI sequences', () { + expect(wrapText(onlyAnsiSequences, columnWidth: lineLength, shouldWrap: true), + equals('${AnsiTerminal.red}${AnsiTerminal.resetAll}')); + }); + + testWithoutContext('preserves indentation in the presence of newlines', () { + expect(wrapText(indentedLongLineWithNewlines, columnWidth: lineLength, shouldWrap: true), equals(''' + This is an indented long line with + newlines that +needs to be wrapped. +\tAnd preserves tabs. + + 01234567890123456789012345678901234567 + 890123456789''')); + }); + + testWithoutContext('removes trailing whitespace when wrapping', () { + expect(wrapText('$longLine \t', columnWidth: lineLength, shouldWrap: true), equals(''' +This is a long line that needs to be +wrapped.''')); + }); + + testWithoutContext('honors hangingIndent parameter', () { + expect(wrapText(longLine, columnWidth: lineLength, hangingIndent: 6, shouldWrap: true), equals(''' +This is a long line that needs to be + wrapped.''')); + }); + + testWithoutContext('handles hangingIndent with a single unwrapped line.', () { + expect(wrapText(shortLine, columnWidth: lineLength, hangingIndent: 6, shouldWrap: true), equals(''' +Short line.''')); + }); + + testWithoutContext('handles hangingIndent with two unwrapped lines and the second is empty.', () { + expect(wrapText('$shortLine\n', columnWidth: lineLength, hangingIndent: 6, shouldWrap: true), equals(''' +Short line. +''')); + }); + + testWithoutContext('honors hangingIndent parameter on already indented line.', () { + expect(wrapText(indentedLongLine, columnWidth: lineLength, hangingIndent: 6, shouldWrap: true), equals(''' + This is an indented long line that + needs to be wrapped and + indentation preserved.''')); + }); + + testWithoutContext('honors hangingIndent and indent parameters at the same time.', () { + expect(wrapText(indentedLongLine, columnWidth: lineLength, indent: 6, hangingIndent: 6, shouldWrap: true), equals(''' + This is an indented long line + that needs to be wrapped + and indentation + preserved.''')); + }); + + testWithoutContext('honors indent parameter on already indented line.', () { + expect(wrapText(indentedLongLine, columnWidth: lineLength, indent: 6, shouldWrap: true), equals(''' + This is an indented long line + that needs to be wrapped and + indentation preserved.''')); + }); + + testWithoutContext('honors hangingIndent parameter on already indented line.', () { + expect(wrapText(indentedLongLineWithNewlines, columnWidth: lineLength, hangingIndent: 6, shouldWrap: true), equals(''' + This is an indented long line with + newlines that +needs to be wrapped. + And preserves tabs. + + 01234567890123456789012345678901234567 + 890123456789''')); + }); + + testWithoutContext('', () { + expect(wrapText( + '${' ' * 7}abc def ghi', columnWidth: 20, hangingIndent: 5, indent: 3, shouldWrap: true), + equals( + ' abc def\n' + ' ghi' + ), + ); + expect(wrapText( + 'abc def ghi', columnWidth: 0, hangingIndent: 5, shouldWrap: true), + equals( + 'abc def\n' + 'ghi' + ), + ); + expect(wrapText( + 'abc def ghi', columnWidth: 0, indent: 5, shouldWrap: true), + equals( + 'abc def\n' + 'ghi' + ), + ); + expect(wrapText( + ' abc def ghi', columnWidth: 0, shouldWrap: true), + equals( + 'abc def\n' + 'ghi' + ), + ); + expect(wrapText( + 'abc def ghi', columnWidth: kMinColumnWidth - 2, hangingIndent: 5, shouldWrap: true), + equals( + 'abc def\n' + 'ghi' + ), + ); + expect(wrapText( + 'abc def ghi', columnWidth: kMinColumnWidth - 2, indent: 5, shouldWrap: true), + equals( + 'abc def\n' + 'ghi' + ), + ); + expect(wrapText( + ' abc def ghi', columnWidth: kMinColumnWidth - 2, shouldWrap: true), + equals( + 'abc def\n' + 'ghi' + ), + ); + expect(wrapText( + 'abc def ghi jkl', columnWidth: kMinColumnWidth + 2, hangingIndent: 5, shouldWrap: true), + equals( + 'abc def ghi\n' + ' jkl' + ), + ); + expect(wrapText( + 'abc def ghi', columnWidth: kMinColumnWidth + 2, indent: 5, shouldWrap: true), + equals( + ' abc def\n' + ' ghi' + ), + ); + expect(wrapText( + ' abc def ghi', columnWidth: kMinColumnWidth + 2, shouldWrap: true), + equals( + ' abc def\n' + ' ghi' + ), + ); + }); + }); +} diff --git a/flutter/packages/flutter_tools/test/general.shard/version_test.dart b/flutter/packages/flutter_tools/test/general.shard/version_test.dart new file mode 100644 index 0000000000000000000000000000000000000000..54ba0bcc16673cede5dfd12f1dad42e8f8e8386a --- /dev/null +++ b/flutter/packages/flutter_tools/test/general.shard/version_test.dart @@ -0,0 +1,972 @@ +// 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: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/time.dart'; +import 'package:flutter_tools/src/cache.dart'; +import 'package:flutter_tools/src/version.dart'; +import 'package:test/fake.dart'; + +import '../src/common.dart'; +import '../src/context.dart'; +import '../src/fake_process_manager.dart'; +import '../src/fakes.dart' show FakeFlutterVersion; + +final SystemClock _testClock = SystemClock.fixed(DateTime.utc(2015)); +final DateTime _stampUpToDate = _testClock.ago(VersionFreshnessValidator.checkAgeConsideredUpToDate ~/ 2); +final DateTime _stampOutOfDate = _testClock.ago(VersionFreshnessValidator.checkAgeConsideredUpToDate * 2); + +void main() { + late FakeCache cache; + late FakeProcessManager processManager; + + setUp(() { + processManager = FakeProcessManager.empty(); + cache = FakeCache(); + }); + + testUsingContext('Channel enum and string transform to each other', () { + for (final Channel channel in Channel.values) { + expect(getNameForChannel(channel), kOfficialChannels.toList()[channel.index]); + } + expect(kOfficialChannels.toList().map((String str) => getChannelForName(str)).toList(), + Channel.values); + }); + + for (final String channel in kOfficialChannels) { + DateTime getChannelUpToDateVersion() { + return _testClock.ago(VersionFreshnessValidator.versionAgeConsideredUpToDate(channel) ~/ 2); + } + + DateTime getChannelOutOfDateVersion() { + return _testClock.ago(VersionFreshnessValidator.versionAgeConsideredUpToDate(channel) * 2); + } + + group('$FlutterVersion for $channel', () { + late FileSystem fs; + const String flutterRoot = '/path/to/flutter'; + + setUpAll(() { + fs = MemoryFileSystem.test(); + Cache.disableLocking(); + VersionFreshnessValidator.timeToPauseToLetUserReadTheMessage = Duration.zero; + }); + + testUsingContext('prints nothing when Flutter installation looks fresh', () async { + const String flutterUpstreamUrl = 'https://github.com/flutter/flutter.git'; + processManager.addCommands([ + const FakeCommand( + command: ['git', '-c', 'log.showSignature=false', 'log', '-n', '1', '--pretty=format:%H'], + stdout: '1234abcd', + ), + const FakeCommand( + command: ['git', 'tag', '--points-at', '1234abcd'], + ), + const FakeCommand( + command: ['git', 'describe', '--match', '*.*.*', '--long', '--tags', '1234abcd'], + stdout: '0.1.2-3-1234abcd', + ), + FakeCommand( + command: const ['git', 'symbolic-ref', '--short', 'HEAD'], + stdout: channel, + ), + FakeCommand( + command: const ['git', 'rev-parse', '--abbrev-ref', '--symbolic', '@{upstream}'], + stdout: 'origin/$channel', + ), + const FakeCommand( + command: ['git', 'ls-remote', '--get-url', 'origin'], + stdout: flutterUpstreamUrl, + ), + FakeCommand( + command: const ['git', '-c', 'log.showSignature=false', 'log', 'HEAD', '-n', '1', '--pretty=format:%ad', '--date=iso'], + stdout: getChannelUpToDateVersion().toString(), + ), + const FakeCommand( + command: ['git', 'fetch', '--tags'], + ), + FakeCommand( + command: const ['git', '-c', 'log.showSignature=false', 'log', '@{upstream}', '-n', '1', '--pretty=format:%ad', '--date=iso'], + stdout: getChannelOutOfDateVersion().toString(), + ), + const FakeCommand( + command: ['git', '-c', 'log.showSignature=false', 'log', '-n', '1', '--pretty=format:%ar'], + stdout: '1 second ago', + ), + FakeCommand( + command: const ['git', '-c', 'log.showSignature=false', 'log', 'HEAD', '-n', '1', '--pretty=format:%ad', '--date=iso'], + stdout: getChannelUpToDateVersion().toString(), + ), + ]); + + final FlutterVersion flutterVersion = FlutterVersion(clock: _testClock, fs: fs, flutterRoot: flutterRoot); + await flutterVersion.checkFlutterVersionFreshness(); + expect(flutterVersion.channel, channel); + expect(flutterVersion.repositoryUrl, flutterUpstreamUrl); + expect(flutterVersion.frameworkRevision, '1234abcd'); + expect(flutterVersion.frameworkRevisionShort, '1234abcd'); + expect(flutterVersion.frameworkVersion, '0.0.0-unknown'); + expect( + flutterVersion.toString(), + 'Flutter • channel $channel • $flutterUpstreamUrl\n' + 'Framework • revision 1234abcd (1 second ago) • ${getChannelUpToDateVersion()}\n' + 'Engine • revision abcdefg\n' + 'Tools • Dart 2.12.0 • DevTools 2.8.0', + ); + expect(flutterVersion.frameworkAge, '1 second ago'); + expect(flutterVersion.getVersionString(), '$channel/1234abcd'); + expect(flutterVersion.getBranchName(), channel); + expect(flutterVersion.getVersionString(redactUnknownBranches: true), '$channel/1234abcd'); + expect(flutterVersion.getBranchName(redactUnknownBranches: true), channel); + + expect(testLogger.statusText, isEmpty); + expect(processManager, hasNoRemainingExpectations); + }, overrides: { + ProcessManager: () => processManager, + Cache: () => cache, + }); + + testUsingContext('does not crash when git log outputs malformed output', () async { + const String flutterUpstreamUrl = 'https://github.com/flutter/flutter.git'; + + final String malformedGitLogOutput = '${getChannelUpToDateVersion()}[0x7FF9E2A75000] ANOMALY: meaningless REX prefix used'; + processManager.addCommands([ + const FakeCommand( + command: ['git', '-c', 'log.showSignature=false', 'log', '-n', '1', '--pretty=format:%H'], + stdout: '1234abcd', + ), + const FakeCommand( + command: ['git', 'tag', '--points-at', '1234abcd'], + ), + const FakeCommand( + command: ['git', 'describe', '--match', '*.*.*', '--long', '--tags', '1234abcd'], + stdout: '0.1.2-3-1234abcd', + ), + FakeCommand( + command: const ['git', 'symbolic-ref', '--short', 'HEAD'], + stdout: channel, + ), + FakeCommand( + command: const ['git', 'rev-parse', '--abbrev-ref', '--symbolic', '@{upstream}'], + stdout: 'origin/$channel', + ), + const FakeCommand( + command: ['git', 'ls-remote', '--get-url', 'origin'], + stdout: flutterUpstreamUrl, + ), + FakeCommand( + command: const ['git', '-c', 'log.showSignature=false', 'log', 'HEAD', '-n', '1', '--pretty=format:%ad', '--date=iso'], + stdout: malformedGitLogOutput, + ), + ]); + + final FlutterVersion flutterVersion = FlutterVersion(clock: _testClock, fs: fs, flutterRoot: flutterRoot); + await flutterVersion.checkFlutterVersionFreshness(); + + expect(testLogger.statusText, isEmpty); + expect(processManager, hasNoRemainingExpectations); + }, overrides: { + ProcessManager: () => processManager, + Cache: () => cache, + }); + + testWithoutContext('prints nothing when Flutter installation looks out-of-date but is actually up-to-date', () async { + final FakeFlutterVersion flutterVersion = FakeFlutterVersion(branch: channel); + final BufferLogger logger = BufferLogger.test(); + final VersionCheckStamp stamp = VersionCheckStamp( + lastTimeVersionWasChecked: _stampOutOfDate, + lastKnownRemoteVersion: getChannelOutOfDateVersion(), + ); + cache.versionStamp = json.encode(stamp); + + await VersionFreshnessValidator( + version: flutterVersion, + cache: cache, + clock: _testClock, + logger: logger, + localFrameworkCommitDate: getChannelOutOfDateVersion(), + latestFlutterCommitDate: getChannelOutOfDateVersion(), + ).run(); + + expect(logger.statusText, isEmpty); + }); + + testWithoutContext('does not ping server when version stamp is up-to-date', () async { + final FakeFlutterVersion flutterVersion = FakeFlutterVersion(branch: channel); + final BufferLogger logger = BufferLogger.test(); + final VersionCheckStamp stamp = VersionCheckStamp( + lastTimeVersionWasChecked: _stampUpToDate, + lastKnownRemoteVersion: getChannelUpToDateVersion(), + ); + cache.versionStamp = json.encode(stamp); + + await VersionFreshnessValidator( + version: flutterVersion, + cache: cache, + clock: _testClock, + logger: logger, + localFrameworkCommitDate: getChannelOutOfDateVersion(), + latestFlutterCommitDate: getChannelUpToDateVersion(), + ).run(); + + expect(logger.statusText, contains('A new version of Flutter is available!')); + expect(cache.setVersionStamp, true); + }); + + testWithoutContext('does not print warning if printed recently', () async { + final FakeFlutterVersion flutterVersion = FakeFlutterVersion(branch: channel); + final BufferLogger logger = BufferLogger.test(); + final VersionCheckStamp stamp = VersionCheckStamp( + lastTimeVersionWasChecked: _stampUpToDate, + lastKnownRemoteVersion: getChannelUpToDateVersion(), + lastTimeWarningWasPrinted: _testClock.now(), + ); + cache.versionStamp = json.encode(stamp); + + await VersionFreshnessValidator( + version: flutterVersion, + cache: cache, + clock: _testClock, + logger: logger, + localFrameworkCommitDate: getChannelOutOfDateVersion(), + latestFlutterCommitDate: getChannelUpToDateVersion(), + ).run(); + + expect(logger.statusText, isEmpty); + }); + + testWithoutContext('pings server when version stamp is missing', () async { + final FakeFlutterVersion flutterVersion = FakeFlutterVersion(branch: channel); + final BufferLogger logger = BufferLogger.test(); + cache.versionStamp = '{}'; + + await VersionFreshnessValidator( + version: flutterVersion, + cache: cache, + clock: _testClock, + logger: logger, + localFrameworkCommitDate: getChannelOutOfDateVersion(), + latestFlutterCommitDate: getChannelUpToDateVersion(), + ).run(); + + expect(logger.statusText, contains('A new version of Flutter is available!')); + expect(cache.setVersionStamp, true); + }); + + testWithoutContext('pings server when version stamp is out-of-date', () async { + final FakeFlutterVersion flutterVersion = FakeFlutterVersion(branch: channel); + final BufferLogger logger = BufferLogger.test(); + final VersionCheckStamp stamp = VersionCheckStamp( + lastTimeVersionWasChecked: _stampOutOfDate, + lastKnownRemoteVersion: _testClock.ago(const Duration(days: 2)), + ); + cache.versionStamp = json.encode(stamp); + + await VersionFreshnessValidator( + version: flutterVersion, + cache: cache, + clock: _testClock, + logger: logger, + localFrameworkCommitDate: getChannelOutOfDateVersion(), + latestFlutterCommitDate: getChannelUpToDateVersion(), + ).run(); + + expect(logger.statusText, contains('A new version of Flutter is available!')); + }); + + testWithoutContext('does not print warning when unable to connect to server if not out of date', () async { + final FakeFlutterVersion flutterVersion = FakeFlutterVersion(branch: channel); + final BufferLogger logger = BufferLogger.test(); + cache.versionStamp = '{}'; + + await VersionFreshnessValidator( + version: flutterVersion, + cache: cache, + clock: _testClock, + logger: logger, + localFrameworkCommitDate: getChannelUpToDateVersion(), + // latestFlutterCommitDate defaults to null because we failed to get remote version + ).run(); + + expect(logger.statusText, isEmpty); + }); + + testWithoutContext('prints warning when unable to connect to server if really out of date', () async { + final FakeFlutterVersion flutterVersion = FakeFlutterVersion(branch: channel); + final BufferLogger logger = BufferLogger.test(); + final VersionCheckStamp stamp = VersionCheckStamp( + lastTimeVersionWasChecked: _stampOutOfDate, + lastKnownRemoteVersion: _testClock.ago(const Duration(days: 2)), + ); + cache.versionStamp = json.encode(stamp); + + await VersionFreshnessValidator( + version: flutterVersion, + cache: cache, + clock: _testClock, + logger: logger, + localFrameworkCommitDate: getChannelOutOfDateVersion(), + // latestFlutterCommitDate defaults to null because we failed to get remote version + ).run(); + + final Duration frameworkAge = _testClock.now().difference(getChannelOutOfDateVersion()); + expect(logger.statusText, contains('WARNING: your installation of Flutter is ${frameworkAge.inDays} days old.')); + }); + + group('$VersionCheckStamp for $channel', () { + void expectDefault(VersionCheckStamp stamp) { + expect(stamp.lastKnownRemoteVersion, isNull); + expect(stamp.lastTimeVersionWasChecked, isNull); + expect(stamp.lastTimeWarningWasPrinted, isNull); + } + + testWithoutContext('loads blank when stamp file missing', () async { + cache.versionStamp = null; + + expectDefault(await VersionCheckStamp.load(cache, BufferLogger.test())); + }); + + testWithoutContext('loads blank when stamp file is malformed JSON', () async { + cache.versionStamp = '<'; + + expectDefault(await VersionCheckStamp.load(cache, BufferLogger.test())); + }); + + testWithoutContext('loads blank when stamp file is well-formed but invalid JSON', () async { + cache.versionStamp = '[]'; + + expectDefault(await VersionCheckStamp.load(cache, BufferLogger.test())); + }); + + testWithoutContext('loads valid JSON', () async { + final String value = ''' + { + "lastKnownRemoteVersion": "${_testClock.ago(const Duration(days: 1))}", + "lastTimeVersionWasChecked": "${_testClock.ago(const Duration(days: 2))}", + "lastTimeWarningWasPrinted": "${_testClock.now()}" + } + '''; + cache.versionStamp = value; + + final VersionCheckStamp stamp = await VersionCheckStamp.load(cache, BufferLogger.test()); + + expect(stamp.lastKnownRemoteVersion, _testClock.ago(const Duration(days: 1))); + expect(stamp.lastTimeVersionWasChecked, _testClock.ago(const Duration(days: 2))); + expect(stamp.lastTimeWarningWasPrinted, _testClock.now()); + }); + }); + }); + } + + group('VersionUpstreamValidator', () { + const String flutterStandardUrlDotGit = 'https://github.com/flutter/flutter.git'; + const String flutterNonStandardUrlDotGit = 'https://githubmirror.com/flutter/flutter.git'; + const String flutterStandardSshUrlDotGit = 'git@github.com:flutter/flutter.git'; + const String flutterFullSshUrlDotGit = 'ssh://git@github.com/flutter/flutter.git'; + + VersionCheckError? runUpstreamValidator({ + String? versionUpstreamUrl, + String? flutterGitUrl, + }){ + final Platform testPlatform = FakePlatform(environment: { + if (flutterGitUrl != null) 'FLUTTER_GIT_URL': flutterGitUrl, + }); + return VersionUpstreamValidator( + version: FakeFlutterVersion(repositoryUrl: versionUpstreamUrl), + platform: testPlatform, + ).run(); + } + + testWithoutContext('returns error if repository url is null', () { + final VersionCheckError error = runUpstreamValidator( + // repositoryUrl is null by default + )!; + expect(error, isNotNull); + expect( + error.message, + contains('The tool could not determine the remote upstream which is being tracked by the SDK.'), + ); + }); + + testWithoutContext('does not return error at standard remote url with FLUTTER_GIT_URL unset', () { + expect(runUpstreamValidator(versionUpstreamUrl: flutterStandardUrlDotGit), isNull); + }); + + testWithoutContext('returns error at non-standard remote url with FLUTTER_GIT_URL unset', () { + final VersionCheckError error = runUpstreamValidator(versionUpstreamUrl: flutterNonStandardUrlDotGit)!; + expect(error, isNotNull); + expect( + error.message, + contains( + 'The Flutter SDK is tracking a non-standard remote "$flutterNonStandardUrlDotGit".\n' + 'Set the environment variable "FLUTTER_GIT_URL" to "$flutterNonStandardUrlDotGit". ' + 'If this is intentional, it is recommended to use "git" directly to manage the SDK.' + ), + ); + }); + + testWithoutContext('does not return error at non-standard remote url with FLUTTER_GIT_URL set', () { + expect(runUpstreamValidator( + versionUpstreamUrl: flutterNonStandardUrlDotGit, + flutterGitUrl: flutterNonStandardUrlDotGit, + ), isNull); + }); + + testWithoutContext('respects FLUTTER_GIT_URL even if upstream remote url is standard', () { + final VersionCheckError error = runUpstreamValidator( + versionUpstreamUrl: flutterStandardUrlDotGit, + flutterGitUrl: flutterNonStandardUrlDotGit, + )!; + expect(error, isNotNull); + expect( + error.message, + contains( + 'The Flutter SDK is tracking "$flutterStandardUrlDotGit" but "FLUTTER_GIT_URL" is set to "$flutterNonStandardUrlDotGit".\n' + 'Either remove "FLUTTER_GIT_URL" from the environment or set it to "$flutterStandardUrlDotGit". ' + 'If this is intentional, it is recommended to use "git" directly to manage the SDK.' + ), + ); + }); + + testWithoutContext('does not return error at standard ssh url with FLUTTER_GIT_URL unset', () { + expect(runUpstreamValidator(versionUpstreamUrl: flutterStandardSshUrlDotGit), isNull); + }); + + testWithoutContext('does not return error at full ssh url with FLUTTER_GIT_URL unset', () { + expect(runUpstreamValidator(versionUpstreamUrl: flutterFullSshUrlDotGit), isNull); + }); + + testWithoutContext('stripDotGit removes ".git" suffix if any', () { + expect(VersionUpstreamValidator.stripDotGit('https://github.com/flutter/flutter.git'), 'https://github.com/flutter/flutter'); + expect(VersionUpstreamValidator.stripDotGit('https://github.com/flutter/flutter'), 'https://github.com/flutter/flutter'); + expect(VersionUpstreamValidator.stripDotGit('git@github.com:flutter/flutter.git'), 'git@github.com:flutter/flutter'); + expect(VersionUpstreamValidator.stripDotGit('git@github.com:flutter/flutter'), 'git@github.com:flutter/flutter'); + expect(VersionUpstreamValidator.stripDotGit('https://githubmirror.com/flutter/flutter.git.git'), 'https://githubmirror.com/flutter/flutter.git'); + expect(VersionUpstreamValidator.stripDotGit('https://githubmirror.com/flutter/flutter.gitgit'), 'https://githubmirror.com/flutter/flutter.gitgit'); + }); + }); + + testUsingContext('version handles unknown branch', () async { + processManager.addCommands([ + const FakeCommand( + command: ['git', '-c', 'log.showSignature=false', 'log', '-n', '1', '--pretty=format:%H'], + stdout: '1234abcd', + ), + const FakeCommand( + command: ['git', 'tag', '--points-at', '1234abcd'], + ), + const FakeCommand( + command: ['git', 'describe', '--match', '*.*.*', '--long', '--tags', '1234abcd'], + stdout: '0.1.2-3-1234abcd', + ), + const FakeCommand( + command: ['git', 'symbolic-ref', '--short', 'HEAD'], + stdout: 'feature-branch', + ), + ]); + + final MemoryFileSystem fs = MemoryFileSystem.test(); + final FlutterVersion flutterVersion = FlutterVersion( + clock: _testClock, + fs: fs, + flutterRoot: '/path/to/flutter', + ); + expect(flutterVersion.channel, '[user-branch]'); + expect(flutterVersion.getVersionString(), 'feature-branch/1234abcd'); + expect(flutterVersion.getBranchName(), 'feature-branch'); + expect(flutterVersion.getVersionString(redactUnknownBranches: true), '[user-branch]/1234abcd'); + expect(flutterVersion.getBranchName(redactUnknownBranches: true), '[user-branch]'); + + expect(processManager, hasNoRemainingExpectations); + }, overrides: { + ProcessManager: () => processManager, + Cache: () => cache, + }); + + testUsingContext('ensureVersionFile() writes version information to disk', () async { + processManager.addCommands([ + const FakeCommand( + command: ['git', '-c', 'log.showSignature=false', 'log', '-n', '1', '--pretty=format:%H'], + stdout: '1234abcd', + ), + const FakeCommand( + command: ['git', 'tag', '--points-at', '1234abcd'], + ), + const FakeCommand( + command: ['git', 'describe', '--match', '*.*.*', '--long', '--tags', '1234abcd'], + stdout: '0.1.2-3-1234abcd', + ), + const FakeCommand( + command: ['git', 'symbolic-ref', '--short', 'HEAD'], + stdout: 'feature-branch', + ), + const FakeCommand( + command: ['git', 'rev-parse', '--abbrev-ref', '--symbolic', '@{upstream}'], + ), + FakeCommand( + command: const [ + 'git', + '-c', + 'log.showSignature=false', + 'log', + 'HEAD', + '-n', + '1', + '--pretty=format:%ad', + '--date=iso', + ], + stdout: _testClock.ago(VersionFreshnessValidator.versionAgeConsideredUpToDate('stable') ~/ 2).toString(), + ), + ]); + + final MemoryFileSystem fs = MemoryFileSystem.test(); + final Directory flutterRoot = fs.directory('/path/to/flutter'); + flutterRoot.childDirectory('bin').childDirectory('cache').createSync(recursive: true); + final FlutterVersion flutterVersion = FlutterVersion( + clock: _testClock, + fs: fs, + flutterRoot: flutterRoot.path, + ); + + final File versionFile = fs.file('/path/to/flutter/bin/cache/flutter.version.json'); + expect(versionFile.existsSync(), isFalse); + + flutterVersion.ensureVersionFile(); + expect(versionFile.existsSync(), isTrue); + expect(versionFile.readAsStringSync(), ''' +{ + "frameworkVersion": "0.0.0-unknown", + "channel": "[user-branch]", + "repositoryUrl": "unknown source", + "frameworkRevision": "1234abcd", + "frameworkCommitDate": "2014-10-02 00:00:00.000Z", + "engineRevision": "abcdefg", + "dartSdkVersion": "2.12.0", + "devToolsVersion": "2.8.0", + "flutterVersion": "0.0.0-unknown" +}'''); + expect(processManager, hasNoRemainingExpectations); + }, overrides: { + ProcessManager: () => processManager, + Cache: () => cache, + }); + + testUsingContext('version does not call git if a .version.json file exists', () async { + final MemoryFileSystem fs = MemoryFileSystem.test(); + final Directory flutterRoot = fs.directory('/path/to/flutter'); + final Directory cacheDir = flutterRoot + .childDirectory('bin') + .childDirectory('cache') + ..createSync(recursive: true); + const String devToolsVersion = '0000000'; + const Map versionJson = { + 'channel': 'stable', + 'frameworkVersion': '1.2.3', + 'repositoryUrl': 'https://github.com/flutter/flutter.git', + 'frameworkRevision': '1234abcd', + 'frameworkCommitDate': '2023-04-28 12:34:56 -0400', + 'engineRevision': 'deadbeef', + 'dartSdkVersion': 'deadbeef2', + 'devToolsVersion': devToolsVersion, + 'flutterVersion': 'foo', + }; + cacheDir.childFile('flutter.version.json').writeAsStringSync( + jsonEncode(versionJson), + ); + final FlutterVersion flutterVersion = FlutterVersion( + clock: _testClock, + fs: fs, + flutterRoot: flutterRoot.path, + ); + expect(flutterVersion.channel, 'stable'); + expect(flutterVersion.getVersionString(), 'stable/1.2.3'); + expect(flutterVersion.getBranchName(), 'stable'); + expect(flutterVersion.dartSdkVersion, 'deadbeef2'); + expect(flutterVersion.devToolsVersion, devToolsVersion); + expect(flutterVersion.engineRevision, 'deadbeef'); + + expect(processManager, hasNoRemainingExpectations); + }, overrides: { + ProcessManager: () => processManager, + Cache: () => cache, + }); + + testUsingContext('_FlutterVersionFromFile.ensureVersionFile ensures legacy version file exists', () async { + final MemoryFileSystem fs = MemoryFileSystem.test(); + final Directory flutterRoot = fs.directory('/path/to/flutter'); + final Directory cacheDir = flutterRoot + .childDirectory('bin') + .childDirectory('cache') + ..createSync(recursive: true); + const String devToolsVersion = '0000000'; + final File legacyVersionFile = flutterRoot.childFile('version'); + const Map versionJson = { + 'channel': 'stable', + 'frameworkVersion': '1.2.3', + 'repositoryUrl': 'https://github.com/flutter/flutter.git', + 'frameworkRevision': '1234abcd', + 'frameworkCommitDate': '2023-04-28 12:34:56 -0400', + 'engineRevision': 'deadbeef', + 'dartSdkVersion': 'deadbeef2', + 'devToolsVersion': devToolsVersion, + 'flutterVersion': 'foo', + }; + cacheDir.childFile('flutter.version.json').writeAsStringSync( + jsonEncode(versionJson), + ); + expect(legacyVersionFile.existsSync(), isFalse); + final FlutterVersion flutterVersion = FlutterVersion( + clock: _testClock, + fs: fs, + flutterRoot: flutterRoot.path, + ); + flutterVersion.ensureVersionFile(); + expect(legacyVersionFile.existsSync(), isTrue); + expect(legacyVersionFile.readAsStringSync(), '1.2.3'); + }, overrides: { + ProcessManager: () => processManager, + Cache: () => cache, + }); + + testUsingContext('FlutterVersion() falls back to git if .version.json is malformed', () async { + final MemoryFileSystem fs = MemoryFileSystem.test(); + final Directory flutterRoot = fs.directory(fs.path.join('path', 'to', 'flutter')); + final Directory cacheDir = flutterRoot + .childDirectory('bin') + .childDirectory('cache') + ..createSync(recursive: true); + final File legacyVersionFile = flutterRoot.childFile('version'); + final File versionFile = cacheDir.childFile('flutter.version.json')..writeAsStringSync( + '{', + ); + + processManager.addCommands([ + const FakeCommand( + command: ['git', '-c', 'log.showSignature=false', 'log', '-n', '1', '--pretty=format:%H'], + stdout: '1234abcd', + ), + const FakeCommand( + command: ['git', 'tag', '--points-at', '1234abcd'], + ), + const FakeCommand( + command: ['git', 'describe', '--match', '*.*.*', '--long', '--tags', '1234abcd'], + stdout: '0.1.2-3-1234abcd', + ), + const FakeCommand( + command: ['git', 'symbolic-ref', '--short', 'HEAD'], + stdout: 'feature-branch', + ), + const FakeCommand( + command: ['git', 'rev-parse', '--abbrev-ref', '--symbolic', '@{upstream}'], + stdout: 'feature-branch', + ), + FakeCommand( + command: const [ + 'git', + '-c', + 'log.showSignature=false', + 'log', + 'HEAD', + '-n', + '1', + '--pretty=format:%ad', + '--date=iso', + ], + stdout: _testClock.ago(VersionFreshnessValidator.versionAgeConsideredUpToDate('stable') ~/ 2).toString(), + ), + ]); + + // version file exists in a malformed state + expect(versionFile.existsSync(), isTrue); + final FlutterVersion flutterVersion = FlutterVersion( + clock: _testClock, + fs: fs, + flutterRoot: flutterRoot.path, + ); + + // version file was deleted because it couldn't be parsed + expect(versionFile.existsSync(), isFalse); + expect(legacyVersionFile.existsSync(), isFalse); + // version file was written to disk + flutterVersion.ensureVersionFile(); + expect(processManager, hasNoRemainingExpectations); + expect(versionFile.existsSync(), isTrue); + expect(legacyVersionFile.existsSync(), isTrue); + }, overrides: { + ProcessManager: () => processManager, + Cache: () => cache, + }); + + testUsingContext('GitTagVersion', () { + const String hash = 'abcdef'; + GitTagVersion gitTagVersion; + + // Master channel + gitTagVersion = GitTagVersion.parse('1.2.0-4.5.pre-13-g$hash'); + expect(gitTagVersion.frameworkVersionFor(hash), '1.2.0-5.0.pre.13'); + expect(gitTagVersion.gitTag, '1.2.0-4.5.pre'); + expect(gitTagVersion.devVersion, 4); + expect(gitTagVersion.devPatch, 5); + + // Stable channel + gitTagVersion = GitTagVersion.parse('1.2.3'); + expect(gitTagVersion.frameworkVersionFor(hash), '1.2.3'); + expect(gitTagVersion.x, 1); + expect(gitTagVersion.y, 2); + expect(gitTagVersion.z, 3); + expect(gitTagVersion.devVersion, null); + expect(gitTagVersion.devPatch, null); + + // Beta channel + gitTagVersion = GitTagVersion.parse('1.2.3-4.5.pre'); + expect(gitTagVersion.frameworkVersionFor(hash), '1.2.3-4.5.pre'); + expect(gitTagVersion.gitTag, '1.2.3-4.5.pre'); + expect(gitTagVersion.devVersion, 4); + expect(gitTagVersion.devPatch, 5); + + gitTagVersion = GitTagVersion.parse('1.2.3-13-g$hash'); + expect(gitTagVersion.frameworkVersionFor(hash), '1.2.4-0.0.pre.13'); + expect(gitTagVersion.gitTag, '1.2.3'); + expect(gitTagVersion.devVersion, null); + expect(gitTagVersion.devPatch, null); + + // new tag release format, beta channel + gitTagVersion = GitTagVersion.parse('1.2.3-4.5.pre-0-g$hash'); + expect(gitTagVersion.frameworkVersionFor(hash), '1.2.3-4.5.pre'); + expect(gitTagVersion.gitTag, '1.2.3-4.5.pre'); + expect(gitTagVersion.devVersion, 4); + expect(gitTagVersion.devPatch, 5); + + // new tag release format, stable channel + gitTagVersion = GitTagVersion.parse('1.2.3-13-g$hash'); + expect(gitTagVersion.frameworkVersionFor(hash), '1.2.4-0.0.pre.13'); + expect(gitTagVersion.gitTag, '1.2.3'); + expect(gitTagVersion.devVersion, null); + expect(gitTagVersion.devPatch, null); + + expect(GitTagVersion.parse('98.76.54-32-g$hash').frameworkVersionFor(hash), '98.76.55-0.0.pre.32'); + expect(GitTagVersion.parse('10.20.30-0-g$hash').frameworkVersionFor(hash), '10.20.30'); + expect(testLogger.traceText, ''); + expect(GitTagVersion.parse('v1.2.3+hotfix.1-4-g$hash').frameworkVersionFor(hash), '0.0.0-unknown'); + expect(GitTagVersion.parse('x1.2.3-4-g$hash').frameworkVersionFor(hash), '0.0.0-unknown'); + expect(GitTagVersion.parse('1.0.0-unknown-0-g$hash').frameworkVersionFor(hash), '0.0.0-unknown'); + expect(GitTagVersion.parse('beta-1-g$hash').frameworkVersionFor(hash), '0.0.0-unknown'); + expect(GitTagVersion.parse('1.2.3-4-gx$hash').frameworkVersionFor(hash), '0.0.0-unknown'); + expect(testLogger.statusText, ''); + expect(testLogger.errorText, ''); + expect( + testLogger.traceText, + 'Could not interpret results of "git describe": v1.2.3+hotfix.1-4-gabcdef\n' + 'Could not interpret results of "git describe": x1.2.3-4-gabcdef\n' + 'Could not interpret results of "git describe": 1.0.0-unknown-0-gabcdef\n' + 'Could not interpret results of "git describe": beta-1-gabcdef\n' + 'Could not interpret results of "git describe": 1.2.3-4-gxabcdef\n', + ); + }); + + testUsingContext('determine reports correct stable version if HEAD is at a tag', () { + const String stableTag = '1.2.3'; + final FakeProcessManager fakeProcessManager = FakeProcessManager.list( + [ + const FakeCommand( + command: ['git', 'tag', '--points-at', 'HEAD'], + stdout: stableTag, + ), + ], + ); + final ProcessUtils processUtils = ProcessUtils( + processManager: fakeProcessManager, + logger: BufferLogger.test(), + ); + final FakePlatform platform = FakePlatform(); + final GitTagVersion gitTagVersion = GitTagVersion.determine(processUtils, platform, workingDirectory: '.'); + expect(gitTagVersion.frameworkVersionFor('abcd1234'), stableTag); + }); + + testUsingContext('determine favors stable tag over beta tag if both identify HEAD', () { + const String stableTag = '1.2.3'; + final FakeProcessManager fakeProcessManager = FakeProcessManager.list( + [ + const FakeCommand( + command: ['git', 'tag', '--points-at', 'HEAD'], + // This tests the unlikely edge case where a beta release made it to stable without any cherry picks + stdout: '1.2.3-6.0.pre\n$stableTag', + ), + ], + ); + final ProcessUtils processUtils = ProcessUtils( + processManager: fakeProcessManager, + logger: BufferLogger.test(), + ); + final FakePlatform platform = FakePlatform(); + + final GitTagVersion gitTagVersion = GitTagVersion.determine(processUtils, platform, workingDirectory: '.'); + expect(gitTagVersion.frameworkVersionFor('abcd1234'), stableTag); + }); + + testUsingContext('determine reports correct git describe version if HEAD is not at a tag', () { + const String devTag = '1.2.0-2.0.pre'; + const String headRevision = 'abcd1234'; + const String commitsAhead = '12'; + final FakeProcessManager fakeProcessManager = FakeProcessManager.list( + [ + const FakeCommand( + command: ['git', 'tag', '--points-at', 'HEAD'], + // no output, since there's no tag + ), + const FakeCommand( + command: ['git', 'describe', '--match', '*.*.*', '--long', '--tags', 'HEAD'], + stdout: '$devTag-$commitsAhead-g$headRevision', + ), + ], + ); + final ProcessUtils processUtils = ProcessUtils( + processManager: fakeProcessManager, + logger: BufferLogger.test(), + ); + final FakePlatform platform = FakePlatform(); + + final GitTagVersion gitTagVersion = GitTagVersion.determine(processUtils, platform, workingDirectory: '.'); + // reported version should increment the m + expect(gitTagVersion.frameworkVersionFor(headRevision), '1.2.0-3.0.pre.12'); + }); + + testUsingContext('determine does not call fetch --tags', () { + final FakeProcessManager fakeProcessManager = FakeProcessManager.list([ + const FakeCommand( + command: ['git', 'tag', '--points-at', 'HEAD'], + ), + const FakeCommand( + command: ['git', 'describe', '--match', '*.*.*', '--long', '--tags', 'HEAD'], + stdout: 'v0.1.2-3-1234abcd', + ), + ]); + final ProcessUtils processUtils = ProcessUtils( + processManager: fakeProcessManager, + logger: BufferLogger.test(), + ); + final FakePlatform platform = FakePlatform(); + + GitTagVersion.determine(processUtils, platform, workingDirectory: '.'); + expect(fakeProcessManager, hasNoRemainingExpectations); + }); + + testUsingContext('determine does not fetch tags on beta', () { + final FakeProcessManager fakeProcessManager = FakeProcessManager.list([ + const FakeCommand( + command: ['git', 'symbolic-ref', '--short', 'HEAD'], + stdout: 'beta', + ), + const FakeCommand( + command: ['git', 'tag', '--points-at', 'HEAD'], + ), + const FakeCommand( + command: ['git', 'describe', '--match', '*.*.*', '--long', '--tags', 'HEAD'], + stdout: 'v0.1.2-3-1234abcd', + ), + ]); + final ProcessUtils processUtils = ProcessUtils( + processManager: fakeProcessManager, + logger: BufferLogger.test(), + ); + final FakePlatform platform = FakePlatform(); + + GitTagVersion.determine(processUtils, platform, workingDirectory: '.', fetchTags: true); + expect(fakeProcessManager, hasNoRemainingExpectations); + }); + + testUsingContext('determine calls fetch --tags on master', () { + final FakeProcessManager fakeProcessManager = FakeProcessManager.list([ + const FakeCommand( + command: ['git', 'symbolic-ref', '--short', 'HEAD'], + stdout: 'master', + ), + const FakeCommand( + command: ['git', 'fetch', 'https://github.com/flutter/flutter.git', '--tags', '-f'], + ), + const FakeCommand( + command: ['git', 'tag', '--points-at', 'HEAD'], + ), + const FakeCommand( + command: ['git', 'describe', '--match', '*.*.*', '--long', '--tags', 'HEAD'], + stdout: 'v0.1.2-3-1234abcd', + ), + ]); + final ProcessUtils processUtils = ProcessUtils( + processManager: fakeProcessManager, + logger: BufferLogger.test(), + ); + final FakePlatform platform = FakePlatform(); + + GitTagVersion.determine(processUtils, platform, workingDirectory: '.', fetchTags: true); + expect(fakeProcessManager, hasNoRemainingExpectations); + }); + + testUsingContext('determine uses overridden git url', () { + final FakeProcessManager fakeProcessManager = FakeProcessManager.list([ + const FakeCommand( + command: ['git', 'symbolic-ref', '--short', 'HEAD'], + stdout: 'master', + ), + const FakeCommand( + command: ['git', 'fetch', 'https://githubmirror.com/flutter.git', '--tags', '-f'], + ), + const FakeCommand( + command: ['git', 'tag', '--points-at', 'HEAD'], + ), + const FakeCommand( + command: ['git', 'describe', '--match', '*.*.*', '--long', '--tags', 'HEAD'], + stdout: 'v0.1.2-3-1234abcd', + ), + ]); + final ProcessUtils processUtils = ProcessUtils( + processManager: fakeProcessManager, + logger: BufferLogger.test(), + ); + final FakePlatform platform = FakePlatform( + environment: {'FLUTTER_GIT_URL': 'https://githubmirror.com/flutter.git'}, + ); + + GitTagVersion.determine(processUtils, platform, workingDirectory: '.', fetchTags: true); + expect(fakeProcessManager, hasNoRemainingExpectations); + }); +} + +class FakeCache extends Fake implements Cache { + String? versionStamp; + bool setVersionStamp = false; + + @override + String get engineRevision => 'abcdefg'; + + @override + String get devToolsVersion => '2.8.0'; + + @override + String get dartSdkVersion => '2.12.0'; + + @override + void checkLockAcquired() { } + + @override + String? getStampFor(String artifactName) { + if (artifactName == VersionCheckStamp.flutterVersionCheckStampFile) { + return versionStamp; + } + return null; + } + + @override + void setStampFor(String artifactName, String version) { + if (artifactName == VersionCheckStamp.flutterVersionCheckStampFile) { + setVersionStamp = true; + } + } +} diff --git a/flutter/packages/flutter_tools/test/general.shard/vmservice_test.dart b/flutter/packages/flutter_tools/test/general.shard/vmservice_test.dart new file mode 100644 index 0000000000000000000000000000000000000000..d93f3e3e6d2c7b757dd50a01759b81a787bef6ea --- /dev/null +++ b/flutter/packages/flutter_tools/test/general.shard/vmservice_test.dart @@ -0,0 +1,890 @@ +// 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' as io; +import 'package:flutter_tools/src/base/logger.dart'; +import 'package:flutter_tools/src/convert.dart'; +import 'package:flutter_tools/src/device.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/context.dart' hide testLogger; +import '../src/fake_vm_services.dart'; + +const String kExtensionName = 'ext.flutter.test.interestingExtension'; + +final vm_service.Isolate isolate = vm_service.Isolate( + id: '1', + pauseEvent: vm_service.Event( + kind: vm_service.EventKind.kResume, + timestamp: 0 + ), + breakpoints: [], + libraries: [ + 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: [], + extensionRPCs: [kExtensionName], +); + +final FlutterView fakeFlutterView = FlutterView( + id: 'a', + uiIsolate: isolate, +); + +final FakeVmServiceRequest listViewsRequest = FakeVmServiceRequest( + method: kListViewsMethod, + jsonResponse: { + 'views': [ + fakeFlutterView.toJson(), + ], + }, +); + +void main() { + testWithoutContext('VM Service registers reloadSources', () async { + Future reloadSources(String isolateId, { bool? pause, bool? force}) async {} + + final MockVMService mockVMService = MockVMService(); + await setUpVmService( + reloadSources: reloadSources, + vmService: mockVMService, + ); + + expect(mockVMService.services, containsPair(kReloadSourcesServiceName, kFlutterToolAlias)); + }); + + testWithoutContext('VM Service registers flutterMemoryInfo service', () async { + final FakeDevice mockDevice = FakeDevice(); + + final MockVMService mockVMService = MockVMService(); + await setUpVmService( + device: mockDevice, + vmService: mockVMService, + ); + + expect(mockVMService.services, containsPair(kFlutterMemoryInfoServiceName, kFlutterToolAlias)); + }); + + testWithoutContext('VM Service registers flutterGetSkSL service', () async { + final MockVMService mockVMService = MockVMService(); + await setUpVmService( + skSLMethod: () async => 'hello', + vmService: mockVMService, + ); + + expect(mockVMService.services, containsPair(kFlutterGetSkSLServiceName, kFlutterToolAlias)); + }); + + testWithoutContext('VM Service throws tool exit on service registration failure.', () async { + final MockVMService mockVMService = MockVMService() + ..errorOnRegisterService = true; + + await expectLater(() async => setUpVmService( + skSLMethod: () async => 'hello', + vmService: mockVMService, + ), throwsToolExit()); + }); + + testWithoutContext('VM Service throws tool exit on service registration failure with awaited future.', () async { + final MockVMService mockVMService = MockVMService() + ..errorOnRegisterService = true; + + await expectLater(() async => setUpVmService( + skSLMethod: () async => 'hello', + printStructuredErrorLogMethod: (vm_service.Event event) { }, + vmService: mockVMService, + ), throwsToolExit()); + }); + + testWithoutContext('VM Service registers flutterPrintStructuredErrorLogMethod', () async { + final MockVMService mockVMService = MockVMService(); + await setUpVmService( + printStructuredErrorLogMethod: (vm_service.Event event) async => 'hello', + vmService: mockVMService, + ); + expect(mockVMService.listenedStreams, contains(vm_service.EventStreams.kExtension)); + }); + + testWithoutContext('VM Service returns correct FlutterVersion', () async { + final MockVMService mockVMService = MockVMService(); + await setUpVmService( + vmService: mockVMService, + ); + + expect(mockVMService.services, containsPair(kFlutterVersionServiceName, kFlutterToolAlias)); + }); + + testUsingContext('VM Service prints messages for connection failures', () { + final BufferLogger logger = BufferLogger.test(); + FakeAsync().run((FakeAsync time) { + final Uri uri = Uri.parse('ws://127.0.0.1:12345/QqL7EFEDNG0=/ws'); + unawaited(connectToVmService(uri, logger: logger)); + + time.elapse(const Duration(seconds: 5)); + expect(logger.statusText, isEmpty); + + time.elapse(const Duration(minutes: 2)); + + final String statusText = logger.statusText; + expect( + statusText, + containsIgnoringWhitespace('Connecting to the VM Service is taking longer than expected...'), + ); + expect( + statusText, + containsIgnoringWhitespace('try re-running with --host-vmservice-port'), + ); + expect( + statusText, + containsIgnoringWhitespace('Exception attempting to connect to the VM Service:'), + ); + expect( + statusText, + containsIgnoringWhitespace('This was attempt #50. Will retry'), + ); + }); + }, overrides: { + WebSocketConnector: () => failingWebSocketConnector, + }); + + testWithoutContext('setAssetDirectory forwards arguments correctly', () async { + final Completer completer = Completer(); + final vm_service.VmService vmService = vm_service.VmService( + const Stream.empty(), + completer.complete, + ); + final FlutterVmService flutterVmService = FlutterVmService(vmService); + + unawaited(flutterVmService.setAssetDirectory( + assetsDirectory: Uri(path: 'abc', scheme: 'file'), + viewId: 'abc', + uiIsolateId: 'def', + windows: false, + )); + + final Map? rawRequest = json.decode(await completer.future) as Map?; + + expect(rawRequest, allOf([ + containsPair('method', kSetAssetBundlePathMethod), + containsPair('params', allOf([ + containsPair('viewId', 'abc'), + containsPair('assetDirectory', '/abc'), + containsPair('isolateId', 'def'), + ])), + ])); + }); + + testWithoutContext('setAssetDirectory forwards arguments correctly - windows', () async { + final Completer completer = Completer(); + final vm_service.VmService vmService = vm_service.VmService( + const Stream.empty(), + completer.complete, + ); + final FlutterVmService flutterVmService = FlutterVmService(vmService); + unawaited(flutterVmService.setAssetDirectory( + assetsDirectory: Uri(path: 'C:/Users/Tester/AppData/Local/Temp/hello_worldb42a6da5/hello_world/build/flutter_assets', scheme: 'file'), + viewId: 'abc', + uiIsolateId: 'def', + // If windows is not set to `true`, then the file path below is incorrectly prepended with a `/` which + // causes the engine asset manager to interpret the file scheme as invalid. + windows: true, + )); + + final Map? rawRequest = json.decode(await completer.future) as Map?; + + expect(rawRequest, allOf([ + containsPair('method', kSetAssetBundlePathMethod), + containsPair('params', allOf([ + containsPair('viewId', 'abc'), + containsPair('assetDirectory', r'C:\Users\Tester\AppData\Local\Temp\hello_worldb42a6da5\hello_world\build\flutter_assets'), + containsPair('isolateId', 'def'), + ])), + ])); + }); + + testWithoutContext('getSkSLs forwards arguments correctly', () async { + final Completer completer = Completer(); + final vm_service.VmService vmService = vm_service.VmService( + const Stream.empty(), + completer.complete, + ); + final FlutterVmService flutterVmService = FlutterVmService(vmService); + + unawaited(flutterVmService.getSkSLs( + viewId: 'abc', + )); + + final Map? rawRequest = json.decode(await completer.future) as Map?; + + expect(rawRequest, allOf([ + containsPair('method', kGetSkSLsMethod), + containsPair('params', allOf([ + containsPair('viewId', 'abc'), + ])), + ])); + }); + + testWithoutContext('flushUIThreadTasks forwards arguments correctly', () async { + final Completer completer = Completer(); + final vm_service.VmService vmService = vm_service.VmService( + const Stream.empty(), + completer.complete, + ); + final FlutterVmService flutterVmService = FlutterVmService(vmService); + + unawaited(flutterVmService.flushUIThreadTasks( + uiIsolateId: 'def', + )); + + final Map? rawRequest = json.decode(await completer.future) as Map?; + + expect(rawRequest, allOf([ + containsPair('method', kFlushUIThreadTasksMethod), + containsPair('params', allOf([ + containsPair('isolateId', 'def'), + ])), + ])); + }); + + testWithoutContext('runInView forwards arguments correctly', () async { + final FakeVmServiceHost fakeVmServiceHost = FakeVmServiceHost( + requests: [ + const FakeVmServiceRequest(method: 'streamListen', args: { + 'streamId': 'Isolate', + }), + const FakeVmServiceRequest(method: kRunInViewMethod, args: { + 'viewId': '1234', + 'mainScript': 'main.dart', + 'assetDirectory': 'flutter_assets/', + }), + FakeVmServiceStreamResponse( + streamId: 'Isolate', + event: vm_service.Event( + kind: vm_service.EventKind.kIsolateRunnable, + timestamp: 1, + ) + ), + ] + ); + + await fakeVmServiceHost.vmService.runInView( + viewId: '1234', + main: Uri.file('main.dart'), + assetsDirectory: Uri.file('flutter_assets/'), + ); + expect(fakeVmServiceHost.hasRemainingExpectations, false); + }); + + testWithoutContext('flutterDebugDumpSemanticsTreeInTraversalOrder handles missing method', () async { + final FakeVmServiceHost fakeVmServiceHost = FakeVmServiceHost( + requests: [ + const FakeVmServiceRequest( + method: 'ext.flutter.debugDumpSemanticsTreeInTraversalOrder', + args: { + 'isolateId': '1', + }, + error: FakeRPCError(code: RPCErrorCodes.kMethodNotFound), + ), + ] + ); + + expect(await fakeVmServiceHost.vmService.flutterDebugDumpSemanticsTreeInTraversalOrder( + isolateId: '1', + ), ''); + expect(fakeVmServiceHost.hasRemainingExpectations, false); + }); + + testWithoutContext('flutterDebugDumpSemanticsTreeInInverseHitTestOrder handles missing method', () async { + final FakeVmServiceHost fakeVmServiceHost = FakeVmServiceHost( + requests: [ + const FakeVmServiceRequest( + method: 'ext.flutter.debugDumpSemanticsTreeInInverseHitTestOrder', + args: { + 'isolateId': '1', + }, + error: FakeRPCError(code: RPCErrorCodes.kMethodNotFound), + ), + ] + ); + + expect(await fakeVmServiceHost.vmService.flutterDebugDumpSemanticsTreeInInverseHitTestOrder( + isolateId: '1', + ), ''); + expect(fakeVmServiceHost.hasRemainingExpectations, false); + }); + + testWithoutContext('flutterDebugDumpLayerTree handles missing method', () async { + final FakeVmServiceHost fakeVmServiceHost = FakeVmServiceHost( + requests: [ + const FakeVmServiceRequest( + method: 'ext.flutter.debugDumpLayerTree', + args: { + 'isolateId': '1', + }, + error: FakeRPCError(code: RPCErrorCodes.kMethodNotFound), + ), + ] + ); + + expect(await fakeVmServiceHost.vmService.flutterDebugDumpLayerTree( + isolateId: '1', + ), ''); + expect(fakeVmServiceHost.hasRemainingExpectations, false); + }); + + testWithoutContext('flutterDebugDumpRenderTree handles missing method', () async { + final FakeVmServiceHost fakeVmServiceHost = FakeVmServiceHost( + requests: [ + const FakeVmServiceRequest( + method: 'ext.flutter.debugDumpRenderTree', + args: { + 'isolateId': '1', + }, + error: FakeRPCError(code: RPCErrorCodes.kMethodNotFound), + ), + ] + ); + + expect(await fakeVmServiceHost.vmService.flutterDebugDumpRenderTree( + isolateId: '1', + ), ''); + expect(fakeVmServiceHost.hasRemainingExpectations, false); + }); + + testWithoutContext('flutterDebugDumpApp handles missing method', () async { + final FakeVmServiceHost fakeVmServiceHost = FakeVmServiceHost( + requests: [ + const FakeVmServiceRequest( + method: 'ext.flutter.debugDumpApp', + args: { + 'isolateId': '1', + }, + error: FakeRPCError(code: RPCErrorCodes.kMethodNotFound), + ), + ] + ); + + expect(await fakeVmServiceHost.vmService.flutterDebugDumpApp( + isolateId: '1', + ), ''); + expect(fakeVmServiceHost.hasRemainingExpectations, false); + }); + + testWithoutContext('flutterDebugDumpFocusTree handles missing method', () async { + final FakeVmServiceHost fakeVmServiceHost = FakeVmServiceHost( + requests: [ + const FakeVmServiceRequest( + method: 'ext.flutter.debugDumpFocusTree', + args: { + 'isolateId': '1', + }, + error: FakeRPCError(code: RPCErrorCodes.kMethodNotFound), + ), + ] + ); + + expect(await fakeVmServiceHost.vmService.flutterDebugDumpFocusTree( + isolateId: '1', + ), ''); + expect(fakeVmServiceHost.hasRemainingExpectations, false); + }); + + testWithoutContext('flutterDebugDumpFocusTree returns data', () async { + final FakeVmServiceHost fakeVmServiceHost = FakeVmServiceHost( + requests: [ + const FakeVmServiceRequest( + method: 'ext.flutter.debugDumpFocusTree', + args: { + 'isolateId': '1', + }, + jsonResponse: { + 'data': 'Hello world', + }, + ), + ] + ); + + expect(await fakeVmServiceHost.vmService.flutterDebugDumpFocusTree( + isolateId: '1', + ), 'Hello world'); + expect(fakeVmServiceHost.hasRemainingExpectations, false); + }); + + testWithoutContext('Framework service extension invocations return null if service disappears ', () async { + final FakeVmServiceHost fakeVmServiceHost = FakeVmServiceHost( + requests: [ + const FakeVmServiceRequest( + method: kGetSkSLsMethod, + args: { + 'viewId': '1234', + }, + error: FakeRPCError(code: RPCErrorCodes.kServiceDisappeared), + ), + const FakeVmServiceRequest( + method: kListViewsMethod, + error: FakeRPCError(code: RPCErrorCodes.kServiceDisappeared), + ), + const FakeVmServiceRequest( + method: kScreenshotSkpMethod, + error: FakeRPCError(code: RPCErrorCodes.kServiceDisappeared), + ), + const FakeVmServiceRequest( + method: 'setVMTimelineFlags', + args: { + 'recordedStreams': ['test'], + }, + error: FakeRPCError(code: RPCErrorCodes.kServiceDisappeared), + ), + const FakeVmServiceRequest( + method: 'getVMTimeline', + error: FakeRPCError(code: RPCErrorCodes.kServiceDisappeared), + ), + const FakeVmServiceRequest( + method: kRenderFrameWithRasterStatsMethod, + args: { + 'viewId': '1', + 'isolateId': '12', + }, + error: FakeRPCError(code: RPCErrorCodes.kServiceDisappeared), + ), + ] + ); + + final Map? skSLs = await fakeVmServiceHost.vmService.getSkSLs( + viewId: '1234', + ); + expect(skSLs, isNull); + + final List views = await fakeVmServiceHost.vmService.getFlutterViews(); + expect(views, isEmpty); + + final vm_service.Response? screenshotSkp = await fakeVmServiceHost.vmService.screenshotSkp(); + expect(screenshotSkp, isNull); + + // Checking that this doesn't throw. + await fakeVmServiceHost.vmService.setTimelineFlags(['test']); + + final vm_service.Response? timeline = await fakeVmServiceHost.vmService.getTimeline(); + expect(timeline, isNull); + + final Map? rasterStats = + await fakeVmServiceHost.vmService.renderFrameWithRasterStats(viewId: '1', uiIsolateId: '12'); + expect(rasterStats, isNull); + + expect(fakeVmServiceHost.hasRemainingExpectations, false); + }); + + testWithoutContext('getIsolateOrNull returns null if service disappears ', () async { + final FakeVmServiceHost fakeVmServiceHost = FakeVmServiceHost( + requests: [ + const FakeVmServiceRequest( + method: 'getIsolate', + args: { + 'isolateId': 'isolate/123', + }, + error: FakeRPCError(code: RPCErrorCodes.kServiceDisappeared), + ), + ] + ); + + final vm_service.Isolate? isolate = await fakeVmServiceHost.vmService.getIsolateOrNull( + 'isolate/123', + ); + expect(isolate, null); + + expect(fakeVmServiceHost.hasRemainingExpectations, false); + }); + + testWithoutContext('renderWithStats forwards stats correctly', () async { + // ignore: always_specify_types + const Map response = { + 'type': 'RenderFrameWithRasterStats', + 'snapshots':[ + // ignore: always_specify_types + { + 'layer_unique_id':1512, + 'duration_micros':477, + 'snapshot':'', + }, + ], + }; + final FakeVmServiceHost fakeVmServiceHost = FakeVmServiceHost( + requests: [ + const FakeVmServiceRequest(method: kRenderFrameWithRasterStatsMethod, args: { + 'isolateId': 'isolate/123', + 'viewId': 'view/1', + }, jsonResponse: response), + ] + ); + + final Map? rasterStats = + await fakeVmServiceHost.vmService.renderFrameWithRasterStats(viewId: 'view/1', uiIsolateId: 'isolate/123'); + expect(rasterStats, equals(response)); + + expect(fakeVmServiceHost.hasRemainingExpectations, false); + }); + + testWithoutContext('getFlutterViews polls until a view is returned', () async { + final FakeVmServiceHost fakeVmServiceHost = FakeVmServiceHost( + requests: [ + const FakeVmServiceRequest( + method: kListViewsMethod, + jsonResponse: { + 'views': [], + }, + ), + const FakeVmServiceRequest( + method: kListViewsMethod, + jsonResponse: { + 'views': [], + }, + ), + listViewsRequest, + ] + ); + + expect( + await fakeVmServiceHost.vmService.getFlutterViews( + delay: Duration.zero, + ), + isNotEmpty, + ); + expect(fakeVmServiceHost.hasRemainingExpectations, false); + }); + + testWithoutContext('getFlutterViews does not poll if returnEarly is true', () async { + final FakeVmServiceHost fakeVmServiceHost = FakeVmServiceHost( + requests: [ + const FakeVmServiceRequest( + method: kListViewsMethod, + jsonResponse: { + 'views': [], + }, + ), + ] + ); + + expect( + await fakeVmServiceHost.vmService.getFlutterViews( + returnEarly: true, + ), + isEmpty, + ); + expect(fakeVmServiceHost.hasRemainingExpectations, false); + }); + + group('findExtensionIsolate', () { + + testWithoutContext('returns an isolate with the registered extensionRPC', () async { + final FakeVmServiceHost fakeVmServiceHost = FakeVmServiceHost(requests: [ + const FakeVmServiceRequest( + method: 'streamListen', + args: { + 'streamId': 'Isolate', + }, + ), + listViewsRequest, + FakeVmServiceRequest( + method: 'getIsolate', + jsonResponse: isolate.toJson(), + args: { + 'isolateId': '1', + }, + ), + const FakeVmServiceRequest( + method: 'streamCancel', + args: { + 'streamId': 'Isolate', + }, + ), + ]); + + final vm_service.IsolateRef isolateRef = await fakeVmServiceHost.vmService.findExtensionIsolate(kExtensionName); + expect(isolateRef.id, '1'); + }); + + testWithoutContext('returns the isolate with the registered extensionRPC when there are multiple FlutterViews', () async { + const String otherExtensionName = 'ext.flutter.test.otherExtension'; + + // Copy the other isolate and change a few fields. + final vm_service.Isolate isolate2 = vm_service.Isolate.parse( + isolate.toJson() + ..['id'] = '2' + ..['extensionRPCs'] = [otherExtensionName], + )!; + + final FlutterView fakeFlutterView2 = FlutterView( + id: '2', + uiIsolate: isolate2, + ); + + final FakeVmServiceHost fakeVmServiceHost = FakeVmServiceHost(requests: [ + const FakeVmServiceRequest( + method: 'streamListen', + args: { + 'streamId': 'Isolate', + }, + ), + FakeVmServiceRequest( + method: kListViewsMethod, + jsonResponse: { + 'views': [ + fakeFlutterView.toJson(), + fakeFlutterView2.toJson(), + ], + }, + ), + FakeVmServiceRequest( + method: 'getIsolate', + jsonResponse: isolate.toJson(), + args: { + 'isolateId': '1', + }, + ), + FakeVmServiceRequest( + method: 'getIsolate', + jsonResponse: isolate2.toJson(), + args: { + 'isolateId': '2', + }, + ), + const FakeVmServiceRequest( + method: 'streamCancel', + args: { + 'streamId': 'Isolate', + }, + ), + ]); + + final vm_service.IsolateRef isolateRef = await fakeVmServiceHost.vmService.findExtensionIsolate(otherExtensionName); + expect(isolateRef.id, '2'); + }); + + testWithoutContext('does not rethrow a sentinel exception if the initially queried flutter view disappears', () async { + const String otherExtensionName = 'ext.flutter.test.otherExtension'; + final vm_service.Isolate? isolate2 = vm_service.Isolate.parse( + isolate.toJson() + ..['id'] = '2' + ..['extensionRPCs'] = [otherExtensionName], + ); + + final FakeVmServiceHost fakeVmServiceHost = FakeVmServiceHost(requests: [ + const FakeVmServiceRequest( + method: 'streamListen', + args: { + 'streamId': 'Isolate', + }, + ), + FakeVmServiceRequest( + method: kListViewsMethod, + jsonResponse: { + 'views': [ + fakeFlutterView.toJson(), + ], + }, + ), + const FakeVmServiceRequest( + method: 'getIsolate', + args: { + 'isolateId': '1', + }, + error: FakeRPCError(code: RPCErrorCodes.kServiceDisappeared), + ), + // Assume a different isolate returns. + FakeVmServiceStreamResponse( + streamId: 'Isolate', + event: vm_service.Event( + kind: vm_service.EventKind.kServiceExtensionAdded, + extensionRPC: otherExtensionName, + timestamp: 1, + isolate: isolate2, + ), + ), + const FakeVmServiceRequest( + method: 'streamCancel', + args: { + 'streamId': 'Isolate', + }, + ), + ]); + + final vm_service.IsolateRef isolateRef = await fakeVmServiceHost.vmService.findExtensionIsolate(otherExtensionName); + expect(isolateRef.id, '2'); + }); + + testWithoutContext('when the isolate stream is already subscribed, returns an isolate with the registered extensionRPC', () async { + final FakeVmServiceHost fakeVmServiceHost = FakeVmServiceHost(requests: [ + const FakeVmServiceRequest( + method: 'streamListen', + args: { + 'streamId': 'Isolate', + }, + // Stream already subscribed - https://github.com/dart-lang/sdk/blob/main/runtime/vm/service/service.md#streamlisten + error: FakeRPCError(code: 103), + ), + listViewsRequest, + FakeVmServiceRequest( + method: 'getIsolate', + jsonResponse: isolate.toJson()..['extensionRPCs'] = [kExtensionName], + args: { + 'isolateId': '1', + }, + ), + const FakeVmServiceRequest( + method: 'streamCancel', + args: { + 'streamId': 'Isolate', + }, + ), + ]); + + final vm_service.IsolateRef isolateRef = await fakeVmServiceHost.vmService.findExtensionIsolate(kExtensionName); + expect(isolateRef.id, '1'); + }); + + testWithoutContext('returns an isolate with a extensionRPC that is registered later', () async { + final FakeVmServiceHost fakeVmServiceHost = FakeVmServiceHost(requests: [ + const FakeVmServiceRequest( + method: 'streamListen', + args: { + 'streamId': 'Isolate', + }, + ), + listViewsRequest, + FakeVmServiceRequest( + method: 'getIsolate', + jsonResponse: isolate.toJson(), + args: { + 'isolateId': '1', + }, + ), + FakeVmServiceStreamResponse( + streamId: 'Isolate', + event: vm_service.Event( + kind: vm_service.EventKind.kServiceExtensionAdded, + extensionRPC: kExtensionName, + timestamp: 1, + ), + ), + const FakeVmServiceRequest( + method: 'streamCancel', + args: { + 'streamId': 'Isolate', + }, + ), + ]); + + final vm_service.IsolateRef isolateRef = await fakeVmServiceHost.vmService.findExtensionIsolate(kExtensionName); + expect(isolateRef.id, '1'); + }); + + testWithoutContext('throws when the service disappears', () async { + final FakeVmServiceHost fakeVmServiceHost = FakeVmServiceHost(requests: [ + const FakeVmServiceRequest( + method: 'streamListen', + args: { + 'streamId': 'Isolate', + }, + ), + const FakeVmServiceRequest( + method: kListViewsMethod, + error: FakeRPCError(code: RPCErrorCodes.kServiceDisappeared), + ), + const FakeVmServiceRequest( + method: 'streamCancel', + args: { + 'streamId': 'Isolate', + }, + error: FakeRPCError(code: RPCErrorCodes.kServiceDisappeared), + ), + ]); + + expect( + () => fakeVmServiceHost.vmService.findExtensionIsolate(kExtensionName), + throwsA(isA()), + ); + }); + }); + + testWithoutContext('Can process log events from the vm service', () { + final vm_service.Event event = vm_service.Event( + bytes: base64.encode(utf8.encode('Hello There\n')), + timestamp: 0, + kind: vm_service.EventKind.kLogging, + ); + + expect(processVmServiceMessage(event), 'Hello There'); + }); + + testUsingContext('WebSocket URL construction uses correct URI join primitives', () async { + final Completer completer = Completer(); + openChannelForTesting = (String url, {io.CompressionOptions compression = io.CompressionOptions.compressionDefault, required Logger logger}) async { + completer.complete(url); + throw Exception(''); + }; + + // Construct a URL that does not end in a `/`. + await expectLater(() => connectToVmService(Uri.parse('http://localhost:8181/foo'), logger: BufferLogger.test()), throwsException); + expect(await completer.future, 'ws://localhost:8181/foo/ws'); + openChannelForTesting = null; + }); +} + +class MockVMService extends Fake implements vm_service.VmService { + final Map services = {}; + final Map serviceCallBacks = {}; + final Set listenedStreams = {}; + bool errorOnRegisterService = false; + + @override + void registerServiceCallback(String service, vm_service.ServiceCallback cb) { + serviceCallBacks[service] = cb; + } + + @override + Future registerService(String service, String alias) async { + services[service] = alias; + if (errorOnRegisterService) { + throw vm_service.RPCError('registerService', 1234, 'error'); + } + return vm_service.Success(); + } + + @override + Stream get onExtensionEvent => const Stream.empty(); + + @override + Future streamListen(String streamId) async { + listenedStreams.add(streamId); + return vm_service.Success(); + } +} + +class FakeDevice extends Fake implements Device { } + +/// A [WebSocketConnector] that always throws an [io.SocketException]. +Future failingWebSocketConnector( + String url, { + io.CompressionOptions? compression, + Logger? logger, +}) { + throw const io.SocketException('Failed WebSocket connection'); +} diff --git a/flutter/packages/flutter_tools/test/general.shard/web_template_test.dart b/flutter/packages/flutter_tools/test/general.shard/web_template_test.dart new file mode 100644 index 0000000000000000000000000000000000000000..d752a7527103a3b0d422abafdab560ab64c02612 --- /dev/null +++ b/flutter/packages/flutter_tools/test/general.shard/web_template_test.dart @@ -0,0 +1,341 @@ +// 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/web_template.dart'; + +import '../src/common.dart'; + +const String htmlSample1 = ''' + + + + + + + + + +
+ + + +'''; + +const String htmlSample2 = ''' + + + + + + + + + +
+ + + + + +'''; + +const String htmlSampleInlineFlutterJsBootstrap = ''' + + + + + + + + + +
+ + + +'''; + +const String htmlSampleInlineFlutterJsBootstrapOutput = ''' + + + + + + + + + +
+ + + +'''; + +const String htmlSampleFullFlutterBootstrapReplacement = ''' + + + + + + + + + +
+ + + +'''; + +const String htmlSampleFullFlutterBootstrapReplacementOutput = ''' + + + + + + + + + +
+ + + +'''; + +const String htmlSampleLegacyVar = ''' + + + + + + + + + +
+ + + + + +'''; + +const String htmlSampleLegacyLoadEntrypoint = ''' + + + + + + + + + + +
+ + + +'''; + +String htmlSample2Replaced({ + required String baseHref, + required String serviceWorkerVersion, +}) => + ''' + + + + + + + + + +
+ + + + + +'''; + +const String htmlSample3 = ''' + + + + + + + + +
+ + + +'''; + +void main() { + final MemoryFileSystem fs = MemoryFileSystem(); + final File flutterJs = fs.file('flutter.js'); + flutterJs.writeAsStringSync('(flutter.js content)'); + + test('can parse baseHref', () { + expect(WebTemplate('').getBaseHref(), 'foo/111'); + expect(WebTemplate(htmlSample1).getBaseHref(), 'foo/222'); + expect(WebTemplate(htmlSample2).getBaseHref(), ''); // Placeholder base href. + }); + + test('handles missing baseHref', () { + expect(WebTemplate('').getBaseHref(), ''); + expect(WebTemplate('').getBaseHref(), ''); + expect(WebTemplate(htmlSample3).getBaseHref(), ''); + }); + + test('throws on invalid baseHref', () { + expect(() => WebTemplate('').getBaseHref(), throwsToolExit()); + expect(() => WebTemplate('').getBaseHref(), throwsToolExit()); + expect(() => WebTemplate('').getBaseHref(), throwsToolExit()); + expect( + () => WebTemplate('').getBaseHref(), + throwsToolExit(), + ); + expect( + () => WebTemplate('').getBaseHref(), + throwsToolExit(), + ); + }); + + test('applies substitutions', () { + final WebTemplate indexHtml = WebTemplate(htmlSample2); + indexHtml.applySubstitutions( + baseHref: '/foo/333/', + serviceWorkerVersion: 'v123xyz', + flutterJsFile: flutterJs, + ); + expect( + indexHtml.content, + htmlSample2Replaced( + baseHref: '/foo/333/', + serviceWorkerVersion: 'v123xyz', + ), + ); + }); + + test('applies substitutions with legacy var version syntax', () { + final WebTemplate indexHtml = WebTemplate(htmlSampleLegacyVar); + indexHtml.applySubstitutions( + baseHref: '/foo/333/', + serviceWorkerVersion: 'v123xyz', + flutterJsFile: flutterJs, + ); + expect( + indexHtml.content, + htmlSample2Replaced( + baseHref: '/foo/333/', + serviceWorkerVersion: 'v123xyz', + ), + ); + }); + + test('applies substitutions to inline flutter.js bootstrap script', () { + final WebTemplate indexHtml = WebTemplate(htmlSampleInlineFlutterJsBootstrap); + expect(indexHtml.getWarnings(), isEmpty); + + indexHtml.applySubstitutions( + baseHref: '/', + serviceWorkerVersion: '(service worker version)', + flutterJsFile: flutterJs, + buildConfig: '(build config)', + ); + expect(indexHtml.content, htmlSampleInlineFlutterJsBootstrapOutput); + }); + + test('applies substitutions to full flutter_bootstrap.js replacement', () { + final WebTemplate indexHtml = WebTemplate(htmlSampleFullFlutterBootstrapReplacement); + expect(indexHtml.getWarnings(), isEmpty); + + indexHtml.applySubstitutions( + baseHref: '/', + serviceWorkerVersion: '(service worker version)', + flutterJsFile: flutterJs, + buildConfig: '(build config)', + flutterBootstrapJs: '(flutter bootstrap script)', + ); + expect(indexHtml.content, htmlSampleFullFlutterBootstrapReplacementOutput); + }); + + test('re-parses after substitutions', () { + final WebTemplate indexHtml = WebTemplate(htmlSample2); + expect(indexHtml.getBaseHref(), ''); // Placeholder base href. + + indexHtml.applySubstitutions( + baseHref: '/foo/333/', + serviceWorkerVersion: 'v123xyz', + flutterJsFile: flutterJs, + ); + // The parsed base href should be updated after substitutions. + expect(indexHtml.getBaseHref(), 'foo/333'); + }); + + test('warns on legacy service worker patterns', () { + final WebTemplate indexHtml = WebTemplate(htmlSampleLegacyVar); + final List warnings = indexHtml.getWarnings(); + expect(warnings.length, 2); + + expect(warnings.where((WebTemplateWarning warning) => warning.lineNumber == 13), isNotEmpty); + expect(warnings.where((WebTemplateWarning warning) => warning.lineNumber == 16), isNotEmpty); + }); + + test('warns on legacy FlutterLoader.loadEntrypoint', () { + final WebTemplate indexHtml = WebTemplate(htmlSampleLegacyLoadEntrypoint); + final List warnings = indexHtml.getWarnings(); + + expect(warnings.length, 1); + expect(warnings.single.lineNumber, 14); + }); +} diff --git a/flutter/packages/flutter_tools/test/general.shard/windows_version_validator_test.dart b/flutter/packages/flutter_tools/test/general.shard/windows_version_validator_test.dart new file mode 100644 index 0000000000000000000000000000000000000000..e186de32be39021f5b4600ea74cc8dc34207fd2a --- /dev/null +++ b/flutter/packages/flutter_tools/test/general.shard/windows_version_validator_test.dart @@ -0,0 +1,102 @@ +// 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/os.dart'; +import 'package:flutter_tools/src/doctor_validator.dart'; +import 'package:flutter_tools/src/windows/windows_version_validator.dart'; +import 'package:test/fake.dart'; + +import '../src/common.dart'; + +/// Fake [_WindowsUtils] to use for testing +class FakeValidOperatingSystemUtils extends Fake + implements OperatingSystemUtils { + FakeValidOperatingSystemUtils( + [this.name = 'Microsoft Windows [Version 11.0.22621.963]']); + + @override + final String name; +} + +/// The expected validation result object for +/// a passing windows version test +const ValidationResult validWindows10ValidationResult = ValidationResult( + ValidationType.success, + [], + statusInfo: 'Installed version of Windows is version 10 or higher', +); + +/// The expected validation result object for +/// a passing windows version test +const ValidationResult invalidWindowsValidationResult = ValidationResult( + ValidationType.missing, + [], + statusInfo: 'Unable to confirm if installed Windows version is 10 or greater', +); + +void main() { + testWithoutContext('Successfully running windows version check on windows 10', + () async { + final WindowsVersionValidator windowsVersionValidator = + WindowsVersionValidator( + operatingSystemUtils: FakeValidOperatingSystemUtils()); + + final ValidationResult result = await windowsVersionValidator.validate(); + + expect(result.type, validWindows10ValidationResult.type, + reason: 'The ValidationResult type should be the same (installed)'); + expect(result.statusInfo, validWindows10ValidationResult.statusInfo, + reason: 'The ValidationResult statusInfo messages should be the same'); + }); + + testWithoutContext( + 'Successfully running windows version check on windows 10 for BR', + () async { + final WindowsVersionValidator windowsVersionValidator = + WindowsVersionValidator( + operatingSystemUtils: FakeValidOperatingSystemUtils( + 'Microsoft Windows [versão 10.0.22621.1105]')); + + final ValidationResult result = await windowsVersionValidator.validate(); + + expect(result.type, validWindows10ValidationResult.type, + reason: 'The ValidationResult type should be the same (installed)'); + expect(result.statusInfo, validWindows10ValidationResult.statusInfo, + reason: 'The ValidationResult statusInfo messages should be the same'); + }); + + testWithoutContext('Identifying a windows version before 10', () async { + final WindowsVersionValidator windowsVersionValidator = + WindowsVersionValidator( + operatingSystemUtils: FakeValidOperatingSystemUtils( + 'Microsoft Windows [Version 8.0.22621.1105]')); + + final ValidationResult result = await windowsVersionValidator.validate(); + + expect(result.type, invalidWindowsValidationResult.type, + reason: 'The ValidationResult type should be the same (missing)'); + }); + + testWithoutContext('Unit testing on a regex pattern validator', () async { + const String testStr = r''' +OS Version: 10.0.19044 N/A Build 19044 +OSz Version: 10.0.19044 N/A Build 19044 +OxS Version: 10.0.19044 N/A Build 19044 +OS Version: 10.19044 N/A Build 19044 +OS Version: 10.x.19044 N/A Build 19044 +OS Version: 10.0.19044 N/A Build 19044 +OS Version: .0.19044 N/A Build 19044 +OS 版本: 10.0.22621 暂缺 Build 22621 +'''; + + final RegExp regex = RegExp( + kWindowsOSVersionSemVerPattern, + multiLine: true, + ); + final Iterable matches = regex.allMatches(testStr); + + expect(matches.length, 5, + reason: 'There should be only 5 matches for the pattern provided'); + }); +} diff --git a/flutter/packages/flutter_tools/test/general.shard/xcode_backend_test.dart b/flutter/packages/flutter_tools/test/general.shard/xcode_backend_test.dart new file mode 100644 index 0000000000000000000000000000000000000000..b91968bd9fdfe7dfe1d222445f340a2084cda2ed --- /dev/null +++ b/flutter/packages/flutter_tools/test/general.shard/xcode_backend_test.dart @@ -0,0 +1,280 @@ +// 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 '../../bin/xcode_backend.dart'; +import '../src/common.dart' hide Context; +import '../src/fake_process_manager.dart'; + +void main() { + late MemoryFileSystem fileSystem; + + setUp(() { + fileSystem = MemoryFileSystem(); + }); + + group('build', () { + test('exits with useful error message when build mode not set', () { + final Directory buildDir = fileSystem.directory('/path/to/builds') + ..createSync(recursive: true); + final Directory flutterRoot = fileSystem.directory('/path/to/flutter') + ..createSync(recursive: true); + final File pipe = fileSystem.file('/tmp/pipe') + ..createSync(recursive: true); + const String buildMode = 'Debug'; + final TestContext context = TestContext( + ['build'], + { + 'ACTION': 'build', + 'BUILT_PRODUCTS_DIR': buildDir.path, + 'FLUTTER_ROOT': flutterRoot.path, + 'INFOPLIST_PATH': 'Info.plist', + }, + commands: [ + FakeCommand( + command: [ + '${flutterRoot.path}/bin/flutter', + 'assemble', + '--no-version-check', + '--output=${buildDir.path}/', + '-dTargetPlatform=ios', + '-dTargetFile=lib/main.dart', + '-dBuildMode=${buildMode.toLowerCase()}', + '-dIosArchs=', + '-dSdkRoot=', + '-dSplitDebugInfo=', + '-dTreeShakeIcons=', + '-dTrackWidgetCreation=', + '-dDartObfuscation=', + '-dAction=build', + '-dFrontendServerStarterPath=', + '--ExtraGenSnapshotOptions=', + '--DartDefines=', + '--ExtraFrontEndOptions=', + 'debug_ios_bundle_flutter_assets', + ], + ), + ], + fileSystem: fileSystem, + scriptOutputStreamFile: pipe, + ); + expect( + () => context.run(), + throwsException, + ); + expect( + context.stderr, + contains('ERROR: Unknown FLUTTER_BUILD_MODE: null.\n'), + ); + }); + test('calls flutter assemble', () { + final Directory buildDir = fileSystem.directory('/path/to/builds') + ..createSync(recursive: true); + final Directory flutterRoot = fileSystem.directory('/path/to/flutter') + ..createSync(recursive: true); + final File pipe = fileSystem.file('/tmp/pipe') + ..createSync(recursive: true); + const String buildMode = 'Debug'; + final TestContext context = TestContext( + ['build'], + { + 'BUILT_PRODUCTS_DIR': buildDir.path, + 'CONFIGURATION': buildMode, + 'FLUTTER_ROOT': flutterRoot.path, + 'INFOPLIST_PATH': 'Info.plist', + }, + commands: [ + FakeCommand( + command: [ + '${flutterRoot.path}/bin/flutter', + 'assemble', + '--no-version-check', + '--output=${buildDir.path}/', + '-dTargetPlatform=ios', + '-dTargetFile=lib/main.dart', + '-dBuildMode=${buildMode.toLowerCase()}', + '-dIosArchs=', + '-dSdkRoot=', + '-dSplitDebugInfo=', + '-dTreeShakeIcons=', + '-dTrackWidgetCreation=', + '-dDartObfuscation=', + '-dAction=', + '-dFrontendServerStarterPath=', + '--ExtraGenSnapshotOptions=', + '--DartDefines=', + '--ExtraFrontEndOptions=', + 'debug_ios_bundle_flutter_assets', + ], + ), + ], + fileSystem: fileSystem, + scriptOutputStreamFile: pipe, + )..run(); + final List streamedLines = pipe.readAsLinesSync(); + // Ensure after line splitting, the exact string 'done' appears + expect(streamedLines, contains('done')); + expect(streamedLines, contains(' └─Compiling, linking and signing...')); + expect( + context.stdout, + contains('built and packaged successfully.'), + ); + expect(context.stderr, isEmpty); + }); + + test('forwards all env variables to flutter assemble', () { + final Directory buildDir = fileSystem.directory('/path/to/builds') + ..createSync(recursive: true); + final Directory flutterRoot = fileSystem.directory('/path/to/flutter') + ..createSync(recursive: true); + const String archs = 'arm64'; + const String buildMode = 'Release'; + const String dartObfuscation = 'false'; + const String dartDefines = 'flutter.inspector.structuredErrors%3Dtrue'; + const String expandedCodeSignIdentity = 'F1326572E0B71C3C8442805230CB4B33B708A2E2'; + const String extraFrontEndOptions = '--some-option'; + const String extraGenSnapshotOptions = '--obfuscate'; + const String frontendServerStarterPath = '/path/to/frontend_server_starter.dart'; + const String sdkRoot = '/path/to/sdk'; + const String splitDebugInfo = '/path/to/split/debug/info'; + const String trackWidgetCreation = 'true'; + const String treeShake = 'true'; + final TestContext context = TestContext( + ['build'], + { + 'ACTION': 'install', + 'ARCHS': archs, + 'BUILT_PRODUCTS_DIR': buildDir.path, + 'CODE_SIGNING_REQUIRED': 'YES', + 'CONFIGURATION': buildMode, + 'DART_DEFINES': dartDefines, + 'DART_OBFUSCATION': dartObfuscation, + 'EXPANDED_CODE_SIGN_IDENTITY': expandedCodeSignIdentity, + 'EXTRA_FRONT_END_OPTIONS': extraFrontEndOptions, + 'EXTRA_GEN_SNAPSHOT_OPTIONS': extraGenSnapshotOptions, + 'FLUTTER_ROOT': flutterRoot.path, + 'FRONTEND_SERVER_STARTER_PATH': frontendServerStarterPath, + 'INFOPLIST_PATH': 'Info.plist', + 'SDKROOT': sdkRoot, + 'FLAVOR': 'strawberry', + 'SPLIT_DEBUG_INFO': splitDebugInfo, + 'TRACK_WIDGET_CREATION': trackWidgetCreation, + 'TREE_SHAKE_ICONS': treeShake, + }, + commands: [ + FakeCommand( + command: [ + '${flutterRoot.path}/bin/flutter', + 'assemble', + '--no-version-check', + '--output=${buildDir.path}/', + '-dTargetPlatform=ios', + '-dTargetFile=lib/main.dart', + '-dBuildMode=${buildMode.toLowerCase()}', + '-dFlavor=strawberry', + '-dIosArchs=$archs', + '-dSdkRoot=$sdkRoot', + '-dSplitDebugInfo=$splitDebugInfo', + '-dTreeShakeIcons=$treeShake', + '-dTrackWidgetCreation=$trackWidgetCreation', + '-dDartObfuscation=$dartObfuscation', + '-dAction=install', + '-dFrontendServerStarterPath=$frontendServerStarterPath', + '--ExtraGenSnapshotOptions=$extraGenSnapshotOptions', + '--DartDefines=$dartDefines', + '--ExtraFrontEndOptions=$extraFrontEndOptions', + '-dCodesignIdentity=$expandedCodeSignIdentity', + 'release_ios_bundle_flutter_assets', + ], + ), + ], + fileSystem: fileSystem, + )..run(); + expect( + context.stdout, + contains('built and packaged successfully.'), + ); + expect(context.stderr, isEmpty); + }); + }); + + group('test_vm_service_bonjour_service', () { + test('handles when the Info.plist is missing', () { + final Directory buildDir = fileSystem.directory('/path/to/builds'); + buildDir.createSync(recursive: true); + final TestContext context = TestContext( + ['test_vm_service_bonjour_service'], + { + 'CONFIGURATION': 'Debug', + 'BUILT_PRODUCTS_DIR': buildDir.path, + 'INFOPLIST_PATH': 'Info.plist', + }, + commands: [], + fileSystem: fileSystem, + )..run(); + expect( + context.stdout, + contains( + 'Info.plist does not exist. Skipping _dartVmService._tcp NSBonjourServices insertion.'), + ); + }); + }); +} + +class TestContext extends Context { + TestContext( + List arguments, + Map environment, { + required this.fileSystem, + required List commands, + File? scriptOutputStreamFile, + }) : processManager = FakeProcessManager.list(commands), + super(arguments: arguments, environment: environment, scriptOutputStreamFile: scriptOutputStreamFile); + + final FileSystem fileSystem; + final FakeProcessManager processManager; + + String stdout = ''; + String stderr = ''; + + @override + bool existsFile(String path) { + return fileSystem.file(path).existsSync(); + } + + @override + ProcessResult runSync( + String bin, + List args, { + bool verbose = false, + bool allowFail = false, + String? workingDirectory, + }) { + return processManager.runSync( + [bin, ...args], + workingDirectory: workingDirectory, + environment: environment, + ); + } + + @override + void echoError(String message) { + stderr += '$message\n'; + } + + @override + void echo(String message) { + stdout += message; + } + + @override + Never exitApp(int code) { + // This is an exception for the benefit of unit tests. + // The real implementation calls `exit(code)`. + throw Exception('App exited with code $code'); + } +} diff --git a/flutter/packages/flutter_tools/test/general.shard/xcode_project_test.dart b/flutter/packages/flutter_tools/test/general.shard/xcode_project_test.dart new file mode 100644 index 0000000000000000000000000000000000000000..dfaf6096ccc1574b3f865baae5ea2c5d9713d031 --- /dev/null +++ b/flutter/packages/flutter_tools/test/general.shard/xcode_project_test.dart @@ -0,0 +1,213 @@ +// 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/file_system.dart'; +import 'package:flutter_tools/src/base/logger.dart'; +import 'package:flutter_tools/src/ios/xcodeproj.dart'; +import 'package:flutter_tools/src/project.dart'; +import 'package:test/fake.dart'; + +import '../src/common.dart'; +import '../src/context.dart'; + + +void main() { + group('IosProject', () { + testWithoutContext('managedDirectory', () { + final MemoryFileSystem fs = MemoryFileSystem.test(); + final IosProject project = IosProject.fromFlutter( + FakeFlutterProject(fileSystem: fs), + ); + expect(project.managedDirectory.path, 'app_name/ios/Flutter'); + }); + + testWithoutContext('module managedDirectory', () { + final MemoryFileSystem fs = MemoryFileSystem.test(); + final IosProject project = IosProject.fromFlutter( + FakeFlutterProject(fileSystem: fs, isModule: true), + ); + expect(project.managedDirectory.path, 'app_name/.ios/Flutter'); + }); + + testWithoutContext('ephemeralDirectory', () { + final MemoryFileSystem fs = MemoryFileSystem.test(); + final IosProject project = IosProject.fromFlutter( + FakeFlutterProject(fileSystem: fs), + ); + expect(project.ephemeralDirectory.path, 'app_name/ios/Flutter/ephemeral'); + }); + + testWithoutContext('module ephemeralDirectory', () { + final MemoryFileSystem fs = MemoryFileSystem.test(); + final IosProject project = IosProject.fromFlutter( + FakeFlutterProject(fileSystem: fs, isModule: true), + ); + expect(project.ephemeralDirectory.path, 'app_name/.ios/Flutter/ephemeral'); + }); + + testWithoutContext('flutterPluginSwiftPackageDirectory', () { + final MemoryFileSystem fs = MemoryFileSystem.test(); + final IosProject project = IosProject.fromFlutter( + FakeFlutterProject(fileSystem: fs), + ); + expect( + project.flutterPluginSwiftPackageDirectory.path, + 'app_name/ios/Flutter/ephemeral/Packages/FlutterGeneratedPluginSwiftPackage', + ); + }); + + testWithoutContext('module flutterPluginSwiftPackageDirectory', () { + final MemoryFileSystem fs = MemoryFileSystem.test(); + final IosProject project = IosProject.fromFlutter( + FakeFlutterProject(fileSystem: fs, isModule: true), + ); + expect( + project.flutterPluginSwiftPackageDirectory.path, + 'app_name/.ios/Flutter/ephemeral/Packages/FlutterGeneratedPluginSwiftPackage', + ); + }); + + testWithoutContext('xcodeConfigFor', () { + final MemoryFileSystem fs = MemoryFileSystem.test(); + final IosProject project = IosProject.fromFlutter( + FakeFlutterProject(fileSystem: fs), + ); + expect( + project.xcodeConfigFor('Debug').path, + 'app_name/ios/Flutter/Debug.xcconfig', + ); + }); + + group('projectInfo', () { + testUsingContext('is null if XcodeProjectInterpreter is null', () async { + final MemoryFileSystem fs = MemoryFileSystem.test(); + final IosProject project = IosProject.fromFlutter( + FakeFlutterProject(fileSystem: fs), + ); + project.xcodeProject.createSync(recursive: true); + expect(await project.projectInfo(), isNull); + }, overrides: { + XcodeProjectInterpreter: () => null, + }); + + testUsingContext('is null if XcodeProjectInterpreter is not installed', () async { + final MemoryFileSystem fs = MemoryFileSystem.test(); + final IosProject project = IosProject.fromFlutter( + FakeFlutterProject(fileSystem: fs), + ); + project.xcodeProject.createSync(recursive: true); + expect(await project.projectInfo(), isNull); + }, overrides: { + XcodeProjectInterpreter: () => FakeXcodeProjectInterpreter( + isInstalled: false, + ), + }); + + testUsingContext('is null if xcodeproj does not exist', () async { + final MemoryFileSystem fs = MemoryFileSystem.test(); + final IosProject project = IosProject.fromFlutter( + FakeFlutterProject(fileSystem: fs), + ); + expect(await project.projectInfo(), isNull); + }, overrides: { + XcodeProjectInterpreter: () => FakeXcodeProjectInterpreter(), + }); + + testUsingContext('returns XcodeProjectInfo', () async { + final MemoryFileSystem fs = MemoryFileSystem.test(); + final IosProject project = IosProject.fromFlutter( + FakeFlutterProject(fileSystem: fs), + ); + project.xcodeProject.createSync(recursive: true); + expect(await project.projectInfo(), isNotNull); + }, overrides: { + XcodeProjectInterpreter: () => FakeXcodeProjectInterpreter(), + }); + }); + }); + + group('MacOSProject', () { + testWithoutContext('managedDirectory', () { + final MemoryFileSystem fs = MemoryFileSystem.test(); + final MacOSProject project = MacOSProject.fromFlutter( + FakeFlutterProject(fileSystem: fs), + ); + expect(project.managedDirectory.path, 'app_name/macos/Flutter'); + }); + + testWithoutContext('module managedDirectory', () { + final MemoryFileSystem fs = MemoryFileSystem.test(); + final MacOSProject project = MacOSProject.fromFlutter( + FakeFlutterProject(fileSystem: fs), + ); + expect(project.managedDirectory.path, 'app_name/macos/Flutter'); + }); + + testWithoutContext('ephemeralDirectory', () { + final MemoryFileSystem fs = MemoryFileSystem.test(); + final MacOSProject project = MacOSProject.fromFlutter( + FakeFlutterProject(fileSystem: fs), + ); + expect(project.ephemeralDirectory.path, 'app_name/macos/Flutter/ephemeral'); + }); + + testWithoutContext('flutterPluginSwiftPackageDirectory', () { + final MemoryFileSystem fs = MemoryFileSystem.test(); + final MacOSProject project = MacOSProject.fromFlutter( + FakeFlutterProject(fileSystem: fs), + ); + expect( + project.flutterPluginSwiftPackageDirectory.path, + 'app_name/macos/Flutter/ephemeral/Packages/FlutterGeneratedPluginSwiftPackage', + ); + }); + + testWithoutContext('xcodeConfigFor', () { + final MemoryFileSystem fs = MemoryFileSystem.test(); + final MacOSProject project = MacOSProject.fromFlutter( + FakeFlutterProject(fileSystem: fs), + ); + expect( + project.xcodeConfigFor('Debug').path, + 'app_name/macos/Flutter/Flutter-Debug.xcconfig', + ); + }); + }); +} + +class FakeFlutterProject extends Fake implements FlutterProject { + FakeFlutterProject({ + required this.fileSystem, + this.isModule = false, + }); + + MemoryFileSystem fileSystem; + + @override + late final Directory directory = fileSystem.directory('app_name'); + + @override + bool isModule = false; +} + +class FakeXcodeProjectInterpreter extends Fake implements XcodeProjectInterpreter { + FakeXcodeProjectInterpreter({ + this.isInstalled = true, + }); + + @override + final bool isInstalled; + + @override + Future getInfo(String projectPath, {String? projectFilename}) async { + return XcodeProjectInfo( + [], + [], + ['Runner'], + BufferLogger.test(), + ); + } +} diff --git a/flutter/packages/flutter_tools/test/host_cross_arch.shard/cache_test.dart b/flutter/packages/flutter_tools/test/host_cross_arch.shard/cache_test.dart new file mode 100644 index 0000000000000000000000000000000000000000..1da650ab8675aab801b7d966bdde80d30c0aadf9 --- /dev/null +++ b/flutter/packages/flutter_tools/test/host_cross_arch.shard/cache_test.dart @@ -0,0 +1,62 @@ +// 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/base/io.dart'; +import 'package:flutter_tools/src/base/logger.dart'; +import 'package:flutter_tools/src/base/os.dart'; + +import '../integration.shard/test_utils.dart'; +import '../src/common.dart'; + +Future main() async { + test('verify the dart binary arch matches the host arch', () async { + final HostPlatform dartArch = _identifyMacBinaryArch(_dartBinary.path); + final OperatingSystemUtils os = OperatingSystemUtils( + processManager: processManager, + fileSystem: fileSystem, + platform: platform, + logger: BufferLogger.test(), + ); + expect(dartArch, os.hostPlatform); + }, skip: !platform.isMacOS); // [intended] Calls macOS-specific commands +} + +// Call `file` on the path and parse the output. +HostPlatform _identifyMacBinaryArch(String path) { + // Expect STDOUT like: + // bin/cache/dart-sdk/bin/dart: Mach-O 64-bit executable x86_64 + final RegExp pattern = RegExp(r'Mach-O 64-bit executable (\w+)'); + final ProcessResult result = processManager.runSync( + ['file', _dartBinary.path], + ); + expect( + result, + ProcessResultMatcher( + stdoutPattern: '${_dartBinary.path}: Mach-O 64-bit executable', + ), + ); + final RegExpMatch? match = pattern.firstMatch(result.stdout as String); + if (match == null) { + fail('Unrecognized STDOUT from `file`: "${result.stdout}"'); + } + switch (match.group(1)) { + case 'x86_64': + return HostPlatform.darwin_x64; + case 'arm64': + return HostPlatform.darwin_arm64; + default: + fail('Unexpected architecture ${match.group(1)}'); + } +} + +final String _flutterRootPath = getFlutterRoot(); +final Directory _flutterRoot = fileSystem.directory(_flutterRootPath); +final File _dartBinary = _flutterRoot + .childDirectory('bin') + .childDirectory('cache') + .childDirectory('dart-sdk') + .childDirectory('bin') + .childFile('dart') + .absolute; diff --git a/flutter/packages/flutter_tools/test/host_cross_arch.shard/ios_content_validation_test.dart b/flutter/packages/flutter_tools/test/host_cross_arch.shard/ios_content_validation_test.dart new file mode 100644 index 0000000000000000000000000000000000000000..8b68c28be8d3edd49c1736f84a26e8033bcc0ca0 --- /dev/null +++ b/flutter/packages/flutter_tools/test/host_cross_arch.shard/ios_content_validation_test.dart @@ -0,0 +1,360 @@ +// Copyright 2014 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +import 'package:file_testing/file_testing.dart'; +import 'package:flutter_tools/src/base/file_system.dart'; +import 'package:flutter_tools/src/base/io.dart'; +import 'package:flutter_tools/src/base/utils.dart'; +import 'package:flutter_tools/src/build_info.dart'; + +import '../integration.shard/test_utils.dart'; +import '../src/common.dart'; + +void main() { + group('iOS app validation', () { + late String flutterRoot; + late Directory pluginRoot; + late String projectRoot; + late String flutterBin; + late Directory tempDir; + late File hiddenFile; + + setUpAll(() { + flutterRoot = getFlutterRoot(); + tempDir = createResolvedTempDirectorySync('ios_content_validation.'); + flutterBin = fileSystem.path.join( + flutterRoot, + 'bin', + 'flutter', + ); + + final Directory xcframeworkArtifact = fileSystem.directory( + fileSystem.path.join( + flutterRoot, + 'bin', + 'cache', + 'artifacts', + 'engine', + 'ios', + 'Flutter.xcframework', + ), + ); + + // Pre-cache iOS engine Flutter.xcframework artifacts. + ProcessResult result = processManager.runSync( + [ + flutterBin, + ...getLocalEngineArguments(), + 'precache', + '--ios', + ], + workingDirectory: tempDir.path, + ); + expect(result, const ProcessResultMatcher()); + + // Pretend the SDK was on an external drive with stray "._" files in the xcframework + hiddenFile = xcframeworkArtifact.childFile('._Info.plist')..createSync(); + + // Test a plugin example app to allow plugins validation. + result = processManager.runSync([ + flutterBin, + ...getLocalEngineArguments(), + 'create', + '--verbose', + '--platforms=ios', + '-t', + 'plugin', + 'hello', + ], workingDirectory: tempDir.path); + expect(result, const ProcessResultMatcher()); + + pluginRoot = tempDir.childDirectory('hello'); + projectRoot = pluginRoot.childDirectory('example').path; + }); + + tearDownAll(() { + tryToDelete(hiddenFile); + tryToDelete(tempDir); + }); + + for (final BuildMode buildMode in [BuildMode.debug, BuildMode.release]) { + group('build in ${buildMode.cliName} mode', () { + late Directory outputPath; + late Directory outputApp; + late Directory frameworkDirectory; + late Directory outputFlutterFramework; + late File outputFlutterFrameworkBinary; + late Directory outputAppFramework; + late File outputAppFrameworkBinary; + late File outputPluginFrameworkBinary; + late Directory buildPath; + late Directory buildAppFrameworkDsym; + late File buildAppFrameworkDsymBinary; + late ProcessResult buildResult; + + setUpAll(() { + buildResult = processManager.runSync([ + flutterBin, + ...getLocalEngineArguments(), + 'build', + 'ios', + '--verbose', + '--no-codesign', + '--${buildMode.cliName}', + '--obfuscate', + '--split-debug-info=foo debug info/', + ], workingDirectory: projectRoot); + + outputPath = fileSystem.directory(fileSystem.path.join( + projectRoot, + 'build', + 'ios', + 'iphoneos', + )); + + outputApp = outputPath.childDirectory('Runner.app'); + + frameworkDirectory = outputApp.childDirectory('Frameworks'); + outputFlutterFramework = frameworkDirectory.childDirectory('Flutter.framework'); + outputFlutterFrameworkBinary = outputFlutterFramework.childFile('Flutter'); + + outputAppFramework = frameworkDirectory.childDirectory('App.framework'); + outputAppFrameworkBinary = outputAppFramework.childFile('App'); + + outputPluginFrameworkBinary = frameworkDirectory.childDirectory('hello.framework').childFile('hello'); + + buildPath = fileSystem.directory(fileSystem.path.join( + projectRoot, + 'build', + 'ios', + '${sentenceCase(buildMode.cliName)}-iphoneos', + )); + + buildAppFrameworkDsym = buildPath.childDirectory('App.framework.dSYM'); + buildAppFrameworkDsymBinary = buildAppFrameworkDsym.childFile('Contents/Resources/DWARF/App'); + }); + + testWithoutContext('flutter build ios builds a valid app', () { + printOnFailure('Output of flutter build ios:'); + printOnFailure(buildResult.stdout.toString()); + printOnFailure(buildResult.stderr.toString()); + expect(buildResult.exitCode, 0); + + expect(outputPluginFrameworkBinary, exists); + + expect(outputAppFrameworkBinary, exists); + expect(outputAppFramework.childFile('Info.plist'), exists); + + expect(buildAppFrameworkDsymBinary.existsSync(), buildMode != BuildMode.debug); + + final File vmSnapshot = fileSystem.file(fileSystem.path.join( + outputAppFramework.path, + 'flutter_assets', + 'vm_snapshot_data', + )); + + expect(vmSnapshot.existsSync(), buildMode == BuildMode.debug); + }); + + testWithoutContext('Info.plist dart VM Service Bonjour service', () { + final String infoPlistPath = fileSystem.path.join( + outputApp.path, + 'Info.plist', + ); + final ProcessResult bonjourServices = processManager.runSync( + [ + 'plutil', + '-extract', + 'NSBonjourServices', + 'xml1', + '-o', + '-', + infoPlistPath, + ], + ); + final bool bonjourServicesFound = (bonjourServices.stdout as String).contains('_dartVmService._tcp'); + expect(bonjourServicesFound, buildMode == BuildMode.debug); + + final ProcessResult localNetworkUsage = processManager.runSync( + [ + 'plutil', + '-extract', + 'NSLocalNetworkUsageDescription', + 'xml1', + '-o', + '-', + infoPlistPath, + ], + ); + final bool localNetworkUsageFound = localNetworkUsage.exitCode == 0; + expect(localNetworkUsageFound, buildMode == BuildMode.debug); + }); + + testWithoutContext('check symbols', () { + final List symbols = + AppleTestUtils.getExportedSymbols(outputAppFrameworkBinary.path); + if (buildMode == BuildMode.debug) { + expect(symbols, isEmpty); + } else { + expect(symbols, equals(AppleTestUtils.requiredSymbols)); + } + }); + + testWithoutContext('check symbols in dSYM', () { + if (buildMode == BuildMode.debug) { + // dSYM is not created for a debug build. + expect(buildAppFrameworkDsymBinary.existsSync(), isFalse); + } else { + final List symbols = + AppleTestUtils.getExportedSymbols(buildAppFrameworkDsymBinary.path); + expect(symbols, containsAll(AppleTestUtils.requiredSymbols)); + // The actual number of symbols is going to vary but there should + // be "many" in the dSYM. At the time of writing, it was 7656. + expect(symbols.length, greaterThanOrEqualTo(5000)); + } + }); + + testWithoutContext('xcode_backend embed_and_thin', () { + outputFlutterFramework.deleteSync(recursive: true); + outputAppFramework.deleteSync(recursive: true); + expect(outputFlutterFrameworkBinary.existsSync(), isFalse); + expect(outputAppFrameworkBinary.existsSync(), isFalse); + + final String xcodeBackendPath = fileSystem.path.join( + flutterRoot, + 'packages', + 'flutter_tools', + 'bin', + 'xcode_backend.sh', + ); + + // Simulate a common Xcode build setting misconfiguration + // where FLUTTER_APPLICATION_PATH is missing + final ProcessResult xcodeBackendResult = processManager.runSync( + [ + xcodeBackendPath, + 'embed_and_thin', + ], + environment: { + 'SOURCE_ROOT': fileSystem.path.join(projectRoot, 'ios'), + 'BUILT_PRODUCTS_DIR': fileSystem.path.join( + projectRoot, + 'build', + 'ios', + 'Release-iphoneos', + ), + 'TARGET_BUILD_DIR': outputPath.path, + 'FRAMEWORKS_FOLDER_PATH': 'Runner.app/Frameworks', + 'VERBOSE_SCRIPT_LOGGING': '1', + 'FLUTTER_BUILD_MODE': 'release', + 'ACTION': 'install', + 'FLUTTER_BUILD_DIR': 'build', + // Skip bitcode stripping since we just checked that above. + }, + ); + printOnFailure('Output of xcode_backend.sh:'); + printOnFailure(xcodeBackendResult.stdout.toString()); + printOnFailure(xcodeBackendResult.stderr.toString()); + + expect(xcodeBackendResult.exitCode, 0); + expect(outputFlutterFrameworkBinary.existsSync(), isTrue); + expect(outputAppFrameworkBinary.existsSync(), isTrue); + }, skip: !platform.isMacOS || buildMode != BuildMode.release); // [intended] only makes sense on macos. + + testWithoutContext('validate obfuscation', () { + // HelloPlugin class is present in project. + ProcessResult grepResult = processManager.runSync([ + 'grep', + '-r', + 'HelloPlugin', + pluginRoot.path, + ]); + // Matches exits 0. + expect(grepResult.exitCode, 0); + + // Not present in binary. + grepResult = processManager.runSync([ + 'grep', + 'HelloPlugin', + outputAppFrameworkBinary.path, + ]); + // Does not match exits 1. + expect(grepResult.exitCode, 1); + }); + }); + } + + testWithoutContext('builds all plugin architectures for simulator', () { + final ProcessResult buildSimulator = processManager.runSync( + [ + flutterBin, + ...getLocalEngineArguments(), + 'build', + 'ios', + '--simulator', + '--verbose', + '--no-codesign', + ], + workingDirectory: projectRoot, + ); + expect(buildSimulator.exitCode, 0); + + final File pluginFrameworkBinary = fileSystem.file(fileSystem.path.join( + projectRoot, + 'build', + 'ios', + 'iphonesimulator', + 'Runner.app', + 'Frameworks', + 'hello.framework', + 'hello', + )); + expect(pluginFrameworkBinary, exists); + final ProcessResult archs = processManager.runSync( + ['file', pluginFrameworkBinary.path], + ); + expect(archs.stdout, contains('Mach-O 64-bit dynamically linked shared library x86_64')); + expect(archs.stdout, contains('Mach-O 64-bit dynamically linked shared library arm64')); + }); + + testWithoutContext('build for simulator with all available architectures', () { + final ProcessResult buildSimulator = processManager.runSync( + [ + flutterBin, + ...getLocalEngineArguments(), + 'build', + 'ios', + '--simulator', + '--verbose', + '--no-codesign', + ], + workingDirectory: projectRoot, + environment: { + 'FLUTTER_XCODE_ONLY_ACTIVE_ARCH': 'NO', + }, + ); + // This test case would fail if arm64 or x86_64 simulators could not build. + expect(buildSimulator.exitCode, 0); + + final File simulatorAppFrameworkBinary = fileSystem.file(fileSystem.path.join( + projectRoot, + 'build', + 'ios', + 'iphonesimulator', + 'Runner.app', + 'Frameworks', + 'App.framework', + 'App', + )); + expect(simulatorAppFrameworkBinary, exists); + final ProcessResult archs = processManager.runSync( + ['file', simulatorAppFrameworkBinary.path], + ); + expect(archs.stdout, contains('Mach-O 64-bit dynamically linked shared library x86_64')); + expect(archs.stdout, contains('Mach-O 64-bit dynamically linked shared library arm64')); + }); + }, skip: !platform.isMacOS, // [intended] only makes sense for macos platform. + timeout: const Timeout(Duration(minutes: 7)) + ); +} diff --git a/flutter/packages/flutter_tools/test/host_cross_arch.shard/macos_content_validation_test.dart b/flutter/packages/flutter_tools/test/host_cross_arch.shard/macos_content_validation_test.dart new file mode 100644 index 0000000000000000000000000000000000000000..5bfa8ac987e88d6c88b2fc7b953d85be1a47ae96 --- /dev/null +++ b/flutter/packages/flutter_tools/test/host_cross_arch.shard/macos_content_validation_test.dart @@ -0,0 +1,185 @@ +// 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_testing/file_testing.dart'; +import 'package:flutter_tools/src/base/file_system.dart'; +import 'package:flutter_tools/src/base/io.dart'; + +import '../integration.shard/test_utils.dart'; +import '../src/common.dart'; + +void main() { + final String flutterBin = fileSystem.path.join( + getFlutterRoot(), + 'bin', + 'flutter', + ); + + setUpAll(() { + processManager.runSync([ + flutterBin, + 'config', + '--enable-macos-desktop', + ]); + }); + + for (final String buildMode in ['Debug', 'Release']) { + final String buildModeLower = buildMode.toLowerCase(); + + test('flutter build macos --$buildModeLower builds a valid app', () { + final String workingDirectory = fileSystem.path.join( + getFlutterRoot(), + 'dev', + 'integration_tests', + 'flutter_gallery', + ); + + processManager.runSync([ + flutterBin, + ...getLocalEngineArguments(), + 'clean', + ], workingDirectory: workingDirectory); + + final File podfile = fileSystem.file(fileSystem.path.join(workingDirectory, 'macos', 'Podfile')); + final File podfileLock = fileSystem.file(fileSystem.path.join(workingDirectory, 'macos', 'Podfile.lock')); + expect(podfile, exists); + expect(podfileLock, exists); + + // Simulate a newer Podfile than Podfile.lock. + podfile.setLastModifiedSync(DateTime.now()); + podfileLock.setLastModifiedSync(DateTime.now().subtract(const Duration(days: 1))); + expect(podfileLock.lastModifiedSync().isBefore(podfile.lastModifiedSync()), isTrue); + + final List buildCommand = [ + flutterBin, + ...getLocalEngineArguments(), + 'build', + 'macos', + '--$buildModeLower', + ]; + final ProcessResult result = processManager.runSync(buildCommand, workingDirectory: workingDirectory); + + printOnFailure('Output of flutter build macos:'); + printOnFailure(result.stdout.toString()); + printOnFailure(result.stderr.toString()); + expect(result.exitCode, 0); + + expect(result.stdout, contains('Running pod install')); + expect(podfile.lastModifiedSync().isBefore(podfileLock.lastModifiedSync()), isTrue); + + final Directory buildPath = fileSystem.directory(fileSystem.path.join( + workingDirectory, + 'build', + 'macos', + 'Build', + 'Products', + buildMode, + )); + + final Directory outputApp = buildPath.childDirectory('Flutter Gallery.app'); + final Directory outputAppFramework = + fileSystem.directory(fileSystem.path.join( + outputApp.path, + 'Contents', + 'Frameworks', + 'App.framework', + )); + + final File libBinary = outputAppFramework.childFile('App'); + final File libDsymBinary = + buildPath.childFile('App.framework.dSYM/Contents/Resources/DWARF/App'); + + _checkFatBinary(libBinary, buildModeLower, 'dynamically linked shared library'); + + final List libSymbols = AppleTestUtils.getExportedSymbols(libBinary.path); + + if (buildMode == 'Debug') { + // dSYM is not created for a debug build. + expect(libDsymBinary.existsSync(), isFalse); + expect(libSymbols, isEmpty); + } else { + _checkFatBinary(libDsymBinary, buildModeLower, 'dSYM companion file'); + expect(libSymbols, equals(AppleTestUtils.requiredSymbols)); + final List dSymSymbols = + AppleTestUtils.getExportedSymbols(libDsymBinary.path); + expect(dSymSymbols, containsAll(AppleTestUtils.requiredSymbols)); + // The actual number of symbols is going to vary but there should + // be "many" in the dSYM. At the time of writing, it was 19195. + expect(dSymSymbols.length, greaterThanOrEqualTo(15000)); + } + + expect(outputAppFramework.childLink('Resources'), exists); + + final File vmSnapshot = fileSystem.file(fileSystem.path.join( + outputApp.path, + 'Contents', + 'Frameworks', + 'App.framework', + 'Resources', + 'flutter_assets', + 'vm_snapshot_data', + )); + + expect(vmSnapshot.existsSync(), buildMode == 'Debug'); + + final Directory outputFlutterFramework = fileSystem.directory( + fileSystem.path.join( + outputApp.path, + 'Contents', + 'Frameworks', + 'FlutterMacOS.framework', + ), + ); + + // Check complicated macOS framework symlink structure. + final Link current = outputFlutterFramework.childDirectory('Versions').childLink('Current'); + + expect(current.targetSync(), 'A'); + + expect(outputFlutterFramework.childLink('FlutterMacOS').targetSync(), + fileSystem.path.join('Versions', 'Current', 'FlutterMacOS')); + + expect(outputFlutterFramework.childLink('Resources'), exists); + expect(outputFlutterFramework.childLink('Resources').targetSync(), + fileSystem.path.join('Versions', 'Current', 'Resources')); + + expect(outputFlutterFramework.childLink('Headers'), isNot(exists)); + expect(outputFlutterFramework.childDirectory('Headers'), isNot(exists)); + expect(outputFlutterFramework.childLink('Modules'), isNot(exists)); + expect(outputFlutterFramework.childDirectory('Modules'), isNot(exists)); + + // Build again without cleaning. + final ProcessResult secondBuild = processManager.runSync(buildCommand, workingDirectory: workingDirectory); + + printOnFailure('Output of second build:'); + printOnFailure(secondBuild.stdout.toString()); + printOnFailure(secondBuild.stderr.toString()); + expect(secondBuild.exitCode, 0); + + expect(secondBuild.stdout, isNot(contains('Running pod install'))); + + processManager.runSync([ + flutterBin, + ...getLocalEngineArguments(), + 'clean', + ], workingDirectory: workingDirectory); + }, skip: !platform.isMacOS); // [intended] only makes sense for macos platform. + } +} + +void _checkFatBinary(File file, String buildModeLower, String expectedType) { + final String archs = processManager.runSync( + ['file', file.path], + ).stdout as String; + + final bool containsX64 = archs.contains('Mach-O 64-bit $expectedType x86_64'); + final bool containsArm = archs.contains('Mach-O 64-bit $expectedType arm64'); + if (buildModeLower == 'debug') { + // Only build the architecture matching the machine running this test, not both. + expect(containsX64 ^ containsArm, isTrue, reason: 'Unexpected architecture $archs'); + } else { + expect(containsX64, isTrue, reason: 'Unexpected architecture $archs'); + expect(containsArm, isTrue, reason: 'Unexpected architecture $archs'); + } +} diff --git a/flutter/packages/flutter_tools/test/integration.shard/README.md b/flutter/packages/flutter_tools/test/integration.shard/README.md new file mode 100644 index 0000000000000000000000000000000000000000..94efcf48f78dd2db117a6bf5d43df48aaa089476 --- /dev/null +++ b/flutter/packages/flutter_tools/test/integration.shard/README.md @@ -0,0 +1,26 @@ +# Integration tests + +These tests are not hermetic, and use the actual Flutter SDK. While +they don't require actual devices, they run `flutter_tester` to test +Dart VM and Flutter integration. + +Use this command to run (from the `flutter_tools` directory): + +```shell +../../bin/cache/dart-sdk/bin/dart run test test/integration.shard +``` + +You need to have downloaded the Dart SDK in your Flutter clone for this +to work. Running `../../bin/flutter` will automatically download it. + +## Coverage exclusion + +These tests are expensive to run and do not give meaningful coverage +information for the `flutter` tool (since they are black-box tests that +run the tool as a subprocess, rather than being unit tests). For this +reason, they are in a separate shard when running on continuous +integration and are not run when calculating coverage. + +## Adding new test files + +When adding a new test file make sure that it ends with `_test.dart`, or else it will not be run. diff --git a/flutter/packages/flutter_tools/test/integration.shard/analyze_all_templates_test.dart b/flutter/packages/flutter_tools/test/integration.shard/analyze_all_templates_test.dart new file mode 100644 index 0000000000000000000000000000000000000000..fb1b04e3aaf3eda32ad4d96e04af7f753d7cc3c1 --- /dev/null +++ b/flutter/packages/flutter_tools/test/integration.shard/analyze_all_templates_test.dart @@ -0,0 +1,46 @@ +// 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/base/io.dart'; +import 'package:flutter_tools/src/globals.dart' as globals; + +import '../src/common.dart'; +import '../src/context.dart'; +import '../src/test_flutter_command_runner.dart'; +import 'test_utils.dart'; + +void main() { + group('pass analyze template:', () { + final List templates = [ + 'app', + 'module', + 'package', + 'plugin', + 'plugin_ffi', + 'skeleton', + ]; + late Directory tempDir; + + setUp(() { + tempDir = globals.fs.systemTempDirectory + .createTempSync('flutter_tools_analyze_all_template.'); + }); + + tearDown(() { + tryToDelete(tempDir); + }); + + for (final String template in templates) { + testUsingContext('analysis for $template', () async { + final String projectPath = await createProject(tempDir, + arguments: ['--no-pub', '--template', template]); + final ProcessResult result = await globals.processManager + .run(['flutter', 'analyze'], workingDirectory: projectPath); + + expect(result, const ProcessResultMatcher()); + }); + } + }); +} diff --git a/flutter/packages/flutter_tools/test/integration.shard/analyze_once_test.dart b/flutter/packages/flutter_tools/test/integration.shard/analyze_once_test.dart new file mode 100644 index 0000000000000000000000000000000000000000..6f78a977c6dd1eb76a4eae0aa677d89a9c8f5c66 --- /dev/null +++ b/flutter/packages/flutter_tools/test/integration.shard/analyze_once_test.dart @@ -0,0 +1,480 @@ +// 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/file_system.dart'; +import 'package:flutter_tools/src/base/io.dart'; +import '../src/common.dart'; +import 'test_utils.dart'; + +final String analyzerSeparator = platform.isWindows ? '-' : '•'; + +void main() { + late Directory tempDir; + late String projectPath; + late File libMain; + late File errorFile; + + Future runCommand({ + List arguments = const [], + List statusTextContains = const [], + List errorTextContains = const [], + String exitMessageContains = '', + int exitCode = 0, + }) async { + final ProcessResult result = await processManager.run([ + fileSystem.path.join(getFlutterRoot(), 'bin', 'flutter'), + '--no-color', + ...arguments, + ], workingDirectory: projectPath); + expect(result, ProcessResultMatcher(exitCode: exitCode)); + assertContains(result.stdout.toString(), statusTextContains); + assertContains(result.stdout.toString(), errorTextContains); + expect(result.stderr, contains(exitMessageContains)); + } + + void createDotPackages(String projectPath, [bool nullSafe = false]) { + final StringBuffer flutterRootUri = StringBuffer('file://'); + final String canonicalizedFlutterRootPath = fileSystem.path.canonicalize(getFlutterRoot()); + if (platform.isWindows) { + flutterRootUri + ..write('/') + ..write(canonicalizedFlutterRootPath.replaceAll(r'\', '/')); + } else { + flutterRootUri.write(canonicalizedFlutterRootPath); + } + final String dotPackagesSrc = ''' +{ + "configVersion": 2, + "packages": [ + { + "name": "flutter", + "rootUri": "$flutterRootUri/packages/flutter", + "packageUri": "lib/", + "languageVersion": "2.12" + }, + { + "name": "sky_engine", + "rootUri": "$flutterRootUri/bin/cache/pkg/sky_engine", + "packageUri": "lib/", + "languageVersion": "2.12" + }, + { + "name": "flutter_project", + "rootUri": "../", + "packageUri": "lib/", + "languageVersion": "${nullSafe ? "2.12" : "2.7"}" + } + ] +} +'''; + + fileSystem.file(fileSystem.path.join(projectPath, '.dart_tool', 'package_config.json')) + ..createSync(recursive: true) + ..writeAsStringSync(dotPackagesSrc); + } + + setUp(() { + tempDir = fileSystem.systemTempDirectory.createTempSync('flutter_analyze_once_test_1.').absolute; + projectPath = fileSystem.path.join(tempDir.path, 'flutter_project'); + final String projectWithErrors = fileSystem.path.join(tempDir.path, 'flutter_project_errors'); + fileSystem.file(fileSystem.path.join(projectPath, 'pubspec.yaml')) + ..createSync(recursive: true) + ..writeAsStringSync(pubspecYamlSrc); + createDotPackages(projectPath); + libMain = fileSystem.file(fileSystem.path.join(projectPath, 'lib', 'main.dart')) + ..createSync(recursive: true) + ..writeAsStringSync(mainDartSrc); + errorFile = fileSystem.file(fileSystem.path.join(projectWithErrors, 'other', 'error.dart')) + ..createSync(recursive: true) + ..writeAsStringSync(r"""import 'package:flutter/material.dart"""); + }); + + tearDown(() { + tryToDelete(tempDir); + }); + + // Analyze in the current directory - no arguments + testWithoutContext('working directory', () async { + await runCommand( + arguments: ['analyze', '--no-pub'], + statusTextContains: ['No issues found!'], + ); + }); + + testWithoutContext('passing one file works', () async { + await runCommand( + arguments: ['analyze', '--no-pub', libMain.path], + statusTextContains: ['No issues found!'] + ); + }); + + testWithoutContext('passing one file with errors are detected', () async { + await runCommand( + arguments: ['analyze', '--no-pub', errorFile.path], + statusTextContains: [ + 'Analyzing error.dart', + "error $analyzerSeparator Target of URI doesn't exist", + "error $analyzerSeparator Expected to find ';'", + 'error $analyzerSeparator Unterminated string literal', + ], + exitMessageContains: '3 issues found', + exitCode: 1 + ); + }); + + testWithoutContext('passing more than one file with errors', () async { + await runCommand( + arguments: ['analyze', '--no-pub', libMain.path, errorFile.path], + statusTextContains: [ + 'Analyzing 2 items', + "error $analyzerSeparator Target of URI doesn't exist", + "error $analyzerSeparator Expected to find ';'", + 'error $analyzerSeparator Unterminated string literal', + ], + exitMessageContains: '3 issues found', + exitCode: 1 + ); + }); + + testWithoutContext('passing more than one file success', () async { + final File secondFile = fileSystem.file(fileSystem.path.join(projectPath, 'lib', 'second.dart')) + ..createSync(recursive: true) + ..writeAsStringSync(''); + await runCommand( + arguments: ['analyze', '--no-pub', libMain.path, secondFile.path], + statusTextContains: ['No issues found!'] + ); + }); + + testWithoutContext('mixing directory and files success', () async { + await runCommand( + arguments: ['analyze', '--no-pub', libMain.path, projectPath], + statusTextContains: ['No issues found!'] + ); + }); + + testWithoutContext('file not found', () async { + await runCommand( + arguments: ['analyze', '--no-pub', 'not_found.abc'], + exitMessageContains: "not_found.abc', however it does not exist on disk", + exitCode: 1 + ); + }); + + // Analyze in the current directory - no arguments + testWithoutContext('working directory with errors', () async { + // Break the code to produce an error and a warning. + // Also insert a statement that should not trigger a lint here + // but will trigger a lint later on when an analysis_options.yaml is added. + String source = await libMain.readAsString(); + source = source.replaceFirst( + 'onPressed: _incrementCounter,', + '// onPressed: _incrementCounter,', + ); + source = source.replaceFirst( + '_counter++;', + '_counter++; throw "an error message";', + ); + libMain.writeAsStringSync(source); + + // Analyze in the current directory - no arguments + await runCommand( + arguments: ['analyze', '--no-pub'], + statusTextContains: [ + 'Analyzing', + 'unused_element', + 'missing_required_param', + ], + exitMessageContains: '2 issues found.', + exitCode: 1, + ); + }); + + // Analyze in the current directory - no arguments + testWithoutContext('working directory with local options', () async { + // Insert an analysis_options.yaml file in the project + // which will trigger a lint for broken code that was inserted earlier + final File optionsFile = fileSystem.file(fileSystem.path.join(projectPath, 'analysis_options.yaml')); + optionsFile.writeAsStringSync(''' + linter: + rules: + - only_throw_errors + '''); + String source = libMain.readAsStringSync(); + source = source.replaceFirst( + 'onPressed: _incrementCounter,', + '// onPressed: _incrementCounter,', + ); + source = source.replaceFirst( + '_counter++;', + '_counter++; throw "an error message";', + ); + libMain.writeAsStringSync(source); + + // Analyze in the current directory - no arguments + await runCommand( + arguments: ['analyze', '--no-pub'], + statusTextContains: [ + 'Analyzing', + 'unused_element', + 'only_throw_errors', + 'missing_required_param', + ], + exitMessageContains: '3 issues found.', + exitCode: 1, + ); + }); + + testWithoutContext('analyze once no duplicate issues', () async { + final File foo = fileSystem.file(fileSystem.path.join(projectPath, 'foo.dart')); + foo.writeAsStringSync(''' +import 'bar.dart'; + +void foo() => bar(); +'''); + + final File bar = fileSystem.file(fileSystem.path.join(projectPath, 'bar.dart')); + bar.writeAsStringSync(''' +import 'dart:async'; // unused + +void bar() { +} +'''); + + // Analyze in the current directory - no arguments + await runCommand( + arguments: ['analyze', '--no-pub'], + statusTextContains: [ + 'Analyzing', + ], + exitMessageContains: '1 issue found.', + exitCode: 1 + ); + }); + + testWithoutContext('analyze once returns no issues when source is error-free', () async { + const String contents = ''' +StringBuffer bar = StringBuffer('baz'); +'''; + + fileSystem.directory(projectPath).childFile('main.dart').writeAsStringSync(contents); + await runCommand( + arguments: ['analyze', '--no-pub'], + statusTextContains: ['No issues found!'], + ); + }); + + testWithoutContext('analyze once returns no issues for todo comments', () async { + const String contents = ''' +// TODO(foobar): +StringBuffer bar = StringBuffer('baz'); +'''; + + fileSystem.directory(projectPath).childFile('main.dart').writeAsStringSync(contents); + await runCommand( + arguments: ['analyze', '--no-pub'], + statusTextContains: ['No issues found!'], + ); + }); + + testWithoutContext('analyze once with default options has info issue finally exit code 1.', () async { + const String infoSourceCode = ''' +int analyze() {} +'''; + + final File optionsFile = fileSystem.file(fileSystem.path.join(projectPath, 'analysis_options.yaml')); + optionsFile.writeAsStringSync(''' +analyzer: + errors: + missing_return: info + '''); + + fileSystem.directory(projectPath).childFile('main.dart').writeAsStringSync(infoSourceCode); + await runCommand( + arguments: ['analyze', '--no-pub'], + statusTextContains: [ + 'info', + 'missing_return', + ], + exitMessageContains: '1 issue found.', + exitCode: 1, + ); + }); + + testWithoutContext('analyze once with no-fatal-infos has info issue finally exit code 0.', () async { + const String infoSourceCode = ''' +int analyze() {} +'''; + + final File optionsFile = fileSystem.file(fileSystem.path.join(projectPath, 'analysis_options.yaml')); + optionsFile.writeAsStringSync(''' +analyzer: + errors: + missing_return: info + '''); + + fileSystem.directory(projectPath).childFile('main.dart').writeAsStringSync(infoSourceCode); + await runCommand( + arguments: ['analyze', '--no-pub', '--no-fatal-infos'], + statusTextContains: [ + 'info', + 'missing_return', + ], + exitMessageContains: '1 issue found.', + ); + }); + + testWithoutContext('analyze once only fatal-warnings has info issue finally exit code 0.', () async { + const String infoSourceCode = ''' +int analyze() {} +'''; + + final File optionsFile = fileSystem.file(fileSystem.path.join(projectPath, 'analysis_options.yaml')); + optionsFile.writeAsStringSync(''' +analyzer: + errors: + missing_return: info + '''); + + fileSystem.directory(projectPath).childFile('main.dart').writeAsStringSync(infoSourceCode); + await runCommand( + arguments: ['analyze', '--no-pub', '--fatal-warnings', '--no-fatal-infos'], + statusTextContains: [ + 'info', + 'missing_return', + ], + exitMessageContains: '1 issue found.', + ); + }); + + testWithoutContext('analyze once only fatal-infos has warning issue finally exit code 0.', () async { + const String warningSourceCode = ''' +int analyze() {} +'''; + + final File optionsFile = fileSystem.file(fileSystem.path.join(projectPath, 'analysis_options.yaml')); + optionsFile.writeAsStringSync(''' +analyzer: + errors: + missing_return: warning + '''); + + fileSystem.directory(projectPath).childFile('main.dart').writeAsStringSync(warningSourceCode); + await runCommand( + arguments: ['analyze','--no-pub', '--fatal-infos', '--no-fatal-warnings'], + statusTextContains: [ + 'warning', + 'missing_return', + ], + exitMessageContains: '1 issue found.', + ); + }); + + + testWithoutContext('analyze once only fatal-warnings has warning issue finally exit code 1.', () async { + const String warningSourceCode = ''' +int analyze() {} +'''; + + final File optionsFile = fileSystem.file(fileSystem.path.join(projectPath, 'analysis_options.yaml')); + optionsFile.writeAsStringSync(''' +analyzer: + errors: + missing_return: warning + '''); + + fileSystem.directory(projectPath).childFile('main.dart').writeAsStringSync(warningSourceCode); + await runCommand( + arguments: ['analyze','--no-pub', '--no-fatal-infos', '--fatal-warnings'], + statusTextContains: [ + 'warning', + 'missing_return', + ], + exitMessageContains: '1 issue found.', + exitCode: 1, + ); + }); +} + +void assertContains(String text, List patterns) { + for (final String pattern in patterns) { + expect(text, contains(pattern)); + } +} + +const String mainDartSrc = r''' +import 'package:flutter/material.dart'; + +void main() => runApp(MyApp()); + +class MyApp extends StatelessWidget { + @override + Widget build(BuildContext context) { + return MaterialApp( + title: 'Flutter Demo', + theme: ThemeData( + primarySwatch: Colors.blue, + ), + home: MyHomePage(title: 'Flutter Demo Home Page'), + ); + } +} + +class MyHomePage extends StatefulWidget { + MyHomePage({Key key, this.title}) : super(key: key); + + final String title; + + @override + _MyHomePageState createState() => _MyHomePageState(); +} + +class _MyHomePageState extends State { + int _counter = 0; + + void _incrementCounter() { + setState(() { + _counter++; + }); + } + + @override + Widget build(BuildContext context) { + return Scaffold( + appBar: AppBar( + title: Text(widget.title), + ), + body: Center( + child: Column( + mainAxisAlignment: MainAxisAlignment.center, + children: [ + Text( + 'You have pushed the button this many times:', + ), + Text( + '$_counter', + style: Theme.of(context).textTheme.headlineMedium, + ), + ], + ), + ), + floatingActionButton: FloatingActionButton( + onPressed: _incrementCounter, + tooltip: 'Increment', + child: Icon(Icons.add), + ), + ); + } +} +'''; + +const String pubspecYamlSrc = r''' +name: flutter_project +environment: + sdk: '>=3.2.0-0 <4.0.0' + +dependencies: + flutter: + sdk: flutter +'''; diff --git a/flutter/packages/flutter_tools/test/integration.shard/analyze_size_test.dart b/flutter/packages/flutter_tools/test/integration.shard/analyze_size_test.dart new file mode 100644 index 0000000000000000000000000000000000000000..13e85cb5e742bdf242fcd9d29ac25ade60d188c5 --- /dev/null +++ b/flutter/packages/flutter_tools/test/integration.shard/analyze_size_test.dart @@ -0,0 +1,225 @@ +// 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_testing/file_testing.dart'; +import 'package:flutter_tools/src/base/io.dart'; + +import '../src/common.dart'; +import 'test_utils.dart'; + +// This test file does not use [getLocalEngineArguments] because it requires +// multiple specific artifact output types. + +const String apkDebugMessage = 'A summary of your APK analysis can be found at: '; +const String iosDebugMessage = 'A summary of your iOS bundle analysis can be found at: '; +const String macOSDebugMessage = 'A summary of your macOS bundle analysis can be found at: '; +const String runDevToolsMessage = 'dart devtools '; + +void main() { + testWithoutContext('--analyze-size flag produces expected output on hello_world for Android', () async { + final String workingDirectory = fileSystem.path.join(getFlutterRoot(), 'examples', 'hello_world'); + final String flutterBin = fileSystem.path.join(getFlutterRoot(), 'bin', 'flutter'); + final ProcessResult result = await processManager.run([ + flutterBin, + 'build', + 'apk', + '--verbose', + '--analyze-size', + '--target-platform=android-arm64', + ], workingDirectory: workingDirectory); + + expect( + result, + const ProcessResultMatcher(stdoutPattern: 'app-release.apk (total compressed)'), + ); + + final String line = result.stdout.toString() + .split('\n') + .firstWhere((String line) => line.contains(apkDebugMessage)); + + final String outputFilePath = line.split(apkDebugMessage).last.trim(); + expect(fileSystem.file(fileSystem.path.join(workingDirectory, outputFilePath)), exists); + expect(outputFilePath, contains('.flutter-devtools')); + + final String devToolsCommand = result.stdout.toString() + .split('\n') + .firstWhere((String line) => line.contains(runDevToolsMessage)); + final String commandArguments = devToolsCommand.split(runDevToolsMessage).last.trim(); + final String relativeAppSizePath = outputFilePath.split('.flutter-devtools/').last.trim(); + expect(commandArguments.contains('--appSizeBase=$relativeAppSizePath'), isTrue); + }); + + testWithoutContext('--analyze-size flag produces expected output on hello_world for iOS', () async { + final String workingDirectory = fileSystem.path.join(getFlutterRoot(), 'examples', 'hello_world'); + final String flutterBin = fileSystem.path.join(getFlutterRoot(), 'bin', 'flutter'); + final Directory tempDir = fileSystem.systemTempDirectory.createTempSync('flutter_size_test.'); + final Directory codeSizeDir = tempDir.childDirectory('code size dir')..createSync(); + final ProcessResult result = await processManager.run([ + flutterBin, + 'build', + 'ios', + '--verbose', + '--analyze-size', + '--code-size-directory=${codeSizeDir.path}', + '--no-codesign', + ], workingDirectory: workingDirectory); + + expect( + result, + const ProcessResultMatcher(stdoutPattern: 'Dart AOT symbols accounted decompressed size'), + ); + + final String line = result.stdout.toString() + .split('\n') + .firstWhere((String line) => line.contains(iosDebugMessage)); + + final String outputFilePath = line.split(iosDebugMessage).last.trim(); + expect(fileSystem.file(fileSystem.path.join(workingDirectory, outputFilePath)), exists); + + final String devToolsCommand = result.stdout.toString() + .split('\n') + .firstWhere((String line) => line.contains(runDevToolsMessage)); + final String commandArguments = devToolsCommand.split(runDevToolsMessage).last.trim(); + final String relativeAppSizePath = outputFilePath.split('.flutter-devtools/').last.trim(); + + expect(commandArguments.contains('--appSizeBase=$relativeAppSizePath'), isTrue); + expect(codeSizeDir.existsSync(), true); + tempDir.deleteSync(recursive: true); + }, skip: !platform.isMacOS); // [intended] iOS can only be built on macos. + + testWithoutContext('--analyze-size flag produces expected output on hello_world for macOS', () async { + final String workingDirectory = fileSystem.path.join(getFlutterRoot(), 'examples', 'hello_world'); + final String flutterBin = fileSystem.path.join(getFlutterRoot(), 'bin', 'flutter'); + final Directory tempDir = fileSystem.systemTempDirectory.createTempSync('flutter_size_test.'); + final Directory codeSizeDir = tempDir.childDirectory('code size dir')..createSync(); + + final ProcessResult configResult = await processManager.run([ + flutterBin, + 'config', + '--verbose', + '--enable-macos-desktop', + ], workingDirectory: workingDirectory); + + expect( + configResult, + const ProcessResultMatcher(), + ); + + printOnFailure('Output of flutter config:'); + printOnFailure(configResult.stdout.toString()); + printOnFailure(configResult.stderr.toString()); + + final ProcessResult result = await processManager.run([ + flutterBin, + 'build', + 'macos', + '--analyze-size', + '--code-size-directory=${codeSizeDir.path}', + ], workingDirectory: workingDirectory); + + expect( + result, + const ProcessResultMatcher(stdoutPattern: 'Dart AOT symbols accounted decompressed size'), + ); + + final String line = result.stdout.toString() + .split('\n') + .firstWhere((String line) => line.contains(macOSDebugMessage)); + + final String outputFilePath = line.split(macOSDebugMessage).last.trim(); + expect(fileSystem.file(fileSystem.path.join(workingDirectory, outputFilePath)), exists); + + final String devToolsCommand = result.stdout.toString() + .split('\n') + .firstWhere((String line) => line.contains(runDevToolsMessage)); + final String commandArguments = devToolsCommand.split(runDevToolsMessage).last.trim(); + final String relativeAppSizePath = outputFilePath.split('.flutter-devtools/').last.trim(); + + expect(commandArguments.contains('--appSizeBase=$relativeAppSizePath'), isTrue); + expect(codeSizeDir.existsSync(), true); + tempDir.deleteSync(recursive: true); + }, skip: !platform.isMacOS); // [intended] this is a macos only test. + + testWithoutContext('--analyze-size is only supported in release mode', () async { + final String flutterBin = fileSystem.path.join(getFlutterRoot(), 'bin', 'flutter'); + final ProcessResult result = await processManager.run([ + flutterBin, + 'build', + 'apk', + '--verbose', + '--analyze-size', + '--target-platform=android-arm64', + '--debug', + ], workingDirectory: fileSystem.path.join(getFlutterRoot(), 'examples', 'hello_world')); + expect( + result, + const ProcessResultMatcher( + exitCode: 1, + stderrPattern: '"--analyze-size" can only be used on release builds', + ), + ); + }); + + testWithoutContext('--analyze-size is not supported in combination with --split-debug-info', () async { + final String flutterBin = fileSystem.path.join(getFlutterRoot(), 'bin', 'flutter'); + final List command = [ + flutterBin, + 'build', + 'apk', + '--verbose', + '--analyze-size', + '--target-platform=android-arm64', + '--split-debug-info=infos', + ]; + final String workingDirectory = + fileSystem.path.join(getFlutterRoot(), 'examples', 'hello_world'); + final ProcessResult result = + await processManager.run(command, workingDirectory: workingDirectory); + + expect( + result, + const ProcessResultMatcher( + exitCode: 1, + stderrPattern: '"--analyze-size" cannot be combined with "--split-debug-info"', + ), + ); + }); + + testWithoutContext('--analyze-size allows overriding the directory for code size files', () async { + final String flutterBin = fileSystem.path.join(getFlutterRoot(), 'bin', 'flutter'); + final Directory tempDir = fileSystem.systemTempDirectory.createTempSync('flutter_size_test.'); + + final List command = [ + flutterBin, + 'build', + 'apk', + '--verbose', + '--analyze-size', + '--code-size-directory=${tempDir.path}', + '--target-platform=android-arm64', + '--release', + ]; + final String workingDirectory = fileSystem.path.join( + getFlutterRoot(), + 'examples', + 'hello_world', + ); + final ProcessResult result = await processManager.run( + command, + workingDirectory: workingDirectory, + ); + + expect( + result, + const ProcessResultMatcher(), + ); + + expect(tempDir, exists); + expect(tempDir.childFile('snapshot.arm64-v8a.json'), exists); + expect(tempDir.childFile('trace.arm64-v8a.json'), exists); + + tempDir.deleteSync(recursive: true); + }); +} diff --git a/flutter/packages/flutter_tools/test/integration.shard/analyze_suggestions_integration_test.dart b/flutter/packages/flutter_tools/test/integration.shard/analyze_suggestions_integration_test.dart new file mode 100644 index 0000000000000000000000000000000000000000..bac0d2f80c71b962190c129e1a85361a1d4c94aa --- /dev/null +++ b/flutter/packages/flutter_tools/test/integration.shard/analyze_suggestions_integration_test.dart @@ -0,0 +1,170 @@ +// 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:args/command_runner.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/commands/analyze.dart'; +import 'package:flutter_tools/src/globals.dart' as globals; +import 'package:flutter_tools/src/project.dart'; +import 'package:flutter_tools/src/project_validator.dart'; + +import '../src/common.dart'; +import '../src/context.dart'; +import '../src/test_flutter_command_runner.dart'; +import 'test_utils.dart'; + +void main() { + late FileSystem fileSystem; + + group('analyze --suggestions command integration', () { + + setUp(() { + fileSystem = globals.localFileSystem; + }); + + testUsingContext('General Info Project Validator', () async { + final BufferLogger loggerTest = BufferLogger.test(); + final AnalyzeCommand command = AnalyzeCommand( + artifacts: globals.artifacts!, + fileSystem: fileSystem, + logger: loggerTest, + platform: globals.platform, + terminal: globals.terminal, + processManager: globals.processManager, + allProjectValidators: [GeneralInfoProjectValidator()], + suppressAnalytics: true, + ); + final CommandRunner runner = createTestCommandRunner(command); + + await runner.run([ + 'analyze', + '--no-pub', + '--no-current-package', + '--suggestions', + '../../dev/integration_tests/flutter_gallery', + ]); + + const String expected = '\n' + '┌───────────────────────────────────────────────────────────────────┐\n' + '│ General Info │\n' + '│ [✓] App Name: flutter_gallery │\n' + '│ [✓] Supported Platforms: android, ios, web, macos, linux, windows │\n' + '│ [✓] Is Flutter Package: yes │\n' + '│ [✓] Uses Material Design: yes │\n' + '│ [✓] Is Plugin: no │\n' + '│ [✓] Java/Gradle/Android Gradle Plugin: ${AndroidProject.validJavaGradleAgpString} │\n' + '└───────────────────────────────────────────────────────────────────┘\n'; + + expect(loggerTest.statusText, contains(expected)); + }); + + testUsingContext('PubDependenciesProjectValidator success ', () async { + final BufferLogger loggerTest = BufferLogger.test(); + final AnalyzeCommand command = AnalyzeCommand( + artifacts: globals.artifacts!, + fileSystem: fileSystem, + logger: loggerTest, + platform: globals.platform, + terminal: globals.terminal, + processManager: globals.processManager, + allProjectValidators: [ + PubDependenciesProjectValidator(globals.processManager), + ], + suppressAnalytics: true, + ); + final CommandRunner runner = createTestCommandRunner(command); + + await runner.run([ + 'analyze', + '--no-pub', + '--no-current-package', + '--suggestions', + '../../dev/integration_tests/flutter_gallery', + ]); + + const String expected = '\n' + '┌────────────────────────────────────────────────────────────────────────────────────┐\n' + '│ Pub dependencies │\n' + '│ [✓] Dart dependencies: All pub dependencies are hosted on https://pub.dartlang.org │\n' + '└────────────────────────────────────────────────────────────────────────────────────┘\n'; + expect(loggerTest.statusText, contains(expected)); + }); + }); + + group('analyze --suggestions --machine command integration', () { + late Directory tempDir; + late Platform platform; + + setUpAll(() async { + platform = const LocalPlatform(); + tempDir = createResolvedTempDirectorySync('run_test.'); + await globals.processManager.run(['flutter', 'create', 'test_project'], workingDirectory: tempDir.path); + }); + + tearDown(() async { + tryToDelete(tempDir); + }); + + testUsingContext('analyze --suggestions --machine produces expected values', () async { + final ProcessResult result = await globals.processManager.run(['flutter', 'analyze', '--suggestions', '--machine'], workingDirectory: tempDir.childDirectory('test_project').path); + + expect(result.stdout is String, true); + expect((result.stdout as String).startsWith('{\n'), true); + expect(result.stdout, isNot(contains(',\n}'))); // No trailing commas allowed in JSON + expect((result.stdout as String).endsWith('}\n'), true); + + final Map decoded = jsonDecode(result.stdout as String) as Map; + + expect(decoded.containsKey('FlutterProject.android.exists'), true); + expect(decoded.containsKey('FlutterProject.ios.exists'), true); + expect(decoded.containsKey('FlutterProject.web.exists'), true); + expect(decoded.containsKey('FlutterProject.macos.exists'), true); + expect(decoded.containsKey('FlutterProject.linux.exists'), true); + expect(decoded.containsKey('FlutterProject.windows.exists'), true); + expect(decoded.containsKey('FlutterProject.fuchsia.exists'), true); + expect(decoded.containsKey('FlutterProject.android.isKotlin'), true); + expect(decoded.containsKey('FlutterProject.ios.isSwift'), true); + expect(decoded.containsKey('FlutterProject.isModule'), true); + expect(decoded.containsKey('FlutterProject.isPlugin'), true); + expect(decoded.containsKey('FlutterProject.manifest.appname'), true); + expect(decoded.containsKey('FlutterVersion.frameworkRevision'), true); + + expect(decoded.containsKey('FlutterProject.directory'), true); + expect(decoded.containsKey('FlutterProject.metadataFile'), true); + expect(decoded.containsKey('Platform.operatingSystem'), true); + expect(decoded.containsKey('Platform.isAndroid'), true); + expect(decoded.containsKey('Platform.isIOS'), true); + expect(decoded.containsKey('Platform.isWindows'), true); + expect(decoded.containsKey('Platform.isMacOS'), true); + expect(decoded.containsKey('Platform.isFuchsia'), true); + expect(decoded.containsKey('Platform.pathSeparator'), true); + expect(decoded.containsKey('Cache.flutterRoot'), true); + + expect(decoded['FlutterProject.android.exists'], true); + expect(decoded['FlutterProject.ios.exists'], true); + expect(decoded['FlutterProject.web.exists'], true); + expect(decoded['FlutterProject.macos.exists'], true); + expect(decoded['FlutterProject.linux.exists'], true); + expect(decoded['FlutterProject.windows.exists'], true); + expect(decoded['FlutterProject.fuchsia.exists'], false); + expect(decoded['FlutterProject.android.isKotlin'], true); + expect(decoded['FlutterProject.ios.isSwift'], true); + expect(decoded['FlutterProject.isModule'], false); + expect(decoded['FlutterProject.isPlugin'], false); + expect(decoded['FlutterProject.manifest.appname'], 'test_project'); + + expect(decoded['Platform.isAndroid'], false); + expect(decoded['Platform.isIOS'], false); + expect(decoded['Platform.isWindows'], platform.isWindows); + expect(decoded['Platform.isMacOS'], platform.isMacOS); + expect(decoded['Platform.isFuchsia'], platform.isFuchsia); + expect(decoded['Platform.pathSeparator'], platform.pathSeparator); + }, overrides: {}); + }); +} diff --git a/flutter/packages/flutter_tools/test/integration.shard/android_e2e_api_test.dart b/flutter/packages/flutter_tools/test/integration.shard/android_e2e_api_test.dart new file mode 100644 index 0000000000000000000000000000000000000000..73d11c688b14790c53e4e10a8209ab533dba61ae --- /dev/null +++ b/flutter/packages/flutter_tools/test/integration.shard/android_e2e_api_test.dart @@ -0,0 +1,73 @@ +// 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/base/io.dart'; + +import '../src/common.dart'; +import 'test_utils.dart'; + +void main() { + late Directory tempDir; + + setUp(() async { + tempDir = createResolvedTempDirectorySync('run_test.'); + }); + + tearDown(() async { + tryToDelete(tempDir); + }); + + testWithoutContext('build succeeds with api 33 features', () async { + final String flutterBin = fileSystem.path.join(getFlutterRoot(), 'bin', 'flutter'); + ProcessResult result = await processManager.run([ + flutterBin, + 'create', + tempDir.path, + '--project-name=testapp', + ], workingDirectory: tempDir.path); + expect(result, const ProcessResultMatcher()); + + final File api33File = tempDir + .childDirectory('android') + .childDirectory('app') + .childDirectory('src') + .childDirectory('main') + .childDirectory('java') + .childFile('Android33Api.java'); + + api33File.createSync(recursive: true); + // AccessibilityManager.isAudioDescriptionRequested() is an API 33 feature + api33File.writeAsStringSync(''' +import android.app.Activity; +import android.view.accessibility.AccessibilityManager; +import androidx.annotation.Keep; +import io.flutter.Log; + +@Keep +public final class Android33Api extends Activity { + private AccessibilityManager accessibilityManager; + + public Android33Api() { + accessibilityManager = getSystemService(AccessibilityManager.class); + } + + public void doSomething() { + if (accessibilityManager.isAudioDescriptionRequested()) { + Log.e("flutter", "User has requested to enable audio descriptions"); + } + } +} + +'''); + + result = await processManager.run([ + flutterBin, + ...getLocalEngineArguments(), + 'build', + 'apk', + ], workingDirectory: tempDir.path); + expect(result, const ProcessResultMatcher(stdoutPattern: 'app-release.apk')); + }); +} diff --git a/flutter/packages/flutter_tools/test/integration.shard/android_gradle_daemon_cache_test.dart b/flutter/packages/flutter_tools/test/integration.shard/android_gradle_daemon_cache_test.dart new file mode 100644 index 0000000000000000000000000000000000000000..b9b3af1db55285757c23c76fff803332ffd46968 --- /dev/null +++ b/flutter/packages/flutter_tools/test/integration.shard/android_gradle_daemon_cache_test.dart @@ -0,0 +1,115 @@ +// 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/base/io.dart'; + +import '../src/common.dart'; +import 'test_utils.dart'; + +void main() { + late Directory tempDir; + + setUp(() async { + tempDir = createResolvedTempDirectorySync('gradle_daemon_test.'); + }); + + tearDown(() async { + tryToDelete(tempDir); + }); + + testWithoutContext( + 'gradle task succeeds when adding plugins with gradle daemon enabled', + () async { + final String flutterBin = + fileSystem.path.join(getFlutterRoot(), 'bin', 'flutter'); + final Directory appDir = tempDir.childDirectory('testapp'); + final Directory androidDir = appDir.childDirectory('android'); + + // Create dummy plugins + processManager.runSync([ + flutterBin, + ...getLocalEngineArguments(), + 'create', + '--template=plugin', + '--platforms=android', + 'test_plugin_one', + ], workingDirectory: tempDir.path); + processManager.runSync([ + flutterBin, + ...getLocalEngineArguments(), + 'create', + '--template=plugin', + '--platforms=android', + 'test_plugin_two', + ], workingDirectory: tempDir.path); + + // Create a new flutter project. + ProcessResult result = await processManager.run([ + flutterBin, + 'create', + appDir.path, + '--project-name=testapp', + ], workingDirectory: tempDir.path); + expect(result, const ProcessResultMatcher()); + + // Enable gradle daemon for this project + final File gradleProperties = androidDir.childFile('gradle.properties'); + gradleProperties.writeAsStringSync(r''' +org.gradle.daemon=true +''', mode: FileMode.append); + + // TODO(gustl22): Override with in 'gradle.properties' has no effect, set GRADLE_OPTS instead, + // see https://github.com/gradle/gradle/issues/19501 + final Map envVars = { + 'GRADLE_OPTS': '-Dorg.gradle.daemon=true' + }; + + // Stop gradle daemon + result = await processManager.run([ + androidDir.childFile('gradlew').path, + '--stop', + ], workingDirectory: androidDir.path); + expect(result, const ProcessResultMatcher()); + + result = await processManager.run([ + flutterBin, + 'pub', + 'add', + 'test_plugin_one', + '--path', + '../test_plugin_one', + ], workingDirectory: appDir.path, environment: envVars); + expect(result, const ProcessResultMatcher()); + + // Build with gradle daemon + result = await processManager.run([ + flutterBin, + 'build', + 'apk', + '--debug', + ], workingDirectory: appDir.path, environment: envVars); + expect(result, const ProcessResultMatcher()); + + // Add second plugin + result = await processManager.run([ + flutterBin, + 'pub', + 'add', + 'test_plugin_two', + '--path', + '../test_plugin_two', + ], workingDirectory: appDir.path, environment: envVars); + expect(result, const ProcessResultMatcher()); + + // Build again with cached plugin through daemon + result = await processManager.run([ + flutterBin, + 'build', + 'apk', + '--debug', + ], workingDirectory: appDir.path, environment: envVars); + expect(result, const ProcessResultMatcher()); + }); +} diff --git a/flutter/packages/flutter_tools/test/integration.shard/android_gradle_deprecated_plugin_apply_test.dart b/flutter/packages/flutter_tools/test/integration.shard/android_gradle_deprecated_plugin_apply_test.dart new file mode 100644 index 0000000000000000000000000000000000000000..2c68c5e446b51c664c8ecaa053f574032cecf8da --- /dev/null +++ b/flutter/packages/flutter_tools/test/integration.shard/android_gradle_deprecated_plugin_apply_test.dart @@ -0,0 +1,195 @@ +// 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:flutter_tools/src/base/io.dart'; + +import '../src/common.dart'; +import 'test_utils.dart'; + +void main() { + late Directory tempDir; + + setUp(() async { + tempDir = createResolvedTempDirectorySync('run_test.'); + }); + + tearDown(() async { + tryToDelete(tempDir); + }); + + testWithoutContext( + 'gradle prints warning when Flutter\'s Gradle plugins are applied using deprecated "apply plugin" way', () async { + // Create a new flutter project. + final String flutterBin = + fileSystem.path.join(getFlutterRoot(), 'bin', 'flutter'); + ProcessResult result = await processManager.run([ + flutterBin, + 'create', + tempDir.path, + '--project-name=testapp', + ], workingDirectory: tempDir.path); + expect(result.exitCode, 0); + // Ensure that gradle files exists from templates. + result = await processManager.run([ + flutterBin, + 'build', + 'apk', + '--config-only', + ], workingDirectory: tempDir.path); + expect(result.exitCode, 0); + + // Change build files to use deprecated "apply plugin:" way. + // Contents are taken from https://github.com/flutter/flutter/issues/135392 (for Flutter 3.10) + final File settings = tempDir.childDirectory('android').childFile('settings.gradle'); + final File buildGradle = tempDir.childDirectory('android').childFile('build.gradle'); + final File appBuildGradle = tempDir.childDirectory('android').childDirectory('app').childFile('build.gradle'); + settings.writeAsStringSync(r''' +include ':app' + +def localPropertiesFile = new File(rootProject.projectDir, "local.properties") +def properties = new Properties() + +assert localPropertiesFile.exists() +localPropertiesFile.withReader("UTF-8") { reader -> properties.load(reader) } + +def flutterSdkPath = properties.getProperty("flutter.sdk") +assert flutterSdkPath != null, "flutter.sdk not set in local.properties" +apply from: "$flutterSdkPath/packages/flutter_tools/gradle/app_plugin_loader.gradle" +''' + ); + buildGradle.writeAsStringSync(r''' +buildscript { + ext.kotlin_version = '1.7.10' + repositories { + google() + mavenCentral() + } + + dependencies { + classpath 'com.android.tools.build:gradle:7.3.0' + classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version" + } +} + +allprojects { + repositories { + google() + mavenCentral() + } +} + +rootProject.buildDir = '../build' +subprojects { + project.buildDir = "${rootProject.buildDir}/${project.name}" +} +subprojects { + project.evaluationDependsOn(':app') +} + +tasks.register("clean", Delete) { + delete rootProject.buildDir +} +'''); + appBuildGradle.writeAsStringSync(r''' +def localProperties = new Properties() +def localPropertiesFile = rootProject.file('local.properties') +if (localPropertiesFile.exists()) { + localPropertiesFile.withReader('UTF-8') { reader -> + localProperties.load(reader) + } +} + +def flutterRoot = localProperties.getProperty('flutter.sdk') +if (flutterRoot == null) { + throw new GradleException("Flutter SDK not found. Define location with flutter.sdk in the local.properties file.") +} + +def flutterVersionCode = localProperties.getProperty('flutter.versionCode') +if (flutterVersionCode == null) { + flutterVersionCode = '1' +} + +def flutterVersionName = localProperties.getProperty('flutter.versionName') +if (flutterVersionName == null) { + flutterVersionName = '1.0' +} + +apply plugin: 'com.android.application' +apply plugin: 'kotlin-android' +apply from: "$flutterRoot/packages/flutter_tools/gradle/flutter.gradle" + +android { + compileSdkVersion flutter.compileSdkVersion + ndkVersion flutter.ndkVersion + namespace "com.example.testapp" + + 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.testapp" + // You can update the following values to match your application needs. + // For more information, see: https://docs.flutter.dev/deployment/android#reviewing-the-build-configuration. + minSdkVersion flutter.minSdkVersion + targetSdkVersion flutter.targetSdkVersion + versionCode flutterVersionCode.toInteger() + versionName flutterVersionName + testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner" + } + + 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 { + implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version" +} +'''); + + result = await processManager.run([ + flutterBin, + 'build', + 'apk', + '--debug', + ], workingDirectory: tempDir.path); + expect(result.exitCode, 0); + // Verify that stderr output contains deprecation warnings. + final List actualLines = LineSplitter.split(result.stderr.toString()).toList(); + expect( + actualLines.any((String msg) => msg.contains( + "You are applying Flutter's main Gradle plugin imperatively"), + ), + isTrue, + ); + expect( + actualLines.any((String msg) => msg.contains( + "You are applying Flutter's app_plugin_loader Gradle plugin imperatively"), + ), + isTrue, + ); + }); +} diff --git a/flutter/packages/flutter_tools/test/integration.shard/android_gradle_flutter_source_path_test.dart b/flutter/packages/flutter_tools/test/integration.shard/android_gradle_flutter_source_path_test.dart new file mode 100644 index 0000000000000000000000000000000000000000..814cdfec9ab1c842208d426d06e19ea9b1f70618 --- /dev/null +++ b/flutter/packages/flutter_tools/test/integration.shard/android_gradle_flutter_source_path_test.dart @@ -0,0 +1,70 @@ +// 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/file_system.dart'; +import 'package:flutter_tools/src/base/io.dart'; +import 'package:flutter_tools/src/cache.dart'; + +import '../src/common.dart'; +import 'test_data/deferred_components_project.dart'; +import 'test_data/project.dart'; +import 'test_utils.dart'; + +void main() { + late Directory tempDir; + + setUp(() { + Cache.flutterRoot = getFlutterRoot(); + tempDir = + createResolvedTempDirectorySync('flutter_gradle_source_path_test.'); + }); + + tearDown(() async { + tryToDelete(tempDir); + }); + + test('gradle task builds without setting a source path in app/build.gradle', + () async { + final Project project = DeferredComponentsProject( + MissingFlutterSourcePathDeferredComponentsConfig(), + ); + final String flutterBin = fileSystem.path.join( + getFlutterRoot(), + 'bin', + 'flutter', + ); + + final Directory exampleAppDir = tempDir.childDirectory('example'); + await project.setUpIn(exampleAppDir); + + // Run flutter build apk to build example project. + final ProcessResult buildApkResult = processManager.runSync([ + flutterBin, + ...getLocalEngineArguments(), + 'build', + 'apk', + '--debug', + ], workingDirectory: exampleAppDir.path); + + expect(buildApkResult, const ProcessResultMatcher()); + }); +} + +class MissingFlutterSourcePathDeferredComponentsConfig + extends BasicDeferredComponentsConfig { + final String _flutterSourcePath = ''' + flutter { + source '../..' + } +'''; + + @override + String get appBuild { + if (!super.appBuild.contains(_flutterSourcePath)) { + throw Exception( + 'Flutter source path not found in original configuration!'); + } + return super.appBuild.replaceAll(_flutterSourcePath, ''); + } +} diff --git a/flutter/packages/flutter_tools/test/integration.shard/android_gradle_java_version_test.dart b/flutter/packages/flutter_tools/test/integration.shard/android_gradle_java_version_test.dart new file mode 100644 index 0000000000000000000000000000000000000000..6dea44867adb501b3867abe6fe90649d06e102d7 --- /dev/null +++ b/flutter/packages/flutter_tools/test/integration.shard/android_gradle_java_version_test.dart @@ -0,0 +1,57 @@ +// 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/android/gradle_utils.dart' + show getGradlewFileName; +import 'package:flutter_tools/src/base/io.dart'; + +import '../src/common.dart'; +import 'test_utils.dart'; + +void main() { + late Directory tempDir; + + setUp(() async { + tempDir = createResolvedTempDirectorySync('run_test.'); + }); + + tearDown(() async { + tryToDelete(tempDir); + }); + + testWithoutContext( + 'gradle task exists named javaVersion that prints jdk version', () async { + // Create a new flutter project. + final String flutterBin = + fileSystem.path.join(getFlutterRoot(), 'bin', 'flutter'); + ProcessResult result = await processManager.run([ + flutterBin, + 'create', + tempDir.path, + '--project-name=testapp', + ], workingDirectory: tempDir.path); + expect(result, const ProcessResultMatcher()); + // Ensure that gradle files exists from templates. + result = await processManager.run([ + flutterBin, + 'build', + 'apk', + '--config-only', + ], workingDirectory: tempDir.path); + expect(result, const ProcessResultMatcher()); + + final Directory androidApp = tempDir.childDirectory('android'); + result = await processManager.run([ + '.${platform.pathSeparator}${getGradlewFileName(platform)}', + ...getLocalEngineArguments(), + '-q', // quiet output. + 'javaVersion', + ], workingDirectory: androidApp.path); + // Verify that gradlew has a javaVersion task. + expect(result, const ProcessResultMatcher()); + // Verify the format is a number on its own line. + expect(result.stdout.toString(), matches(RegExp(r'\d+$', multiLine: true))); + }); +} diff --git a/flutter/packages/flutter_tools/test/integration.shard/android_gradle_outputs_app_link_settings_test.dart b/flutter/packages/flutter_tools/test/integration.shard/android_gradle_outputs_app_link_settings_test.dart new file mode 100644 index 0000000000000000000000000000000000000000..0d42ddbd94f0b2e8c156766f1de0f309a318a2c3 --- /dev/null +++ b/flutter/packages/flutter_tools/test/integration.shard/android_gradle_outputs_app_link_settings_test.dart @@ -0,0 +1,239 @@ +// 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 'dart:io' as io; + +import 'package:file/file.dart'; +import 'package:flutter_tools/src/android/gradle_utils.dart' + show getGradlewFileName; +import 'package:flutter_tools/src/base/io.dart'; +import 'package:xml/xml.dart'; + +import '../src/common.dart'; +import 'test_utils.dart'; + +final XmlElement pureHttpIntentFilter = XmlElement( + XmlName('intent-filter'), + [XmlAttribute(XmlName('autoVerify', 'android'), 'true')], + [ + XmlElement( + XmlName('action'), + [XmlAttribute(XmlName('name', 'android'), 'android.intent.action.VIEW')], + ), + XmlElement( + XmlName('category'), + [XmlAttribute(XmlName('name', 'android'), 'android.intent.category.DEFAULT')], + ), + XmlElement( + XmlName('category'), + [XmlAttribute(XmlName('name', 'android'), 'android.intent.category.BROWSABLE')], + ), + XmlElement( + XmlName('data'), + [ + XmlAttribute(XmlName('scheme', 'android'), 'http'), + XmlAttribute(XmlName('host', 'android'), 'pure-http.com'), + ], + ), + ], +); + +final XmlElement nonHttpIntentFilter = XmlElement( + XmlName('intent-filter'), + [XmlAttribute(XmlName('autoVerify', 'android'), 'true')], + [ + XmlElement( + XmlName('action'), + [XmlAttribute(XmlName('name', 'android'), 'android.intent.action.VIEW')], + ), + XmlElement( + XmlName('category'), + [XmlAttribute(XmlName('name', 'android'), 'android.intent.category.DEFAULT')], + ), + XmlElement( + XmlName('category'), + [XmlAttribute(XmlName('name', 'android'), 'android.intent.category.BROWSABLE')], + ), + XmlElement( + XmlName('data'), + [ + XmlAttribute(XmlName('scheme', 'android'), 'custom'), + XmlAttribute(XmlName('host', 'android'), 'custom.com'), + ], + ), + ], +); + +final XmlElement hybridIntentFilter = XmlElement( + XmlName('intent-filter'), + [XmlAttribute(XmlName('autoVerify', 'android'), 'true')], + [ + XmlElement( + XmlName('action'), + [XmlAttribute(XmlName('name', 'android'), 'android.intent.action.VIEW')], + ), + XmlElement( + XmlName('category'), + [XmlAttribute(XmlName('name', 'android'), 'android.intent.category.DEFAULT')], + ), + XmlElement( + XmlName('category'), + [XmlAttribute(XmlName('name', 'android'), 'android.intent.category.BROWSABLE')], + ), + XmlElement( + XmlName('data'), + [ + XmlAttribute(XmlName('scheme', 'android'), 'custom'), + XmlAttribute(XmlName('host', 'android'), 'hybrid.com'), + ], + ), + XmlElement( + XmlName('data'), + [ + XmlAttribute(XmlName('scheme', 'android'), 'http'), + ], + ), + ], +); + +final XmlElement nonAutoVerifyIntentFilter = XmlElement( + XmlName('intent-filter'), + [], + [ + XmlElement( + XmlName('action'), + [XmlAttribute(XmlName('name', 'android'), 'android.intent.action.VIEW')], + ), + XmlElement( + XmlName('category'), + [XmlAttribute(XmlName('name', 'android'), 'android.intent.category.DEFAULT')], + ), + XmlElement( + XmlName('category'), + [XmlAttribute(XmlName('name', 'android'), 'android.intent.category.BROWSABLE')], + ), + XmlElement( + XmlName('data'), + [ + XmlAttribute(XmlName('scheme', 'android'), 'http'), + XmlAttribute(XmlName('host', 'android'), 'non-auto-verify.com'), + ], + ), + ], +); + +void main() { + late Directory tempDir; + + setUp(() async { + tempDir = createResolvedTempDirectorySync('run_test.'); + }); + + tearDown(() async { + tryToDelete(tempDir); + }); + + void testDeeplink(dynamic deeplink, String scheme, String host, String path) { + deeplink as Map; + expect(deeplink['scheme'], scheme); + expect(deeplink['host'], host); + expect(deeplink['path'], path); + } + + testWithoutContext( + 'gradle task outputsAppLinkSettings works when a project has app links', () async { + // Create a new flutter project. + final String flutterBin = + fileSystem.path.join(getFlutterRoot(), 'bin', 'flutter'); + ProcessResult result = await processManager.run([ + flutterBin, + 'create', + tempDir.path, + '--project-name=testapp', + ], workingDirectory: tempDir.path); + expect(result, const ProcessResultMatcher()); + // Adds intent filters for app links + final String androidManifestPath = fileSystem.path.join(tempDir.path, 'android', 'app', 'src', 'main', 'AndroidManifest.xml'); + final io.File androidManifestFile = io.File(androidManifestPath); + final XmlDocument androidManifest = XmlDocument.parse(androidManifestFile.readAsStringSync()); + final XmlElement activity = androidManifest.findAllElements('activity').first; + activity.children.add(pureHttpIntentFilter); + activity.children.add(nonHttpIntentFilter); + activity.children.add(hybridIntentFilter); + activity.children.add(nonAutoVerifyIntentFilter); + androidManifestFile.writeAsStringSync(androidManifest.toString(), flush: true); + + // Ensure that gradle files exists from templates. + result = await processManager.run([ + flutterBin, + 'build', + 'apk', + '--config-only', + ], workingDirectory: tempDir.path); + expect(result, const ProcessResultMatcher()); + + final Directory androidApp = tempDir.childDirectory('android'); + final io.File fileDump = tempDir.childDirectory('build').childDirectory('app').childFile('app-link-settings-debug.json'); + result = await processManager.run([ + '.${platform.pathSeparator}${getGradlewFileName(platform)}', + ...getLocalEngineArguments(), + '-q', // quiet output. + '-PoutputPath=${fileDump.path}', + 'outputDebugAppLinkSettings', + ], workingDirectory: androidApp.path); + + expect(result, const ProcessResultMatcher()); + expect(fileDump.existsSync(), true); + final Map json = jsonDecode(fileDump.readAsStringSync()) as Map; + expect(json['applicationId'], 'com.example.testapp'); + final List deeplinks = json['deeplinks']! as List; + expect(deeplinks.length, 5); + testDeeplink(deeplinks[0], 'http', 'pure-http.com', '.*'); + testDeeplink(deeplinks[1], 'custom', 'custom.com', '.*'); + testDeeplink(deeplinks[2], 'custom', 'hybrid.com', '.*'); + testDeeplink(deeplinks[3], 'http', 'hybrid.com', '.*'); + testDeeplink(deeplinks[4], 'http', 'non-auto-verify.com', '.*'); + }); + + testWithoutContext( + 'gradle task outputsAppLinkSettings works when a project does not have app link', () async { + // Create a new flutter project. + final String flutterBin = + fileSystem.path.join(getFlutterRoot(), 'bin', 'flutter'); + ProcessResult result = await processManager.run([ + flutterBin, + 'create', + tempDir.path, + '--project-name=testapp', + ], workingDirectory: tempDir.path); + expect(result, const ProcessResultMatcher()); + + // Ensure that gradle files exists from templates. + result = await processManager.run([ + flutterBin, + 'build', + 'apk', + '--config-only', + ], workingDirectory: tempDir.path); + expect(result, const ProcessResultMatcher()); + + final Directory androidApp = tempDir.childDirectory('android'); + final io.File fileDump = tempDir.childDirectory('build').childDirectory('app').childFile('app-link-settings-debug.json'); + result = await processManager.run([ + '.${platform.pathSeparator}${getGradlewFileName(platform)}', + ...getLocalEngineArguments(), + '-q', // quiet output. + '-PoutputPath=${fileDump.path}', + 'outputDebugAppLinkSettings', + ], workingDirectory: androidApp.path); + + expect(result, const ProcessResultMatcher()); + expect(fileDump.existsSync(), true); + final Map json = jsonDecode(fileDump.readAsStringSync()) as Map; + expect(json['applicationId'], 'com.example.testapp'); + final List deeplinks = json['deeplinks']! as List; + expect(deeplinks.length, 0); + }); +} diff --git a/flutter/packages/flutter_tools/test/integration.shard/android_gradle_print_build_variants_test.dart b/flutter/packages/flutter_tools/test/integration.shard/android_gradle_print_build_variants_test.dart new file mode 100644 index 0000000000000000000000000000000000000000..085d3a583285ba8fecad7ea4aae4daf4b4aaa104 --- /dev/null +++ b/flutter/packages/flutter_tools/test/integration.shard/android_gradle_print_build_variants_test.dart @@ -0,0 +1,66 @@ +// 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:collection/collection.dart'; +import 'package:file/file.dart'; +import 'package:flutter_tools/src/android/gradle_utils.dart' + show getGradlewFileName; +import 'package:flutter_tools/src/base/io.dart'; + +import '../src/common.dart'; +import 'test_utils.dart'; + +void main() { + late Directory tempDir; + + setUp(() async { + tempDir = createResolvedTempDirectorySync('run_test.'); + }); + + tearDown(() async { + tryToDelete(tempDir); + }); + + testWithoutContext( + 'gradle task exists named printBuildVariants that prints build variants', () async { + // Create a new flutter project. + final String flutterBin = + fileSystem.path.join(getFlutterRoot(), 'bin', 'flutter'); + ProcessResult result = await processManager.run([ + flutterBin, + 'create', + tempDir.path, + '--project-name=testapp', + ], workingDirectory: tempDir.path); + expect(result.exitCode, 0); + // Ensure that gradle files exists from templates. + result = await processManager.run([ + flutterBin, + 'build', + 'apk', + '--config-only', + ], workingDirectory: tempDir.path); + expect(result.exitCode, 0); + + final Directory androidApp = tempDir.childDirectory('android'); + result = await processManager.run([ + '.${platform.pathSeparator}${getGradlewFileName(platform)}', + ...getLocalEngineArguments(), + '-q', // quiet output. + 'printBuildVariants', + ], workingDirectory: androidApp.path); + // Verify that gradlew has a javaVersion task. + expect(result.exitCode, 0); + // Verify the format is a number on its own line. + const List expectedLines = [ + 'BuildVariant: debug', + 'BuildVariant: release', + 'BuildVariant: profile', + ]; + final List actualLines = LineSplitter.split(result.stdout.toString()).toList(); + expect(const ListEquality().equals(actualLines, expectedLines), isTrue); + }); +} diff --git a/flutter/packages/flutter_tools/test/integration.shard/android_plugin_compilesdkversion_mismatch_test.dart b/flutter/packages/flutter_tools/test/integration.shard/android_plugin_compilesdkversion_mismatch_test.dart new file mode 100644 index 0000000000000000000000000000000000000000..cd2bb46cae7b8c10f0aaa999427d5c95d5897107 --- /dev/null +++ b/flutter/packages/flutter_tools/test/integration.shard/android_plugin_compilesdkversion_mismatch_test.dart @@ -0,0 +1,90 @@ +// 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_testing/file_testing.dart'; +import 'package:flutter_tools/src/base/file_system.dart'; +import 'package:flutter_tools/src/base/io.dart'; +import 'package:flutter_tools/src/cache.dart'; + +import '../src/common.dart'; +import 'test_utils.dart'; + +void main() { + + late Directory tempDir; + + setUp(() { + Cache.flutterRoot = getFlutterRoot(); + tempDir = createResolvedTempDirectorySync('flutter_plugin_test.'); + }); + + tearDown(() async { + tryToDelete(tempDir); + }); + + test('error logged when plugin Android compileSdk version higher than project', () async { + final String flutterBin = fileSystem.path.join( + getFlutterRoot(), + 'bin', + 'flutter', + ); + + // Create dummy plugin + processManager.runSync([ + flutterBin, + ...getLocalEngineArguments(), + 'create', + '--template=plugin', + '--platforms=android', + 'test_plugin', + ], workingDirectory: tempDir.path); + + final Directory pluginAppDir = tempDir.childDirectory('test_plugin'); + final File pluginGradleFile = pluginAppDir.childDirectory('android').childFile('build.gradle'); + expect(pluginGradleFile, exists); + + final String pluginBuildGradle = pluginGradleFile.readAsStringSync(); + + // Bump up plugin compileSdk version to 31 + final RegExp androidCompileSdkVersionRegExp = RegExp(r'compileSdk ([0-9]+|flutter.compileSdkVersion)'); + final String newPluginGradleFile = pluginBuildGradle.replaceAll( + androidCompileSdkVersionRegExp, 'compileSdk 31'); + pluginGradleFile.writeAsStringSync(newPluginGradleFile); + + final Directory pluginExampleAppDir = pluginAppDir.childDirectory('example'); + + final File projectGradleFile = pluginExampleAppDir.childDirectory('android').childDirectory('app').childFile('build.gradle'); + expect(projectGradleFile, exists); + + final String projectBuildGradle = projectGradleFile.readAsStringSync(); + + // Bump down plugin example app compileSdk version to 30 + final String newProjectGradleFile = projectBuildGradle.replaceAll( + androidCompileSdkVersionRegExp, 'compileSdk 30'); + projectGradleFile.writeAsStringSync(newProjectGradleFile); + + // Run flutter build apk to build plugin example project + final ProcessResult result = processManager.runSync([ + flutterBin, + ...getLocalEngineArguments(), + 'build', + 'apk', + '--target-platform=android-arm', + ], workingDirectory: pluginExampleAppDir.path); + + // Check error message is thrown + expect( + result.stdout, + contains( + 'Warning: The plugin test_plugin requires Android SDK version 31 or higher.')); + expect( + result.stderr, + contains('One or more plugins require a higher Android SDK version.'), + ); + expect( + result.stderr, + contains( + 'Fix this issue by adding the following to ${projectGradleFile.path}')); + }); +} diff --git a/flutter/packages/flutter_tools/test/integration.shard/android_plugin_example_app_build_test.dart b/flutter/packages/flutter_tools/test/integration.shard/android_plugin_example_app_build_test.dart new file mode 100644 index 0000000000000000000000000000000000000000..3a4d27477f6b31141a1cfb461fc9dac563b3cb36 --- /dev/null +++ b/flutter/packages/flutter_tools/test/integration.shard/android_plugin_example_app_build_test.dart @@ -0,0 +1,149 @@ +// 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_testing/file_testing.dart'; +import 'package:flutter_tools/src/base/file_system.dart'; +import 'package:flutter_tools/src/base/io.dart'; + +import '../src/common.dart'; +import 'test_utils.dart'; + +void main() { + late Directory tempDirPluginMethodChannels; + late Directory tempDirPluginFfi; + + setUp(() async { + tempDirPluginMethodChannels = createResolvedTempDirectorySync('flutter_plugin_test.'); + tempDirPluginFfi = + createResolvedTempDirectorySync('flutter_ffi_plugin_test.'); + }); + + tearDown(() async { + tryToDelete(tempDirPluginMethodChannels); + tryToDelete(tempDirPluginFfi); + }); + + Future testPlugin({ + required String template, + required Directory tempDir, + }) async { + final String flutterBin = fileSystem.path.join( + getFlutterRoot(), + 'bin', + 'flutter', + ); + + final String testName = '${template}_test'; + + ProcessResult result = processManager.runSync([ + flutterBin, + ...getLocalEngineArguments(), + 'create', + '--template=$template', + '--platforms=android', + testName, + ], workingDirectory: tempDir.path); + if (result.exitCode != 0) { + throw Exception('flutter create failed: ${result.exitCode}\n${result.stderr}\n${result.stdout}'); + } + + final Directory exampleAppDir = + tempDir.childDirectory(testName).childDirectory('example'); + + final File buildGradleFile = exampleAppDir.childDirectory('android').childFile('build.gradle'); + expect(buildGradleFile, exists); + + final String buildGradle = buildGradleFile.readAsStringSync(); + final RegExp androidPluginRegExp = + RegExp(r'com\.android\.tools\.build:gradle:(\d+\.\d+\.\d+)'); + + // Use AGP 7.2.0 + final String newBuildGradle = buildGradle.replaceAll( + androidPluginRegExp, 'com.android.tools.build:gradle:7.2.0'); + buildGradleFile.writeAsStringSync(newBuildGradle); + + // Run flutter build apk using AGP 7.2.0 + result = processManager.runSync([ + flutterBin, + ...getLocalEngineArguments(), + 'build', + 'apk', + '--target-platform=android-arm', + ], workingDirectory: exampleAppDir.path); + if (result.exitCode != 0) { + throw Exception('flutter build failed: ${result.exitCode}\n${result.stderr}\n${result.stdout}'); + } + + final File exampleApk = fileSystem.file(fileSystem.path.join( + exampleAppDir.path, + 'build', + 'app', + 'outputs', + 'flutter-apk', + 'app-release.apk', + )); + expect(exampleApk, exists); + + if (template == 'plugin_ffi') { + // Does not support AGP 3.3.0. + return; + } + + // Clean + result = processManager.runSync([ + flutterBin, + ...getLocalEngineArguments(), + 'clean', + ], workingDirectory: exampleAppDir.path); + if (result.exitCode != 0) { + throw Exception('flutter clean failed: ${result.exitCode}\n${result.stderr}\n${result.stdout}'); + } + + // Remove Gradle wrapper + fileSystem + .directory(fileSystem.path + .join(exampleAppDir.path, 'android', 'gradle', 'wrapper')) + .deleteSync(recursive: true); + + // Enable R8 in gradle.properties + final File gradleProperties = + exampleAppDir.childDirectory('android').childFile('gradle.properties'); + expect(gradleProperties, exists); + + gradleProperties.writeAsStringSync(''' +org.gradle.jvmargs=-Xmx4G +android.useAndroidX=true +android.enableJetifier=true +android.enableR8=true'''); + + // Run flutter build apk using AGP 3.3.0 + result = processManager.runSync([ + flutterBin, + ...getLocalEngineArguments(), + 'build', + 'apk', + '--target-platform=android-arm', + ], workingDirectory: exampleAppDir.path); + if (result.exitCode != 0) { + throw Exception('flutter build failed: ${result.exitCode}\n${result.stderr}\n${result.stdout}'); + } + expect(exampleApk, exists); + } + + test('plugin example can be built using current Flutter Gradle plugin', + () async { + await testPlugin( + template: 'plugin', + tempDir: tempDirPluginMethodChannels, + ); + }); + + test('FFI plugin example can be built using current Flutter Gradle plugin', + () async { + await testPlugin( + template: 'plugin_ffi', + tempDir: tempDirPluginFfi, + ); + }); +} diff --git a/flutter/packages/flutter_tools/test/integration.shard/android_plugin_ndkversion_mismatch_test.dart b/flutter/packages/flutter_tools/test/integration.shard/android_plugin_ndkversion_mismatch_test.dart new file mode 100644 index 0000000000000000000000000000000000000000..2580c4d16ea8d050259bd9ba31e27ac29837cb53 --- /dev/null +++ b/flutter/packages/flutter_tools/test/integration.shard/android_plugin_ndkversion_mismatch_test.dart @@ -0,0 +1,86 @@ +// 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_testing/file_testing.dart'; +import 'package:flutter_tools/src/base/file_system.dart'; +import 'package:flutter_tools/src/base/io.dart'; +import 'package:flutter_tools/src/cache.dart'; + +import '../src/common.dart'; +import 'test_utils.dart'; + +void main() { + late Directory tempDir; + + setUp(() { + Cache.flutterRoot = getFlutterRoot(); + tempDir = createResolvedTempDirectorySync('flutter_plugin_test.'); + }); + + tearDown(() async { + tryToDelete(tempDir); + }); + + test('error logged when plugin Android ndkVersion higher than project', () async { + final String flutterBin = fileSystem.path.join( + getFlutterRoot(), + 'bin', + 'flutter', + ); + + // Create dummy plugin + processManager.runSync([ + flutterBin, + ...getLocalEngineArguments(), + 'create', + '--template=plugin_ffi', + '--platforms=android', + 'test_plugin', + ], workingDirectory: tempDir.path); + + final Directory pluginAppDir = tempDir.childDirectory('test_plugin'); + final File pluginGradleFile = pluginAppDir.childDirectory('android').childFile('build.gradle'); + expect(pluginGradleFile, exists); + + final String pluginBuildGradle = pluginGradleFile.readAsStringSync(); + + // Bump up plugin ndkVersion to 21.4.7075529. + final RegExp androidNdkVersionRegExp = RegExp(r'ndkVersion (\"[0-9\.]+\"|flutter.ndkVersion|android.ndkVersion)'); + final String newPluginGradleFile = pluginBuildGradle.replaceAll(androidNdkVersionRegExp, 'ndkVersion "21.4.7075529"'); + expect(newPluginGradleFile, contains('21.4.7075529')); + pluginGradleFile.writeAsStringSync(newPluginGradleFile); + + final Directory pluginExampleAppDir = pluginAppDir.childDirectory('example'); + + final File projectGradleFile = pluginExampleAppDir.childDirectory('android').childDirectory('app').childFile('build.gradle'); + expect(projectGradleFile, exists); + + final String projectBuildGradle = projectGradleFile.readAsStringSync(); + + // Bump down plugin example app ndkVersion to 21.1.6352462. + final String newProjectGradleFile = projectBuildGradle.replaceAll(androidNdkVersionRegExp, 'ndkVersion "21.1.6352462"'); + expect(newProjectGradleFile, contains('21.1.6352462')); + projectGradleFile.writeAsStringSync(newProjectGradleFile); + + // Run flutter build apk to build plugin example project + final ProcessResult result = processManager.runSync([ + flutterBin, + ...getLocalEngineArguments(), + 'build', + 'apk', + '--target-platform=android-arm', + ], workingDirectory: pluginExampleAppDir.path); + + // Check that an error message is thrown. + expect(result.stderr, contains(''' +One or more plugins require a higher Android NDK version. +Fix this issue by adding the following to ${projectGradleFile.path}: +android { + ndkVersion "21.4.7075529" + ... +} + +''')); + }); +} diff --git a/flutter/packages/flutter_tools/test/integration.shard/android_plugin_new_output_dir_test.dart b/flutter/packages/flutter_tools/test/integration.shard/android_plugin_new_output_dir_test.dart new file mode 100644 index 0000000000000000000000000000000000000000..872e9c0cbf68dca523f5137483d5c3aabef39646 --- /dev/null +++ b/flutter/packages/flutter_tools/test/integration.shard/android_plugin_new_output_dir_test.dart @@ -0,0 +1,73 @@ +// 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:math'; + +import 'package:file_testing/file_testing.dart'; +import 'package:flutter_tools/src/base/file_system.dart'; +import 'package:flutter_tools/src/base/io.dart'; +import 'package:flutter_tools/src/cache.dart'; + +import '../src/common.dart'; +import 'test_utils.dart'; + +void main() { + + late Directory tempDir; + + setUp(() { + Cache.flutterRoot = getFlutterRoot(); + tempDir = createResolvedTempDirectorySync('android_plugin_new_output_dir_test.'); + }); + + tearDown(() async { + tryToDelete(tempDir); + }); + + test("error logged when plugin's build output dir was not private.", () async { + final String flutterBin = fileSystem.path.join( + getFlutterRoot(), + 'bin', + 'flutter', + ); + // create flutter module project + ProcessResult result = processManager.runSync([ + flutterBin, + ...getLocalEngineArguments(), + 'create', + '--template=module', + 'flutter_project' + ], workingDirectory: tempDir.path); + + final String projectPath = fileSystem.path.join(tempDir.path, 'flutter_project'); + + final File modulePubspec = fileSystem.file(fileSystem.path.join(projectPath, 'pubspec.yaml')); + String pubspecContent = modulePubspec.readAsStringSync(); + pubspecContent = pubspecContent.replaceFirst( + 'dependencies:', + ''' +dependencies: + image_picker: 0.8.5+3''', + ); + modulePubspec.writeAsStringSync(pubspecContent); + + // Run flutter build apk to build module example project + result = processManager.runSync([ + flutterBin, + ...getLocalEngineArguments(), + 'build', + 'aar', + '--target-platform=android-arm', + ], workingDirectory: projectPath); + + log(result.exitCode); + + // Check outputDir existed + final Directory outputDir = fileSystem.directory(fileSystem.path.join( + projectPath, '.android', 'plugins_build_output', 'image_picker_android' + )); + expect(outputDir, exists); + + }); +} diff --git a/flutter/packages/flutter_tools/test/integration.shard/android_plugin_skip_unsupported_test.dart b/flutter/packages/flutter_tools/test/integration.shard/android_plugin_skip_unsupported_test.dart new file mode 100644 index 0000000000000000000000000000000000000000..c52c0b6ee3ff547d461d1a05f92dfc0d54a90c56 --- /dev/null +++ b/flutter/packages/flutter_tools/test/integration.shard/android_plugin_skip_unsupported_test.dart @@ -0,0 +1,208 @@ +// 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_testing/file_testing.dart'; +import 'package:flutter_tools/src/base/file_system.dart'; +import 'package:flutter_tools/src/base/io.dart'; +import 'package:flutter_tools/src/cache.dart'; + +import '../src/common.dart'; +import 'test_data/plugin_each_settings_gradle_project.dart'; +import 'test_data/plugin_project.dart'; +import 'test_data/project.dart'; +import 'test_utils.dart'; + +void main() { + late Directory tempDir; + + setUp(() { + Cache.flutterRoot = getFlutterRoot(); + tempDir = createResolvedTempDirectorySync('flutter_plugin_test.'); + }); + + tearDown(() async { + tryToDelete(tempDir); + }); + + // Regression test for https://github.com/flutter/flutter/issues/97729 (#137115). + /// Creates a project which uses a plugin, which is not supported on Android. + /// This means it has no entry in pubspec.yaml for: + /// flutter -> plugin -> platforms -> android + /// + /// [createAndroidPluginFolder] indicates that the plugin can additionally + /// have a functioning `android` folder. + Future testUnsupportedPlugin({ + required Project project, + required bool createAndroidPluginFolder, + }) async { + final String flutterBin = fileSystem.path.join( + getFlutterRoot(), + 'bin', + 'flutter', + ); + + // Create dummy plugin that supports iOS and optionally Android. + processManager.runSync([ + flutterBin, + ...getLocalEngineArguments(), + 'create', + '--template=plugin', + '--platforms=ios${createAndroidPluginFolder ? ',android' : ''}', + 'test_plugin', + ], workingDirectory: tempDir.path); + + final Directory pluginAppDir = tempDir.childDirectory('test_plugin'); + + final File pubspecFile = pluginAppDir.childFile('pubspec.yaml'); + String pubspecYamlSrc = + pubspecFile.readAsStringSync().replaceAll('\r\n', '\n'); + if (createAndroidPluginFolder) { + // Override pubspec to drop support for the Android implementation. + pubspecYamlSrc = pubspecYamlSrc + .replaceFirst( + RegExp(r'name:.*\n'), + 'name: test_plugin\n', + ) + .replaceFirst(''' + android: + package: com.example.test_plugin + pluginClass: TestPlugin +''', ''' +# android: +# package: com.example.test_plugin +# pluginClass: TestPlugin +'''); + + pubspecFile.writeAsStringSync(pubspecYamlSrc); + + // Check the android directory and the build.gradle file within. + final File pluginGradleFile = + pluginAppDir.childDirectory('android').childFile('build.gradle'); + expect(pluginGradleFile, exists); + } else { + expect(pubspecYamlSrc, isNot(contains('android:'))); + } + + // Create a project which includes the plugin to test against + final Directory pluginExampleAppDir = + pluginAppDir.childDirectory('example'); + + await project.setUpIn(pluginExampleAppDir); + + // Run flutter build apk to build plugin example project. + return processManager.runSync([ + flutterBin, + ...getLocalEngineArguments(), + 'build', + 'apk', + '--debug', + ], workingDirectory: pluginExampleAppDir.path); + } + + test('skip plugin if it does not support the Android platform', () async { + final Project project = PluginWithPathAndroidProject(); + final ProcessResult buildApkResult = await testUnsupportedPlugin( + project: project, createAndroidPluginFolder: false); + expect(buildApkResult.stderr.toString(), + isNot(contains('Please fix your settings.gradle'))); + expect(buildApkResult, const ProcessResultMatcher()); + }); + + test( + 'skip plugin with android folder if it does not support the Android platform', + () async { + final Project project = PluginWithPathAndroidProject(); + final ProcessResult buildApkResult = await testUnsupportedPlugin( + project: project, createAndroidPluginFolder: true); + expect(buildApkResult.stderr.toString(), + isNot(contains('Please fix your settings.gradle'))); + expect(buildApkResult, const ProcessResultMatcher()); + }); + + // TODO(54566): Remove test when issue is resolved. + /// Test project with a `settings.gradle` (PluginEach) that apps were created + /// with until Flutter v1.22.0. + /// It uses the `.flutter-plugins` file to load EACH plugin. + test( + 'skip plugin if it does not support the Android platform with a _plugin.each_ settings.gradle', + () async { + final Project project = PluginEachWithPathAndroidProject(); + final ProcessResult buildApkResult = await testUnsupportedPlugin( + project: project, createAndroidPluginFolder: false); + expect(buildApkResult.stderr.toString(), + isNot(contains('Please fix your settings.gradle'))); + expect(buildApkResult, const ProcessResultMatcher()); + }); + + // TODO(54566): Remove test when issue is resolved. + /// Test project with a `settings.gradle` (PluginEach) that apps were created + /// with until Flutter v1.22.0. + /// It uses the `.flutter-plugins` file to load EACH plugin. + /// The plugin includes a functional 'android' folder. + test( + 'skip plugin with android folder if it does not support the Android platform with a _plugin.each_ settings.gradle', + () async { + final Project project = PluginEachWithPathAndroidProject(); + final ProcessResult buildApkResult = await testUnsupportedPlugin( + project: project, createAndroidPluginFolder: true); + expect(buildApkResult.stderr.toString(), + isNot(contains('Please fix your settings.gradle'))); + expect(buildApkResult, const ProcessResultMatcher()); + }); + + // TODO(54566): Remove test when issue is resolved. + /// Test project with a `settings.gradle` (PluginEach) that apps were created + /// with until Flutter v1.22.0. + /// It is compromised by removing the 'include' statement of the plugins. + /// As the "'.flutter-plugins'" keyword is still present, the framework + /// assumes that all plugins are included, which is not the case. + /// Therefore it should throw an error. + test( + 'skip plugin if it does not support the Android platform with a compromised _plugin.each_ settings.gradle', + () async { + final Project project = PluginCompromisedEachWithPathAndroidProject(); + final ProcessResult buildApkResult = await testUnsupportedPlugin( + project: project, createAndroidPluginFolder: true); + expect( + buildApkResult, + const ProcessResultMatcher( + stderrPattern: 'Please fix your settings.gradle'), + ); + }); +} + +const String pubspecWithPluginPath = r''' +name: test +environment: + sdk: '>=3.2.0-0 <4.0.0' +dependencies: + flutter: + sdk: flutter + + test_plugin: + path: ../ +'''; + +/// Project that load's a plugin from the specified path. +class PluginWithPathAndroidProject extends PluginProject { + @override + String get pubspec => pubspecWithPluginPath; +} + +// TODO(54566): Remove class when issue is resolved. +/// [PluginEachSettingsGradleProject] that load's a plugin from the specified +/// path. +class PluginEachWithPathAndroidProject extends PluginEachSettingsGradleProject { + @override + String get pubspec => pubspecWithPluginPath; +} + +// TODO(54566): Remove class when issue is resolved. +/// [PluginCompromisedEachSettingsGradleProject] that load's a plugin from the +/// specified path. +class PluginCompromisedEachWithPathAndroidProject + extends PluginCompromisedEachSettingsGradleProject { + @override + String get pubspec => pubspecWithPluginPath; +} diff --git a/flutter/packages/flutter_tools/test/integration.shard/asset_transformation_test.dart b/flutter/packages/flutter_tools/test/integration.shard/asset_transformation_test.dart new file mode 100644 index 0000000000000000000000000000000000000000..e53ea82b08dbfd99868767980e4cac7de58099f2 --- /dev/null +++ b/flutter/packages/flutter_tools/test/integration.shard/asset_transformation_test.dart @@ -0,0 +1,153 @@ +// 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_testing/file_testing.dart'; +import 'package:flutter_tools/src/base/file_system.dart'; +import 'package:flutter_tools/src/base/io.dart'; + +import '../src/common.dart'; +import 'test_data/project.dart'; +import 'test_utils.dart'; + +final class _AssetTransformationTestProject extends Project { + @override + final String pubspec = ''' +name: test +environment: + sdk: '>=3.2.0-0 <4.0.0' +dependencies: + flutter: + sdk: flutter +dev_dependencies: + capitalizer_transformer: + path: ./capitalizer_transformer +flutter: + assets: + - path: assets/text_asset.txt + transformers: + - package: capitalizer_transformer +'''; + + @override + final String main = ''' +import 'package:flutter/material.dart'; + +void main() { + runApp(const MyApp()); +} + +class MyApp extends StatelessWidget { + const MyApp({super.key}); + + @override + Widget build(BuildContext context) { + return const MaterialApp( + home: Scaffold( + body: Center( + child: Text('Hello, World!'), + ), + ), + ); + } +} +'''; +} + +Future main() async { + testWithoutContext('asset is transformed when declared with a transformation', () async { + final Directory tempProjectDirectory = createResolvedTempDirectorySync( + 'asset_transformation_test.', + ); + + try { + _setUpCapitalizerTransformer(tempProjectDirectory); + await _AssetTransformationTestProject().setUpIn(tempProjectDirectory); + tempProjectDirectory.childDirectory('assets').childFile('text_asset.txt') + ..createSync(recursive: true) + ..writeAsStringSync('abc'); + + final String flutterBin = fileSystem.path.join( + getFlutterRoot(), + 'bin', + 'flutter', + ); + final ProcessResult result = await processManager.run( + [ + flutterBin, + 'build', + 'web', + ], + workingDirectory: tempProjectDirectory.path, + ); + + expect(result.exitCode, 0, reason: result.stderr as String); + + final File asset = fileSystem.file( + fileSystem.path.join( + tempProjectDirectory.path, + 'build', + 'web', + 'assets', + 'assets', + 'text_asset.txt', + ), + ); + + expect(asset, exists); + + expect( + asset.readAsStringSync(), + equals('ABC'), + reason: + "The original contents of the asset (which should be 'abc') should " + "have been transformed to 'ABC' by the capitalizer_transformer as " + 'configured in the pubspec.', + ); + } finally { + tryToDelete(tempProjectDirectory); + } + }); +} + +void _setUpCapitalizerTransformer(Directory projectDir) { + final Directory targetDir = projectDir.childDirectory('capitalizer_transformer'); + targetDir.createSync(recursive: true); + + targetDir.childFile('pubspec.yaml') + ..createSync() + ..writeAsStringSync(''' +name: capitalizer_transformer +version: 1.0.0 + +environment: + sdk: '>=3.2.0-0 <4.0.0' + +dependencies: + args: ^2.4.2 +'''); + + targetDir.childDirectory('bin').childFile('capitalizer_transformer.dart') + ..createSync(recursive: true) + ..writeAsStringSync(''' +import 'dart:io'; + +import 'package:args/args.dart'; + +void main(List args) { + final ArgParser parser = ArgParser() + ..addOption('input') + ..addOption('output'); + + final ArgResults parsedArgs = parser.parse(args); + + final String inputFilePath = parsedArgs['input'] as String; + final String outputFilePath = parsedArgs['output'] as String; + + final String input = File(inputFilePath).readAsStringSync(); + File(outputFilePath) + ..createSync(recursive: true) + ..writeAsStringSync(input.toUpperCase()); +} +'''); +} diff --git a/flutter/packages/flutter_tools/test/integration.shard/background_isolate_test.dart b/flutter/packages/flutter_tools/test/integration.shard/background_isolate_test.dart new file mode 100644 index 0000000000000000000000000000000000000000..eef89db5fc39cf8a8c58e2b8248ec2e95bd40ea1 --- /dev/null +++ b/flutter/packages/flutter_tools/test/integration.shard/background_isolate_test.dart @@ -0,0 +1,87 @@ +// 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/file.dart'; + +import '../src/common.dart'; +import 'test_data/background_project.dart'; +import 'test_driver.dart'; +import 'test_utils.dart'; + +void main() { + late Directory tempDir; + + setUp(() async { + tempDir = createResolvedTempDirectorySync('hot_reload_test.'); + }); + + tearDown(() async { + tryToDelete(tempDir); + }); + + testWithoutContext('Hot restart kills background isolates', () async { + final BackgroundProject project = BackgroundProject(); + await project.setUpIn(tempDir); + final FlutterRunTestDriver flutter = FlutterRunTestDriver(tempDir); + + const String newBackgroundMessage = 'New Background'; + final Completer sawForegroundMessage = Completer.sync(); + final Completer sawBackgroundMessage = Completer.sync(); + final Completer sawNewBackgroundMessage = Completer.sync(); + final StreamSubscription subscription = flutter.stdout.listen((String line) { + printOnFailure('[LOG]:"$line"'); + if (line.contains('Main thread') && !sawForegroundMessage.isCompleted) { + sawForegroundMessage.complete(); + } + if (line.contains('Isolate thread')) { + sawBackgroundMessage.complete(); + } + if (line.contains(newBackgroundMessage)) { + sawNewBackgroundMessage.complete(); + } + }, + ); + await flutter.run(); + await sawForegroundMessage.future; + await sawBackgroundMessage.future; + + project.updateTestIsolatePhrase(newBackgroundMessage); + await flutter.hotRestart(); + await sawNewBackgroundMessage.future; + // Wait a tiny amount of time in case we did not kill the background isolate. + await Future.delayed(const Duration(milliseconds: 10)); + await subscription.cancel(); + await flutter.stop(); + }); + + testWithoutContext('Hot reload updates background isolates', () async { + final RepeatingBackgroundProject project = RepeatingBackgroundProject(); + await project.setUpIn(tempDir); + final FlutterRunTestDriver flutter = FlutterRunTestDriver(tempDir); + + const String newBackgroundMessage = 'New Background'; + final Completer sawBackgroundMessage = Completer.sync(); + final Completer sawNewBackgroundMessage = Completer.sync(); + final StreamSubscription subscription = flutter.stdout.listen((String line) { + printOnFailure('[LOG]:"$line"'); + if (line.contains('Isolate thread') && !sawBackgroundMessage.isCompleted) { + sawBackgroundMessage.complete(); + } + if (line.contains(newBackgroundMessage) && !sawNewBackgroundMessage.isCompleted) { + sawNewBackgroundMessage.complete(); + } + }, + ); + await flutter.run(); + await sawBackgroundMessage.future; + + project.updateTestIsolatePhrase(newBackgroundMessage); + await flutter.hotReload(); + await sawNewBackgroundMessage.future; + await subscription.cancel(); + await flutter.stop(); + }); +} diff --git a/flutter/packages/flutter_tools/test/integration.shard/bash_entrypoint_test.dart b/flutter/packages/flutter_tools/test/integration.shard/bash_entrypoint_test.dart new file mode 100644 index 0000000000000000000000000000000000000000..7fd91cbc4bd27b1e0a7fab896bdffe4b58c5d225 --- /dev/null +++ b/flutter/packages/flutter_tools/test/integration.shard/bash_entrypoint_test.dart @@ -0,0 +1,134 @@ +// Copyright 2014 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +import 'dart:async'; +import 'dart:convert'; + +import 'package:file/file.dart'; +import 'package:flutter_tools/src/base/io.dart'; + +import '../src/common.dart'; +import 'test_utils.dart'; + +final String flutterRootPath = getFlutterRoot(); +final Directory flutterRoot = fileSystem.directory(flutterRootPath); + +Future main() async { + test('verify terminating flutter/bin/dart terminates the underlying dart process', () async { + final Completer childReadyCompleter = Completer(); + String stdout = ''; + final Process process = await processManager.start( + [ + dartBash.path, + listenForSigtermScript.path, + ], + ); + final Future stdoutFuture = process.stdout + .transform(utf8.decoder) + .forEach((String str) { + stdout += str; + if (stdout.contains('Ready to receive signals') && !childReadyCompleter.isCompleted) { + childReadyCompleter.complete(); + } + }); + // Ensure that the child app has registered its signal handler + await childReadyCompleter.future; + final bool killSuccess = process.kill(); + expect(killSuccess, true); + // Wait for stdout to complete + await stdoutFuture; + // Ensure child exited successfully + expect( + await process.exitCode, + 0, + reason: 'child process exited with code ${await process.exitCode}, and ' + 'stdout:\n$stdout', + ); + expect(stdout, contains('Successfully received SIGTERM!')); + }, + skip: platform.isWindows); // [intended] Windows does not use the bash entrypoint + + test('shared.sh does not compile flutter tool if PROG_NAME=dart', () async { + final Directory tempDir = fileSystem.systemTempDirectory.createTempSync('bash_entrypoint_test'); + try { + // bash script checks it is in a git repo + ProcessResult result = await processManager.run(['git', 'init'], workingDirectory: tempDir.path); + expect(result, const ProcessResultMatcher()); + result = await processManager.run(['git', 'commit', '--allow-empty', '-m', 'init commit'], workingDirectory: tempDir.path); + expect(result, const ProcessResultMatcher()); + + // copy dart and shared.sh to temp dir + final File trueSharedSh = flutterRoot.childDirectory('bin').childDirectory('internal').childFile('shared.sh'); + final File fakeSharedSh = (tempDir.childDirectory('bin').childDirectory('internal') + ..createSync(recursive: true)) + .childFile('shared.sh'); + trueSharedSh.copySync(fakeSharedSh.path); + final File fakeDartBash = tempDir.childDirectory('bin').childFile('dart'); + dartBash.copySync(fakeDartBash.path); + // mark dart executable + makeExecutable(fakeDartBash); + + // create no-op fake update_dart_sdk.sh script + final File updateDartSdk = tempDir.childDirectory('bin').childDirectory('internal').childFile('update_dart_sdk.sh')..writeAsStringSync(''' +#!/usr/bin/env bash + +echo downloaded dart sdk +'''); + makeExecutable(updateDartSdk); + + // create a fake dart runtime + final File dartBin = (tempDir.childDirectory('bin') + .childDirectory('cache') + .childDirectory('dart-sdk') + .childDirectory('bin') + ..createSync(recursive: true)) + .childFile('dart'); + dartBin.writeAsStringSync(''' +#!/usr/bin/env bash + +echo executed dart binary +'''); + makeExecutable(dartBin); + + result = await processManager.run([fakeDartBash.path]); + expect(result, const ProcessResultMatcher()); + expect( + (result.stdout as String).split('\n'), + // verify we ran updateDartSdk and dartBin + containsAll(['downloaded dart sdk', 'executed dart binary']), + ); + + // Verify we did not try to compile the flutter_tool + expect(result.stderr, isNot(contains('Building flutter tool...'))); + } finally { + tryToDelete(tempDir); + } + }, + skip: platform.isWindows); // [intended] Windows does not use the bash entrypoint +} + +// A test Dart app that will run until it receives SIGTERM +File get listenForSigtermScript { + return flutterRoot + .childDirectory('packages') + .childDirectory('flutter_tools') + .childDirectory('test') + .childDirectory('integration.shard') + .childDirectory('test_data') + .childFile('listen_for_sigterm.dart') + .absolute; +} + +// The executable bash entrypoint for the Dart binary. +File get dartBash { + return flutterRoot + .childDirectory('bin') + .childFile('dart') + .absolute; +} + +void makeExecutable(File file) { + final ProcessResult result = processManager.runSync(['chmod', '+x', file.path]); + expect(result, const ProcessResultMatcher()); +} diff --git a/flutter/packages/flutter_tools/test/integration.shard/batch_entrypoint_test.dart b/flutter/packages/flutter_tools/test/integration.shard/batch_entrypoint_test.dart new file mode 100644 index 0000000000000000000000000000000000000000..233f978a3ca363d3f1ebdde4492d9157d053f570 --- /dev/null +++ b/flutter/packages/flutter_tools/test/integration.shard/batch_entrypoint_test.dart @@ -0,0 +1,109 @@ +// Copyright 2014 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +import 'dart:async'; +import 'dart:convert'; + +import 'package:file/file.dart'; +import 'package:flutter_tools/src/base/io.dart'; + +import '../src/common.dart'; +import 'test_utils.dart'; + +final String flutterRootPath = getFlutterRoot(); +final Directory flutterRoot = fileSystem.directory(flutterRootPath); + +Future main() async { + // Regression test for https://github.com/flutter/flutter/issues/132592 + test('flutter/bin/dart updates the Dart SDK without hanging', () async { + // Run the Dart entrypoint once to ensure the Dart SDK is downloaded. + await runDartBatch(); + + expect(dartSdkStamp.existsSync(), true); + + // Remove the Dart SDK stamp and run the Dart entrypoint again to trigger + // the Dart SDK update. + dartSdkStamp.deleteSync(); + final Future runFuture = runDartBatch(); + final Timer timer = Timer(const Duration(minutes: 5), () { + // This print is useful for people debugging this test. Normally we would + // avoid printing in a test but this is an exception because it's useful + // ambient information. + // ignore: avoid_print + print( + 'The Dart batch entrypoint did not complete after 5 minutes. ' + 'Historically this is a sign that 7-Zip zip extraction is waiting for ' + 'the user to confirm they would like to overwrite files. ' + "This likely means the test isn't a flake and will fail. " + 'See: https://github.com/flutter/flutter/issues/132592' + ); + }); + + final String output = await runFuture; + timer.cancel(); + + // Check the Dart SDK was re-downloaded and extracted. + // If 7-Zip is installed, unexpected overwrites causes this to hang. + // If 7-Zip is not installed, unexpected overwrites results in error messages. + // See: https://github.com/flutter/flutter/issues/132592 + expect(dartSdkStamp.existsSync(), true); + expect(output, contains('Downloading Dart SDK from Flutter engine ...')); + // Do not assert on the exact unzipping method, as this could change on CI + expect(output, contains(RegExp(r'Expanding downloaded archive with (.*)...'))); + expect(output, isNot(contains('Use the -Force parameter' /* Luke */))); + }, + skip: !platform.isWindows); // [intended] Only Windows uses the batch entrypoint +} + +Future runDartBatch() async { + String output = ''; + final Process process = await processManager.start( + [ + dartBatch.path + ], + ); + final Future stdoutFuture = process.stdout + .transform(utf8.decoder) + .forEach((String str) { + output += str; + }); + final Future stderrFuture = process.stderr + .transform(utf8.decoder) + .forEach((String str) { + output += str; + }); + + // Wait for the output to complete + await Future.wait(>[stdoutFuture, stderrFuture]); + // Ensure child exited successfully + expect( + await process.exitCode, + 0, + reason: 'child process exited with code ${await process.exitCode}, and ' + 'output:\n$output', + ); + + // Check the Dart tool prints the expected output. + expect(output, contains('A command-line utility for Dart development.')); + expect(output, contains('Usage: dart [arguments]')); + + return output; +} + +// The executable batch entrypoint for the Dart binary. +File get dartBatch { + return flutterRoot + .childDirectory('bin') + .childFile('dart.bat') + .absolute; +} + +// The Dart SDK's stamp file. +File get dartSdkStamp { + return flutterRoot + .childDirectory('bin') + .childDirectory('cache') + .childFile('engine-dart-sdk.stamp') + .absolute; +} diff --git a/flutter/packages/flutter_tools/test/integration.shard/break_on_framework_exceptions_test.dart b/flutter/packages/flutter_tools/test/integration.shard/break_on_framework_exceptions_test.dart new file mode 100644 index 0000000000000000000000000000000000000000..ea59152b81ecd426580a9ba72e5e1d85dc7b631a --- /dev/null +++ b/flutter/packages/flutter_tools/test/integration.shard/break_on_framework_exceptions_test.dart @@ -0,0 +1,676 @@ +// 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. + +// TODO(gspencergoog): Remove this tag once this test's state leaks/test +// dependencies have been fixed. +// https://github.com/flutter/flutter/issues/85160 +// Fails with "flutter test --test-randomize-ordering-seed=1000" +@Tags(['no-shuffle']) +library; + +import 'dart:async'; + +import 'package:file/file.dart'; + +import '../src/common.dart'; +import 'test_data/project.dart'; +import 'test_driver.dart'; +import 'test_utils.dart'; + +void main() { + late Directory tempDir; + + setUp(() async { + tempDir = createResolvedTempDirectorySync('break_on_framework_exceptions.'); + }); + + tearDown(() async { + tryToDelete(tempDir); + }); + + Future expectException(TestProject project, String exceptionMessage) async { + await _timeoutAfter( + message: 'Timed out setting up project in $tempDir', + work: () => project.setUpIn(tempDir), + ); + + final FlutterTestTestDriver flutter = FlutterTestTestDriver(tempDir); + + await _timeoutAfter( + message: 'Timed out launching `flutter test`', + work: () => flutter.test(withDebugger: true, pauseOnExceptions: true), + ); + + await _timeoutAfter( + message: 'Timed out waiting for VM service pause debug event', + work: flutter.waitForPause, + ); + + int? breakLine; + await _timeoutAfter( + message: 'Timed out getting source location of top stack frome', + work: () async => breakLine = (await flutter.getSourceLocation())?.line, + ); + + expect(breakLine, project.lineContaining(project.test, exceptionMessage)); + } + + testWithoutContext('breaks when AnimationController listener throws', () async { + final TestProject project = TestProject( + r''' + AnimationController(vsync: TestVSync(), duration: Duration.zero) + ..addListener(() { + throw 'AnimationController listener'; + }) + ..forward(); + ''' + ); + + await expectException(project, "throw 'AnimationController listener';"); + }); + + testWithoutContext('breaks when AnimationController status listener throws', () async { + final TestProject project = TestProject( + r''' + AnimationController(vsync: TestVSync(), duration: Duration.zero) + ..addStatusListener((AnimationStatus _) { + throw 'AnimationController status listener'; + }) + ..forward(); + ''' + ); + + await expectException(project, "throw 'AnimationController status listener';"); + }); + + testWithoutContext('breaks when ChangeNotifier listener throws', () async { + final TestProject project = TestProject( + r''' + ValueNotifier(0) + ..addListener(() { + throw 'ValueNotifier listener'; + }) + ..value = 1; + ''' + ); + + await expectException(project, "throw 'ValueNotifier listener';"); + }); + + testWithoutContext('breaks when handling a gesture throws', () async { + final TestProject project = TestProject( + r''' + await tester.pumpWidget( + MaterialApp( + home: Center( + child: ElevatedButton( + child: const Text('foo'), + onPressed: () { + throw 'while handling a gesture'; + }, + ), + ), + ) + ); + await tester.tap(find.byType(ElevatedButton)); + ''' + ); + + await expectException(project, "throw 'while handling a gesture';"); + }); + + testWithoutContext('breaks when platform message callback throws', () async { + final TestProject project = TestProject( + r''' + BasicMessageChannel('foo', const StringCodec()).setMessageHandler((_) { + throw 'platform message callback'; + }); + tester.binding.defaultBinaryMessenger.handlePlatformMessage('foo', const StringCodec().encodeMessage('Hello'), (_) {}); + ''' + ); + + await expectException(project, "throw 'platform message callback';"); + }); + + testWithoutContext('breaks when SliverChildBuilderDelegate.builder throws', () async { + final TestProject project = TestProject( + r''' + await tester.pumpWidget(MaterialApp( + home: ListView.builder( + itemBuilder: (BuildContext context, int index) { + throw 'cannot build child'; + }, + ), + )); + ''' + ); + + await expectException(project, "throw 'cannot build child';"); + }); + + testWithoutContext('breaks when EditableText.onChanged throws', () async { + final TestProject project = TestProject( + r''' + await tester.pumpWidget(MaterialApp( + home: Material( + child: TextField( + onChanged: (String t) { + throw 'onChanged'; + }, + ), + ), + )); + await tester.enterText(find.byType(TextField), 'foo'); + ''' + ); + + await expectException(project, "throw 'onChanged';"); + }); + + testWithoutContext('breaks when EditableText.onEditingComplete throws', () async { + final TestProject project = TestProject( + r''' + await tester.pumpWidget(MaterialApp( + home: Material( + child: TextField( + onEditingComplete: () { + throw 'onEditingComplete'; + }, + ), + ), + )); + await tester.tap(find.byType(EditableText)); + await tester.pump(); + await tester.testTextInput.receiveAction(TextInputAction.done); + ''' + ); + + await expectException(project, "throw 'onEditingComplete';"); + }); + + testWithoutContext('breaks when EditableText.onSelectionChanged throws', () async { + final TestProject project = TestProject( + r''' + await tester.pumpWidget(MaterialApp( + home: SelectableText('hello', + onSelectionChanged: (TextSelection selection, SelectionChangedCause? cause) { + throw 'onSelectionChanged'; + }, + ), + )); + await tester.tap(find.byType(SelectableText)); + ''' + ); + + await expectException(project, "throw 'onSelectionChanged';"); + }); + + testWithoutContext('breaks when Action listener throws', () async { + final TestProject project = TestProject( + r''' + CallbackAction(onInvoke: (Intent _) { }) + ..addActionListener((_) { + throw 'action listener'; + }) + ..notifyActionListeners(); + ''' + ); + + await expectException(project, "throw 'action listener';"); + }); + + testWithoutContext('breaks when pointer route throws', () async { + final TestProject project = TestProject( + r''' + PointerRouter() + ..addRoute(2, (PointerEvent event) { + throw 'pointer route'; + }) + ..route(TestPointer(2).down(Offset.zero)); + ''' + ); + + await expectException(project, "throw 'pointer route';"); + }); + + testWithoutContext('breaks when PointerSignalResolver callback throws', () async { + final TestProject project = TestProject( + r''' + const PointerScrollEvent originalEvent = PointerScrollEvent(); + PointerSignalResolver() + ..register(originalEvent, (PointerSignalEvent event) { + throw 'PointerSignalResolver callback'; + }) + ..resolve(originalEvent); + ''' + ); + + await expectException(project, "throw 'PointerSignalResolver callback';"); + }); + + testWithoutContext('breaks when PointerSignalResolver callback throws', () async { + final TestProject project = TestProject( + r''' + FocusManager.instance + ..addHighlightModeListener((_) { + throw 'highlight mode listener'; + }) + ..highlightStrategy = FocusHighlightStrategy.alwaysTouch + ..highlightStrategy = FocusHighlightStrategy.alwaysTraditional; + ''' + ); + + await expectException(project, "throw 'highlight mode listener';"); + }); + + testWithoutContext('breaks when GestureBinding.dispatchEvent throws', () async { + final TestProject project = TestProject( + r''' + await tester.pumpWidget( + MouseRegion( + onHover: (_) { + throw 'onHover'; + }, + ) + ); + final TestGesture gesture = await tester.createGesture(kind: PointerDeviceKind.mouse); + await gesture.addPointer(location: Offset.zero); + await tester.pump(); + await gesture.moveTo(tester.getCenter(find.byType(MouseRegion))); + await tester.pump(); + gesture.removePointer(); + ''' + ); + + await expectException(project, "throw 'onHover';"); + }); + + testWithoutContext('breaks when ImageStreamListener.onImage throws', () async { + final TestProject project = TestProject( + r''' + final Completer completer = Completer(); + OneFrameImageStreamCompleter(completer.future) + ..addListener(ImageStreamListener((ImageInfo _, bool __) { + throw 'setImage'; + })); + completer.complete(ImageInfo(image: image)); + ''', + setup: r''' + late ui.Image image; + setUp(() async { + image = await createTestImage(); + }); + ''' + ); + + await expectException(project, "throw 'setImage';"); + }); + + testWithoutContext('breaks when ImageStreamListener.onError throws', () async { + final TestProject project = TestProject( + r''' + final Completer completer = Completer(); + OneFrameImageStreamCompleter(completer.future) + ..addListener(ImageStreamListener( + (ImageInfo _, bool __) { }, + onError: (Object _, StackTrace? __) { + throw 'onError'; + }, + )); + completer.completeError('ERROR'); + ''' + ); + + await expectException(project, "throw 'onError';"); + }); + + testWithoutContext('breaks when LayoutBuilder.builder throws', () async { + final TestProject project = TestProject( + r''' + await tester.pumpWidget(LayoutBuilder( + builder: (_, __) { + throw 'LayoutBuilder.builder'; + }, + )); + ''' + ); + + await expectException(project, "throw 'LayoutBuilder.builder';"); + }); + + testWithoutContext('breaks when _CallbackHookProvider callback throws', () async { + final TestProject project = TestProject( + r''' + RootBackButtonDispatcher() + ..addCallback(() { + throw '_CallbackHookProvider.callback'; + }) + ..invokeCallback(Future.value(false)); + ''' + ); + + await expectException(project, "throw '_CallbackHookProvider.callback';"); + }); + + testWithoutContext('breaks when TimingsCallback throws', () async { + final TestProject project = TestProject( + r''' + SchedulerBinding.instance!.addTimingsCallback((List timings) { + throw 'TimingsCallback'; + }); + ui.window.onReportTimings!([]); + ''' + ); + + await expectException(project, "throw 'TimingsCallback';"); + }); + + testWithoutContext('breaks when TimingsCallback throws', () async { + final TestProject project = TestProject( + r''' + SchedulerBinding.instance!.scheduleTask( + () { + throw 'scheduled task'; + }, + Priority.touch, + ); + await tester.pumpAndSettle(); + ''' + ); + + await expectException(project, "throw 'scheduled task';"); + }); + + testWithoutContext('breaks when FrameCallback throws', () async { + final TestProject project = TestProject( + r''' + SchedulerBinding.instance!.addPostFrameCallback((_) { + throw 'FrameCallback'; + }); + await tester.pump(); + ''' + ); + + await expectException(project, "throw 'FrameCallback';"); + }); + + testWithoutContext('breaks when attaching to render tree throws', () async { + final TestProject project = TestProject( + r''' + await tester.pumpWidget(TestWidget()); + ''', + classes: r''' + class TestWidget extends StatelessWidget { + @override + StatelessElement createElement() { + throw 'create element'; + } + + @override + Widget build(BuildContext context) => Container(); + } + ''', + ); + + await expectException(project, "throw 'create element';"); + }); + + testWithoutContext('breaks when RenderObject.performLayout throws', () async { + final TestProject project = TestProject( + r''' + TestRender().layout(BoxConstraints()); + ''', + classes: r''' + class TestRender extends RenderBox { + @override + void performLayout() { + throw 'performLayout'; + } + } + ''', + ); + + await expectException(project, "throw 'performLayout';"); + }); + + testWithoutContext('breaks when RenderObject.performResize throws', () async { + final TestProject project = TestProject( + r''' + TestRender().layout(BoxConstraints()); + ''', + classes: r''' + class TestRender extends RenderBox { + @override + bool get sizedByParent => true; + + @override + void performResize() { + throw 'performResize'; + } + } + ''', + ); + + await expectException(project, "throw 'performResize';"); + }); + + testWithoutContext('breaks when RenderObject.performLayout (without resize) throws', () async { + final TestProject project = TestProject( + r''' + await tester.pumpWidget(TestWidget()); + tester.renderObject(find.byType(TestWidget)).layoutThrows = true; + await tester.pump(); + ''', + classes: r''' + class TestWidget extends LeafRenderObjectWidget { + @override + RenderObject createRenderObject(BuildContext context) => TestRender(); + } + + class TestRender extends RenderBox { + bool get layoutThrows => _layoutThrows; + bool _layoutThrows = false; + set layoutThrows(bool value) { + if (value == _layoutThrows) { + return; + } + _layoutThrows = value; + markNeedsLayout(); + } + + @override + void performLayout() { + if (layoutThrows) { + throw 'performLayout without resize'; + } + size = constraints.biggest; + } + } + ''', + ); + + await expectException(project, "throw 'performLayout without resize';"); + }); + + testWithoutContext('breaks when StatelessWidget.build throws', () async { + final TestProject project = TestProject( + r''' + await tester.pumpWidget(TestWidget()); + ''', + classes: r''' + class TestWidget extends StatelessWidget { + @override + Widget build(BuildContext context) { + throw 'StatelessWidget.build'; + } + } + ''', + ); + + await expectException(project, "throw 'StatelessWidget.build';"); + }); + + testWithoutContext('breaks when StatefulWidget.build throws', () async { + final TestProject project = TestProject( + r''' + await tester.pumpWidget(TestWidget()); + ''', + classes: r''' + class TestWidget extends StatefulWidget { + @override + _TestWidgetState createState() => _TestWidgetState(); + } + + class _TestWidgetState extends State { + @override + Widget build(BuildContext context) { + throw 'StatefulWidget.build'; + } + } + ''', + ); + + await expectException(project, "throw 'StatefulWidget.build';"); + }); + + testWithoutContext('breaks when finalizing the tree throws', () async { + final TestProject project = TestProject( + r''' + await tester.pumpWidget(TestWidget()); + ''', + classes: r''' + class TestWidget extends StatefulWidget { + @override + _TestWidgetState createState() => _TestWidgetState(); + } + + class _TestWidgetState extends State { + @override + void dispose() { + super.dispose(); + throw 'dispose'; + } + + @override + Widget build(BuildContext context) => Container(); + } + ''', + ); + + await expectException(project, "throw 'dispose';"); + }); + + testWithoutContext('breaks when rebuilding dirty elements throws', () async { + final TestProject project = TestProject( + r''' + await tester.pumpWidget(TestWidget()); + tester.element(find.byType(TestWidget)).throwOnRebuild = true; + await tester.pump(); + ''', + classes: r''' + class TestWidget extends StatelessWidget { + @override + StatelessElement createElement() => TestElement(this); + + @override + Widget build(BuildContext context) => Container(); + } + + class TestElement extends StatelessElement { + TestElement(StatelessWidget widget) : super(widget); + + bool get throwOnRebuild => _throwOnRebuild; + bool _throwOnRebuild = false; + set throwOnRebuild(bool value) { + if (value == _throwOnRebuild) { + return; + } + _throwOnRebuild = value; + markNeedsBuild(); + } + + @override + void rebuild({bool force = false}) { + if (_throwOnRebuild) { + throw 'rebuild'; + } + super.rebuild(force: force); + } + } + ''', + ); + + await expectException(project, "throw 'rebuild';"); + }); +} + +/// A debugging wrapper to help diagnose tests that are already timing out. +/// +/// When these tests are timed out by package:test (after 15 minutes), there +/// is no hint in logs as to where the test got stuck. By passing async calls +/// to this function with a [duration] less than that configured in +/// package:test can be set and a helpful message used to help debugging. +/// +/// See https://github.com/flutter/flutter/issues/125241 for more context. +Future _timeoutAfter({ + required String message, + Duration duration = const Duration(minutes: 10), + required Future Function() work, +}) async { + final Timer timer = Timer( + duration, + () => fail(message), + ); + await work(); + timer.cancel(); +} + +class TestProject extends Project { + TestProject(this.testBody, { this.setup, this.classes }); + + final String testBody; + final String? setup; + final String? classes; + + @override + final String pubspec = ''' + name: test + environment: + sdk: '>=3.2.0-0 <4.0.0' + + dependencies: + flutter: + sdk: flutter + dev_dependencies: + flutter_test: + sdk: flutter + '''; + + @override + final String main = ''; + + @override + String get test => _test.replaceFirst('// SETUP', setup ?? '').replaceFirst('// TEST_BODY', testBody).replaceFirst('// CLASSES', classes ?? ''); + + final String _test = r''' + import 'dart:async'; + import 'dart:ui' as ui; + + import 'package:flutter/animation.dart'; + import 'package:flutter/foundation.dart'; + import 'package:flutter/gestures.dart'; + import 'package:flutter/material.dart'; + import 'package:flutter/scheduler.dart'; + import 'package:flutter/services.dart'; + import 'package:flutter_test/flutter_test.dart'; + + void main() { + // SETUP + testWidgets('test', (WidgetTester tester) async { + // TEST_BODY + }); + } + // CLASSES + '''; +} diff --git a/flutter/packages/flutter_tools/test/integration.shard/build_ios_config_only_test.dart b/flutter/packages/flutter_tools/test/integration.shard/build_ios_config_only_test.dart new file mode 100644 index 0000000000000000000000000000000000000000..86adcfba17fa1299a121f7f7538bac046851482b --- /dev/null +++ b/flutter/packages/flutter_tools/test/integration.shard/build_ios_config_only_test.dart @@ -0,0 +1,73 @@ +// 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_testing/file_testing.dart'; +import 'package:flutter_tools/src/base/file_system.dart'; +import 'package:flutter_tools/src/base/io.dart'; + +import '../src/common.dart'; +import 'test_utils.dart'; + +void main() { + test('flutter build ios --config only updates generated xcconfig file without performing build', () async { + final String workingDirectory = fileSystem.path.join( + getFlutterRoot(), + 'dev', + 'integration_tests', + 'flutter_gallery', + ); + final String flutterBin = fileSystem.path.join(getFlutterRoot(), 'bin', 'flutter'); + + await processManager.run([ + flutterBin, + ...getLocalEngineArguments(), + 'clean', + ], workingDirectory: workingDirectory); + final List buildCommand = [ + flutterBin, + ...getLocalEngineArguments(), + 'build', + 'ios', + '--config-only', + '--release', + '--obfuscate', + '--split-debug-info=info', + '--no-codesign', + ]; + final ProcessResult firstRunResult = await processManager.run(buildCommand, workingDirectory: workingDirectory); + + expect(firstRunResult, const ProcessResultMatcher(stdoutPattern: 'Running pod install')); + + final File generatedConfig = fileSystem.file(fileSystem.path.join( + workingDirectory, + 'ios', + 'Flutter', + 'Generated.xcconfig', + )); + + // Config is updated if command succeeded. + expect(generatedConfig, exists); + expect(generatedConfig.readAsStringSync(), contains('DART_OBFUSCATION=true')); + + // file that only exists if app was fully built. + final File frameworkPlist = fileSystem.file(fileSystem.path.join( + workingDirectory, + 'build', + 'ios', + 'iphoneos', + 'Runner.app', + 'AppFrameworkInfo.plist', + )); + + expect(frameworkPlist, isNot(exists)); + + // Run again with no changes. + final ProcessResult secondRunResult = await processManager.run(buildCommand, workingDirectory: workingDirectory); + final String secondRunStdout = secondRunResult.stdout.toString(); + + expect(secondRunResult, const ProcessResultMatcher()); + // Do not run "pod install" when nothing changes. + expect(secondRunStdout, isNot(contains('pod install'))); + }, skip: !platform.isMacOS); // [intended] iOS builds only work on macos. +} diff --git a/flutter/packages/flutter_tools/test/integration.shard/build_macos_config_only_test.dart b/flutter/packages/flutter_tools/test/integration.shard/build_macos_config_only_test.dart new file mode 100644 index 0000000000000000000000000000000000000000..6fd271c55aa15429e3b7035c96e2bec76bcd6fcb --- /dev/null +++ b/flutter/packages/flutter_tools/test/integration.shard/build_macos_config_only_test.dart @@ -0,0 +1,73 @@ +// 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_testing/file_testing.dart'; +import 'package:flutter_tools/src/base/file_system.dart'; +import 'package:flutter_tools/src/base/io.dart'; + +import '../src/common.dart'; +import 'test_utils.dart'; + +void main() { + test('flutter build macOS --config only updates generated xcconfig file without performing build', () async { + final String workingDirectory = fileSystem.path.join( + getFlutterRoot(), + 'dev', + 'integration_tests', + 'flutter_gallery', + ); + final String flutterBin = fileSystem.path.join(getFlutterRoot(), 'bin', 'flutter'); + + await processManager.run([ + flutterBin, + ...getLocalEngineArguments(), + 'clean', + ], workingDirectory: workingDirectory); + final List buildCommand = [ + flutterBin, + ...getLocalEngineArguments(), + 'build', + 'macos', + '--config-only', + '--release', + '--obfuscate', + '--split-debug-info=info', + ]; + final ProcessResult firstRunResult = await processManager.run(buildCommand, workingDirectory: workingDirectory); + + expect(firstRunResult, const ProcessResultMatcher(stdoutPattern: 'Running pod install')); + + final File generatedConfig = fileSystem.file(fileSystem.path.join( + workingDirectory, + 'macos', + 'Flutter', + 'ephemeral', + 'Flutter-Generated.xcconfig', + )); + + // Config is updated if command succeeded. + expect(generatedConfig, exists); + expect(generatedConfig.readAsStringSync(), contains('DART_OBFUSCATION=true')); + + // file that only exists if app was fully built. + final File frameworkPlist = fileSystem.file(fileSystem.path.join( + workingDirectory, + 'build', + 'macos', + 'Build', + 'Products', + 'Release', + 'App.framework', + 'Resources', + 'Info.plist' + )); + + expect(frameworkPlist, isNot(exists)); + + // Run again with no changes. + final ProcessResult secondRunResult = await processManager.run(buildCommand, workingDirectory: workingDirectory); + + expect(secondRunResult, const ProcessResultMatcher()); + }, skip: !platform.isMacOS); // [intended] macOS builds only work on macos. +} diff --git a/flutter/packages/flutter_tools/test/integration.shard/build_preview_test.dart b/flutter/packages/flutter_tools/test/integration.shard/build_preview_test.dart new file mode 100644 index 0000000000000000000000000000000000000000..f1d3f3770413160c96517141152eecb55e61895e --- /dev/null +++ b/flutter/packages/flutter_tools/test/integration.shard/build_preview_test.dart @@ -0,0 +1,53 @@ +// 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:io'; + +import 'package:file_testing/file_testing.dart'; +import 'package:flutter_tools/src/base/file_system.dart'; +import 'package:flutter_tools/src/base/platform.dart'; +import 'package:flutter_tools/src/cache.dart'; + +import '../src/common.dart'; +import '../src/context.dart'; +import 'test_utils.dart'; + +void main() { + Cache.disableLocking(); + + late Directory tempDir; + final FileSystem fs = LocalFileSystemBlockingSetCurrentDirectory(); + final String flutterBin = fs.path.join(getFlutterRoot(), 'bin', 'flutter'); + final File previewBin = fs + .directory(getFlutterRoot()) + .childDirectory('bin') + .childDirectory('cache') + .childDirectory('artifacts') + .childDirectory('flutter_preview') + .childFile('flutter_preview.exe'); + + setUp(() { + tempDir = fs.systemTempDirectory.createTempSync('flutter_tools_preview_integration_test.'); + }); + + tearDown(() { + tryToDelete(tempDir); + tryToDelete(previewBin); + }); + + testUsingContext('flutter build _preview creates preview device', () async { + final ProcessResult result = await processManager.run([ + flutterBin, + 'build', + '_preview', + '--verbose', + ]); + + expect(result, const ProcessResultMatcher()); + expect( + previewBin, + exists, + ); + }, skip: !const LocalPlatform().isWindows); // [intended] Flutter Preview only supported on Windows currently +} diff --git a/flutter/packages/flutter_tools/test/integration.shard/cache_test.dart b/flutter/packages/flutter_tools/test/integration.shard/cache_test.dart new file mode 100644 index 0000000000000000000000000000000000000000..68d1ba62581e3fc69f569408d6594491a77b7bfd --- /dev/null +++ b/flutter/packages/flutter_tools/test/integration.shard/cache_test.dart @@ -0,0 +1,194 @@ +// 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:io' as io show ProcessSignal; + +import 'package:file/file.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/os.dart'; +import 'package:flutter_tools/src/base/terminal.dart'; +import 'package:flutter_tools/src/cache.dart'; +import 'package:process/process.dart'; +import 'package:test/fake.dart'; + +import '../src/common.dart'; +import '../src/fake_process_manager.dart'; +import '../src/fakes.dart'; +import 'test_utils.dart'; + +final String dart = fileSystem.path + .join(getFlutterRoot(), 'bin', platform.isWindows ? 'dart.bat' : 'dart'); + +void main() { + group('Cache.lock', () { + // Windows locking is too flaky for this to work reliably. + if (platform.isWindows) { + return; + } + testWithoutContext( + 'should log a message to stderr when lock is not acquired', () async { + final String? oldRoot = Cache.flutterRoot; + final Directory tempDir = fileSystem.systemTempDirectory.createTempSync('cache_test.'); + final BufferLogger logger = BufferLogger( + terminal: Terminal.test(), + outputPreferences: OutputPreferences(), + ); + logger.fatalWarnings = true; + Process? process; + try { + Cache.flutterRoot = tempDir.absolute.path; + final Cache cache = Cache.test( + fileSystem: fileSystem, + processManager: FakeProcessManager.any(), + logger: logger, + ); + final File cacheFile = fileSystem.file(fileSystem.path + .join(Cache.flutterRoot!, 'bin', 'cache', 'lockfile')) + ..createSync(recursive: true); + final File script = fileSystem.file(fileSystem.path + .join(Cache.flutterRoot!, 'bin', 'cache', 'test_lock.dart')); + script.writeAsStringSync(r''' +import 'dart:async'; +import 'dart:io'; + +Future main(List args) async { + File file = File(args[0]); + final RandomAccessFile lock = file.openSync(mode: FileMode.write); + while (true) { + try { + lock.lockSync(); + break; + } on FileSystemException {} + } + await Future.delayed(const Duration(seconds: 1)); + exit(0); +} +'''); + // Locks are per-process, so we have to launch a separate process to + // test out cache locking. + process = await const LocalProcessManager().start( + [dart, script.absolute.path, cacheFile.absolute.path], + ); + // Wait for the script to lock the test cache file before checking to + // see that the cache is unable to. + bool locked = false; + while (!locked) { + // Give the script a chance to try for the lock much more often. + await Future.delayed(const Duration(milliseconds: 100)); + final RandomAccessFile lock = cacheFile.openSync(mode: FileMode.write); + try { + // If we can lock it, unlock immediately to give the script a + // chance. + lock.lockSync(); + lock.unlockSync(); + } on FileSystemException { + // If we can't lock it, then the child script succeeded in locking + // it, and we can now test. + locked = true; + break; + } + } + // Finally, test that the cache cannot lock a locked file. This should + // print a message if it can't lock the file. + await cache.lock(); + } finally { + // Just to keep from leaving the process hanging around. + process?.kill(io.ProcessSignal.sighup); + tryToDelete(tempDir); + Cache.flutterRoot = oldRoot; + } + expect(logger.statusText, isEmpty); + expect(logger.errorText, isEmpty); + expect(logger.warningText, + equals('Waiting for another flutter command to release the startup lock...\n')); + expect(logger.hadErrorOutput, isFalse); + // Should still be false, since the particular "Waiting..." message above + // aims to avoid triggering failure as a fatal warning. + expect(logger.hadWarningOutput, isFalse); + }); + testWithoutContext( + 'should log a warning message for unknown version ', () async { + final String? oldRoot = Cache.flutterRoot; + final Directory tempDir = fileSystem.systemTempDirectory.createTempSync('cache_test.'); + final BufferLogger logger = BufferLogger( + terminal: Terminal.test(), + outputPreferences: OutputPreferences(), + ); + logger.fatalWarnings = true; + try { + Cache.flutterRoot = tempDir.absolute.path; + final Cache cache = Cache.test( + fileSystem: fileSystem, + processManager: FakeProcessManager.any(), + logger: logger, + ); + final FakeVersionlessArtifact artifact = FakeVersionlessArtifact(cache); + cache.registerArtifact(artifact); + await artifact.update(FakeArtifactUpdater(), logger, fileSystem, FakeOperatingSystemUtils()); + } finally { + tryToDelete(tempDir); + Cache.flutterRoot = oldRoot; + } + expect(logger.statusText, isEmpty); + expect(logger.warningText, equals('No known version for the artifact name "fake". ' + 'Flutter can continue, but the artifact may be re-downloaded on ' + 'subsequent invocations until the problem is resolved.\n')); + expect(logger.hadErrorOutput, isFalse); + expect(logger.hadWarningOutput, isTrue); + }); + }); + + testWithoutContext('Dart SDK target arch matches host arch', () async { + if (platform.isWindows) { + return; + } + final ProcessResult dartResult = await const LocalProcessManager().run( + [dart, '--version'], + ); + // Parse 'arch' out of a string like '... "os_arch"\n'. + final String dartTargetArch = (dartResult.stdout as String) + .trim().split(' ').last.replaceAll('"', '').split('_')[1]; + final ProcessResult unameResult = await const LocalProcessManager().run( + ['uname', '-m'], + ); + final String unameArch = (unameResult.stdout as String) + .trim().replaceAll('aarch64', 'arm64') + .replaceAll('x86_64', 'x64'); + expect(dartTargetArch, equals(unameArch)); + }); +} + +class FakeArtifactUpdater extends Fake implements ArtifactUpdater { + void Function(String, Uri, Directory)? onDownloadZipArchive; + void Function(String, Uri, Directory)? onDownloadZipTarball; + + @override + Future downloadZippedTarball(String message, Uri url, Directory location) async { + onDownloadZipTarball?.call(message, url, location); + } + + @override + Future downloadZipArchive(String message, Uri url, Directory location) async { + onDownloadZipArchive?.call(message, url, location); + } + + @override + void removeDownloadedFiles() { } +} + +class FakeVersionlessArtifact extends CachedArtifact { + FakeVersionlessArtifact(Cache cache) : super( + 'fake', + cache, + DevelopmentArtifact.universal, + ); + + @override + String? get version => null; + + @override + Future updateInner(ArtifactUpdater artifactUpdater, FileSystem fileSystem, OperatingSystemUtils operatingSystemUtils) async { } +} diff --git a/flutter/packages/flutter_tools/test/integration.shard/command_output_test.dart b/flutter/packages/flutter_tools/test/integration.shard/command_output_test.dart new file mode 100644 index 0000000000000000000000000000000000000000..60c34113dec4ff84fa6cb07048afe49337b83ce2 --- /dev/null +++ b/flutter/packages/flutter_tools/test/integration.shard/command_output_test.dart @@ -0,0 +1,274 @@ +// Copyright 2014 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +import 'dart:convert'; + +import 'package:flutter_tools/src/base/file_system.dart'; +import 'package:flutter_tools/src/base/io.dart'; +import 'package:flutter_tools/src/features.dart'; + +import '../src/common.dart'; +import 'test_utils.dart'; + +// This test file does not use [getLocalEngineArguments] because it is testing +// command output and not using cached artifacts. + +void main() { + testWithoutContext('All development tools and deprecated commands are hidden and help text is not verbose', () async { + final String flutterBin = fileSystem.path.join(getFlutterRoot(), 'bin', 'flutter'); + final ProcessResult result = await processManager.run([ + flutterBin, + '-h', + '-v', + ]); + + // Development tools. + expect(result.stdout, isNot(contains('update-packages'))); + + // Deprecated. + expect(result.stdout, isNot(contains('make-host-app-editable'))); + + // Only printed by verbose tool. + expect(result.stdout, isNot(contains('exiting with code 0'))); + }); + + testWithoutContext('Flutter help is shown with -? command line argument', () async { + final String flutterBin = fileSystem.path.join(getFlutterRoot(), 'bin', 'flutter'); + final ProcessResult result = await processManager.run([ + flutterBin, + '-?', + ]); + + // Development tools. + expect(result.stdout, contains( + 'Run "flutter help " for more information about a command.\n' + 'Run "flutter help -v" for verbose help output, including less commonly used options.' + )); + }); + + testWithoutContext('flutter doctor is not verbose', () async { + final String flutterBin = fileSystem.path.join(getFlutterRoot(), 'bin', 'flutter'); + final ProcessResult result = await processManager.run([ + flutterBin, + 'doctor', + '-v', + ]); + + // Only printed by verbose tool. + expect(result.stdout, isNot(contains('exiting with code 0'))); + }); + + testWithoutContext('flutter doctor -vv super verbose', () async { + final String flutterBin = fileSystem.path.join(getFlutterRoot(), 'bin', 'flutter'); + final ProcessResult result = await processManager.run([ + flutterBin, + 'doctor', + '-vv', + ]); + + // Check for message only printed in verbose mode. + expect(result.stdout, contains('Shutdown hooks complete')); + }); + + testWithoutContext('flutter config --list contains all features', () async { + final String flutterBin = fileSystem.path.join(getFlutterRoot(), 'bin', 'flutter'); + final ProcessResult result = await processManager.run([ + flutterBin, + 'config', + '--list' + ]); + + // contains all of the experiments in features.dart + expect((result.stdout as String).split('\n'), containsAll([ + for (final Feature feature in allConfigurableFeatures) + contains(feature.configSetting), + ])); + }); + + testWithoutContext('flutter run --machine uses AppRunLogger', () async { + final Directory directory = createResolvedTempDirectorySync('flutter_run_test.') + .createTempSync('_flutter_run_test.') + ..createSync(recursive: true); + + try { + directory + .childFile('pubspec.yaml') + .writeAsStringSync('name: foo'); + directory + .childFile('.packages') + .writeAsStringSync('\n'); + directory + .childDirectory('lib') + .childFile('main.dart') + .createSync(recursive: true); + final String flutterBin = fileSystem.path.join(getFlutterRoot(), 'bin', 'flutter'); + final ProcessResult result = await processManager.run([ + flutterBin, + 'run', + '--show-test-device', // ensure command can fail to run and hit injection of correct logger. + '--machine', + '-v', + '--no-resident', + ], workingDirectory: directory.path); + expect(result.stderr, isNot(contains('Oops; flutter has exited unexpectedly:'))); + } finally { + tryToDelete(directory); + } + }); + + testWithoutContext('flutter attach --machine uses AppRunLogger', () async { + final String flutterBin = fileSystem.path.join(getFlutterRoot(), 'bin', 'flutter'); + final ProcessResult result = await processManager.run([ + flutterBin, + 'attach', + '--machine', + '-v', + ]); + + expect(result.stderr, contains('Target file')); // Target file not found, but different paths on Windows and Linux/macOS. + }); + + testWithoutContext('flutter --version --machine outputs JSON with flutterRoot', () async { + final String flutterBin = fileSystem.path.join(getFlutterRoot(), 'bin', 'flutter'); + final ProcessResult result = await processManager.run([ + flutterBin, + '--version', + '--machine', + ]); + + final Map versionInfo = json.decode(result.stdout + .toString() + .replaceAll('Building flutter tool...', '') + .replaceAll('Waiting for another flutter command to release the startup lock...', '') + .trim()) as Map; + + expect(versionInfo, containsPair('flutterRoot', isNotNull)); + }); + + testWithoutContext('A tool exit is thrown for an invalid debug-url in flutter attach', () async { + // This test is almost exactly like the next one; update them together please. + final String flutterBin = fileSystem.path.join(getFlutterRoot(), 'bin', 'flutter'); + final String helloWorld = fileSystem.path.join(getFlutterRoot(), 'examples', 'hello_world'); + final ProcessResult result = await processManager.run([ + flutterBin, + '--show-test-device', + 'attach', + '-d', + 'flutter-tester', + '--debug-url=http://127.0.0.1:3333*/', + ], workingDirectory: helloWorld); + + expect( + result, + const ProcessResultMatcher(exitCode: 1, stderrPattern: 'Invalid `--debug-url`: http://127.0.0.1:3333*/'), + ); + }); + + testWithoutContext('--debug-uri is an alias for --debug-url', () async { + // This text is exactly the same as the previous one but with a "l" turned to an "i". + final String flutterBin = fileSystem.path.join(getFlutterRoot(), 'bin', 'flutter'); + final String helloWorld = fileSystem.path.join(getFlutterRoot(), 'examples', 'hello_world'); + final ProcessResult result = await processManager.run([ + flutterBin, + '--show-test-device', + 'attach', + '-d', + 'flutter-tester', + '--debug-uri=http://127.0.0.1:3333*/', // "uri" not "url" + ], workingDirectory: helloWorld); + + expect( + result, + const ProcessResultMatcher( + exitCode: 1, + // _"url"_ not "uri"! + stderrPattern: 'Invalid `--debug-url`: http://127.0.0.1:3333*/', + ), + ); + }); + + testWithoutContext('will load bootstrap script before starting', () async { + final String flutterBin = fileSystem.path.join(getFlutterRoot(), 'bin', 'flutter'); + + final File bootstrap = fileSystem.file(fileSystem.path.join( + getFlutterRoot(), + 'bin', + 'internal', + platform.isWindows ? 'bootstrap.bat' : 'bootstrap.sh'), + ); + + try { + bootstrap.writeAsStringSync('echo TESTING 1 2 3'); + final ProcessResult result = await processManager.run([ + flutterBin, + ]); + + expect(result.stdout, contains('TESTING 1 2 3')); + } finally { + bootstrap.deleteSync(); + } + }); + + testWithoutContext('Providing sksl bundle with missing file with tool exit', () async { + final String flutterBin = fileSystem.path.join(getFlutterRoot(), 'bin', 'flutter'); + final String helloWorld = fileSystem.path.join(getFlutterRoot(), 'examples', 'hello_world'); + final ProcessResult result = await processManager.run([ + flutterBin, + 'build', + 'apk', + '--bundle-sksl-path=foo/bar/baz.json', // This file does not exist. + ], workingDirectory: helloWorld); + + expect(result, const ProcessResultMatcher( + exitCode: 1, + stderrPattern: 'No SkSL shader bundle found at foo/bar/baz.json'), + ); + }); + + testWithoutContext('flutter attach does not support --release', () async { + final String flutterBin = fileSystem.path.join(getFlutterRoot(), 'bin', 'flutter'); + final String helloWorld = fileSystem.path.join(getFlutterRoot(), 'examples', 'hello_world'); + final ProcessResult result = await processManager.run([ + flutterBin, + '--show-test-device', + 'attach', + '--release', + ], workingDirectory: helloWorld); + + expect(result.exitCode, isNot(0)); + expect(result.stderr, contains('Could not find an option named "release"')); + }); + + testWithoutContext('flutter can report crashes', () async { + final String flutterBin = fileSystem.path.join(getFlutterRoot(), 'bin', 'flutter'); + final ProcessResult result = await processManager.run([ + flutterBin, + 'update-packages', + '--crash', + ], environment: { + 'BOT': 'false', + }); + + expect(result.exitCode, isNot(0)); + expect(result.stderr, contains( + 'Oops; flutter has exited unexpectedly: "Bad state: test crash please ignore.".\n' + 'A crash report has been written to', + )); + }); + + testWithoutContext('flutter supports trailing args', () async { + final String flutterBin = fileSystem.path.join(getFlutterRoot(), 'bin', 'flutter'); + final String helloWorld = fileSystem.path.join(getFlutterRoot(), 'examples', 'hello_world'); + final ProcessResult result = await processManager.run([ + flutterBin, + 'test', + 'test/hello_test.dart', + '-r', + 'json', + ], workingDirectory: helloWorld); + + expect(result, const ProcessResultMatcher()); + expect(result.stderr, isEmpty); + }); +} diff --git a/flutter/packages/flutter_tools/test/integration.shard/coverage_collection_test.dart b/flutter/packages/flutter_tools/test/integration.shard/coverage_collection_test.dart new file mode 100644 index 0000000000000000000000000000000000000000..22a52a3a01067adbfceccff6649b9f9ea278ba5b --- /dev/null +++ b/flutter/packages/flutter_tools/test/integration.shard/coverage_collection_test.dart @@ -0,0 +1,37 @@ +// 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_testing/file_testing.dart'; + +import '../src/common.dart'; + +import 'test_data/test_project.dart'; +import 'test_driver.dart'; +import 'test_utils.dart'; + +void main() { + late Directory tempDir; + + setUp(() async { + tempDir = createResolvedTempDirectorySync('flutter_coverage_collection_test.'); + }); + + tearDown(() async { + tryToDelete(tempDir); + }); + + testWithoutContext('Can collect coverage in machine mode', () async { + final TestProject project = TestProject(); + await project.setUpIn(tempDir); + final FlutterTestTestDriver flutter = FlutterTestTestDriver(tempDir); + await flutter.test(coverage: true); + await flutter.done; + + final File lcovFile = tempDir.childDirectory('coverage').childFile('lcov.info'); + + expect(lcovFile, exists); + expect(lcovFile.readAsStringSync(), contains('main.dart')); // either 'SF:lib/main.dart or SF:lib\\main.dart + }); +} diff --git a/flutter/packages/flutter_tools/test/integration.shard/daemon_mode_test.dart b/flutter/packages/flutter_tools/test/integration.shard/daemon_mode_test.dart new file mode 100644 index 0000000000000000000000000000000000000000..c8d4b3952b806cd4febfea7e0e799a49c528194b --- /dev/null +++ b/flutter/packages/flutter_tools/test/integration.shard/daemon_mode_test.dart @@ -0,0 +1,80 @@ +// Copyright 2014 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +import 'dart:async'; +import 'dart:convert'; +import 'dart:io' hide Directory; + +import 'package:file/file.dart'; +import 'package:process/process.dart'; + +import '../src/common.dart'; +import 'test_data/basic_project.dart'; +import 'test_driver.dart'; +import 'test_utils.dart'; + +void main() { + late Directory tempDir; + late Process daemonProcess; + + setUp(() async { + tempDir = createResolvedTempDirectorySync('daemon_mode_test.'); + }); + + tearDown(() async { + tryToDelete(tempDir); + daemonProcess.kill(); + }); + + testWithoutContext('device.getDevices', () async { + final BasicProject project = BasicProject(); + await project.setUpIn(tempDir); + + final String flutterBin = fileSystem.path.join(getFlutterRoot(), 'bin', 'flutter'); + + const ProcessManager processManager = LocalProcessManager(); + daemonProcess = await processManager.start( + [flutterBin, ...getLocalEngineArguments(), '--show-test-device', 'daemon'], + workingDirectory: tempDir.path, + ); + + final StreamController stdout = StreamController.broadcast(); + transformToLines(daemonProcess.stdout).listen((String line) => stdout.add(line)); + final Stream?> stream = stdout + .stream + .map?>(parseFlutterResponse) + .where((Map? value) => value != null); + + Map response = (await stream.first)!; + expect(response['event'], 'daemon.connected'); + + // start listening for devices + daemonProcess.stdin.writeln('[${jsonEncode({ + 'id': 1, + 'method': 'device.enable', + })}]'); + response = (await stream.firstWhere((Map? json) => json!['id'] == 1))!; + expect(response['id'], 1); + expect(response['error'], isNull); + + // [{"event":"device.added","params":{"id":"flutter-tester","name": + // "Flutter test device","platform":"flutter-tester","emulator":false}}] + response = (await stream.first)!; + expect(response['event'], 'device.added'); + + // get the list of all devices + daemonProcess.stdin.writeln('[${jsonEncode({ + 'id': 2, + 'method': 'device.getDevices', + })}]'); + // Skip other device.added events that may fire (desktop/web devices). + response = (await stream.firstWhere((Map? response) => response!['event'] != 'device.added'))!; + expect(response['id'], 2); + expect(response['error'], isNull); + + final dynamic result = response['result']; + expect(result, isList); + expect(result, isNotEmpty); + }); +} diff --git a/flutter/packages/flutter_tools/test/integration.shard/debugger_stepping_test.dart b/flutter/packages/flutter_tools/test/integration.shard/debugger_stepping_test.dart new file mode 100644 index 0000000000000000000000000000000000000000..652ca848754014815e06b33e8f59304ae4f81765 --- /dev/null +++ b/flutter/packages/flutter_tools/test/integration.shard/debugger_stepping_test.dart @@ -0,0 +1,52 @@ +// 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 '../src/common.dart'; +import 'test_data/stepping_project.dart'; +import 'test_driver.dart'; +import 'test_utils.dart'; + +void main() { + late Directory tempDir; + + setUp(() async { + tempDir = createResolvedTempDirectorySync('debugger_stepping_test.'); + }); + + tearDown(() async { + tryToDelete(tempDir); + }); + + testWithoutContext('can step over statements', () async { + final SteppingProject project = SteppingProject(); + await project.setUpIn(tempDir); + + final FlutterRunTestDriver flutter = FlutterRunTestDriver(tempDir); + + await flutter.run(withDebugger: true, startPaused: true); + await flutter.addBreakpoint(project.breakpointUri, project.breakpointLine); + await flutter.resume(waitForNextPause: true); // Now we should be on the breakpoint. + + expect((await flutter.getSourceLocation())?.line, equals(project.breakpointLine)); + + // Issue 5 steps, ensuring that we end up on the annotated lines each time. + for (int i = 1; i <= project.numberOfSteps; i += 1) { + await flutter.stepOverOrOverAsyncSuspension(); + final SourcePosition? location = await flutter.getSourceLocation(); + final int? actualLine = location?.line; + + // Get the line we're expected to stop at by searching for the comment + // within the source code. + final int expectedLine = project.lineForStep(i); + + expect(actualLine, equals(expectedLine), + reason: 'After $i steps, debugger should stop at $expectedLine but stopped at $actualLine' + ); + } + + await flutter.stop(); + }); +} diff --git a/flutter/packages/flutter_tools/test/integration.shard/deferred_components_test.dart b/flutter/packages/flutter_tools/test/integration.shard/deferred_components_test.dart new file mode 100644 index 0000000000000000000000000000000000000000..f01ea24bf59766db341263cae5f60e3e42b45827 --- /dev/null +++ b/flutter/packages/flutter_tools/test/integration.shard/deferred_components_test.dart @@ -0,0 +1,273 @@ +// 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/file.dart'; +import 'package:file_testing/file_testing.dart'; +import 'package:flutter_tools/src/base/io.dart'; + +import '../src/common.dart'; +import 'test_data/deferred_components_project.dart'; +import 'test_driver.dart'; +import 'test_utils.dart'; + + +void main() { + late Directory tempDir; + late FlutterRunTestDriver flutter; + + setUp(() async { + tempDir = createResolvedTempDirectorySync('run_test.'); + flutter = FlutterRunTestDriver(tempDir); + }); + + tearDown(() async { + await flutter.stop(); + tryToDelete(tempDir); + }); + + testWithoutContext('simple build appbundle android-arm64 target succeeds', () async { + final DeferredComponentsProject project = DeferredComponentsProject(BasicDeferredComponentsConfig()); + await project.setUpIn(tempDir); + final String flutterBin = fileSystem.path.join(getFlutterRoot(), 'bin', 'flutter'); + final ProcessResult result = await processManager.run([ + flutterBin, + ...getLocalEngineArguments(), + 'build', + 'appbundle', + '--target-platform=android-arm64', + ], workingDirectory: tempDir.path); + + expect(result, const ProcessResultMatcher(stdoutPattern: 'app-release.aab')); + expect(result.stdout.toString(), contains('Deferred components prebuild validation passed.')); + expect(result.stdout.toString(), contains('Deferred components gen_snapshot validation passed.')); + + final String line = result.stdout.toString() + .split('\n') + .firstWhere((String line) => line.contains('app-release.aab')); + + final String outputFilePath = line.split(' ')[2].trim(); + final File outputFile = fileSystem.file(fileSystem.path.join(tempDir.path, outputFilePath)); + expect(outputFile, exists); + + final Archive archive = ZipDecoder().decodeBytes(outputFile.readAsBytesSync()); + + expect(archive.findFile('base/lib/arm64-v8a/libapp.so') != null, true); + expect(archive.findFile('base/lib/arm64-v8a/libflutter.so') != null, true); + expect(archive.findFile('component1/lib/arm64-v8a/libapp.so-2.part.so') != null, true); + + expect(archive.findFile('component1/assets/flutter_assets/test_assets/asset2.txt') != null, true); + expect(archive.findFile('base/assets/flutter_assets/test_assets/asset1.txt') != null, true); + }); + + testWithoutContext('simple build appbundle all targets succeeds', () async { + final DeferredComponentsProject project = DeferredComponentsProject(BasicDeferredComponentsConfig()); + await project.setUpIn(tempDir); + final String flutterBin = fileSystem.path.join(getFlutterRoot(), 'bin', 'flutter'); + final ProcessResult result = await processManager.run([ + flutterBin, + ...getLocalEngineArguments(), + 'build', + 'appbundle', + ], workingDirectory: tempDir.path); + + printOnFailure('stdout:\n${result.stdout}'); + printOnFailure('stderr:\n${result.stderr}'); + expect(result.stdout.toString(), contains('app-release.aab')); + expect(result.stdout.toString(), contains('Deferred components prebuild validation passed.')); + expect(result.stdout.toString(), contains('Deferred components gen_snapshot validation passed.')); + + final String line = result.stdout.toString() + .split('\n') + .firstWhere((String line) => line.contains('app-release.aab')); + + final String outputFilePath = line.split(' ')[2].trim(); + final File outputFile = fileSystem.file(fileSystem.path.join(tempDir.path, outputFilePath)); + expect(outputFile, exists); + + final Archive archive = ZipDecoder().decodeBytes(outputFile.readAsBytesSync()); + + expect(archive.findFile('base/lib/arm64-v8a/libapp.so') != null, true); + expect(archive.findFile('base/lib/arm64-v8a/libflutter.so') != null, true); + expect(archive.findFile('component1/lib/arm64-v8a/libapp.so-2.part.so') != null, true); + + expect(archive.findFile('base/lib/armeabi-v7a/libapp.so') != null, true); + expect(archive.findFile('base/lib/armeabi-v7a/libflutter.so') != null, true); + expect(archive.findFile('component1/lib/armeabi-v7a/libapp.so-2.part.so') != null, true); + + expect(archive.findFile('base/lib/x86_64/libapp.so') != null, true); + expect(archive.findFile('base/lib/x86_64/libflutter.so') != null, true); + expect(archive.findFile('component1/lib/x86_64/libapp.so-2.part.so') != null, true); + + expect(archive.findFile('component1/assets/flutter_assets/test_assets/asset2.txt') != null, true); + expect(archive.findFile('base/assets/flutter_assets/test_assets/asset1.txt') != null, true); + + expect(result, const ProcessResultMatcher()); + }); + + testWithoutContext('simple build appbundle no-deferred-components succeeds', () async { + final DeferredComponentsProject project = DeferredComponentsProject(BasicDeferredComponentsConfig()); + await project.setUpIn(tempDir); + final String flutterBin = fileSystem.path.join(getFlutterRoot(), 'bin', 'flutter'); + final ProcessResult result = await processManager.run([ + flutterBin, + ...getLocalEngineArguments(), + 'build', + 'appbundle', + '--no-deferred-components', + ], workingDirectory: tempDir.path); + + expect(result, const ProcessResultMatcher(stdoutPattern: 'app-release.aab')); + expect(result.stdout.toString(), isNot(contains('Deferred components prebuild validation passed.'))); + expect(result.stdout.toString(), isNot(contains('Deferred components gen_snapshot validation passed.'))); + + final String line = result.stdout.toString() + .split('\n') + .firstWhere((String line) => line.contains('app-release.aab')); + + final String outputFilePath = line.split(' ')[2].trim(); + final File outputFile = fileSystem.file(fileSystem.path.join(tempDir.path, outputFilePath)); + expect(outputFile, exists); + + final Archive archive = ZipDecoder().decodeBytes(outputFile.readAsBytesSync()); + + expect(archive.findFile('base/lib/arm64-v8a/libapp.so') != null, true); + expect(archive.findFile('base/lib/arm64-v8a/libflutter.so') != null, true); + expect(archive.findFile('component1/lib/arm64-v8a/libapp.so-2.part.so') != null, false); + + expect(archive.findFile('base/lib/armeabi-v7a/libapp.so') != null, true); + expect(archive.findFile('base/lib/armeabi-v7a/libflutter.so') != null, true); + expect(archive.findFile('component1/lib/armeabi-v7a/libapp.so-2.part.so') != null, false); + + expect(archive.findFile('base/lib/x86_64/libapp.so') != null, true); + expect(archive.findFile('base/lib/x86_64/libflutter.so') != null, true); + expect(archive.findFile('component1/lib/x86_64/libapp.so-2.part.so') != null, false); + + // Asset 2 is merged into the base module assets. + expect(archive.findFile('component1/assets/flutter_assets/test_assets/asset2.txt') != null, false); + expect(archive.findFile('base/assets/flutter_assets/test_assets/asset2.txt') != null, true); + expect(archive.findFile('base/assets/flutter_assets/test_assets/asset1.txt') != null, true); + }); + + testWithoutContext('simple build appbundle mismatched golden no-validate-deferred-components succeeds', () async { + final DeferredComponentsProject project = DeferredComponentsProject(MismatchedGoldenDeferredComponentsConfig()); + await project.setUpIn(tempDir); + final String flutterBin = fileSystem.path.join(getFlutterRoot(), 'bin', 'flutter'); + final ProcessResult result = await processManager.run([ + flutterBin, + ...getLocalEngineArguments(), + 'build', + 'appbundle', + '--no-validate-deferred-components', + ], workingDirectory: tempDir.path); + + expect(result, const ProcessResultMatcher(stdoutPattern: 'app-release.aab')); + printOnFailure('stdout:\n${result.stdout}'); + printOnFailure('stderr:\n${result.stderr}'); + expect(result.stdout.toString(), isNot(contains('Deferred components prebuild validation passed.'))); + expect(result.stdout.toString(), isNot(contains('Deferred components gen_snapshot validation passed.'))); + expect(result.stdout.toString(), isNot(contains('New loading units were found:'))); + expect(result.stdout.toString(), isNot(contains('Previously existing loading units no longer exist:'))); + + final String line = result.stdout.toString() + .split('\n') + .firstWhere((String line) => line.contains('app-release.aab')); + + final String outputFilePath = line.split(' ')[2].trim(); + final File outputFile = fileSystem.file(fileSystem.path.join(tempDir.path, outputFilePath)); + expect(outputFile, exists); + + final Archive archive = ZipDecoder().decodeBytes(outputFile.readAsBytesSync()); + + expect(archive.findFile('base/lib/arm64-v8a/libapp.so') != null, true); + expect(archive.findFile('base/lib/arm64-v8a/libflutter.so') != null, true); + expect(archive.findFile('component1/lib/arm64-v8a/libapp.so-2.part.so') != null, true); + + expect(archive.findFile('base/lib/armeabi-v7a/libapp.so') != null, true); + expect(archive.findFile('base/lib/armeabi-v7a/libflutter.so') != null, true); + expect(archive.findFile('component1/lib/armeabi-v7a/libapp.so-2.part.so') != null, true); + + expect(archive.findFile('base/lib/x86_64/libapp.so') != null, true); + expect(archive.findFile('base/lib/x86_64/libflutter.so') != null, true); + expect(archive.findFile('component1/lib/x86_64/libapp.so-2.part.so') != null, true); + + expect(archive.findFile('component1/assets/flutter_assets/test_assets/asset2.txt') != null, true); + expect(archive.findFile('base/assets/flutter_assets/test_assets/asset1.txt') != null, true); + }); + + testWithoutContext('simple build appbundle missing android dynamic feature module fails', () async { + final DeferredComponentsProject project = DeferredComponentsProject(NoAndroidDynamicFeatureModuleDeferredComponentsConfig()); + await project.setUpIn(tempDir); + final String flutterBin = fileSystem.path.join(getFlutterRoot(), 'bin', 'flutter'); + final ProcessResult result = await processManager.run([ + flutterBin, + ...getLocalEngineArguments(), + 'build', + 'appbundle', + ], workingDirectory: tempDir.path); + + expect(result, const ProcessResultMatcher(exitCode: 1, stdoutPattern: 'Newly generated android files:')); + + expect(result.stdout.toString(), isNot(contains('app-release.aab'))); + expect(result.stdout.toString(), isNot(contains('Deferred components prebuild validation passed.'))); + expect(result.stdout.toString(), isNot(contains('Deferred components gen_snapshot validation passed.'))); + + final String pathSeparator = fileSystem.path.separator; + expect(result.stdout.toString(), contains('build${pathSeparator}android_deferred_components_setup_files${pathSeparator}component1${pathSeparator}build.gradle')); + expect(result.stdout.toString(), contains('build${pathSeparator}android_deferred_components_setup_files${pathSeparator}component1${pathSeparator}src${pathSeparator}main${pathSeparator}AndroidManifest.xml')); + }); + + testWithoutContext('simple build appbundle missing golden fails', () async { + final DeferredComponentsProject project = DeferredComponentsProject(NoGoldenDeferredComponentsConfig()); + await project.setUpIn(tempDir); + final String flutterBin = fileSystem.path.join(getFlutterRoot(), 'bin', 'flutter'); + final ProcessResult result = await processManager.run([ + flutterBin, + ...getLocalEngineArguments(), + 'build', + 'appbundle', + ], workingDirectory: tempDir.path); + + expect(result, const ProcessResultMatcher(exitCode: 1)); + expect(result.stdout.toString(), isNot(contains('app-release.aab'))); + expect(result.stdout.toString(), contains('Deferred components prebuild validation passed.')); + expect(result.stdout.toString(), isNot(contains('Deferred components gen_snapshot validation passed.'))); + + expect(result.stdout.toString(), contains('New loading units were found:')); + expect(result.stdout.toString(), contains('- package:test/deferred_library.dart')); + + expect(result.stdout.toString(), isNot(contains('Previously existing loading units no longer exist:'))); + }); + + testWithoutContext('simple build appbundle mismatched golden fails', () async { + final DeferredComponentsProject project = DeferredComponentsProject(MismatchedGoldenDeferredComponentsConfig()); + await project.setUpIn(tempDir); + final String flutterBin = fileSystem.path.join(getFlutterRoot(), 'bin', 'flutter'); + final ProcessResult result = await processManager.run([ + flutterBin, + ...getLocalEngineArguments(), + 'build', + 'appbundle', + ], workingDirectory: tempDir.path); + + expect( + result, + const ProcessResultMatcher( + exitCode: 1, + stdoutPattern: 'Deferred components prebuild validation passed.', + ), + ); + expect(result.stdout.toString(), isNot(contains('app-release.aab'))); + expect(result.stdout.toString(), isNot(contains('Deferred components gen_snapshot validation passed.'))); + + expect(result.stdout.toString(), contains('New loading units were found:')); + expect(result.stdout.toString(), contains('- package:test/deferred_library.dart')); + + expect(result.stdout.toString(), contains('Previously existing loading units no longer exist:')); + expect(result.stdout.toString(), contains('- package:test/invalid_lib_name.dart')); + + expect(result.stdout.toString(), contains('This loading unit check will not fail again on the next build attempt')); + + }); +} diff --git a/flutter/packages/flutter_tools/test/integration.shard/deprecated_gradle_settings_test.dart b/flutter/packages/flutter_tools/test/integration.shard/deprecated_gradle_settings_test.dart new file mode 100644 index 0000000000000000000000000000000000000000..dd4723d4a4297bf6d032853e2efbae389423acc8 --- /dev/null +++ b/flutter/packages/flutter_tools/test/integration.shard/deprecated_gradle_settings_test.dart @@ -0,0 +1,69 @@ +// 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/src/interface/file.dart'; +import 'package:file_testing/file_testing.dart'; +import 'package:flutter_tools/src/base/io.dart'; + +import '../src/common.dart'; +import 'test_utils.dart'; + +/// Tests that apps can be built using the deprecated `android/settings.gradle` file. +/// This test should be removed once apps have been migrated to this new file. +// TODO(egarciad): Migrate existing files, https://github.com/flutter/flutter/issues/54566 +void main() { + test('android project using deprecated settings.gradle will still build', () async { + final String workingDirectory = fileSystem.path.join(getFlutterRoot(), 'dev', 'integration_tests', 'gradle_deprecated_settings'); + final String flutterBin = fileSystem.path.join(getFlutterRoot(), 'bin', 'flutter'); + + final File settingsDotGradleFile = fileSystem.file( + fileSystem.path.join(workingDirectory, 'android', 'settings.gradle')); + const String expectedSettingsDotGradle = r""" +// Copyright 2014 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +// This is the `settings.gradle` file that apps were created with until Flutter +// v1.22.0. This file has changed, so it must be migrated in existing projects. + +include ':app' + +def flutterProjectRoot = rootProject.projectDir.parentFile.toPath() +def localPropertiesFile = new File(rootProject.projectDir, "local.properties") +def properties = new Properties() + +def plugins = new Properties() +def pluginsFile = new File(flutterProjectRoot.toFile(), '.flutter-plugins') +if (pluginsFile.exists()) { + pluginsFile.withReader('UTF-8') { reader -> plugins.load(reader) } +} + +plugins.each { name, path -> + def pluginDirectory = flutterProjectRoot.resolve(path).resolve('android').toFile() + include ":$name" + project(":$name").projectDir = pluginDirectory +} +"""; + + expect( + settingsDotGradleFile.readAsStringSync().trim().replaceAll('\r', ''), + equals(expectedSettingsDotGradle.trim()), + ); + + final ProcessResult result = await processManager.run([ + flutterBin, + 'build', + 'apk', + '--debug', + '--target-platform', 'android-arm', + '--verbose', + ], workingDirectory: workingDirectory); + + expect(result, const ProcessResultMatcher()); + + final String apkPath = fileSystem.path.join( + workingDirectory, 'build', 'app', 'outputs', 'flutter-apk', 'app-debug.apk'); + expect(fileSystem.file(apkPath), exists); + }); +} diff --git a/flutter/packages/flutter_tools/test/integration.shard/devtools_uri_test.dart b/flutter/packages/flutter_tools/test/integration.shard/devtools_uri_test.dart new file mode 100644 index 0000000000000000000000000000000000000000..af15861554ed7203abe1f1fb13c9fb0af843e7fe --- /dev/null +++ b/flutter/packages/flutter_tools/test/integration.shard/devtools_uri_test.dart @@ -0,0 +1,53 @@ +// 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/file_system.dart'; +import 'package:flutter_tools/src/base/io.dart'; +import 'package:flutter_tools/src/convert.dart'; + +import '../src/common.dart'; +import 'test_data/basic_project.dart'; +import 'test_utils.dart'; + +void main() { + late Directory tempDir; + final BasicProject project = BasicProject(); + + setUp(() async { + tempDir = createResolvedTempDirectorySync('run_test.'); + await project.setUpIn(tempDir); + }); + + tearDown(() async { + tryToDelete(tempDir); + }); + + // Regression test for https://github.com/flutter/flutter/issues/126691 + testWithoutContext('flutter run --start-paused prints DevTools URI', () async { + final Completer completer = Completer(); + const String matcher = 'The Flutter DevTools debugger and profiler on'; + + final String flutterBin = fileSystem.path.join(getFlutterRoot(), 'bin', 'flutter'); + final Process process = await processManager.start([ + flutterBin, + 'run', + '--start-paused', + '-d', + 'flutter-tester', + ], workingDirectory: tempDir.path); + + final StreamSubscription sub; + sub = process.stdout.transform(utf8.decoder).listen((String message) { + if (message.contains(matcher)) { + completer.complete(); + } + }); + await completer.future; + await sub.cancel(); + process.kill(); + await process.exitCode; + }); +} diff --git a/flutter/packages/flutter_tools/test/integration.shard/downgrade_upgrade_integration_test.dart b/flutter/packages/flutter_tools/test/integration.shard/downgrade_upgrade_integration_test.dart new file mode 100644 index 0000000000000000000000000000000000000000..20b7675b78a5175e406689069ac40930fed5d316 --- /dev/null +++ b/flutter/packages/flutter_tools/test/integration.shard/downgrade_upgrade_integration_test.dart @@ -0,0 +1,141 @@ +// 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/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/process.dart'; +import 'package:flutter_tools/src/base/terminal.dart'; + +import '../src/common.dart'; +import 'test_utils.dart'; + +const String _kInitialVersion = '3.0.0'; +const String _kBranch = 'beta'; + +final Stdio stdio = Stdio(); +final BufferLogger logger = BufferLogger.test( + terminal: AnsiTerminal( + platform: platform, + stdio: stdio, + ), + outputPreferences: OutputPreferences.test(wrapText: true), +); +final ProcessUtils processUtils = ProcessUtils(processManager: processManager, logger: logger); +final String flutterBin = fileSystem.path.join(getFlutterRoot(), 'bin', platform.isWindows ? 'flutter.bat' : 'flutter'); + +/// A test for flutter upgrade & downgrade that checks out a parallel flutter repo. +void main() { + late Directory parentDirectory; + + setUp(() { + parentDirectory = fileSystem.systemTempDirectory + .createTempSync('flutter_tools.'); + parentDirectory.createSync(recursive: true); + }); + + tearDown(() { + tryToDelete(parentDirectory); + }); + + testWithoutContext('Can upgrade and downgrade a Flutter checkout', () async { + final Directory testDirectory = parentDirectory.childDirectory('flutter'); + testDirectory.createSync(recursive: true); + + // Enable longpaths for windows integration test. + await processManager.run([ + 'git', 'config', '--system', 'core.longpaths', 'true', + ]); + + void checkExitCode(int code) { + expect( + exitCode, + 0, + reason: ''' +trace: +${logger.traceText} + +status: +${logger.statusText} + +error: +${logger.errorText}''', + ); + } + + printOnFailure('Step 1 - clone the $_kBranch of flutter into the test directory'); + exitCode = await processUtils.stream([ + 'git', + 'clone', + 'https://github.com/flutter/flutter.git', + ], workingDirectory: parentDirectory.path, trace: true); + checkExitCode(exitCode); + + printOnFailure('Step 2 - switch to the $_kBranch'); + exitCode = await processUtils.stream([ + 'git', + 'checkout', + '--track', + '-b', + _kBranch, + 'origin/$_kBranch', + ], workingDirectory: testDirectory.path, trace: true); + checkExitCode(exitCode); + + printOnFailure('Step 3 - revert back to $_kInitialVersion'); + exitCode = await processUtils.stream([ + 'git', + 'reset', + '--hard', + _kInitialVersion, + ], workingDirectory: testDirectory.path, trace: true); + checkExitCode(exitCode); + + printOnFailure('Step 4 - upgrade to the newest $_kBranch'); + // This should update the persistent tool state with the sha for HEAD + // This is probably a source of flakes as it mutates system-global state. + exitCode = await processUtils.stream([ + flutterBin, + 'upgrade', + '--verbose', + '--working-directory=${testDirectory.path}', + // we intentionally run this in a directory outside the test repo to + // verify the tool overrides the working directory when invoking git + ], workingDirectory: parentDirectory.path, trace: true); + checkExitCode(exitCode); + + printOnFailure('Step 5 - verify that the version is different'); + final RunResult versionResult = await processUtils.run([ + 'git', + 'describe', + '--match', + '*.*.*', + '--long', + '--tags', + ], workingDirectory: testDirectory.path); + expect(versionResult.stdout, isNot(contains(_kInitialVersion))); + printOnFailure('current version is ${versionResult.stdout.trim()}\ninitial was $_kInitialVersion'); + + printOnFailure('Step 6 - downgrade back to the initial version'); + exitCode = await processUtils.stream([ + flutterBin, + 'downgrade', + '--no-prompt', + '--working-directory=${testDirectory.path}', + ], workingDirectory: parentDirectory.path, trace: true); + checkExitCode(exitCode); + + printOnFailure('Step 7 - verify downgraded version matches original version'); + final RunResult oldVersionResult = await processUtils.run([ + 'git', + 'describe', + '--match', + '*.*.*', + '--long', + '--tags', + ], workingDirectory: testDirectory.path); + expect(oldVersionResult.stdout, contains(_kInitialVersion)); + printOnFailure('current version is ${oldVersionResult.stdout.trim()}\ninitial was $_kInitialVersion'); + }); +} diff --git a/flutter/packages/flutter_tools/test/integration.shard/exit_code_test.dart b/flutter/packages/flutter_tools/test/integration.shard/exit_code_test.dart new file mode 100644 index 0000000000000000000000000000000000000000..e919a6efc0d75b83583f0147de5705e02cc1bbd2 --- /dev/null +++ b/flutter/packages/flutter_tools/test/integration.shard/exit_code_test.dart @@ -0,0 +1,56 @@ +// 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/base/io.dart'; + +import '../src/common.dart'; +import 'test_utils.dart'; + +void main() { + final String dartBin = fileSystem.path.join(getFlutterRoot(), 'bin', 'dart'); + late Directory tempDir; + + setUp(() { + tempDir = createResolvedTempDirectorySync('exit_code_test.'); + }); + + tearDown(() { + tryToDelete(tempDir); + }); + + testWithoutContext('dart.sh/bat can return a zero exit code', () async { + tempDir.childFile('main.dart') + .writeAsStringSync(''' +import 'dart:io'; +void main() { + exit(0); +} +'''); + + final ProcessResult result = await processManager.run([ + dartBin, + fileSystem.path.join(tempDir.path, 'main.dart'), + ]); + + expect(result, const ProcessResultMatcher()); + }); + + testWithoutContext('dart.sh/bat can return a non-zero exit code', () async { + tempDir.childFile('main.dart') + .writeAsStringSync(''' +import 'dart:io'; +void main() { + exit(1); +} +'''); + + final ProcessResult result = await processManager.run([ + dartBin, + fileSystem.path.join(tempDir.path, 'main.dart'), + ]); + + expect(result, const ProcessResultMatcher(exitCode: 1)); + }); +} diff --git a/flutter/packages/flutter_tools/test/integration.shard/expression_evaluation_test.dart b/flutter/packages/flutter_tools/test/integration.shard/expression_evaluation_test.dart new file mode 100644 index 0000000000000000000000000000000000000000..4676de1fac9fe1df31fc5db5ff69026920d145ae --- /dev/null +++ b/flutter/packages/flutter_tools/test/integration.shard/expression_evaluation_test.dart @@ -0,0 +1,237 @@ +// 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:vm_service/vm_service.dart'; + +import '../src/common.dart'; +import 'test_data/basic_project.dart'; +import 'test_data/integration_tests_project.dart'; +import 'test_data/tests_project.dart'; +import 'test_driver.dart'; +import 'test_utils.dart'; + +void batch1() { + final BasicProject project = BasicProject(); + late Directory tempDir; + late FlutterRunTestDriver flutter; + + Future initProject() async { + tempDir = createResolvedTempDirectorySync('run_expression_eval_test.'); + await project.setUpIn(tempDir); + flutter = FlutterRunTestDriver(tempDir); + } + + Future cleanProject() async { + await flutter.stop(); + tryToDelete(tempDir); + } + + Future breakInBuildMethod(FlutterTestDriver flutter) async { + await flutter.breakAt( + project.buildMethodBreakpointUri, + project.buildMethodBreakpointLine, + ); + } + + Future breakInTopLevelFunction(FlutterTestDriver flutter) async { + await flutter.breakAt( + project.topLevelFunctionBreakpointUri, + project.topLevelFunctionBreakpointLine, + ); + } + + testWithoutContext('flutter run expression evaluation - can evaluate trivial expressions in top level function', () async { + await initProject(); + await flutter.run(withDebugger: true); + await breakInTopLevelFunction(flutter); + await evaluateTrivialExpressions(flutter); + await cleanProject(); + }); + + testWithoutContext('flutter run expression evaluation - can evaluate trivial expressions in build method', () async { + await initProject(); + await flutter.run(withDebugger: true); + await breakInBuildMethod(flutter); + await evaluateTrivialExpressions(flutter); + await cleanProject(); + }); + + testWithoutContext('flutter run expression evaluation - can evaluate complex expressions in top level function', () async { + await initProject(); + await flutter.run(withDebugger: true); + await breakInTopLevelFunction(flutter); + await evaluateComplexExpressions(flutter); + await cleanProject(); + }); + + testWithoutContext('flutter run expression evaluation - can evaluate complex expressions in build method', () async { + await initProject(); + await flutter.run(withDebugger: true); + await breakInBuildMethod(flutter); + await evaluateComplexExpressions(flutter); + await cleanProject(); + }); + + testWithoutContext('flutter run expression evaluation - can evaluate expressions returning complex objects in top level function', () async { + await initProject(); + await flutter.run(withDebugger: true); + await breakInTopLevelFunction(flutter); + await evaluateComplexReturningExpressions(flutter); + await cleanProject(); + }); + + testWithoutContext('flutter run expression evaluation - can evaluate expressions returning complex objects in build method', () async { + await initProject(); + await flutter.run(withDebugger: true); + await breakInBuildMethod(flutter); + await evaluateComplexReturningExpressions(flutter); + await cleanProject(); + }); +} + +void batch2() { + final TestsProject project = TestsProject(); + late Directory tempDir; + late FlutterTestTestDriver flutter; + + Future initProject() async { + tempDir = createResolvedTempDirectorySync('test_expression_eval_test.'); + await project.setUpIn(tempDir); + flutter = FlutterTestTestDriver(tempDir); + } + + Future cleanProject() async { + await flutter.waitForCompletion(); + tryToDelete(tempDir); + } + + testWithoutContext('flutter test expression evaluation - can evaluate trivial expressions in a test', () async { + await initProject(); + await flutter.test( + withDebugger: true, + beforeStart: () => flutter.addBreakpoint(project.breakpointUri, project.breakpointLine), + ); + await flutter.waitForPause(); + await evaluateTrivialExpressions(flutter); + + // Ensure we did not leave a dill file alongside the test. + // https://github.com/Dart-Code/Dart-Code/issues/4243. + final String dillFilename = '${project.testFilePath}.dill'; + expect(fileSystem.file(dillFilename).existsSync(), isFalse); + + await cleanProject(); + }); + + testWithoutContext('flutter test expression evaluation - can evaluate complex expressions in a test', () async { + await initProject(); + await flutter.test( + withDebugger: true, + beforeStart: () => flutter.addBreakpoint(project.breakpointUri, project.breakpointLine), + ); + await flutter.waitForPause(); + await evaluateComplexExpressions(flutter); + await cleanProject(); + }); + + testWithoutContext('flutter test expression evaluation - can evaluate expressions returning complex objects in a test', () async { + await initProject(); + await flutter.test( + withDebugger: true, + beforeStart: () => flutter.addBreakpoint(project.breakpointUri, project.breakpointLine), + ); + await flutter.waitForPause(); + await evaluateComplexReturningExpressions(flutter); + await cleanProject(); + }); +} + +void batch3() { + final IntegrationTestsProject project = IntegrationTestsProject(); + late Directory tempDir; + late FlutterTestTestDriver flutter; + + Future initProject() async { + tempDir = createResolvedTempDirectorySync('integration_test_expression_eval_test.'); + await project.setUpIn(tempDir); + flutter = FlutterTestTestDriver(tempDir); + } + + Future cleanProject() async { + await flutter.waitForCompletion(); + tryToDelete(tempDir); + } + + testWithoutContext('flutter integration test expression evaluation - can evaluate expressions in a test', () async { + await initProject(); + await flutter.test( + deviceId: 'flutter-tester', + testFile: project.testFilePath, + withDebugger: true, + beforeStart: () => flutter.addBreakpoint(project.breakpointUri, project.breakpointLine), + ); + await flutter.waitForPause(); + await evaluateTrivialExpressions(flutter); + + // Ensure we did not leave a dill file alongside the test. + // https://github.com/Dart-Code/Dart-Code/issues/4243. + final String dillFilename = '${project.testFilePath}.dill'; + expect(fileSystem.file(dillFilename).existsSync(), isFalse); + + await cleanProject(); + }); + +} + +Future evaluateTrivialExpressions(FlutterTestDriver flutter) async { + ObjRef res; + + res = await flutter.evaluateInFrame('"test"'); + expectValueOfType(res, InstanceKind.kString, 'test'); + + res = await flutter.evaluateInFrame('1'); + expectValueOfType(res, InstanceKind.kInt, 1.toString()); + + res = await flutter.evaluateInFrame('true'); + expectValueOfType(res, InstanceKind.kBool, true.toString()); +} + +Future evaluateComplexExpressions(FlutterTestDriver flutter) async { + final ObjRef res = await flutter.evaluateInFrame('new DateTime(2000).year'); + expectValueOfType(res, InstanceKind.kInt, '2000'); +} + +Future evaluateComplexReturningExpressions(FlutterTestDriver flutter) async { + final DateTime date = DateTime(2000); + final ObjRef resp = await flutter.evaluateInFrame('new DateTime(2000)'); + expectInstanceOfClass(resp, 'DateTime'); + final ObjRef res = await flutter.evaluate(resp.id!, r'"$year-$month-$day"'); + expectValue(res, '${date.year}-${date.month}-${date.day}'); +} + +void expectInstanceOfClass(ObjRef result, String name) { + expect(result, + const TypeMatcher() + .having((InstanceRef instance) => instance.classRef!.name, 'resp.classRef.name', name)); +} + +void expectValueOfType(ObjRef result, String kind, String message) { + expect(result, + const TypeMatcher() + .having((InstanceRef instance) => instance.kind, 'kind', kind) + .having((InstanceRef instance) => instance.valueAsString, 'valueAsString', message)); +} + +void expectValue(ObjRef result, String message) { + expect(result, + const TypeMatcher() + .having((InstanceRef instance) => instance.valueAsString, 'valueAsString', message)); +} + +void main() { + batch1(); + batch2(); + batch3(); +} diff --git a/flutter/packages/flutter_tools/test/integration.shard/flutter_attach_test.dart b/flutter/packages/flutter_tools/test/integration.shard/flutter_attach_test.dart new file mode 100644 index 0000000000000000000000000000000000000000..f267d53798ee68911bc9932ce015c098d08228b4 --- /dev/null +++ b/flutter/packages/flutter_tools/test/integration.shard/flutter_attach_test.dart @@ -0,0 +1,220 @@ +// 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:flutter_tools/src/base/io.dart'; +import 'package:vm_service/vm_service.dart'; + +import '../src/common.dart'; +import 'test_data/basic_project.dart'; +import 'test_driver.dart'; +import 'test_utils.dart'; + +Future getFreePort() async { + int port = 0; + final ServerSocket serverSocket = await ServerSocket.bind(InternetAddress.loopbackIPv4, 0); + port = serverSocket.port; + await serverSocket.close(); + return port; +} + +void main() { + final BasicProject project = BasicProject(); + late Directory tempDir; + + setUp(() async { + tempDir = createResolvedTempDirectorySync('attach_test.'); + await project.setUpIn(tempDir); + }); + + tearDown(() { + tryToDelete(tempDir); + }); + + group('DDS in flutter run', () { + late FlutterRunTestDriver flutterRun, flutterAttach; + setUp(() { + flutterRun = FlutterRunTestDriver(tempDir, logPrefix: ' RUN '); + flutterAttach = FlutterRunTestDriver( + tempDir, + logPrefix: 'ATTACH ', + // Only one DDS instance can be connected to the VM service at a time. + // DDS can also only initialize if the VM service doesn't have any existing + // clients, so we'll just let _flutterRun be responsible for spawning DDS. + spawnDdsInstance: false, + ); + }); + + tearDown(() async { + await flutterAttach.detach(); + await flutterRun.stop(); + }); + + testWithoutContext('can hot reload', () async { + await flutterRun.run(withDebugger: true); + await flutterAttach.attach(flutterRun.vmServicePort!); + await flutterAttach.hotReload(); + }); + + testWithoutContext('can detach, reattach, hot reload', () async { + await flutterRun.run(withDebugger: true); + await flutterAttach.attach(flutterRun.vmServicePort!); + await flutterAttach.detach(); + await flutterAttach.attach(flutterRun.vmServicePort!); + await flutterAttach.hotReload(); + }); + + testWithoutContext('killing process behaves the same as detach ', () async { + await flutterRun.run(withDebugger: true); + await flutterAttach.attach(flutterRun.vmServicePort!); + await flutterAttach.quit(); + flutterAttach = FlutterRunTestDriver( + tempDir, + logPrefix: 'ATTACH-2', + spawnDdsInstance: false, + ); + await flutterAttach.attach(flutterRun.vmServicePort!); + await flutterAttach.hotReload(); + }); + + testWithoutContext('sets activeDevToolsServerAddress extension', () async { + await flutterRun.run( + startPaused: true, + withDebugger: true, + additionalCommandArgs: ['--devtools-server-address', 'http://127.0.0.1:9105'], + ); + await flutterRun.resume(); + await pollForServiceExtensionValue( + testDriver: flutterRun, + extension: 'ext.flutter.activeDevToolsServerAddress', + continuePollingValue: '', + matches: equals('http://127.0.0.1:9105'), + ); + await pollForServiceExtensionValue( + testDriver: flutterRun, + extension: 'ext.flutter.connectedVmServiceUri', + continuePollingValue: '', + matches: isNotEmpty, + ); + + final Response response = await flutterRun.callServiceExtension('ext.flutter.connectedVmServiceUri'); + final String vmServiceUri = response.json!['value'] as String; + + // Attach with a different DevTools server address. + await flutterAttach.attach( + flutterRun.vmServicePort!, + additionalCommandArgs: ['--devtools-server-address', 'http://127.0.0.1:9110'], + ); + await pollForServiceExtensionValue( + testDriver: flutterAttach, + extension: 'ext.flutter.activeDevToolsServerAddress', + continuePollingValue: '', + matches: equals('http://127.0.0.1:9110'), + ); + await pollForServiceExtensionValue( + testDriver: flutterRun, + extension: 'ext.flutter.connectedVmServiceUri', + continuePollingValue: '', + matches: equals(vmServiceUri), + ); + }); + }); + + group('DDS in flutter attach', () { + late FlutterRunTestDriver flutterRun, flutterAttach; + setUp(() { + flutterRun = FlutterRunTestDriver( + tempDir, + logPrefix: ' RUN ', + spawnDdsInstance: false, + ); + flutterAttach = FlutterRunTestDriver( + tempDir, + logPrefix: 'ATTACH ', + ); + }); + + tearDown(() async { + await flutterAttach.detach(); + await flutterRun.stop(); + }); + + testWithoutContext('uses the designated dds port', () async { + final int ddsPort = await getFreePort(); + + await flutterRun.run(withDebugger: true); + await flutterAttach.attach( + flutterRun.vmServicePort!, + additionalCommandArgs: [ + '--dds-port=$ddsPort', + ], + ); + + final Response response = await flutterAttach.callServiceExtension('ext.flutter.connectedVmServiceUri'); + final String vmServiceUriString = response.json!['value'] as String; + final Uri vmServiceUri = Uri.parse(vmServiceUriString); + expect(vmServiceUri.port, equals(ddsPort)); + }); + }); + + group('--serve-observatory', () { + late FlutterRunTestDriver flutterRun, flutterAttach; + + setUp(() async { + flutterRun = FlutterRunTestDriver(tempDir, logPrefix: ' RUN '); + flutterAttach = FlutterRunTestDriver( + tempDir, + logPrefix: 'ATTACH ', + // Only one DDS instance can be connected to the VM service at a time. + // DDS can also only initialize if the VM service doesn't have any existing + // clients, so we'll just let _flutterRun be responsible for spawning DDS. + spawnDdsInstance: false, + ); + }); + + tearDown(() async { + await flutterAttach.detach(); + await flutterRun.stop(); + }); + + Future isObservatoryAvailable() async { + final HttpClient client = HttpClient(); + final Uri vmServiceUri = Uri( + scheme: 'http', + host: flutterRun.vmServiceWsUri!.host, + port: flutterRun.vmServicePort, + ); + + final HttpClientRequest request = await client.getUrl(vmServiceUri); + final HttpClientResponse response = await request.close(); + final String content = await response.transform(utf8.decoder).join(); + return content.contains('Dart VM Observatory'); + } + + testWithoutContext('enables Observatory on run', () async { + await flutterRun.run( + withDebugger: true, + serveObservatory: true, + ); + expect(await isObservatoryAvailable(), true); + }); + + testWithoutContext('enables Observatory on attach', () async { + await flutterRun.run(withDebugger: true); + // Bail out if Observatory is still served by default in the VM. + // TODO(bkonyi): replace this with the following once Observatory is disabled in the VM: + // expect(await isObservatoryAvailable(), isFalse); + if (await isObservatoryAvailable()) { + return; + } + await flutterAttach.attach( + flutterRun.vmServicePort!, + serveObservatory: true, + ); + expect(await isObservatoryAvailable(), true); + }); + }); +} diff --git a/flutter/packages/flutter_tools/test/integration.shard/flutter_build_android_app_project_builddir_test.dart b/flutter/packages/flutter_tools/test/integration.shard/flutter_build_android_app_project_builddir_test.dart new file mode 100644 index 0000000000000000000000000000000000000000..2f71f983dc8ed9c3e40baa6ec87a4bd9ce9444b1 --- /dev/null +++ b/flutter/packages/flutter_tools/test/integration.shard/flutter_build_android_app_project_builddir_test.dart @@ -0,0 +1,83 @@ +// 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_testing/file_testing.dart'; +import 'package:flutter_tools/src/base/file_system.dart'; + +import '../src/common.dart'; +import 'test_utils.dart'; + +// Test the android/app/build directory not be created unexpectedly after +// `flutter build` commands, see https://github.com/flutter/flutter/issues/91018. +// +// The easiest way to reproduce this issue is to create a plugin project, then run +// `flutter build` command inside the `example` directory, so we create a plugin +// project in the test. +void main() { + late Directory tempDir; + late String flutterBin; + late Directory exampleAppDir; + + setUp(() async { + tempDir = createResolvedTempDirectorySync('flutter_plugin_test.'); + flutterBin = fileSystem.path.join( + getFlutterRoot(), + 'bin', + 'flutter', + ); + exampleAppDir = tempDir.childDirectory('aaa').childDirectory('example'); + + processManager.runSync([ + flutterBin, + ...getLocalEngineArguments(), + 'create', + '--template=plugin', + '--platforms=android', + 'aaa', + ], workingDirectory: tempDir.path); + }); + + tearDown(() async { + tryToDelete(tempDir); + }); + + void checkBuildDir() { + // The android/app/build directory should not exists + final Directory appBuildDir = fileSystem.directory(fileSystem.path.join( + exampleAppDir.path, + 'android', + 'app', + 'build', + )); + expect(appBuildDir, isNot(exists)); + } + + test( + 'android/app/build should not exists after flutter build apk', + () async { + processManager.runSync([ + flutterBin, + ...getLocalEngineArguments(), + 'build', + 'apk', + '--target-platform=android-arm', + ], workingDirectory: exampleAppDir.path); + checkBuildDir(); + }, + ); + + test( + 'android/app/build should not exists after flutter build appbundle', + () async { + processManager.runSync([ + flutterBin, + ...getLocalEngineArguments(), + 'build', + 'appbundle', + '--target-platform=android-arm', + ], workingDirectory: exampleAppDir.path); + checkBuildDir(); + }, + ); +} diff --git a/flutter/packages/flutter_tools/test/integration.shard/flutter_build_apk_verbose_test.dart b/flutter/packages/flutter_tools/test/integration.shard/flutter_build_apk_verbose_test.dart new file mode 100644 index 0000000000000000000000000000000000000000..cff5e463b09dc558dacf4ad8e1baae71867ae4de --- /dev/null +++ b/flutter/packages/flutter_tools/test/integration.shard/flutter_build_apk_verbose_test.dart @@ -0,0 +1,55 @@ +// 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/file_system.dart'; +import 'package:flutter_tools/src/base/io.dart'; + +import '../src/common.dart'; +import 'test_utils.dart'; + +// Test that verbosity it propagated to Gradle tasks correctly. +void main() { + late Directory tempDir; + late String flutterBin; + late Directory exampleAppDir; + + setUp(() async { + tempDir = createResolvedTempDirectorySync('flutter_build_test.'); + flutterBin = fileSystem.path.join( + getFlutterRoot(), + 'bin', + 'flutter', + ); + exampleAppDir = tempDir.childDirectory('aaa').childDirectory('example'); + + processManager.runSync([ + flutterBin, + ...getLocalEngineArguments(), + 'create', + '--template=plugin', + '--platforms=android', + 'aaa', + ], workingDirectory: tempDir.path); + }); + + tearDown(() async { + tryToDelete(tempDir); + }); + + test( + 'flutter build apk -v output should contain gen_snapshot command', + () async { + final ProcessResult result = processManager.runSync([ + flutterBin, + ...getLocalEngineArguments(), + 'build', + 'apk', + '--target-platform=android-arm', + '-v', + ], workingDirectory: exampleAppDir.path); + expect( + result.stdout, contains(RegExp(r'executing:\s+\S+gen_snapshot\s+'))); + }, + ); +} diff --git a/flutter/packages/flutter_tools/test/integration.shard/flutter_build_config_only_test.dart b/flutter/packages/flutter_tools/test/integration.shard/flutter_build_config_only_test.dart new file mode 100644 index 0000000000000000000000000000000000000000..92f38142534f2f174775ecf9f7dcc39fe95d451b --- /dev/null +++ b/flutter/packages/flutter_tools/test/integration.shard/flutter_build_config_only_test.dart @@ -0,0 +1,72 @@ +// 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_testing/file_testing.dart'; +import 'package:flutter_tools/src/base/file_system.dart'; +import 'package:flutter_tools/src/base/io.dart'; + +import '../src/common.dart'; +import 'test_utils.dart'; + +// Test that configOnly creates the gradlew file and does not assemble and app. +void main() { + late Directory tempDir; + late String flutterBin; + late Directory exampleAppDir; + + setUp(() async { + tempDir = createResolvedTempDirectorySync('flutter_build_test.'); + flutterBin = fileSystem.path.join( + getFlutterRoot(), + 'bin', + 'flutter', + ); + exampleAppDir = tempDir.childDirectory('bbb').childDirectory('example'); + + processManager.runSync( + [ + flutterBin, + ...getLocalEngineArguments(), + 'create', + '--template=plugin', + '--platforms=android', + 'bbb', + '-v', + ], + workingDirectory: tempDir.path, + ); + }); + + tearDown(() async { + tryToDelete(tempDir); + }); + + test( + 'flutter build apk --config-only should create gradlew and not assemble', + () async { + final File gradleFile = fileSystem + .directory(exampleAppDir) + .childDirectory('android') + .childFile(platform.isWindows ? 'gradlew.bat' : 'gradlew'); + // Ensure file is gone prior to configOnly running. + await gradleFile.delete(); + + final ProcessResult result = processManager.runSync( + [ + flutterBin, + ...getLocalEngineArguments(), + 'build', + 'apk', + '--target-platform=android-arm', + '--config-only', + ], + workingDirectory: exampleAppDir.path, + ); + + expect(gradleFile, exists); + expect(result.stdout, contains(RegExp(r'Config complete'))); + expect(result.stdout, isNot(contains(RegExp(r'Running Gradle task')))); + }, + ); +} diff --git a/flutter/packages/flutter_tools/test/integration.shard/flutter_build_wasm_test.dart b/flutter/packages/flutter_tools/test/integration.shard/flutter_build_wasm_test.dart new file mode 100644 index 0000000000000000000000000000000000000000..4290db33756a5556b9f2d7a4babaad493867b87a --- /dev/null +++ b/flutter/packages/flutter_tools/test/integration.shard/flutter_build_wasm_test.dart @@ -0,0 +1,67 @@ +// 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:io'; + +import 'package:file_testing/file_testing.dart'; +import 'package:flutter_tools/src/base/file_system.dart'; +import 'package:flutter_tools/src/features.dart'; + +import '../src/common.dart'; +import 'test_utils.dart'; + +void main() { + late Directory tempDir; + late String flutterBin; + late Directory exampleAppDir; + + setUp(() async { + tempDir = createResolvedTempDirectorySync('flutter_web_wasm_test.'); + flutterBin = fileSystem.path.join( + getFlutterRoot(), + 'bin', + 'flutter', + ); + exampleAppDir = tempDir.childDirectory('test_app'); + + processManager.runSync([ + flutterBin, + 'create', + '--platforms=web', + 'test_app', + ], workingDirectory: tempDir.path); + }); + + test('building web with --wasm produces expected files', () async { + final ProcessResult result = processManager.runSync( + [ + flutterBin, + 'build', + 'web', + '--wasm', + ], + workingDirectory: exampleAppDir.path, + environment: { + flutterWebWasm.environmentOverride!: 'true' + }, + ); + expect(result, const ProcessResultMatcher()); + + final Directory appBuildDir = fileSystem.directory(fileSystem.path.join( + exampleAppDir.path, + 'build', + 'web_wasm', + )); + for (final String filename in const [ + 'flutter.js', + 'flutter_service_worker.js', + 'index.html', + 'main.dart.wasm', + 'main.dart.mjs', + 'main.dart.js', + ]) { + expect(appBuildDir.childFile(filename), exists); + } + }); +} diff --git a/flutter/packages/flutter_tools/test/integration.shard/flutter_build_windows_test.dart b/flutter/packages/flutter_tools/test/integration.shard/flutter_build_windows_test.dart new file mode 100644 index 0000000000000000000000000000000000000000..d238bb226a75eecc84e00f6d71f506194e59e27e --- /dev/null +++ b/flutter/packages/flutter_tools/test/integration.shard/flutter_build_windows_test.dart @@ -0,0 +1,155 @@ +// 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:io' as io; + +import 'package:file/file.dart'; +import 'package:file_testing/file_testing.dart'; +import 'package:flutter_tools/src/base/io.dart'; + +import '../src/common.dart'; +import 'test_utils.dart'; + +void main() { + late Directory tempDir; + late Directory projectRoot; + late String flutterBin; + late Directory releaseDir; + late File exeFile; + + group('flutter build windows command', () { + setUpAll(() { + tempDir = createResolvedTempDirectorySync('build_windows_test.'); + flutterBin = fileSystem.path.join( + getFlutterRoot(), + 'bin', + 'flutter', + ); + ProcessResult result = processManager.runSync([flutterBin, 'config', + '--enable-windows-desktop', + ]); + expect(result, const ProcessResultMatcher()); + + result = processManager.runSync([ + flutterBin, + ...getLocalEngineArguments(), + 'create', + 'hello', + ], workingDirectory: tempDir.path); + expect(result, const ProcessResultMatcher()); + + projectRoot = tempDir.childDirectory('hello'); + + releaseDir = fileSystem.directory(fileSystem.path.join( + projectRoot.path, + 'build', + 'windows', + 'x64', + 'runner', + 'Release', + )); + + exeFile = fileSystem.file(fileSystem.path.join( + releaseDir.path, + 'hello.exe', + )); + }); + + tearDownAll(() { + tryToDelete(tempDir); + }); + + testWithoutContext('flutter build windows creates exe', () { + final ProcessResult result = processManager.runSync([ + flutterBin, + ...getLocalEngineArguments(), + 'build', + 'windows', + '--no-pub', + ], workingDirectory: projectRoot.path); + expect(result, const ProcessResultMatcher()); + + expect(releaseDir, exists); + expect(exeFile, exists); + + // Default exe has build name 1.0.0 and build number 1. + final String fileVersion = _getFileVersion(exeFile); + final String productVersion = _getProductVersion(exeFile); + + expect(fileVersion, equals('1.0.0.1')); + expect(productVersion, equals('1.0.0+1')); + }); + + testWithoutContext('flutter build windows sets build name', () { + final ProcessResult result = processManager.runSync([ + flutterBin, + ...getLocalEngineArguments(), + 'build', + 'windows', + '--no-pub', + '--build-name', + '1.2.3', + ], workingDirectory: projectRoot.path); + expect(result, const ProcessResultMatcher()); + + final String fileVersion = _getFileVersion(exeFile); + final String productVersion = _getProductVersion(exeFile); + + expect(fileVersion, equals('1.2.3.0')); + expect(productVersion, equals('1.2.3')); + }); + + testWithoutContext('flutter build windows sets build name and build number', () { + final ProcessResult result = processManager.runSync([ + flutterBin, + ...getLocalEngineArguments(), + 'build', + 'windows', + '--no-pub', + '--build-name', + '1.2.3', + '--build-number', + '4', + ], workingDirectory: projectRoot.path); + expect(result, const ProcessResultMatcher()); + + final String fileVersion = _getFileVersion(exeFile); + final String productVersion = _getProductVersion(exeFile); + + expect(fileVersion, equals('1.2.3.4')); + expect(productVersion, equals('1.2.3+4')); + }); + }, skip: !io.Platform.isWindows); // [intended] Windows integration build. +} + +String _getFileVersion(File file) { + // FileVersionInfo's FileVersion property excludes the private part, + // so this recreates the file version using the individual parts. + final ProcessResult result = Process.runSync( + 'powershell.exe -command " ' + '\$v = [System.Diagnostics.FileVersionInfo]::GetVersionInfo(\\"${file.path}\\"); ' + r'Write-Output \"$($v.FileMajorPart).$($v.FileMinorPart).$($v.FileBuildPart).$($v.FilePrivatePart)\" ' + '"', + [] + ); + + expect(result, const ProcessResultMatcher()); + + // Trim trailing new line. + final String output = result.stdout as String; + return output.trim(); +} + +String _getProductVersion(File file) { + final ProcessResult result = Process.runSync( + 'powershell.exe -command "[System.Diagnostics.FileVersionInfo]::GetVersionInfo(\\"${file.path}\\").ProductVersion"', + [] + ); + + expect(result, const ProcessResultMatcher()); + + // Trim trailing new line. + final String output = result.stdout as String; + return output.trim(); +} diff --git a/flutter/packages/flutter_tools/test/integration.shard/flutter_build_with_compilation_error_test.dart b/flutter/packages/flutter_tools/test/integration.shard/flutter_build_with_compilation_error_test.dart new file mode 100644 index 0000000000000000000000000000000000000000..36d15e90859ecc1d97af1915d397102facb680ec --- /dev/null +++ b/flutter/packages/flutter_tools/test/integration.shard/flutter_build_with_compilation_error_test.dart @@ -0,0 +1,76 @@ +// 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/base/io.dart'; + +import '../src/common.dart'; +import 'test_utils.dart'; + +void main() { + late Directory tempDir; + late Directory projectRoot; + late String flutterBin; + final List targetPlatforms = [ + 'apk', + 'web', + if (platform.isWindows) + 'windows', + if (platform.isMacOS) + ...['macos', 'ios'], + ]; + + setUpAll(() { + tempDir = createResolvedTempDirectorySync('build_compilation_error_test.'); + flutterBin = fileSystem.path.join( + getFlutterRoot(), + 'bin', + 'flutter', + ); + processManager.runSync([flutterBin, 'config', + '--enable-macos-desktop', + '--enable-windows-desktop', + '--enable-web', + ]); + + processManager.runSync([ + flutterBin, + ...getLocalEngineArguments(), + 'create', + 'hello', + ], workingDirectory: tempDir.path); + + projectRoot = tempDir.childDirectory('hello'); + writeFile(fileSystem.path.join(projectRoot.path, 'lib', 'main.dart'), ''' +int x = 'String'; +'''); + }); + + tearDownAll(() { + tryToDelete(tempDir); + }); + + for (final String targetPlatform in targetPlatforms) { + testWithoutContext('flutter build $targetPlatform shows dart compilation error in non-verbose', () { + final ProcessResult result = processManager.runSync([ + flutterBin, + ...getLocalEngineArguments(), + 'build', + targetPlatform, + '--no-pub', + if (targetPlatform == 'ios') + '--no-codesign', + ], workingDirectory: projectRoot.path); + + expect( + result, + const ProcessResultMatcher( + exitCode: 1, + stderrPattern: "A value of type 'String' can't be assigned to a variable of type 'int'.", + ), + ); + expect(result.stderr, isNot(contains("Warning: The 'dart2js' entrypoint script is deprecated"))); + }); + } +} diff --git a/flutter/packages/flutter_tools/test/integration.shard/flutter_gen_test.dart b/flutter/packages/flutter_tools/test/integration.shard/flutter_gen_test.dart new file mode 100644 index 0000000000000000000000000000000000000000..674d5a1c584b8753a4521d60b47907f5b1c604de --- /dev/null +++ b/flutter/packages/flutter_tools/test/integration.shard/flutter_gen_test.dart @@ -0,0 +1,49 @@ +// 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 '../src/common.dart'; +import 'test_data/basic_project.dart'; +import 'test_driver.dart'; +import 'test_utils.dart'; + +void main() { + late Directory tempDir; + final BasicProjectWithFlutterGen project = BasicProjectWithFlutterGen(); + late FlutterRunTestDriver flutter; + + setUp(() async { + tempDir = createResolvedTempDirectorySync('run_test.'); + await project.setUpIn(tempDir); + flutter = FlutterRunTestDriver(tempDir); + }); + + tearDown(() async { + await flutter.stop(); + tryToDelete(tempDir); + }); + + testWithoutContext('can correctly reference flutter generated code.', () async { + await flutter.run(); + final dynamic jsonContent = json.decode(project.dir + .childDirectory('.dart_tool') + .childFile('package_config.json') + .readAsStringSync()); + final Map collection = ((jsonContent as Map)['packages'] as Iterable) + .firstWhere((dynamic entry) => (entry as Map)['name'] == 'collection') as Map; + expect( + Uri.parse(collection['rootUri'] as String).isAbsolute, + isTrue, + reason: 'The generated package_config.json should use absolute root urls', + ); + expect( + collection['packageUri'] as String, + 'lib/', + reason: 'The generated package_config.json should have package urls ending with /' + ); + }); +} diff --git a/flutter/packages/flutter_tools/test/integration.shard/flutter_run_test.dart b/flutter/packages/flutter_tools/test/integration.shard/flutter_run_test.dart new file mode 100644 index 0000000000000000000000000000000000000000..e3b94ed4c4ff399528cd26f65b866c5f84fee48e --- /dev/null +++ b/flutter/packages/flutter_tools/test/integration.shard/flutter_run_test.dart @@ -0,0 +1,77 @@ +// 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/base/io.dart'; +import 'package:process/process.dart'; + +import '../src/common.dart'; +import 'test_data/basic_project.dart'; +import 'test_driver.dart'; +import 'test_utils.dart'; + +void main() { + late Directory tempDir; + final BasicProject project = BasicProject(); + late FlutterRunTestDriver flutter; + + setUp(() async { + tempDir = createResolvedTempDirectorySync('run_test.'); + await project.setUpIn(tempDir); + flutter = FlutterRunTestDriver(tempDir); + }); + + tearDown(() async { + await flutter.stop(); + tryToDelete(tempDir); + }); + + testWithoutContext('flutter run reports an error if an invalid device is supplied', () async { + // This test forces flutter to check for all possible devices to catch issues + // like https://github.com/flutter/flutter/issues/21418 which were skipped + // over because other integration tests run using flutter-tester which short-cuts + // some of the checks for devices. + final String flutterBin = fileSystem.path.join(getFlutterRoot(), 'bin', 'flutter'); + + const ProcessManager processManager = LocalProcessManager(); + final ProcessResult proc = await processManager.run( + [flutterBin, 'run', '-d', 'invalid-device-id'], + workingDirectory: tempDir.path, + ); + + expect(proc.stdout, isNot(contains('flutter has exited unexpectedly'))); + expect(proc.stderr, isNot(contains('flutter has exited unexpectedly'))); + if (!proc.stderr.toString().contains('Unable to locate a development') + && !proc.stdout.toString().contains('No supported devices found with name or id matching')) { + fail("'flutter run -d invalid-device-id' did not produce the expected error"); + } + }); + + testWithoutContext('sets activeDevToolsServerAddress extension', () async { + await flutter.run( + startPaused: true, + withDebugger: true, + additionalCommandArgs: ['--devtools-server-address', 'http://127.0.0.1:9110'], + ); + await flutter.resume(); + await pollForServiceExtensionValue( + testDriver: flutter, + extension: 'ext.flutter.activeDevToolsServerAddress', + continuePollingValue: '', + matches: equals('http://127.0.0.1:9110'), + ); + await pollForServiceExtensionValue( + testDriver: flutter, + extension: 'ext.flutter.connectedVmServiceUri', + continuePollingValue: '', + matches: isNotEmpty, + ); + }); + + testWithoutContext('reports deviceId and mode in app.start event', () async { + await flutter.run(); + expect(flutter.currentRunningDeviceId, 'flutter-tester'); + expect(flutter.currentRunningMode, 'debug'); + }); +} diff --git a/flutter/packages/flutter_tools/test/integration.shard/flutter_run_with_error_test.dart b/flutter/packages/flutter_tools/test/integration.shard/flutter_run_with_error_test.dart new file mode 100644 index 0000000000000000000000000000000000000000..4088ce9683965c5ad8a62bb25b82cdbac8bf1f3e --- /dev/null +++ b/flutter/packages/flutter_tools/test/integration.shard/flutter_run_with_error_test.dart @@ -0,0 +1,102 @@ +// 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/file.dart'; +import 'package:flutter_tools/src/base/io.dart'; +import 'package:vm_service/vm_service.dart'; +import 'package:vm_service/vm_service_io.dart'; + +import '../src/common.dart'; +import 'test_data/project_with_early_error.dart'; +import 'test_driver.dart'; +import 'test_utils.dart'; + +void main() { + late Directory tempDir; + final ProjectWithEarlyError project = ProjectWithEarlyError(); + const String exceptionStart = '══╡ EXCEPTION CAUGHT BY WIDGETS LIBRARY ╞══════════════════'; + late FlutterRunTestDriver flutter; + + setUp(() async { + tempDir = createResolvedTempDirectorySync('run_test.'); + await project.setUpIn(tempDir); + flutter = FlutterRunTestDriver(tempDir); + }); + + tearDown(() async { + tryToDelete(tempDir); + }); + + testWithoutContext('flutter run in non-machine mode reports an early error in an application', () async { + final String flutterBin = fileSystem.path.join( + getFlutterRoot(), + 'bin', + 'flutter', + ); + + final StringBuffer stdout = StringBuffer(); + + final Process process = await processManager.start([ + flutterBin, + 'run', + '--disable-service-auth-codes', + '--show-test-device', + '-dflutter-tester', + '--start-paused', + '--dart-define=flutter.inspector.structuredErrors=true', + ], workingDirectory: tempDir.path); + + transformToLines(process.stdout).listen((String line) async { + stdout.writeln(line); + + if (line.startsWith('A Dart VM Service on')) { + final RegExp exp = RegExp(r'http://127.0.0.1:(\d+)/'); + final RegExpMatch match = exp.firstMatch(line)!; + final String port = match.group(1)!; + final VmService vmService = + await vmServiceConnectUri('ws://localhost:$port/ws'); + final VM vm = await vmService.getVM(); + for (final IsolateRef isolate in vm.isolates!) { + await vmService.resume(isolate.id!); + } + } + + if (line.startsWith('Another exception was thrown')) { + process.kill(); + } + }); + + await process.exitCode; + + expect(stdout.toString(), contains(exceptionStart)); + }); + + testWithoutContext('flutter run in machine mode does not print an error', () async { + final StringBuffer stdout = StringBuffer(); + + await flutter.run( + startPaused: true, + withDebugger: true, + structuredErrors: true, + ); + await flutter.resume(); + + final Completer completer = Completer(); + + await Future(() async { + flutter.stdout.listen((String line) { + stdout.writeln(line); + }); + await completer.future; + }).timeout(const Duration(seconds: 5), onTimeout: () { + // We don't expect to see any output but want to write to stdout anyway. + completer.complete(); + }); + await flutter.stop(); + + expect(stdout.toString(), isNot(contains(exceptionStart))); + }); +} diff --git a/flutter/packages/flutter_tools/test/integration.shard/forbidden_imports_test.dart b/flutter/packages/flutter_tools/test/integration.shard/forbidden_imports_test.dart new file mode 100644 index 0000000000000000000000000000000000000000..92a886319a99cafde45820b5b949641bc0c9bab4 --- /dev/null +++ b/flutter/packages/flutter_tools/test/integration.shard/forbidden_imports_test.dart @@ -0,0 +1,257 @@ +// 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 '../src/common.dart'; +import 'test_utils.dart'; + +void main() { + final String flutterTools = fileSystem.path.join(getFlutterRoot(), 'packages', 'flutter_tools'); + + test('no imports of commands/* or test/* in lib/src/*', () { + final List skippedPaths = [ + fileSystem.path.join(flutterTools, 'lib', 'src', 'commands'), + fileSystem.path.join(flutterTools, 'lib', 'src', 'test'), + ]; + bool isNotSkipped(FileSystemEntity entity) => skippedPaths.every((String path) => !entity.path.startsWith(path)); + + final Iterable files = fileSystem.directory(fileSystem.path.join(flutterTools, 'lib', 'src')) + .listSync(recursive: true) + .where(_isDartFile) + .where(isNotSkipped) + .map(_asFile); + for (final File file in files) { + for (final String line in file.readAsLinesSync()) { + if (line.startsWith(RegExp(r'import.*package:'))) { + continue; + } + if (line.startsWith(RegExp(r'import.*commands/')) + || line.startsWith(RegExp(r'import.*test/'))) { + final String relativePath = fileSystem.path.relative(file.path, from:flutterTools); + fail('$relativePath imports $line. This import introduces a layering violation. ' + 'Please find another way to access the information you are using.'); + } + } + } + }); + + test('no imports of globals without a global prefix', () { + final List skippedPaths = []; + bool isNotSkipped(FileSystemEntity entity) => skippedPaths.every((String path) => !entity.path.startsWith(path)); + + final Iterable files = fileSystem.directory(fileSystem.path.join(flutterTools, 'lib', 'src')) + .listSync(recursive: true) + .followedBy(fileSystem.directory(fileSystem.path.join(flutterTools, 'test',)).listSync(recursive: true)) + .where(_isDartFile) + .where(isNotSkipped) + .map(_asFile); + for (final File file in files) { + for (final String line in file.readAsLinesSync()) { + if ((line.startsWith(RegExp(r'import.*globals.dart')) || + line.startsWith(RegExp(r'import.*globals_null_migrated.dart'))) && + !line.contains(r'as globals')) { + final String relativePath = fileSystem.path.relative(file.path, from:flutterTools); + fail('$relativePath imports globals_null_migrated.dart or globals.dart without a globals prefix.'); + } + } + } + }); + + test('no unauthorized imports of dart:io', () { + final List allowedPaths = [ + // This is a standalone script invoked by xcode, not part of the tool + fileSystem.path.join(flutterTools, 'bin', 'xcode_backend.dart'), + fileSystem.path.join(flutterTools, 'lib', 'src', 'base', 'io.dart'), + fileSystem.path.join(flutterTools, 'lib', 'src', 'base', 'platform.dart'), + fileSystem.path.join(flutterTools, 'lib', 'src', 'base', 'error_handling_io.dart'), + fileSystem.path.join(flutterTools, 'lib', 'src', 'base', 'multi_root_file_system.dart'), + ]; + bool isNotAllowed(FileSystemEntity entity) => allowedPaths.every((String path) => path != entity.path); + + for (final String dirName in ['lib', 'bin']) { + final Iterable files = fileSystem.directory(fileSystem.path.join(flutterTools, dirName)) + .listSync(recursive: true) + .where(_isDartFile) + .where(isNotAllowed) + .map(_asFile); + for (final File file in files) { + for (final String line in file.readAsLinesSync()) { + if (line.startsWith(RegExp(r'import.*dart:io')) && + !line.contains('flutter_ignore: dart_io_import')) { + final String relativePath = fileSystem.path.relative(file.path, from:flutterTools); + fail("$relativePath imports 'dart:io'; import 'lib/src/base/io.dart' instead"); + } + } + } + } + }); + + test('no unauthorized imports of package:http', () { + final List allowedPaths = [ + // Used only for multi-part file uploads, which are non-trivial to reimplement. + fileSystem.path.join(flutterTools, 'lib', 'src', 'reporting', 'crash_reporting.dart'), + ]; + bool isNotAllowed(FileSystemEntity entity) => allowedPaths.every((String path) => path != entity.path); + + for (final String dirName in ['lib', 'bin']) { + final Iterable files = fileSystem.directory(fileSystem.path.join(flutterTools, dirName)) + .listSync(recursive: true) + .where(_isDartFile) + .where(isNotAllowed) + .map(_asFile); + for (final File file in files) { + for (final String line in file.readAsLinesSync()) { + if (line.startsWith(RegExp(r'import.*package:http/')) && + !line.contains('flutter_ignore: package_http_import')) { + final String relativePath = fileSystem.path.relative(file.path, from:flutterTools); + fail("$relativePath imports 'package:http'; import 'lib/src/base/io.dart' instead"); + } + } + } + } + }); + + test('no unauthorized imports of test_api', () { + final List allowedPaths = [ + fileSystem.path.join(flutterTools, 'lib', 'src', 'test', 'flutter_platform.dart'), + fileSystem.path.join(flutterTools, 'lib', 'src', 'test', 'flutter_web_platform.dart'), + fileSystem.path.join(flutterTools, 'lib', 'src', 'test', 'test_wrapper.dart'), + ]; + bool isNotAllowed(FileSystemEntity entity) => allowedPaths.every((String path) => path != entity.path); + + for (final String dirName in ['lib']) { + final Iterable files = fileSystem.directory(fileSystem.path.join(flutterTools, dirName)) + .listSync(recursive: true) + .where(_isDartFile) + .where(isNotAllowed) + .map(_asFile); + for (final File file in files) { + for (final String line in file.readAsLinesSync()) { + if (line.startsWith(RegExp(r'import.*package:test_api')) && + !line.contains('flutter_ignore: test_api_import')) { + final String relativePath = fileSystem.path.relative(file.path, from:flutterTools); + fail("$relativePath imports 'package:test_api/test_api.dart';"); + } + } + } + } + }); + + test('no unauthorized imports of package:path', () { + final List allowedPath = [ + fileSystem.path.join(flutterTools, 'lib', 'src', 'isolated', 'web_compilation_delegate.dart'), + fileSystem.path.join(flutterTools, 'test', 'general.shard', 'platform_plugins_test.dart'), + ]; + for (final String dirName in ['lib', 'bin', 'test']) { + final Iterable files = fileSystem.directory(fileSystem.path.join(flutterTools, dirName)) + .listSync(recursive: true) + .where(_isDartFile) + .where((FileSystemEntity entity) => !allowedPath.contains(entity.path)) + .map(_asFile); + for (final File file in files) { + for (final String line in file.readAsLinesSync()) { + if (line.startsWith(RegExp(r'import.*package:path/path.dart')) && + !line.contains('flutter_ignore: package_path_import')) { + final String relativePath = fileSystem.path.relative(file.path, from:flutterTools); + fail("$relativePath imports 'package:path/path.dart'; use 'fileSystem.path' instead"); + } + } + } + } + }); + + test('no unauthorized imports of package:file/local.dart', () { + final List allowedPath = [ + fileSystem.path.join(flutterTools, 'test', 'integration.shard', 'test_utils.dart'), + fileSystem.path.join(flutterTools, 'lib', 'src', 'base', 'file_system.dart'), + ]; + for (final String dirName in ['lib', 'bin', 'test']) { + final Iterable files = fileSystem.directory(fileSystem.path.join(flutterTools, dirName)) + .listSync(recursive: true) + .where(_isDartFile) + .where((FileSystemEntity entity) => !allowedPath.contains(entity.path)) + .map(_asFile); + for (final File file in files) { + for (final String line in file.readAsLinesSync()) { + if (line.startsWith(RegExp(r'import.*package:file/local.dart'))) { + final String relativePath = fileSystem.path.relative(file.path, from:flutterTools); + fail("$relativePath imports 'package:file/local.dart'; use 'lib/src/base/file_system.dart' instead"); + } + } + } + } + }); + + test('no unauthorized imports of dart:convert', () { + final List allowedPaths = [ + fileSystem.path.join(flutterTools, 'lib', 'src', 'convert.dart'), + fileSystem.path.join(flutterTools, 'lib', 'src', 'base', 'error_handling_io.dart'), + ]; + bool isNotAllowed(FileSystemEntity entity) => allowedPaths.every((String path) => path != entity.path); + + for (final String dirName in ['lib']) { + final Iterable files = fileSystem.directory(fileSystem.path.join(flutterTools, dirName)) + .listSync(recursive: true) + .where(_isDartFile) + .where(isNotAllowed) + .map(_asFile); + for (final File file in files) { + for (final String line in file.readAsLinesSync()) { + if (line.startsWith(RegExp(r'import.*dart:convert')) && + !line.contains('flutter_ignore: dart_convert_import')) { + final String relativePath = fileSystem.path.relative(file.path, from:flutterTools); + fail("$relativePath imports 'dart:convert'; import 'lib/src/convert.dart' instead"); + } + } + } + } + }); + + test('no unauthorized imports of build_runner/dwds/devtools', () { + final List allowedPaths = [ + fileSystem.path.join(flutterTools, 'test', 'src', 'isolated'), + fileSystem.path.join(flutterTools, 'lib', 'src', 'isolated'), + fileSystem.path.join(flutterTools, 'lib', 'executable.dart'), + fileSystem.path.join(flutterTools, 'lib', 'devfs_web.dart'), + fileSystem.path.join(flutterTools, 'lib', 'resident_web_runner.dart'), + ]; + bool isNotAllowed(FileSystemEntity entity) => allowedPaths.every((String path) => !entity.path.contains(path)); + + for (final String dirName in ['lib']) { + final Iterable files = fileSystem.directory(fileSystem.path.join(flutterTools, dirName)) + .listSync(recursive: true) + .where(_isDartFile) + .where(isNotAllowed) + .map(_asFile); + for (final File file in files) { + for (final String line in file.readAsLinesSync()) { + if (line.startsWith(RegExp(r'import.*package:build_runner_core/build_runner_core.dart')) || + line.startsWith(RegExp(r'import.*package:build_runner/build_runner.dart')) || + line.startsWith(RegExp(r'import.*package:build_config/build_config.dart')) || + line.startsWith(RegExp(r'import.*dwds:*.dart')) || + line.startsWith(RegExp(r'import.*devtools_server:*.dart')) || + line.startsWith(RegExp(r'import.*build_runner/.*.dart'))) { + final String relativePath = fileSystem.path.relative(file.path, from:flutterTools); + fail('$relativePath imports a build_runner/dwds/devtools package'); + } + } + } + } + }); + + test('no import of packages in tool_backend.dart', () { + final File file = fileSystem.file(fileSystem.path.join(flutterTools, 'bin', 'tool_backend.dart')); + for (final String line in file.readAsLinesSync()) { + if (line.startsWith(RegExp(r'import.*package:.*'))) { + final String relativePath = fileSystem.path.relative(file.path, from:flutterTools); + fail('$relativePath imports a package'); + } + } + }); +} + +bool _isDartFile(FileSystemEntity entity) => entity is File && entity.path.endsWith('.dart'); + +File _asFile(FileSystemEntity entity) => entity as File; diff --git a/flutter/packages/flutter_tools/test/integration.shard/gen_l10n_test.dart b/flutter/packages/flutter_tools/test/integration.shard/gen_l10n_test.dart new file mode 100644 index 0000000000000000000000000000000000000000..268ec5e024967a76c52c00c7964c32bb605b172a --- /dev/null +++ b/flutter/packages/flutter_tools/test/integration.shard/gen_l10n_test.dart @@ -0,0 +1,195 @@ +// 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/file.dart'; + +import '../src/common.dart'; +import 'test_data/gen_l10n_project.dart'; +import 'test_driver.dart'; +import 'test_utils.dart'; + +final GenL10nProject project = GenL10nProject( + useNamedParameters: false, +); +final GenL10nProject projectWithNamedParameter = GenL10nProject( + useNamedParameters: true, +); + +// Verify that the code generated by gen_l10n executes correctly. +// It can fail if gen_l10n produces a lib/l10n/app_localizations.dart that +// does not analyze cleanly. +void main() { + late Directory tempDir; + late FlutterRunTestDriver flutter; + + setUp(() async { + tempDir = createResolvedTempDirectorySync('gen_l10n_test.'); + }); + + tearDown(() async { + await flutter.stop(); + tryToDelete(tempDir); + }); + + Future runApp() async { + // Run the app defined in GenL10nProject.main and wait for it to + // send '#l10n END' to its stdout. + final Completer l10nEnd = Completer(); + final StringBuffer stdout = StringBuffer(); + final StreamSubscription subscription = flutter.stdout.listen((String line) { + if (line.contains('#l10n')) { + stdout.writeln(line.substring(line.indexOf('#l10n'))); + } + if (line.contains('#l10n END')) { + l10nEnd.complete(); + } + }); + await flutter.run(); + await l10nEnd.future; + await subscription.cancel(); + return stdout; + } + + void expectOutput(StringBuffer stdout) { + expect(stdout.toString(), + '#l10n 0 (--- supportedLocales tests ---)\n' + '#l10n 1 (supportedLocales[0]: languageCode: en, countryCode: null, scriptCode: null)\n' + '#l10n 2 (supportedLocales[1]: languageCode: en, countryCode: CA, scriptCode: null)\n' + '#l10n 3 (supportedLocales[2]: languageCode: en, countryCode: GB, scriptCode: null)\n' + '#l10n 4 (supportedLocales[3]: languageCode: es, countryCode: null, scriptCode: null)\n' + '#l10n 5 (supportedLocales[4]: languageCode: es, countryCode: 419, scriptCode: null)\n' + '#l10n 6 (supportedLocales[5]: languageCode: zh, countryCode: null, scriptCode: null)\n' + '#l10n 7 (supportedLocales[6]: languageCode: zh, countryCode: null, scriptCode: Hans)\n' + '#l10n 8 (supportedLocales[7]: languageCode: zh, countryCode: null, scriptCode: Hant)\n' + '#l10n 9 (supportedLocales[8]: languageCode: zh, countryCode: TW, scriptCode: Hant)\n' + '#l10n 10 (--- countryCode (en_CA) tests ---)\n' + '#l10n 11 (CA Hello World)\n' + '#l10n 12 (Hello CA fallback World)\n' + '#l10n 13 (--- countryCode (en_GB) tests ---)\n' + '#l10n 14 (GB Hello World)\n' + '#l10n 15 (Hello GB fallback World)\n' + '#l10n 16 (--- zh ---)\n' + '#l10n 17 (你好世界)\n' + '#l10n 18 (你好)\n' + '#l10n 19 (你好世界)\n' + '#l10n 20 (你好2个其他世界)\n' + '#l10n 21 (Hello 世界)\n' + '#l10n 22 (zh - Hello for 价钱 CNY123.00)\n' + '#l10n 23 (--- scriptCode: zh_Hans ---)\n' + '#l10n 24 (简体你好世界)\n' + '#l10n 25 (--- scriptCode - zh_Hant ---)\n' + '#l10n 26 (繁體你好世界)\n' + '#l10n 27 (--- scriptCode - zh_Hant_TW ---)\n' + '#l10n 28 (台灣繁體你好世界)\n' + '#l10n 29 (--- General formatting tests ---)\n' + '#l10n 30 (Hello World)\n' + '#l10n 31 (Hello _NEWLINE_ World)\n' + '#l10n 32 (Hello \$ World)\n' + '#l10n 33 (Hello World)\n' + '#l10n 34 (Hello World)\n' + '#l10n 35 (Hello World on Friday, January 1, 1960)\n' + '#l10n 36 (Hello world argument on 1/1/1960 at 00:00)\n' + '#l10n 37 (Hello World from 1960 to 2020)\n' + '#l10n 38 (Hello for 123)\n' + '#l10n 39 (Hello for price USD123.00)\n' + '#l10n 40 (Hello for price BTC0.50 (with optional param))\n' + "#l10n 41 (Hello for price BTC'0.50 (with special character))\n" + '#l10n 42 (Hello for price BTC"0.50 (with special character))\n' + '#l10n 43 (Hello for price BTC"\'0.50 (with special character))\n' + '#l10n 44 (Hello for Decimal Pattern 1,200,000)\n' + '#l10n 45 (Hello for Percent Pattern 120,000,000%)\n' + '#l10n 46 (Hello for Scientific Pattern 1E6)\n' + '#l10n 47 (Hello)\n' + '#l10n 48 (Hello World)\n' + '#l10n 49 (Hello two worlds)\n' + '#l10n 50 (Hello)\n' + '#l10n 51 (Hello new World)\n' + '#l10n 52 (Hello two new worlds)\n' + '#l10n 53 (Hello on Friday, January 1, 1960)\n' + '#l10n 54 (Hello World, on Friday, January 1, 1960)\n' + '#l10n 55 (Hello two worlds, on Friday, January 1, 1960)\n' + '#l10n 56 (Hello other 0 worlds, with a total of 100 citizens)\n' + '#l10n 57 (Hello World of 101 citizens)\n' + '#l10n 58 (Hello two worlds with 102 total citizens)\n' + '#l10n 59 ([Hello] -World- #123#)\n' + '#l10n 60 (\$!)\n' + '#l10n 61 (One \$)\n' + "#l10n 62 (Flutter's amazing!)\n" + "#l10n 63 (Flutter's amazing, times 2!)\n" + '#l10n 64 (Flutter is "amazing"!)\n' + '#l10n 65 (Flutter is "amazing", times 2!)\n' + '#l10n 66 (16 wheel truck)\n' + "#l10n 67 (Sedan's elegance)\n" + '#l10n 68 (Cabriolet has "acceleration")\n' + '#l10n 69 (Oh, she found 1 item!)\n' + '#l10n 70 (Indeed, they like Flutter!)\n' + '#l10n 71 (Indeed, he likes ice cream!)\n' + '#l10n 72 (Indeed, she likes chocolate!)\n' + '#l10n 73 (he)\n' + '#l10n 74 (they)\n' + '#l10n 75 (she)\n' + '#l10n 76 (6/26/2023)\n' + '#l10n 77 (5:23:00 AM)\n' + '#l10n 78 (--- es ---)\n' + '#l10n 79 (ES - Hello world)\n' + '#l10n 80 (ES - Hello _NEWLINE_ World)\n' + '#l10n 81 (ES - Hola \$ Mundo)\n' + '#l10n 82 (ES - Hello Mundo)\n' + '#l10n 83 (ES - Hola Mundo)\n' + '#l10n 84 (ES - Hello World on viernes, 1 de enero de 1960)\n' + '#l10n 85 (ES - Hello world argument on 1/1/1960 at 0:00)\n' + '#l10n 86 (ES - Hello World from 1960 to 2020)\n' + '#l10n 87 (ES - Hello for 123)\n' + '#l10n 88 (ES - Hello)\n' + '#l10n 89 (ES - Hello World)\n' + '#l10n 90 (ES - Hello two worlds)\n' + '#l10n 91 (ES - Hello)\n' + '#l10n 92 (ES - Hello nuevo World)\n' + '#l10n 93 (ES - Hello two nuevo worlds)\n' + '#l10n 94 (ES - Hello on viernes, 1 de enero de 1960)\n' + '#l10n 95 (ES - Hello World, on viernes, 1 de enero de 1960)\n' + '#l10n 96 (ES - Hello two worlds, on viernes, 1 de enero de 1960)\n' + '#l10n 97 (ES - Hello other 0 worlds, with a total of 100 citizens)\n' + '#l10n 98 (ES - Hello World of 101 citizens)\n' + '#l10n 99 (ES - Hello two worlds with 102 total citizens)\n' + '#l10n 100 (ES - [Hola] -Mundo- #123#)\n' + '#l10n 101 (ES - \$!)\n' + '#l10n 102 (ES - One \$)\n' + "#l10n 103 (ES - Flutter's amazing!)\n" + "#l10n 104 (ES - Flutter's amazing, times 2!)\n" + '#l10n 105 (ES - Flutter is "amazing"!)\n' + '#l10n 106 (ES - Flutter is "amazing", times 2!)\n' + '#l10n 107 (ES - 16 wheel truck)\n' + "#l10n 108 (ES - Sedan's elegance)\n" + '#l10n 109 (ES - Cabriolet has "acceleration")\n' + '#l10n 110 (ES - Oh, she found ES - 1 itemES - !)\n' + '#l10n 111 (ES - Indeed, ES - they like ES - Flutter!)\n' + '#l10n 112 (--- es_419 ---)\n' + '#l10n 113 (ES 419 - Hello World)\n' + '#l10n 114 (ES 419 - Hello)\n' + '#l10n 115 (ES 419 - Hello World)\n' + '#l10n 116 (ES 419 - Hello two worlds)\n' + '#l10n END\n' + + ); + } + + // TODO(jsimmons): need a localization test that uses deferred loading + // (see https://github.com/flutter/flutter/issues/61911) + testWithoutContext('generated l10n classes produce expected localized strings', () async { + await project.setUpIn(tempDir); + flutter = FlutterRunTestDriver(tempDir); + final StringBuffer stdout = await runApp(); + expectOutput(stdout); + }); + + testWithoutContext('generated l10n classes produce expected localized strings when named parameter is used', () async { + await projectWithNamedParameter.setUpIn(tempDir); + flutter = FlutterRunTestDriver(tempDir); + final StringBuffer stdout = await runApp(); + expectOutput(stdout); + }); +} diff --git a/flutter/packages/flutter_tools/test/integration.shard/gradle_non_android_plugin_test.dart b/flutter/packages/flutter_tools/test/integration.shard/gradle_non_android_plugin_test.dart new file mode 100644 index 0000000000000000000000000000000000000000..59899ce826a0538e127ab59cefeb30206b432c1e --- /dev/null +++ b/flutter/packages/flutter_tools/test/integration.shard/gradle_non_android_plugin_test.dart @@ -0,0 +1,95 @@ +// 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_testing/file_testing.dart'; +import 'package:flutter_tools/src/base/io.dart'; + +import '../src/common.dart'; +import 'test_utils.dart'; + +void main() { + late Directory tempDir; + + setUp(() { + tempDir = createResolvedTempDirectorySync('flutter_plugin_test.'); + }); + + tearDown(() { + tryToDelete(tempDir); + }); + + testWithoutContext('Flutter app that depends on a non-Android plugin can still build for Android', () { + final String flutterRoot = getFlutterRoot(); + final String flutterBin = fileSystem.path.join( + flutterRoot, + 'bin', + 'flutter', + ); + processManager.runSync([ + flutterBin, + ...getLocalEngineArguments(), + 'create', + '-t', + 'plugin', + '--platforms=ios,android', + 'ios_only', + ], workingDirectory: tempDir.path); + + // Delete plugin's Android folder + final Directory projectRoot = tempDir.childDirectory('ios_only'); + projectRoot.childDirectory('android').deleteSync(recursive: true); + + // Update pubspec.yaml to iOS only plugin + final File pubspecFile = projectRoot.childFile('pubspec.yaml'); + final String pubspecString = pubspecFile.readAsStringSync(); + + final StringBuffer iosOnlyPubspec = StringBuffer(); + bool inAndroidSection = false; + const String pluginPlatformIndentation = ' '; + for (final String line in pubspecString.split('\n')) { + // Skip everything in the Android section of the plugin platforms list. + if (line.startsWith('${pluginPlatformIndentation}android:')) { + inAndroidSection = true; + continue; + } + if (inAndroidSection) { + if (line.startsWith('$pluginPlatformIndentation ')) { + continue; + } else { + inAndroidSection = false; + } + } + iosOnlyPubspec.write('$line\n'); + } + + pubspecFile.writeAsStringSync(iosOnlyPubspec.toString()); + + // Build example APK + final Directory exampleDir = projectRoot.childDirectory('example'); + + final ProcessResult result = processManager.runSync([ + flutterBin, + ...getLocalEngineArguments(), + 'build', + 'apk', + '--target-platform', + 'android-arm', + '--verbose', + ], workingDirectory: exampleDir.path); + + expect(result, const ProcessResultMatcher()); + + final String exampleAppApk = fileSystem.path.join( + exampleDir.path, + 'build', + 'app', + 'outputs', + 'apk', + 'release', + 'app-release.apk', + ); + expect(fileSystem.file(exampleAppApk), exists); + }); +} diff --git a/flutter/packages/flutter_tools/test/integration.shard/hot_reload_errors_test.dart b/flutter/packages/flutter_tools/test/integration.shard/hot_reload_errors_test.dart new file mode 100644 index 0000000000000000000000000000000000000000..edddb6864b9b606f708297b71e5ba09b73ff7f92 --- /dev/null +++ b/flutter/packages/flutter_tools/test/integration.shard/hot_reload_errors_test.dart @@ -0,0 +1,34 @@ +// 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 '../src/common.dart'; +import 'test_data/hot_reload_const_project.dart'; +import 'test_driver.dart'; +import 'test_utils.dart'; + +void main() { + late Directory tempDir; + final HotReloadConstProject project = HotReloadConstProject(); + late FlutterRunTestDriver flutter; + + setUp(() async { + tempDir = createResolvedTempDirectorySync('hot_reload_test.'); + await project.setUpIn(tempDir); + flutter = FlutterRunTestDriver(tempDir); + }); + + tearDown(() async { + await flutter.stop(); + tryToDelete(tempDir); + }); + + testWithoutContext('hot reload displays a formatted error message when removing a field from a const class', () async { + await flutter.run(); + project.removeFieldFromConstClass(); + + expect(flutter.hotReload(), throwsA(isA().having((Exception e) => e.toString(), 'message', contains('Try performing a hot restart instead.')))); + }); +} diff --git a/flutter/packages/flutter_tools/test/integration.shard/hot_reload_test.dart b/flutter/packages/flutter_tools/test/integration.shard/hot_reload_test.dart new file mode 100644 index 0000000000000000000000000000000000000000..0d5f132f486cb308957d99c1945cae669b647e48 --- /dev/null +++ b/flutter/packages/flutter_tools/test/integration.shard/hot_reload_test.dart @@ -0,0 +1,198 @@ +// 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/file.dart'; +import 'package:vm_service/vm_service.dart'; + +import '../src/common.dart'; +import 'test_data/hot_reload_project.dart'; +import 'test_driver.dart'; +import 'test_utils.dart'; + +void main() { + late Directory tempDir; + final HotReloadProject project = HotReloadProject(); + late FlutterRunTestDriver flutter; + + setUp(() async { + tempDir = createResolvedTempDirectorySync('hot_reload_test.'); + await project.setUpIn(tempDir); + flutter = FlutterRunTestDriver(tempDir); + }); + + tearDown(() async { + await flutter.stop(); + tryToDelete(tempDir); + }); + + testWithoutContext('hot reload works without error', () async { + await flutter.run(); + await flutter.hotReload(); + }); + + testWithoutContext('multiple overlapping hot reload are debounced and queued', () async { + await flutter.run(); + // Capture how many *real* hot reloads occur. + int numReloads = 0; + final StreamSubscription subscription = flutter.stdout + .map(parseFlutterResponse) + .where(_isHotReloadCompletionEvent) + .listen((_) => numReloads++); + + // To reduce tests flaking, override the debounce timer to something higher than + // the default to ensure the hot reloads that are supposed to arrive within the + // debounce period will even on slower CI machines. + const int hotReloadDebounceOverrideMs = 250; + const Duration delay = Duration(milliseconds: hotReloadDebounceOverrideMs * 2); + + Future doReload([void _]) => + flutter.hotReload(debounce: true, debounceDurationOverrideMs: hotReloadDebounceOverrideMs); + + try { + await Future.wait(>[ + doReload(), + doReload(), + Future.delayed(delay).then(doReload), + Future.delayed(delay).then(doReload), + ]); + + // We should only get two reloads, as the first two will have been + // merged together by the debounce, and the second two also. + expect(numReloads, equals(2)); + } finally { + await subscription.cancel(); + } + }); + + testWithoutContext('newly added code executes during hot reload', () async { + final StringBuffer stdout = StringBuffer(); + final StreamSubscription subscription = flutter.stdout.listen(stdout.writeln); + await flutter.run(); + project.uncommentHotReloadPrint(); + try { + await flutter.hotReload(); + expect(stdout.toString(), contains('(((((RELOAD WORKED)))))')); + } finally { + await subscription.cancel(); + } + }); + + testWithoutContext('hot restart works without error', () async { + await flutter.run(); + await flutter.hotRestart(); + }); + + testWithoutContext('breakpoints are hit after hot reload', () async { + Isolate isolate; + final Completer sawTick1 = Completer(); + final Completer sawDebuggerPausedMessage = Completer(); + final StreamSubscription subscription = flutter.stdout.listen( + (String line) { + if (line.contains('((((TICK 1))))')) { + expect(sawTick1.isCompleted, isFalse); + sawTick1.complete(); + } + if (line.contains('The application is paused in the debugger on a breakpoint.')) { + expect(sawDebuggerPausedMessage.isCompleted, isFalse); + sawDebuggerPausedMessage.complete(); + } + }, + ); + await flutter.run(withDebugger: true, startPaused: true); + await flutter.resume(); // we start paused so we can set up our TICK 1 listener before the app starts + unawaited(sawTick1.future.timeout( + const Duration(seconds: 5), + onTimeout: () { + // This print is useful for people debugging this test. Normally we would avoid printing in + // a test but this is an exception because it's useful ambient information. + // ignore: avoid_print + print('The test app is taking longer than expected to print its synchronization line...'); + }, + )); + printOnFailure('waiting for synchronization line...'); + await sawTick1.future; // after this, app is in steady state + await flutter.addBreakpoint( + project.scheduledBreakpointUri, + project.scheduledBreakpointLine, + ); + await Future.delayed(const Duration(seconds: 2)); + await flutter.hotReload(); // reload triggers code which eventually hits the breakpoint + isolate = await flutter.waitForPause(); + expect(isolate.pauseEvent?.kind, equals(EventKind.kPauseBreakpoint)); + await flutter.resume(); + await flutter.addBreakpoint( + project.buildBreakpointUri, + project.buildBreakpointLine, + ); + bool reloaded = false; + final Future reloadFuture = flutter.hotReload().then((void value) { reloaded = true; }); + printOnFailure('waiting for pause...'); + isolate = await flutter.waitForPause(); + expect(isolate.pauseEvent?.kind, equals(EventKind.kPauseBreakpoint)); + printOnFailure('waiting for debugger message...'); + await sawDebuggerPausedMessage.future; + expect(reloaded, isFalse); + printOnFailure('waiting for resume...'); + await flutter.resume(); + printOnFailure('waiting for reload future...'); + await reloadFuture; + expect(reloaded, isTrue); + reloaded = false; + printOnFailure('subscription cancel...'); + await subscription.cancel(); + }); + + testWithoutContext("hot reload doesn't reassemble if paused", () async { + final Completer sawTick1 = Completer(); + final Completer sawDebuggerPausedMessage1 = Completer(); + final Completer sawDebuggerPausedMessage2 = Completer(); + final StreamSubscription subscription = flutter.stdout.listen( + (String line) { + printOnFailure('[LOG]:"$line"'); + if (line.contains('(((TICK 1)))')) { + expect(sawTick1.isCompleted, isFalse); + sawTick1.complete(); + } + if (line.contains('The application is paused in the debugger on a breakpoint.')) { + expect(sawDebuggerPausedMessage1.isCompleted, isFalse); + sawDebuggerPausedMessage1.complete(); + } + if (line.contains('The application is paused in the debugger on a breakpoint; interface might not update.')) { + expect(sawDebuggerPausedMessage2.isCompleted, isFalse); + sawDebuggerPausedMessage2.complete(); + } + }, + ); + await flutter.run(withDebugger: true); + await Future.delayed(const Duration(seconds: 1)); + await sawTick1.future; + await flutter.addBreakpoint( + project.buildBreakpointUri, + project.buildBreakpointLine, + ); + bool reloaded = false; + await Future.delayed(const Duration(seconds: 1)); + final Future reloadFuture = flutter.hotReload().then((void value) { reloaded = true; }); + final Isolate isolate = await flutter.waitForPause(); + expect(isolate.pauseEvent?.kind, equals(EventKind.kPauseBreakpoint)); + expect(reloaded, isFalse); + await sawDebuggerPausedMessage1.future; // this is the one where it say "uh, you broke into the debugger while reloading" + await reloadFuture; // this is the one where it times out because you're in the debugger + expect(reloaded, isTrue); + await flutter.hotReload(); // now we're already paused + await sawDebuggerPausedMessage2.future; // so we just get told that nothing is going to happen + await flutter.resume(); + await subscription.cancel(); + }); +} + +bool _isHotReloadCompletionEvent(Map? event) { + return event != null && + event['event'] == 'app.progress' && + event['params'] != null && + (event['params']! as Map)['progressId'] == 'hot.reload' && + (event['params']! as Map)['finished'] == true; +} diff --git a/flutter/packages/flutter_tools/test/integration.shard/hot_reload_with_asset_test.dart b/flutter/packages/flutter_tools/test/integration.shard/hot_reload_with_asset_test.dart new file mode 100644 index 0000000000000000000000000000000000000000..4de27d074f63b8f7b8d3c3f22927e8c48ec39d4f --- /dev/null +++ b/flutter/packages/flutter_tools/test/integration.shard/hot_reload_with_asset_test.dart @@ -0,0 +1,83 @@ +// 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/file.dart'; + +import '../src/common.dart'; +import 'test_data/hot_reload_with_asset.dart'; +import 'test_driver.dart'; +import 'test_utils.dart'; + +void main() { + late Directory tempDir; + final HotReloadWithAssetProject project = HotReloadWithAssetProject(); + late FlutterRunTestDriver flutter; + + setUp(() async { + tempDir = createResolvedTempDirectorySync('hot_reload_test.'); + await project.setUpIn(tempDir); + flutter = FlutterRunTestDriver(tempDir); + }); + + tearDown(() async { + await flutter.stop(); + tryToDelete(tempDir); + }); + + testWithoutContext('hot reload does not need to sync assets on the first reload', () async { + final Completer onFirstLoad = Completer(); + final Completer onSecondLoad = Completer(); + + flutter.stdout.listen((String line) { + // If the asset fails to load, this message will be printed instead. + // this indicates that the devFS was not able to locate the asset + // after the hot reload. + if (line.contains('FAILED TO LOAD')) { + fail('Did not load asset: $line'); + } + if (line.contains('LOADED DATA')) { + onFirstLoad.complete(); + } + if (line.contains('SECOND DATA')) { + onSecondLoad.complete(); + } + }); + flutter.stdout.listen(printOnFailure); + await flutter.run(); + await onFirstLoad.future; + + project.uncommentHotReloadPrint(); + await flutter.hotReload(); + await onSecondLoad.future; + }); + + testWithoutContext('hot restart does not need to sync assets on the first reload', () async { + final Completer onFirstLoad = Completer(); + final Completer onSecondLoad = Completer(); + + flutter.stdout.listen((String line) { + // If the asset fails to load, this message will be printed instead. + // this indicates that the devFS was not able to locate the asset + // after the hot reload. + if (line.contains('FAILED TO LOAD')) { + fail('Did not load asset: $line'); + } + if (line.contains('LOADED DATA')) { + onFirstLoad.complete(); + } + if (line.contains('SECOND DATA')) { + onSecondLoad.complete(); + } + }); + flutter.stdout.listen(printOnFailure); + await flutter.run(); + await onFirstLoad.future; + + project.uncommentHotReloadPrint(); + await flutter.hotRestart(); + await onSecondLoad.future; + }); +} diff --git a/flutter/packages/flutter_tools/test/integration.shard/lifetime_test.dart b/flutter/packages/flutter_tools/test/integration.shard/lifetime_test.dart new file mode 100644 index 0000000000000000000000000000000000000000..bab2ee3e9fa9dc85ae285319472b3b571f843b4e --- /dev/null +++ b/flutter/packages/flutter_tools/test/integration.shard/lifetime_test.dart @@ -0,0 +1,44 @@ +// 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 '../src/common.dart'; +import 'test_data/basic_project.dart'; +import 'test_driver.dart'; +import 'test_utils.dart'; + +/// This duration is arbitrary but is ideally: +/// a) Long enough to ensure that if the app is crashing at startup, we notice. +/// b) As short as possible, to avoid inflating build times. +const Duration requiredLifespan = Duration(seconds: 5); + +void main() { + final BasicProject project = BasicProject(); + late FlutterRunTestDriver flutter; + late Directory tempDir; + + setUp(() async { + tempDir = createResolvedTempDirectorySync('lifetime_test.'); + await project.setUpIn(tempDir); + flutter = FlutterRunTestDriver(tempDir); + }); + + tearDown(() async { + await flutter.stop(); + tryToDelete(tempDir); + }); + + testWithoutContext('flutter run does not terminate when a debugger is attached', () async { + await flutter.run(withDebugger: true); + await Future.delayed(requiredLifespan); + expect(flutter.hasExited, equals(false)); + }); + + testWithoutContext('flutter run does not terminate when a debugger is attached and pause-on-exceptions', () async { + await flutter.run(withDebugger: true, pauseOnExceptions: true); + await Future.delayed(requiredLifespan); + expect(flutter.hasExited, equals(false)); + }); +} diff --git a/flutter/packages/flutter_tools/test/integration.shard/multidex_build_test.dart b/flutter/packages/flutter_tools/test/integration.shard/multidex_build_test.dart new file mode 100644 index 0000000000000000000000000000000000000000..b3e838aa27ddfd438580b88a61dc755f5c6d491b --- /dev/null +++ b/flutter/packages/flutter_tools/test/integration.shard/multidex_build_test.dart @@ -0,0 +1,58 @@ +// 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/base/io.dart'; + +import '../src/common.dart'; +import 'test_data/multidex_project.dart'; +import 'test_driver.dart'; +import 'test_utils.dart'; + +void main() { + late Directory tempDir; + late FlutterRunTestDriver flutter; + + setUp(() async { + tempDir = createResolvedTempDirectorySync('run_test.'); + flutter = FlutterRunTestDriver(tempDir); + }); + + tearDown(() async { + await flutter.stop(); + tryToDelete(tempDir); + }); + + testWithoutContext('simple build apk succeeds', () async { + final MultidexProject project = MultidexProject(true); + await project.setUpIn(tempDir); + final String flutterBin = fileSystem.path.join(getFlutterRoot(), 'bin', 'flutter'); + final ProcessResult result = await processManager.run([ + flutterBin, + ...getLocalEngineArguments(), + 'build', + 'apk', + '--debug', + ], workingDirectory: tempDir.path); + + expect(result, const ProcessResultMatcher(stdoutPattern: 'app-debug.apk')); + }); + + testWithoutContext('simple build apk without FlutterMultiDexApplication fails', () async { + final MultidexProject project = MultidexProject(false); + await project.setUpIn(tempDir); + final String flutterBin = fileSystem.path.join(getFlutterRoot(), 'bin', 'flutter'); + final ProcessResult result = await processManager.run([ + flutterBin, + ...getLocalEngineArguments(), + 'build', + 'apk', + '--debug', + ], workingDirectory: tempDir.path); + + expect(result, const ProcessResultMatcher(exitCode: 1)); + expect(result.stderr.toString(), contains('Cannot fit requested classes in a single dex file')); + expect(result.stderr.toString(), contains('The number of method references in a .dex file cannot exceed 64K.')); + }); +} diff --git a/flutter/packages/flutter_tools/test/integration.shard/native_assets_test.dart b/flutter/packages/flutter_tools/test/integration.shard/native_assets_test.dart new file mode 100644 index 0000000000000000000000000000000000000000..ae577cca1b0ddb67d77b82ec065f68a9fd656a02 --- /dev/null +++ b/flutter/packages/flutter_tools/test/integration.shard/native_assets_test.dart @@ -0,0 +1,467 @@ +// Copyright 2014 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +// This test exercises the embedding of the native assets mapping in dill files. +// An initial dill file is created by `flutter assemble` and used for running +// the application. This dill must contain the mapping. +// When doing hot reload, this mapping must stay in place. +// When doing a hot restart, a new dill file is pushed. This dill file must also +// contain the native assets mapping. +// When doing a hot reload, this mapping must stay in place. + +@Timeout(Duration(minutes: 10)) +library; + +import 'dart:io'; + +import 'package:file/file.dart'; +import 'package:file_testing/file_testing.dart'; +import 'package:flutter_tools/src/base/logger.dart'; +import 'package:flutter_tools/src/base/os.dart'; +import 'package:native_assets_cli/native_assets_cli.dart'; + +import '../src/common.dart'; +import 'test_utils.dart' show ProcessResultMatcher, fileSystem, platform; +import 'transition_test_utils.dart'; + +final String hostOs = platform.operatingSystem; + +final List devices = [ + 'flutter-tester', + hostOs, +]; + +final List buildSubcommands = [ + hostOs, + if (hostOs == 'macos') 'ios', + 'apk', +]; + +final List add2appBuildSubcommands = [ + if (hostOs == 'macos') ...[ + 'macos-framework', + 'ios-framework', + ], +]; + +/// The build modes to target for each flutter command that supports passing +/// a build mode. +/// +/// The flow of compiling kernel as well as bundling dylibs can differ based on +/// build mode, so we should cover this. +const List buildModes = [ + 'debug', + 'profile', + 'release', +]; + +const String packageName = 'package_with_native_assets'; + +const String exampleAppName = '${packageName}_example'; + +void main() { + if (!platform.isMacOS && !platform.isLinux && !platform.isWindows) { + // TODO(dacoharkes): Implement Fuchsia. https://github.com/flutter/flutter/issues/129757 + return; + } + + setUpAll(() { + processManager.runSync([ + flutterBin, + 'config', + '--enable-native-assets', + ]); + }); + + for (final String device in devices) { + for (final String buildMode in buildModes) { + if (device == 'flutter-tester' && buildMode != 'debug') { + continue; + } + final String hotReload = buildMode == 'debug' ? ' hot reload and hot restart' : ''; + testWithoutContext('flutter run$hotReload with native assets $device $buildMode', () async { + await inTempDir((Directory tempDirectory) async { + final Directory packageDirectory = await createTestProject(packageName, tempDirectory); + final Directory exampleDirectory = packageDirectory.childDirectory('example'); + + final ProcessTestResult result = await runFlutter( + [ + 'run', + '-d$device', + '--$buildMode', + ], + exampleDirectory.path, + [ + Multiple([ + 'Flutter run key commands.', + ], handler: (String line) { + if (buildMode == 'debug') { + // Do a hot reload diff on the initial dill file. + return 'r'; + } else { + // No hot reload and hot restart in release mode. + return 'q'; + } + }), + if (buildMode == 'debug') ...[ + Barrier( + 'Performing hot reload...'.padRight(progressMessageWidth), + logging: true, + ), + Multiple([ + RegExp('Reloaded .*'), + ], handler: (String line) { + // Do a hot restart, pushing a new complete dill file. + return 'R'; + }), + Barrier('Performing hot restart...'.padRight(progressMessageWidth)), + Multiple([ + RegExp('Restarted application .*'), + ], handler: (String line) { + // Do another hot reload, pushing a diff to the second dill file. + return 'r'; + }), + Barrier( + 'Performing hot reload...'.padRight(progressMessageWidth), + logging: true, + ), + Multiple([ + RegExp('Reloaded .*'), + ], handler: (String line) { + return 'q'; + }), + ], + const Barrier('Application finished.'), + ], + logging: false, + ); + if (result.exitCode != 0) { + throw Exception('flutter run failed: ${result.exitCode}\n${result.stderr}\n${result.stdout}'); + } + final String stdout = result.stdout.join('\n'); + // Check that we did not fail to resolve the native function in the + // dynamic library. + expect(stdout, isNot(contains("Invalid argument(s): Couldn't resolve native function 'sum'"))); + // And also check that we did not have any other exceptions that might + // shadow the exception we would have gotten. + expect(stdout, isNot(contains('EXCEPTION CAUGHT BY WIDGETS LIBRARY'))); + + if (device == 'macos') { + expectDylibIsBundledMacOS(exampleDirectory, buildMode); + } else if (device == 'linux') { + expectDylibIsBundledLinux(exampleDirectory, buildMode); + } else if (device == 'windows') { + expectDylibIsBundledWindows(exampleDirectory, buildMode); + } + if (device == hostOs) { + expectCCompilerIsConfigured(exampleDirectory); + } + }); + }); + } + } + + testWithoutContext('flutter test with native assets', () async { + await inTempDir((Directory tempDirectory) async { + final Directory packageDirectory = await createTestProject(packageName, tempDirectory); + + final ProcessTestResult result = await runFlutter( + [ + 'test', + ], + packageDirectory.path, + [ + Barrier(RegExp('.* All tests passed!')), + ], + logging: false, + ); + if (result.exitCode != 0) { + throw Exception('flutter test failed: ${result.exitCode}\n${result.stderr}\n${result.stdout}'); + } + }); + }); + + for (final String buildSubcommand in buildSubcommands) { + for (final String buildMode in buildModes) { + testWithoutContext('flutter build $buildSubcommand with native assets $buildMode', () async { + await inTempDir((Directory tempDirectory) async { + final Directory packageDirectory = await createTestProject(packageName, tempDirectory); + final Directory exampleDirectory = packageDirectory.childDirectory('example'); + + final ProcessResult result = processManager.runSync( + [ + flutterBin, + 'build', + buildSubcommand, + '--$buildMode', + if (buildSubcommand == 'ios') '--no-codesign', + ], + workingDirectory: exampleDirectory.path, + ); + if (result.exitCode != 0) { + throw Exception('flutter build failed: ${result.exitCode}\n${result.stderr}\n${result.stdout}'); + } + + if (buildSubcommand == 'macos') { + expectDylibIsBundledMacOS(exampleDirectory, buildMode); + } else if (buildSubcommand == 'ios') { + expectDylibIsBundledIos(exampleDirectory, buildMode); + } else if (buildSubcommand == 'linux') { + expectDylibIsBundledLinux(exampleDirectory, buildMode); + } else if (buildSubcommand == 'windows') { + expectDylibIsBundledWindows(exampleDirectory, buildMode); + } else if (buildSubcommand == 'apk') { + expectDylibIsBundledAndroid(exampleDirectory, buildMode); + } + expectCCompilerIsConfigured(exampleDirectory); + }); + }); + } + + // This could be an hermetic unit test if the native_assets_builder + // could mock process runs and file system. + // https://github.com/dart-lang/native/issues/90. + testWithoutContext('flutter build $buildSubcommand error on static libraries', () async { + await inTempDir((Directory tempDirectory) async { + final Directory packageDirectory = await createTestProject(packageName, tempDirectory); + final File buildDotDart = packageDirectory.childFile('build.dart'); + final String buildDotDartContents = await buildDotDart.readAsString(); + // Overrides the build to output static libraries. + final String buildDotDartContentsNew = buildDotDartContents.replaceFirst( + 'final buildConfig = await BuildConfig.fromArgs(args);', + r''' + final buildConfig = await BuildConfig.fromArgs([ + '-D${LinkModePreference.configKey}=${LinkModePreference.static}', + ...args, + ]); +''', + ); + expect(buildDotDartContentsNew, isNot(buildDotDartContents)); + await buildDotDart.writeAsString(buildDotDartContentsNew); + final Directory exampleDirectory = packageDirectory.childDirectory('example'); + + final ProcessResult result = processManager.runSync( + [ + flutterBin, + 'build', + buildSubcommand, + if (buildSubcommand == 'ios') '--no-codesign', + if (buildSubcommand == 'windows') '-v' // Requires verbose mode for error. + ], + workingDirectory: exampleDirectory.path, + ); + expect( + (result.stdout as String) + (result.stderr as String), + contains('link mode set to static, but this is not yet supported'), + ); + expect(result.exitCode, isNot(0)); + }); + }); + } + + for (final String add2appBuildSubcommand in add2appBuildSubcommands) { + testWithoutContext('flutter build $add2appBuildSubcommand with native assets', () async { + await inTempDir((Directory tempDirectory) async { + final Directory packageDirectory = await createTestProject(packageName, tempDirectory); + final Directory exampleDirectory = packageDirectory.childDirectory('example'); + + final ProcessResult result = processManager.runSync( + [ + flutterBin, + 'build', + add2appBuildSubcommand, + ], + workingDirectory: exampleDirectory.path, + ); + if (result.exitCode != 0) { + throw Exception('flutter build failed: ${result.exitCode}\n${result.stderr}\n${result.stdout}'); + } + + for (final String buildMode in buildModes) { + expectDylibIsBundledWithFrameworks(exampleDirectory, buildMode, add2appBuildSubcommand.replaceAll('-framework', '')); + } + expectCCompilerIsConfigured(exampleDirectory); + }); + }); + } +} + +/// For `flutter build` we can't easily test whether running the app works. +/// Check that we have the dylibs in the app. +void expectDylibIsBundledMacOS(Directory appDirectory, String buildMode) { + final Directory appBundle = appDirectory.childDirectory('build/$hostOs/Build/Products/${buildMode.upperCaseFirst()}/$exampleAppName.app'); + expect(appBundle, exists); + final Directory dylibsFolder = appBundle.childDirectory('Contents/Frameworks'); + expect(dylibsFolder, exists); + final File dylib = dylibsFolder.childFile(OS.macOS.dylibFileName(packageName)); + expect(dylib, exists); +} + +void expectDylibIsBundledIos(Directory appDirectory, String buildMode) { + final Directory appBundle = appDirectory.childDirectory('build/ios/${buildMode.upperCaseFirst()}-iphoneos/Runner.app'); + expect(appBundle, exists); + final Directory dylibsFolder = appBundle.childDirectory('Frameworks'); + expect(dylibsFolder, exists); + final File dylib = dylibsFolder.childFile(OS.iOS.dylibFileName(packageName)); + expect(dylib, exists); +} + +/// Checks that dylibs are bundled. +/// +/// Sample path: build/linux/x64/release/bundle/lib/libmy_package.so +void expectDylibIsBundledLinux(Directory appDirectory, String buildMode) { + // Linux does not support cross compilation, so always only check current architecture. + final String architecture = Architecture.current.dartPlatform; + final Directory appBundle = appDirectory + .childDirectory('build') + .childDirectory(hostOs) + .childDirectory(architecture) + .childDirectory(buildMode) + .childDirectory('bundle'); + expect(appBundle, exists); + final Directory dylibsFolder = appBundle.childDirectory('lib'); + expect(dylibsFolder, exists); + final File dylib = dylibsFolder.childFile(OS.linux.dylibFileName(packageName)); + expect(dylib, exists); +} + +/// Checks that dylibs are bundled. +/// +/// Sample path: build\windows\x64\runner\Debug\my_package_example.exe +void expectDylibIsBundledWindows(Directory appDirectory, String buildMode) { + // Linux does not support cross compilation, so always only check current architecture. + final String architecture = Architecture.current.dartPlatform; + final Directory appBundle = appDirectory + .childDirectory('build') + .childDirectory(hostOs) + .childDirectory(architecture) + .childDirectory('runner') + .childDirectory(buildMode.upperCaseFirst()); + expect(appBundle, exists); + final File dylib = appBundle.childFile(OS.windows.dylibFileName(packageName)); + expect(dylib, exists); +} + +void expectDylibIsBundledAndroid(Directory appDirectory, String buildMode) { + final File apk = appDirectory + .childDirectory('build') + .childDirectory('app') + .childDirectory('outputs') + .childDirectory('flutter-apk') + .childFile('app-$buildMode.apk'); + expect(apk, exists); + final OperatingSystemUtils osUtils = OperatingSystemUtils( + fileSystem: fileSystem, + logger: BufferLogger.test(), + platform: platform, + processManager: processManager, + ); + final Directory apkUnzipped = appDirectory.childDirectory('apk-unzipped'); + apkUnzipped.createSync(); + osUtils.unzip(apk, apkUnzipped); + final Directory lib = apkUnzipped.childDirectory('lib'); + for (final String arch in ['arm64-v8a', 'armeabi-v7a', 'x86_64']) { + final Directory archDir = lib.childDirectory(arch); + expect(archDir, exists); + // The dylibs should be next to the flutter and app so. + expect(archDir.childFile('libflutter.so'), exists); + if (buildMode != 'debug') { + expect(archDir.childFile('libapp.so'), exists); + } + final File dylib = archDir.childFile(OS.android.dylibFileName(packageName)); + expect(dylib, exists); + } +} + +/// For `flutter build` we can't easily test whether running the app works. +/// Check that we have the dylibs in the app. +void expectDylibIsBundledWithFrameworks(Directory appDirectory, String buildMode, String os) { + final Directory frameworksFolder = appDirectory.childDirectory('build/$os/framework/${buildMode.upperCaseFirst()}'); + expect(frameworksFolder, exists); + final File dylib = frameworksFolder.childFile(OS.macOS.dylibFileName(packageName)); + expect(dylib, exists); +} + +/// Check that the native assets are built with the C Compiler that Flutter uses. +/// +/// This inspects the build configuration to see if the C compiler was configured. +void expectCCompilerIsConfigured(Directory appDirectory) { + final Directory nativeAssetsBuilderDir = appDirectory.childDirectory('.dart_tool/native_assets_builder/'); + for (final Directory subDir in nativeAssetsBuilderDir.listSync().whereType()) { + final File config = subDir.childFile('config.yaml'); + expect(config, exists); + final String contents = config.readAsStringSync(); + // Dry run does not pass compiler info. + if (contents.contains('dry_run: true')) { + continue; + } + expect(contents, contains('cc: ')); + } +} + +extension on String { + String upperCaseFirst() { + return replaceFirst(this[0], this[0].toUpperCase()); + } +} + +Future createTestProject(String packageName, Directory tempDirectory) async { + final ProcessResult result = processManager.runSync( + [ + flutterBin, + 'create', + '--no-pub', + '--template=package_ffi', + packageName, + ], + workingDirectory: tempDirectory.path, + ); + if (result.exitCode != 0) { + throw Exception( + 'flutter create failed: ${result.exitCode}\n${result.stderr}\n${result.stdout}', + ); + } + + final Directory packageDirectory = tempDirectory.childDirectory(packageName); + + // No platform-specific boilerplate files. + expect(packageDirectory.childDirectory('android/'), isNot(exists)); + expect(packageDirectory.childDirectory('ios/'), isNot(exists)); + expect(packageDirectory.childDirectory('linux/'), isNot(exists)); + expect(packageDirectory.childDirectory('macos/'), isNot(exists)); + expect(packageDirectory.childDirectory('windows/'), isNot(exists)); + + await pinDependencies(packageDirectory.childFile('pubspec.yaml')); + await pinDependencies( + packageDirectory.childDirectory('example').childFile('pubspec.yaml')); + + final ProcessResult result2 = await processManager.run( + [ + flutterBin, + 'pub', + 'get', + ], + workingDirectory: packageDirectory.path, + ); + expect(result2, const ProcessResultMatcher()); + + return packageDirectory; +} + +Future pinDependencies(File pubspecFile) async { + expect(pubspecFile, exists); + final String oldPubspec = await pubspecFile.readAsString(); + final String newPubspec = oldPubspec.replaceAll(RegExp(r':\s*\^'), ': '); + expect(newPubspec, isNot(oldPubspec)); + await pubspecFile.writeAsString(newPubspec); +} + +Future inTempDir(Future Function(Directory tempDirectory) fun) async { + final Directory tempDirectory = fileSystem.directory(fileSystem.systemTempDirectory.createTempSync().resolveSymbolicLinksSync()); + try { + await fun(tempDirectory); + } finally { + tryToDelete(tempDirectory); + } +} diff --git a/flutter/packages/flutter_tools/test/integration.shard/observatory_port_test.dart b/flutter/packages/flutter_tools/test/integration.shard/observatory_port_test.dart new file mode 100644 index 0000000000000000000000000000000000000000..94e5cf9f434af443cedc96a01e9bf125e40c115a --- /dev/null +++ b/flutter/packages/flutter_tools/test/integration.shard/observatory_port_test.dart @@ -0,0 +1,115 @@ +// 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/file_system.dart'; +import 'package:flutter_tools/src/base/io.dart'; +import 'package:flutter_tools/src/convert.dart'; + +import '../src/common.dart'; +import 'test_data/basic_project.dart'; +import 'test_utils.dart'; + +Future getFreePort() async { + int port = 0; + final ServerSocket serverSocket = await ServerSocket.bind(InternetAddress.loopbackIPv4, 0); + port = serverSocket.port; + await serverSocket.close(); + return port; +} + +Future waitForVmServiceMessage(Process process, int port) async { + final Completer completer = Completer(); + process.stdout + .transform(utf8.decoder) + .listen((String line) { + printOnFailure(line); + if (line.contains('A Dart VM Service on Flutter test device is available at')) { + if (line.contains('http://127.0.0.1:$port')) { + completer.complete(); + } else { + completer.completeError(Exception('Did not forward to provided port $port, instead found $line')); + } + } + }); + process.stderr + .transform(utf8.decoder) + .listen(printOnFailure); + return completer.future; +} + +void main() { + late Directory tempDir; + final BasicProject project = BasicProject(); + + setUp(() async { + tempDir = createResolvedTempDirectorySync('run_test.'); + await project.setUpIn(tempDir); + }); + + tearDown(() async { + tryToDelete(tempDir); + }); + + testWithoutContext('flutter run --vm-service-port', () async { + final String flutterBin = fileSystem.path.join(getFlutterRoot(), 'bin', 'flutter'); + final int port = await getFreePort(); + // If only --vm-service-port is provided, --vm-service-port will be used by DDS + // and the VM service will bind to a random port. + final Process process = await processManager.start([ + flutterBin, + 'run', + '--show-test-device', + '--vm-service-port=$port', + '-d', + 'flutter-tester', + ], workingDirectory: tempDir.path); + await waitForVmServiceMessage(process, port); + process.kill(); + await process.exitCode; + }); + + testWithoutContext('flutter run --dds-port --vm-service-port', () async { + final String flutterBin = fileSystem.path.join(getFlutterRoot(), 'bin', 'flutter'); + final int vmServicePort = await getFreePort(); + int ddsPort = await getFreePort(); + while (ddsPort == vmServicePort) { + ddsPort = await getFreePort(); + } + // If both --dds-port and --vm-service-port are provided, --dds-port will be used by + // DDS and --vm-service-port will be used by the VM service. + final Process process = await processManager.start([ + flutterBin, + 'run', + '--show-test-device', + '--vm-service-port=$vmServicePort', + '--dds-port=$ddsPort', + '-d', + 'flutter-tester', + ], workingDirectory: tempDir.path); + await waitForVmServiceMessage(process, ddsPort); + process.kill(); + await process.exitCode; + }); + + testWithoutContext('flutter run --dds-port', () async { + final String flutterBin = fileSystem.path.join(getFlutterRoot(), 'bin', 'flutter'); + final int ddsPort = await getFreePort(); + // If only --dds-port is provided, --dds-port will be used by DDS and the VM service + // will bind to a random port. + final Process process = await processManager.start([ + flutterBin, + 'run', + '--show-test-device', + '--dds-port=$ddsPort', + '-d', + 'flutter-tester', + ], workingDirectory: tempDir.path); + await waitForVmServiceMessage(process, ddsPort); + process.kill(); + await process.exitCode; + }); + +} diff --git a/flutter/packages/flutter_tools/test/integration.shard/overall_experience_test.dart b/flutter/packages/flutter_tools/test/integration.shard/overall_experience_test.dart new file mode 100644 index 0000000000000000000000000000000000000000..8cc4fff7e374ee0f4dba2eafc648799a6416c4e8 --- /dev/null +++ b/flutter/packages/flutter_tools/test/integration.shard/overall_experience_test.dart @@ -0,0 +1,332 @@ +// 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. + +// The purpose of this test is to verify the end-to-end behavior of +// "flutter run" and other such commands, as closely as possible to +// the default behavior. To that end, it avoids the use of any test +// features that are not critical (-dflutter-test being the primary +// example of a test feature that it does use). For example, no use +// is made of "--machine" in these tests. + +// There are a number of risks when it comes to writing a test such +// as this one. Typically these tests are hard to debug if they are +// in a failing condition, because they just hang as they await the +// next expected line that never comes. To avoid this, here we have +// the policy of looking for multiple lines, printing what expected +// lines were not seen when a short timeout expires (but timing out +// does not cause the test to fail, to reduce flakes), and wherever +// possible recording all output and comparing the actual output to +// the expected output only once the test is completed. + +// To aid in debugging, consider passing the `debug: true` argument +// to the runFlutter function. + +// This file intentionally assumes the tests run in order. +@Tags(['no-shuffle']) +library; + +import 'dart:io'; + +import '../src/common.dart'; +import 'test_utils.dart' show fileSystem; +import 'transition_test_utils.dart'; + +void main() { + testWithoutContext('flutter run writes and clears pidfile appropriately', () async { + final String tempDirectory = fileSystem.systemTempDirectory.createTempSync('flutter_overall_experience_test.').resolveSymbolicLinksSync(); + final String pidFile = fileSystem.path.join(tempDirectory, 'flutter.pid'); + final String testDirectory = fileSystem.path.join(flutterRoot, 'examples', 'hello_world'); + bool? existsDuringTest; + try { + expect(fileSystem.file(pidFile).existsSync(), isFalse); + final ProcessTestResult result = await runFlutter( + ['run', '-dflutter-tester', '--pid-file', pidFile], + testDirectory, + [ + Barrier('q Quit (terminate the application on the device).', handler: (String line) { + existsDuringTest = fileSystem.file(pidFile).existsSync(); + return 'q'; + }), + const Barrier('Application finished.'), + ], + ); + expect(existsDuringTest, isNot(isNull)); + expect(existsDuringTest, isTrue); + expect(result.exitCode, 0, reason: 'subprocess failed; $result'); + expect(fileSystem.file(pidFile).existsSync(), isFalse); + // This first test ignores the stdout and stderr, so that if the + // first run outputs "building flutter", or the "there's a new + // flutter" banner, or other such first-run messages, they won't + // fail the tests. This does mean that running this test first is + // actually important in the case where you're running the tests + // manually. (On CI, all those messages are expected to be seen + // long before we get here, e.g. because we run "flutter doctor".) + } finally { + tryToDelete(fileSystem.directory(tempDirectory)); + } + }, skip: Platform.isWindows); // [intended] Windows doesn't support sending signals so we don't care if it can store the PID. + testWithoutContext('flutter run handle SIGUSR1/2', () async { + final String tempDirectory = fileSystem.systemTempDirectory.createTempSync('flutter_overall_experience_test.').resolveSymbolicLinksSync(); + final String pidFile = fileSystem.path.join(tempDirectory, 'flutter.pid'); + final String testDirectory = fileSystem.path.join(flutterRoot, 'dev', 'integration_tests', 'ui'); + final String testScript = fileSystem.path.join('lib', 'commands.dart'); + late int pid; + try { + final ProcessTestResult result = await runFlutter( + ['run', '-dflutter-tester', '--report-ready', '--pid-file', pidFile, '--no-devtools', testScript], + testDirectory, + [ + Multiple(['Flutter run key commands.', 'called paint'], handler: (String line) { + pid = int.parse(fileSystem.file(pidFile).readAsStringSync()); + processManager.killPid(pid, ProcessSignal.sigusr1); + return null; + }), + Barrier('Performing hot reload...'.padRight(progressMessageWidth), logging: true), + Multiple([RegExp(r'^Reloaded 0 libraries in [0-9]+ms \(compile: \d+ ms, reload: \d+ ms, reassemble: \d+ ms\)\.$'), 'called reassemble', 'called paint'], handler: (String line) { + processManager.killPid(pid, ProcessSignal.sigusr2); + return null; + }), + Barrier('Performing hot restart...'.padRight(progressMessageWidth)), + // This could look like 'Restarted application in 1,237ms.' + Multiple([RegExp(r'^Restarted application in .+m?s.$'), 'called main', 'called paint'], handler: (String line) { + return 'q'; + }), + const Barrier('Application finished.'), + ], + logging: false, // we ignore leading log lines to avoid making this test sensitive to e.g. the help message text + ); + // We check the output from the app (all starts with "called ...") and the output from the tool + // (everything else) separately, because their relative timing isn't guaranteed. Their rough timing + // is verified by the expected transitions above. + expect(result.stdout.where((String line) => line.startsWith('called ')), [ + // logs start after we receive the response to sending SIGUSR1 + // SIGUSR1: + 'called reassemble', + 'called paint', + // SIGUSR2: + 'called main', + 'called paint', + ]); + expect(result.stdout.where((String line) => !line.startsWith('called ')), [ + // logs start after we receive the response to sending SIGUSR1 + 'Performing hot reload...'.padRight(progressMessageWidth), + startsWith('Reloaded 0 libraries in '), + 'Performing hot restart...'.padRight(progressMessageWidth), + startsWith('Restarted application in '), + '', // this newline is the one for after we hit "q" + 'Application finished.', + 'ready', + ]); + expect(result.exitCode, 0); + } finally { + tryToDelete(fileSystem.directory(tempDirectory)); + } + }, skip: Platform.isWindows); // [intended] Windows doesn't support sending signals. + + testWithoutContext('flutter run can hot reload and hot restart, handle "p" key', () async { + final String tempDirectory = fileSystem.systemTempDirectory.createTempSync('flutter_overall_experience_test.').resolveSymbolicLinksSync(); + final String testDirectory = fileSystem.path.join(flutterRoot, 'dev', 'integration_tests', 'ui'); + final String testScript = fileSystem.path.join('lib', 'commands.dart'); + try { + final ProcessTestResult result = await runFlutter( + ['run', '-dflutter-tester', '--report-ready', '--no-devtools', testScript], + testDirectory, + [ + Multiple(['Flutter run key commands.', 'called main', 'called paint'], handler: (String line) { + return 'r'; + }), + Barrier('Performing hot reload...'.padRight(progressMessageWidth), logging: true), + Multiple(['ready', 'called reassemble', 'called paint'], handler: (String line) { + return 'R'; + }), + Barrier('Performing hot restart...'.padRight(progressMessageWidth)), + Multiple(['ready', 'called main', 'called paint'], handler: (String line) { + return 'p'; + }), + Multiple(['ready', 'called paint', 'called debugPaintSize'], handler: (String line) { + return 'p'; + }), + Multiple(['ready', 'called paint'], handler: (String line) { + return 'q'; + }), + const Barrier('Application finished.'), + ], + logging: false, // we ignore leading log lines to avoid making this test sensitive to e.g. the help message text + ); + // We check the output from the app (all starts with "called ...") and the output from the tool + // (everything else) separately, because their relative timing isn't guaranteed. Their rough timing + // is verified by the expected transitions above. + expect(result.stdout.where((String line) => line.startsWith('called ')), [ + // logs start after we initiate the hot reload + // hot reload: + 'called reassemble', + 'called paint', + // hot restart: + 'called main', + 'called paint', + // debugPaintSizeEnabled = true: + 'called paint', + 'called debugPaintSize', + // debugPaintSizeEnabled = false: + 'called paint', + ]); + expect(result.stdout.where((String line) => !line.startsWith('called ')), [ + // logs start after we receive the response to hitting "r" + 'Performing hot reload...'.padRight(progressMessageWidth), + startsWith('Reloaded 0 libraries in '), + 'ready', + '', // this newline is the one for after we hit "R" + 'Performing hot restart...'.padRight(progressMessageWidth), + startsWith('Restarted application in '), + 'ready', + '', // newline for after we hit "p" the first time + 'ready', + '', // newline for after we hit "p" the second time + 'ready', + '', // this newline is the one for after we hit "q" + 'Application finished.', + 'ready', + ]); + expect(result.exitCode, 0); + } finally { + tryToDelete(fileSystem.directory(tempDirectory)); + } + }); + + testWithoutContext('flutter error messages include a DevTools link', () async { + final String testDirectory = fileSystem.path.join(flutterRoot, 'dev', 'integration_tests', 'ui'); + final String tempDirectory = fileSystem.systemTempDirectory.createTempSync('flutter_overall_experience_test.').resolveSymbolicLinksSync(); + final String testScript = fileSystem.path.join('lib', 'overflow.dart'); + try { + final ProcessTestResult result = await runFlutter( + ['run', '-dflutter-tester', testScript], + testDirectory, + [ + Barrier(RegExp(r'^A Dart VM Service on Flutter test device is available at: ')), + Barrier(RegExp(r'^The Flutter DevTools debugger and profiler on Flutter test device is available at: '), handler: (String line) { + return 'r'; + }), + Barrier('Performing hot reload...'.padRight(progressMessageWidth), logging: true), + Barrier(RegExp(r'^Reloaded 0 libraries in [0-9]+ms.'), handler: (String line) { + return 'q'; + }), + ], + logging: false, + ); + expect(result.exitCode, 0); + expect(result.stdout, [ + startsWith('Performing hot reload...'), + '', + '══╡ EXCEPTION CAUGHT BY RENDERING LIBRARY ╞═════════════════════════════════════════════════════════', + 'The following assertion was thrown during layout:', + 'A RenderFlex overflowed by 69200 pixels on the right.', + '', + 'The relevant error-causing widget was:', + matches(RegExp(r'^ Row .+flutter/dev/integration_tests/ui/lib/overflow\.dart:32:18$')), + '', + 'To inspect this widget in Flutter DevTools, visit:', + startsWith('http'), + '', + 'The overflowing RenderFlex has an orientation of Axis.horizontal.', + 'The edge of the RenderFlex that is overflowing has been marked in the rendering with a yellow and', + 'black striped pattern. This is usually caused by the contents being too big for the RenderFlex.', + 'Consider applying a flex factor (e.g. using an Expanded widget) to force the children of the', + 'RenderFlex to fit within the available space instead of being sized to their natural size.', + 'This is considered an error condition because it indicates that there is content that cannot be', + 'seen. If the content is legitimately bigger than the available space, consider clipping it with a', + 'ClipRect widget before putting it in the flex, or using a scrollable container rather than a Flex,', + 'like a ListView.', + matches(RegExp(r'^The specific RenderFlex in question is: RenderFlex#..... OVERFLOWING:$')), + startsWith(' creator: Row ← Test ← '), + contains(' ← '), + endsWith(' ⋯'), + ' parentData: (can use size)', + ' constraints: BoxConstraints(w=800.0, h=600.0)', + ' size: Size(800.0, 600.0)', + ' direction: horizontal', + ' mainAxisAlignment: start', + ' mainAxisSize: max', + ' crossAxisAlignment: center', + ' textDirection: ltr', + ' verticalDirection: down', + '◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤', + '════════════════════════════════════════════════════════════════════════════════════════════════════', + '', + startsWith('Reloaded 0 libraries in '), + '', + 'Application finished.', + ]); + } finally { + tryToDelete(fileSystem.directory(tempDirectory)); + } + }); + + testWithoutContext('flutter run help output', () async { + // This test enables all logging so that it checks the exact text of starting up an application. + // The idea is to verify that we're not outputting spurious messages. + // WHEN EDITING THIS TEST PLEASE CAREFULLY CONSIDER WHETHER THE NEW OUTPUT IS AN IMPROVEMENT. + final String testDirectory = fileSystem.path.join(flutterRoot, 'examples', 'hello_world'); + final RegExp finalLine = RegExp(r'^The Flutter DevTools'); + final ProcessTestResult result = await runFlutter( + ['run', '-dflutter-tester'], + testDirectory, + [ + Barrier(finalLine, handler: (String line) { + return 'h'; + }), + Barrier(finalLine, handler: (String line) { + return 'q'; + }), + const Barrier('Application finished.'), + ], + ); + expect(result.exitCode, 0); + expect(result.stderr, isEmpty); + expect(result.stdout, containsAllInOrder([ + startsWith('Launching '), + startsWith('Syncing files to device Flutter test device...'), + '', + 'Flutter run key commands.', + startsWith('r Hot reload.'), + 'R Hot restart.', + 'h List all available interactive commands.', + 'd Detach (terminate "flutter run" but leave application running).', + 'c Clear the screen', + 'q Quit (terminate the application on the device).', + '', + startsWith('A Dart VM Service on Flutter test device is available at: http://'), + startsWith('The Flutter DevTools debugger and profiler on Flutter test device is available at: http://'), + '', + 'Flutter run key commands.', + startsWith('r Hot reload.'), + 'R Hot restart.', + 'v Open Flutter DevTools.', + 'w Dump widget hierarchy to the console. (debugDumpApp)', + 't Dump rendering tree to the console. (debugDumpRenderTree)', + 'L Dump layer tree to the console. (debugDumpLayerTree)', + 'f Dump focus tree to the console. (debugDumpFocusTree)', + 'S Dump accessibility tree in traversal order. (debugDumpSemantics)', + 'U Dump accessibility tree in inverse hit test order. (debugDumpSemantics)', + 'i Toggle widget inspector. (WidgetsApp.showWidgetInspectorOverride)', + 'p Toggle the display of construction lines. (debugPaintSizeEnabled)', + 'I Toggle oversized image inversion. (debugInvertOversizedImages)', + 'o Simulate different operating systems. (defaultTargetPlatform)', + 'b Toggle platform brightness (dark and light mode). (debugBrightnessOverride)', + 'P Toggle performance overlay. (WidgetsApp.showPerformanceOverlay)', + 'a Toggle timeline events for all widget build methods. (debugProfileWidgetBuilds)', + 'M Write SkSL shaders to a unique file in the project directory.', + 'g Run source code generators.', + 'j Dump frame raster stats for the current frame. (Unsupported for web)', + 'h Repeat this help message.', + 'd Detach (terminate "flutter run" but leave application running).', + 'c Clear the screen', + 'q Quit (terminate the application on the device).', + '', + startsWith('A Dart VM Service on Flutter test device is available at: http://'), + startsWith('The Flutter DevTools debugger and profiler on Flutter test device is available at: http://'), + '', + 'Application finished.', + ])); + }); +} diff --git a/flutter/packages/flutter_tools/test/integration.shard/plist_parser_test.dart b/flutter/packages/flutter_tools/test/integration.shard/plist_parser_test.dart new file mode 100644 index 0000000000000000000000000000000000000000..da1dd99108b02d7276381fd6bf53e96ef7ca4ac4 --- /dev/null +++ b/flutter/packages/flutter_tools/test/integration.shard/plist_parser_test.dart @@ -0,0 +1,216 @@ +// 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: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/base/terminal.dart'; +import 'package:flutter_tools/src/ios/plist_parser.dart'; + +import '../src/common.dart'; +import '../src/fakes.dart'; +import 'test_utils.dart'; + +const String base64PlistXml = + 'PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0iVVRGLTgiPz4KPCFET0NUWVBFIHBsaXN0I' + 'FBVQkxJQyAiLS8vQXBwbGUvL0RURCBQTElTVCAxLjAvL0VOIiAiaHR0cDovL3d3dy5hcHBsZS' + '5jb20vRFREcy9Qcm9wZXJ0eUxpc3QtMS4wLmR0ZCI+CjxwbGlzdCB2ZXJzaW9uPSIxLjAiPgo' + '8ZGljdD4KICA8a2V5PkNGQnVuZGxlRXhlY3V0YWJsZTwva2V5PgogIDxzdHJpbmc+QXBwPC9z' + 'dHJpbmc+CiAgPGtleT5DRkJ1bmRsZUlkZW50aWZpZXI8L2tleT4KICA8c3RyaW5nPmlvLmZsd' + 'XR0ZXIuZmx1dHRlci5hcHA8L3N0cmluZz4KPC9kaWN0Pgo8L3BsaXN0Pgo='; + +const String base64PlistBinary = + 'YnBsaXN0MDDSAQIDBF8QEkNGQnVuZGxlRXhlY3V0YWJsZV8QEkNGQnVuZGxlSWRlbnRpZmllc' + 'lNBcHBfEBZpby5mbHV0dGVyLmZsdXR0ZXIuYXBwCA0iNzsAAAAAAAABAQAAAAAAAAAFAAAAAA' + 'AAAAAAAAAAAAAAVA=='; + +const String base64PlistJson = + 'eyJDRkJ1bmRsZUV4ZWN1dGFibGUiOiJBcHAiLCJDRkJ1bmRsZUlkZW50aWZpZXIiOiJpby5mb' + 'HV0dGVyLmZsdXR0ZXIuYXBwIn0='; + +const String base64PlistXmlWithComplexDatatypes = + 'PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0iVVRGLTgiPz4KPCFET0NUWVBFIHBsaXN0I' + 'FBVQkxJQyAiLS8vQXBwbGUvL0RURCBQTElTVCAxLjAvL0VOIiAiaHR0cDovL3d3dy5hcHBsZS' + '5jb20vRFREcy9Qcm9wZXJ0eUxpc3QtMS4wLmR0ZCI+CjxwbGlzdCB2ZXJzaW9uPSIxLjAiPgo' + '8ZGljdD4KICA8a2V5PkNGQnVuZGxlRXhlY3V0YWJsZTwva2V5PgogIDxzdHJpbmc+QXBwPC9z' + 'dHJpbmc+CiAgPGtleT5DRkJ1bmRsZUlkZW50aWZpZXI8L2tleT4KICA8c3RyaW5nPmlvLmZsd' + 'XR0ZXIuZmx1dHRlci5hcHA8L3N0cmluZz4KICA8a2V5PmludFZhbHVlPC9rZXk+CiAgPGludG' + 'VnZXI+MjwvaW50ZWdlcj4KICA8a2V5PmRvdWJsZVZhbHVlPC9rZXk+CiAgPHJlYWw+MS41PC9' + 'yZWFsPgogIDxrZXk+YmluYXJ5VmFsdWU8L2tleT4KICA8ZGF0YT5ZV0pqWkE9PTwvZGF0YT4K' + 'ICA8a2V5PmFycmF5VmFsdWU8L2tleT4KICA8YXJyYXk+CiAgICA8dHJ1ZSAvPgogICAgPGZhb' + 'HNlIC8+CiAgICA8aW50ZWdlcj4zPC9pbnRlZ2VyPgogIDwvYXJyYXk+CiAgPGtleT5kYXRlVm' + 'FsdWU8L2tleT4KICA8ZGF0ZT4yMDIxLTEyLTAxVDEyOjM0OjU2WjwvZGF0ZT4KPC9kaWN0Pgo' + '8L3BsaXN0Pg=='; + +void main() { + // The tests herein explicitly don't use `MemoryFileSystem` or a mocked + // `ProcessManager` because doing so wouldn't actually test what we want to + // test, which is that the underlying tool we're using to parse Plist files + // works with the way we're calling it. + late File file; + late PlistParser parser; + late BufferLogger logger; + + setUp(() { + logger = BufferLogger( + outputPreferences: OutputPreferences.test(), + terminal: AnsiTerminal( + platform: const LocalPlatform(), + stdio: FakeStdio(), + ), + ); + parser = PlistParser( + fileSystem: fileSystem, + processManager: processManager, + logger: logger, + ); + file = fileSystem.file('foo.plist')..createSync(); + }); + + tearDown(() { + file.deleteSync(); + }); + + testWithoutContext('PlistParser.getValueFromFile works with an XML file', () { + file.writeAsBytesSync(base64.decode(base64PlistXml)); + + expect(parser.getValueFromFile(file.path, 'CFBundleIdentifier'), 'io.flutter.flutter.app'); + expect(parser.getValueFromFile(file.absolute.path, 'CFBundleIdentifier'), 'io.flutter.flutter.app'); + expect(logger.statusText, isEmpty); + expect(logger.errorText, isEmpty); + }, skip: !platform.isMacOS); // [intended] requires macos tool chain. + + testWithoutContext('PlistParser.getValueFromFile works with a binary file', () { + file.writeAsBytesSync(base64.decode(base64PlistBinary)); + + expect(parser.getValueFromFile(file.path, 'CFBundleIdentifier'), 'io.flutter.flutter.app'); + expect(parser.getValueFromFile(file.absolute.path, 'CFBundleIdentifier'), 'io.flutter.flutter.app'); + expect(logger.statusText, isEmpty); + expect(logger.errorText, isEmpty); + }, skip: !platform.isMacOS); // [intended] requires macos tool chain. + + testWithoutContext('PlistParser.getValueFromFile works with a JSON file', () { + file.writeAsBytesSync(base64.decode(base64PlistJson)); + + expect(parser.getValueFromFile(file.path, 'CFBundleIdentifier'), 'io.flutter.flutter.app'); + expect(parser.getValueFromFile(file.absolute.path, 'CFBundleIdentifier'), 'io.flutter.flutter.app'); + expect(logger.statusText, isEmpty); + expect(logger.errorText, isEmpty); + }, skip: !platform.isMacOS); // [intended] requires macos tool chain. + + testWithoutContext('PlistParser.getValueFromFile returns null for a non-existent plist file', () { + expect(parser.getValueFromFile('missing.plist', 'CFBundleIdentifier'), null); + expect(logger.statusText, isEmpty); + expect(logger.errorText, isEmpty); + }, skip: !platform.isMacOS); // [intended] requires macos tool chain. + + testWithoutContext('PlistParser.getValueFromFile returns null for a non-existent key within a plist', () { + file.writeAsBytesSync(base64.decode(base64PlistXml)); + + expect(parser.getValueFromFile(file.path, 'BadKey'), null); + expect(parser.getValueFromFile(file.absolute.path, 'BadKey'), null); + expect(logger.statusText, isEmpty); + expect(logger.errorText, isEmpty); + }, skip: !platform.isMacOS); // [intended] requires macos tool chain. + + testWithoutContext('PlistParser.getValueFromFile returns null for a malformed plist file', () { + file.writeAsBytesSync(const [1, 2, 3, 4, 5, 6]); + + expect(parser.getValueFromFile(file.path, 'CFBundleIdentifier'), null); + expect(logger.statusText, contains('Property List error: Unexpected character \x01 at line 1 / ' + 'JSON error: JSON text did not start with array or object and option to allow fragments not ' + 'set. around line 1, column 0.\n')); + expect(logger.errorText, 'ProcessException: The command failed with exit code 1\n' + ' Command: /usr/bin/plutil -convert xml1 -o - ${file.absolute.path}\n'); + }, skip: !platform.isMacOS); // [intended] requires macos tool chain. + + testWithoutContext('PlistParser.getValueFromFile throws when /usr/bin/plutil is not found', () async { + file.writeAsBytesSync(base64.decode(base64PlistXml)); + + expect( + () => parser.getValueFromFile(file.path, 'unused'), + throwsA(isA()), + ); + expect(logger.statusText, isEmpty); + expect(logger.errorText, isEmpty); + }, skip: platform.isMacOS); // [intended] requires absence of macos tool chain. + + testWithoutContext('PlistParser.replaceKey can replace a key', () async { + file.writeAsBytesSync(base64.decode(base64PlistXml)); + + expect(parser.getValueFromFile(file.path, 'CFBundleIdentifier'), 'io.flutter.flutter.app'); + expect(parser.replaceKey(file.path, key: 'CFBundleIdentifier', value: 'dev.flutter.fake'), isTrue); + expect(logger.statusText, isEmpty); + expect(logger.errorText, isEmpty); + expect(parser.getValueFromFile(file.path, 'CFBundleIdentifier'), equals('dev.flutter.fake')); + }, skip: !platform.isMacOS); // [intended] requires macos tool chain. + + testWithoutContext('PlistParser.replaceKey can create a new key', () async { + file.writeAsBytesSync(base64.decode(base64PlistXml)); + + expect(parser.getValueFromFile(file.path, 'CFNewKey'), isNull); + expect(parser.replaceKey(file.path, key: 'CFNewKey', value: 'dev.flutter.fake'), isTrue); + expect(logger.statusText, isEmpty); + expect(logger.errorText, isEmpty); + expect(parser.getValueFromFile(file.path, 'CFNewKey'), equals('dev.flutter.fake')); + }, skip: !platform.isMacOS); // [intended] requires macos tool chain. + + testWithoutContext('PlistParser.replaceKey can delete a key', () async { + file.writeAsBytesSync(base64.decode(base64PlistXml)); + + expect(parser.replaceKey(file.path, key: 'CFBundleIdentifier'), isTrue); + expect(logger.statusText, isEmpty); + expect(logger.errorText, isEmpty); + expect(parser.getValueFromFile(file.path, 'CFBundleIdentifier'), isNull); + }, skip: !platform.isMacOS); // [intended] requires macos tool chain. + + testWithoutContext('PlistParser.replaceKey throws when /usr/bin/plutil is not found', () async { + file.writeAsBytesSync(base64.decode(base64PlistXml)); + + expect( + () => parser.replaceKey(file.path, key: 'CFBundleIdentifier', value: 'dev.flutter.fake'), + throwsA(isA()), + ); + expect(logger.statusText, isEmpty); + expect(logger.errorText, isEmpty); + }, skip: platform.isMacOS); // [intended] requires absence of macos tool chain. + + testWithoutContext('PlistParser.replaceKey returns false for a malformed plist file', () { + file.writeAsBytesSync(const [1, 2, 3, 4, 5, 6]); + + expect(parser.replaceKey(file.path, key: 'CFBundleIdentifier', value: 'dev.flutter.fake'), isFalse); + expect(logger.statusText, contains('foo.plist: Property List error: Unexpected character \x01 ' + 'at line 1 / JSON error: JSON text did not start with array or object and option to allow ' + 'fragments not set. around line 1, column 0.\n')); + expect(logger.errorText, equals('ProcessException: The command failed with exit code 1\n' + ' Command: /usr/bin/plutil -replace CFBundleIdentifier -string dev.flutter.fake foo.plist\n')); + }, skip: !platform.isMacOS); // [intended] requires macos tool chain. + + testWithoutContext('PlistParser.replaceKey works with a JSON file', () { + file.writeAsBytesSync(base64.decode(base64PlistJson)); + + expect(parser.getValueFromFile(file.absolute.path, 'CFBundleIdentifier'), 'io.flutter.flutter.app'); + expect(parser.replaceKey(file.path, key:'CFBundleIdentifier', value: 'dev.flutter.fake'), isTrue); + expect(parser.getValueFromFile(file.absolute.path, 'CFBundleIdentifier'), 'dev.flutter.fake'); + expect(logger.statusText, isEmpty); + expect(logger.errorText, isEmpty); + }, skip: !platform.isMacOS); // [intended] requires macos tool chain. + + testWithoutContext('PlistParser.parseFile can handle different datatypes', () async { + file.writeAsBytesSync(base64.decode(base64PlistXmlWithComplexDatatypes)); + final Map values = parser.parseFile(file.path); + + expect(values['CFBundleIdentifier'], 'io.flutter.flutter.app'); + expect(values['CFBundleIdentifier'], 'io.flutter.flutter.app'); + expect(values['intValue'], 2); + expect(values['doubleValue'], 1.5); + expect(values['binaryValue'], base64.decode('YWJjZA==')); + expect(values['arrayValue'], [true, false, 3]); + expect(values['dateValue'], DateTime.utc(2021, 12, 1, 12, 34, 56)); + expect(logger.statusText, isEmpty); + expect(logger.errorText, isEmpty); + }, skip: !platform.isMacOS); // [intended] requires macos tool chain. +} diff --git a/flutter/packages/flutter_tools/test/integration.shard/shader_compiler_test.dart b/flutter/packages/flutter_tools/test/integration.shard/shader_compiler_test.dart new file mode 100644 index 0000000000000000000000000000000000000000..53a3bb350b521c77194f159c1cb01ee0b822ffdd --- /dev/null +++ b/flutter/packages/flutter_tools/test/integration.shard/shader_compiler_test.dart @@ -0,0 +1,158 @@ +// 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/file_system.dart'; +import 'package:flutter_tools/src/base/logger.dart'; +import 'package:flutter_tools/src/build_system/targets/shader_compiler.dart'; +import 'package:flutter_tools/src/globals.dart' as globals; + +import '../src/common.dart'; +import '../src/context.dart'; + +void main() { + late BufferLogger logger; + + setUp(() { + logger = BufferLogger.test(); + }); + + Future testCompileShader(String source) async { + final Directory tmpDir = globals.fs.systemTempDirectory.createTempSync( + 'shader_compiler_test.', + ); + final File file = tmpDir.childFile('test_shader.frag') + ..writeAsStringSync(source); + final ShaderCompiler shaderCompiler = ShaderCompiler( + processManager: globals.processManager, + logger: logger, + fileSystem: globals.fs, + artifacts: globals.artifacts!, + ); + await shaderCompiler.compileShader( + input: file, + outputPath: tmpDir.childFile('test_shader.frag.out').path, + target: ShaderTarget.sksl, + json: false, + ); + } + + testUsingContext('impellerc .iplr output has correct permissions', () async { + if (globals.platform.isWindows) { + return; + } + + final String flutterRoot = getFlutterRoot(); + final String inkSparklePath = globals.fs.path.join(flutterRoot, + 'packages', 'flutter', 'lib', 'src', 'material', 'shaders', + 'ink_sparkle.frag'); + final Directory tmpDir = globals.fs.systemTempDirectory.createTempSync( + 'shader_compiler_test.', + ); + final String inkSparkleOutputPath = globals.fs.path.join( + tmpDir.path, 'ink_sparkle.frag', + ); + + final ShaderCompiler shaderCompiler = ShaderCompiler( + processManager: globals.processManager, + logger: logger, + fileSystem: globals.fs, + artifacts: globals.artifacts!, + ); + final bool compileResult = await shaderCompiler.compileShader( + input: globals.fs.file(inkSparklePath), + outputPath: inkSparkleOutputPath, + target: ShaderTarget.sksl, + json: false, + ); + final File resultFile = globals.fs.file(inkSparkleOutputPath); + + + expect(compileResult, true); + expect(resultFile.existsSync(), true); + + final int expectedMode = int.parse('644', radix: 8); + expect(resultFile.statSync().mode & expectedMode, equals(expectedMode)); + }); + + testUsingContext('Compilation error with in storage', () async { + const String kShaderWithInput = ''' +in float foo; + +out vec4 fragColor; + +void main() { + fragColor = vec4(1.0, 0.0, 0.0, 1.0); +} +'''; + + expect(() => testCompileShader(kShaderWithInput), throwsA(isA() + .having( + (ShaderCompilerException exception) => exception.message, + 'message', + contains('SkSL does not support inputs'), + ), + )); + }); + + testUsingContext('Compilation error with UBO', () async { + const String kShaderWithInput = ''' +uniform Data { + vec4 foo; +} data; + +out vec4 fragColor; + +void main() { + fragColor = data.foo; +} +'''; + + expect(() => testCompileShader(kShaderWithInput), throwsA(isA() + .having( + (ShaderCompilerException exception) => exception.message, + 'message', + contains('SkSL does not support UBOs or SSBOs'), + ), + )); + }); + + testUsingContext('Compilation error with texture arguments besides position or sampler', () async { + const String kShaderWithInput = ''' +uniform sampler2D tex; + +out vec4 fragColor; + +void main() { + fragColor = texture(tex, vec2(0.5, 0.3), 0.5); +} +'''; + + expect(() => testCompileShader(kShaderWithInput), throwsA(isA() + .having( + (ShaderCompilerException exception) => exception.message, + 'message', + contains('Only sampler and position arguments are supported in texture() calls'), + ), + )); + }); + + testUsingContext('Compilation error with uint8 uniforms', () async { + const String kShaderWithInput = ''' +#version 310 es + +layout(location = 0) uniform uint foo; +layout(location = 0) out vec4 fragColor; + +void main() {} +'''; + + expect(() => testCompileShader(kShaderWithInput), throwsA(isA() + .having( + (ShaderCompilerException exception) => exception.message, + 'message', + contains('SkSL does not support unsigned integers'), + ), + )); + }); +} diff --git a/flutter/packages/flutter_tools/test/integration.shard/stateless_stateful_hot_reload_test.dart b/flutter/packages/flutter_tools/test/integration.shard/stateless_stateful_hot_reload_test.dart new file mode 100644 index 0000000000000000000000000000000000000000..21f911d1925fa089f947ccaa5773a0e0a77d376e --- /dev/null +++ b/flutter/packages/flutter_tools/test/integration.shard/stateless_stateful_hot_reload_test.dart @@ -0,0 +1,47 @@ +// 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/file.dart'; + +import '../src/common.dart'; +import 'test_data/stateless_stateful_project.dart'; +import 'test_driver.dart'; +import 'test_utils.dart'; + +// This test verifies that we can hot reload a stateless widget into a +// stateful one and back. +void main() { + late Directory tempDir; + final HotReloadProject project = HotReloadProject(); + late FlutterRunTestDriver flutter; + + setUp(() async { + tempDir = createResolvedTempDirectorySync('hot_reload_test.'); + await project.setUpIn(tempDir); + flutter = FlutterRunTestDriver(tempDir); + }); + + tearDown(() async { + await flutter.stop(); + tryToDelete(tempDir); + }); + + testWithoutContext('Can switch from stateless to stateful', () async { + await flutter.run(); + await flutter.hotReload(); + final StringBuffer stdout = StringBuffer(); + final StreamSubscription subscription = flutter.stdout.listen(stdout.writeln); + + // switch to stateful. + project.toggleState(); + await flutter.hotReload(); + + final String logs = stdout.toString(); + + expect(logs, contains('STATEFUL')); + await subscription.cancel(); + }); +} diff --git a/flutter/packages/flutter_tools/test/integration.shard/swift_package_manager_create_app_test.dart b/flutter/packages/flutter_tools/test/integration.shard/swift_package_manager_create_app_test.dart new file mode 100644 index 0000000000000000000000000000000000000000..f40e0f6de236fd1b3b45715f9d56e91419b804fc --- /dev/null +++ b/flutter/packages/flutter_tools/test/integration.shard/swift_package_manager_create_app_test.dart @@ -0,0 +1,151 @@ +// 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/error_handling_io.dart'; +import 'package:flutter_tools/src/base/file_system.dart'; + +import '../src/common.dart'; +import 'swift_package_manager_utils.dart'; +import 'test_utils.dart'; + +void main() { + final String flutterBin = fileSystem.path.join( + getFlutterRoot(), + 'bin', + 'flutter', + ); + + final List platforms = ['ios', 'macos']; + for (final String platformName in platforms) { + final List iosLanguages = [ + if (platformName == 'ios') 'objc', + 'swift', + ]; + + for (final String iosLanguage in iosLanguages) { + test('Create $platformName $iosLanguage app with Swift Package Manager disabled', () async { + final Directory workingDirectory = fileSystem.systemTempDirectory + .createTempSync('swift_package_manager_create_app_disabled.'); + final String workingDirectoryPath = workingDirectory.path; + try { + await SwiftPackageManagerUtils.disableSwiftPackageManager(flutterBin, workingDirectoryPath); + + final String appDirectoryPath = await SwiftPackageManagerUtils.createApp( + flutterBin, + workingDirectoryPath, + iosLanguage: iosLanguage, + platform: platformName, + options: ['--platforms=$platformName'], + ); + + final File pbxprojFile = fileSystem + .directory(appDirectoryPath) + .childDirectory(platformName) + .childDirectory('Runner.xcodeproj') + .childFile('project.pbxproj'); + expect(pbxprojFile.existsSync(), isTrue); + expect( + pbxprojFile.readAsStringSync().contains('FlutterGeneratedPluginSwiftPackage'), + isFalse, + ); + + final File xcschemeFile = fileSystem + .directory(appDirectoryPath) + .childDirectory(platformName) + .childDirectory('Runner.xcodeproj') + .childDirectory('xcshareddata') + .childDirectory('xcschemes') + .childFile('Runner.xcscheme'); + expect(xcschemeFile.existsSync(), isTrue); + expect( + xcschemeFile.readAsStringSync().contains('Run Prepare Flutter Framework Script'), + isFalse, + ); + + await SwiftPackageManagerUtils.buildApp( + flutterBin, + appDirectoryPath, + options: [platformName, '--debug', '-v'], + expectedLines: SwiftPackageManagerUtils.expectedLines( + platform: platformName, + appDirectoryPath: appDirectoryPath, + ), + unexpectedLines: SwiftPackageManagerUtils.unexpectedLines( + platform: platformName, + appDirectoryPath: appDirectoryPath, + ), + ); + } finally { + await SwiftPackageManagerUtils.disableSwiftPackageManager(flutterBin, workingDirectoryPath); + ErrorHandlingFileSystem.deleteIfExists( + workingDirectory, + recursive: true, + ); + } + }, skip: !platform.isMacOS); // [intended] Swift Package Manager only works on macos. + + test('Create $platformName $iosLanguage app with Swift Package Manager enabled', () async { + final Directory workingDirectory = fileSystem.systemTempDirectory + .createTempSync('swift_package_manager_create_app_enabled.'); + final String workingDirectoryPath = workingDirectory.path; + try { + await SwiftPackageManagerUtils.enableSwiftPackageManager(flutterBin, workingDirectoryPath); + + final String appDirectoryPath = await SwiftPackageManagerUtils.createApp( + flutterBin, + workingDirectoryPath, + iosLanguage: iosLanguage, + platform: platformName, + options: ['--platforms=$platformName'], + ); + + final File pbxprojFile = fileSystem + .directory(appDirectoryPath) + .childDirectory(platformName) + .childDirectory('Runner.xcodeproj') + .childFile('project.pbxproj'); + expect(pbxprojFile.existsSync(), isTrue); + expect( + pbxprojFile.readAsStringSync(), + contains('FlutterGeneratedPluginSwiftPackage'), + ); + + final File xcschemeFile = fileSystem + .directory(appDirectoryPath) + .childDirectory(platformName) + .childDirectory('Runner.xcodeproj') + .childDirectory('xcshareddata') + .childDirectory('xcschemes') + .childFile('Runner.xcscheme'); + expect(xcschemeFile.existsSync(), isTrue); + expect( + xcschemeFile.readAsStringSync(), + contains('Run Prepare Flutter Framework Script'), + ); + + await SwiftPackageManagerUtils.buildApp( + flutterBin, + appDirectoryPath, + options: [platformName, '--debug', '-v'], + expectedLines: SwiftPackageManagerUtils.expectedLines( + platform: platformName, + appDirectoryPath: appDirectoryPath, + ), + unexpectedLines: SwiftPackageManagerUtils.unexpectedLines( + platform: platformName, + appDirectoryPath: appDirectoryPath, + ), + ); + + } finally { + await SwiftPackageManagerUtils.disableSwiftPackageManager(flutterBin, workingDirectoryPath); + ErrorHandlingFileSystem.deleteIfExists( + workingDirectory, + recursive: true, + ); + } + }, skip: !platform.isMacOS); // [intended] Swift Package Manager only works on macos. + } + } +} diff --git a/flutter/packages/flutter_tools/test/integration.shard/swift_package_manager_create_plugin_test.dart b/flutter/packages/flutter_tools/test/integration.shard/swift_package_manager_create_plugin_test.dart new file mode 100644 index 0000000000000000000000000000000000000000..64b9761f97e50764333b0d4d0d68deee0e0d0a9a --- /dev/null +++ b/flutter/packages/flutter_tools/test/integration.shard/swift_package_manager_create_plugin_test.dart @@ -0,0 +1,175 @@ +// 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/error_handling_io.dart'; +import 'package:flutter_tools/src/base/file_system.dart'; + +import '../src/common.dart'; +import 'swift_package_manager_utils.dart'; +import 'test_utils.dart'; + +void main() { + final String flutterBin = fileSystem.path.join( + getFlutterRoot(), + 'bin', + 'flutter', + ); + + final List platforms = ['ios', 'macos']; + for (final String platformName in platforms) { + final List iosLanguages = [ + if (platformName == 'ios') 'objc', + 'swift', + ]; + + for (final String iosLanguage in iosLanguages) { + test('Create $platformName $iosLanguage plugin with Swift Package Manager disabled', () async { + final Directory workingDirectory = fileSystem.systemTempDirectory + .createTempSync('swift_package_manager_create_plugin_disabled.'); + final String workingDirectoryPath = workingDirectory.path; + try { + await SwiftPackageManagerUtils.disableSwiftPackageManager(flutterBin, workingDirectoryPath); + + final SwiftPackageManagerPlugin createdCocoaPodsPlugin = await SwiftPackageManagerUtils.createPlugin( + flutterBin, + workingDirectoryPath, + platform: platformName, + iosLanguage: iosLanguage, + ); + + final String appDirectoryPath = createdCocoaPodsPlugin.exampleAppPath; + + final File pbxprojFile = fileSystem + .directory(appDirectoryPath) + .childDirectory(platformName) + .childDirectory('Runner.xcodeproj') + .childFile('project.pbxproj'); + expect(pbxprojFile.existsSync(), isTrue); + expect( + pbxprojFile.readAsStringSync().contains('FlutterGeneratedPluginSwiftPackage'), + isFalse, + ); + + final File xcschemeFile = fileSystem + .directory(appDirectoryPath) + .childDirectory(platformName) + .childDirectory('Runner.xcodeproj') + .childDirectory('xcshareddata') + .childDirectory('xcschemes') + .childFile('Runner.xcscheme'); + expect(xcschemeFile.existsSync(), isTrue); + expect( + xcschemeFile.readAsStringSync().contains('Run Prepare Flutter Framework Script'), + isFalse, + ); + + final File podspec = fileSystem + .directory(createdCocoaPodsPlugin.pluginPath) + .childDirectory(platformName) + .childFile('${createdCocoaPodsPlugin.pluginName}.podspec'); + expect(podspec.existsSync(), isTrue); + expect(podspec.readAsStringSync(), contains('Classes')); + expect(podspec.readAsStringSync().contains('Sources'), isFalse); + + await SwiftPackageManagerUtils.buildApp( + flutterBin, + appDirectoryPath, + options: [platformName, '--debug', '-v'], + expectedLines: SwiftPackageManagerUtils.expectedLines( + platform: platformName, + appDirectoryPath: appDirectoryPath, + cocoaPodsPlugin: createdCocoaPodsPlugin, + ), + unexpectedLines: SwiftPackageManagerUtils.unexpectedLines( + platform: platformName, + appDirectoryPath: appDirectoryPath, + cocoaPodsPlugin: createdCocoaPodsPlugin, + ), + ); + } finally { + await SwiftPackageManagerUtils.disableSwiftPackageManager(flutterBin, workingDirectoryPath); + ErrorHandlingFileSystem.deleteIfExists( + workingDirectory, + recursive: true, + ); + } + }, skip: !platform.isMacOS); // [intended] Swift Package Manager only works on macos. + + test('Create $platformName $iosLanguage plugin with Swift Package Manager enabled', () async { + final Directory workingDirectory = fileSystem.systemTempDirectory + .createTempSync('swift_package_manager_create_plugin_enabled.'); + final String workingDirectoryPath = workingDirectory.path; + try { + await SwiftPackageManagerUtils.enableSwiftPackageManager(flutterBin, workingDirectoryPath); + + final SwiftPackageManagerPlugin createdSwiftPackagePlugin = await SwiftPackageManagerUtils.createPlugin( + flutterBin, + workingDirectoryPath, + platform: platformName, + iosLanguage: iosLanguage, + ); + + final String appDirectoryPath = createdSwiftPackagePlugin.exampleAppPath; + + final File pbxprojFile = fileSystem + .directory(appDirectoryPath) + .childDirectory(platformName) + .childDirectory('Runner.xcodeproj') + .childFile('project.pbxproj'); + expect(pbxprojFile.existsSync(), isTrue); + expect( + pbxprojFile.readAsStringSync(), + contains('FlutterGeneratedPluginSwiftPackage'), + ); + + final File xcschemeFile = fileSystem + .directory(appDirectoryPath) + .childDirectory(platformName) + .childDirectory('Runner.xcodeproj') + .childDirectory('xcshareddata') + .childDirectory('xcschemes') + .childFile('Runner.xcscheme'); + expect(xcschemeFile.existsSync(), isTrue); + expect( + xcschemeFile.readAsStringSync(), + contains('Run Prepare Flutter Framework Script'), + ); + + final File podspec = fileSystem + .directory(createdSwiftPackagePlugin.pluginPath) + .childDirectory(platformName) + .childFile('${createdSwiftPackagePlugin.pluginName}.podspec'); + expect(podspec.existsSync(), isTrue); + expect(podspec.readAsStringSync(), contains('Sources')); + expect(podspec.readAsStringSync().contains('Classes'), isFalse); + + await SwiftPackageManagerUtils.buildApp( + flutterBin, + appDirectoryPath, + options: [platformName, '--debug', '-v'], + expectedLines: SwiftPackageManagerUtils.expectedLines( + platform: platformName, + appDirectoryPath: appDirectoryPath, + swiftPackagePlugin: createdSwiftPackagePlugin, + swiftPackageMangerEnabled: true, + ), + unexpectedLines: SwiftPackageManagerUtils.unexpectedLines( + platform: platformName, + appDirectoryPath: appDirectoryPath, + swiftPackagePlugin: createdSwiftPackagePlugin, + swiftPackageMangerEnabled: true, + ), + ); + + } finally { + await SwiftPackageManagerUtils.disableSwiftPackageManager(flutterBin, workingDirectoryPath); + ErrorHandlingFileSystem.deleteIfExists( + workingDirectory, + recursive: true, + ); + } + }, skip: !platform.isMacOS); // [intended] Swift Package Manager only works on macos. + } + } +} diff --git a/flutter/packages/flutter_tools/test/integration.shard/swift_package_manager_test.dart b/flutter/packages/flutter_tools/test/integration.shard/swift_package_manager_test.dart new file mode 100644 index 0000000000000000000000000000000000000000..3dbc4897334db9be59531239bc04df636394d056 --- /dev/null +++ b/flutter/packages/flutter_tools/test/integration.shard/swift_package_manager_test.dart @@ -0,0 +1,478 @@ +// 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/error_handling_io.dart'; +import 'package:flutter_tools/src/base/file_system.dart'; + +import '../src/common.dart'; +import 'swift_package_manager_utils.dart'; +import 'test_utils.dart'; + +void main() { + final String flutterBin = fileSystem.path.join( + getFlutterRoot(), + 'bin', + 'flutter', + ); + + final List platforms = ['ios', 'macos']; + for (final String platformName in platforms) { + final List iosLanguages = [ + if (platformName == 'ios') 'objc', + 'swift', + ]; + final SwiftPackageManagerPlugin integrationTestPlugin = SwiftPackageManagerUtils.integrationTestPlugin(platformName); + + for (final String iosLanguage in iosLanguages) { + test('Swift Package Manager integration for $platformName with $iosLanguage', () async { + final Directory workingDirectory = fileSystem.systemTempDirectory + .createTempSync('swift_package_manager_enabled.'); + final String workingDirectoryPath = workingDirectory.path; + try { + // Create and build an app using the CocoaPods version of + // integration_test. + await SwiftPackageManagerUtils.disableSwiftPackageManager(flutterBin, workingDirectoryPath); + final String appDirectoryPath = await SwiftPackageManagerUtils.createApp( + flutterBin, + workingDirectoryPath, + iosLanguage: iosLanguage, + platform: platformName, + usesSwiftPackageManager: true, + options: ['--platforms=$platformName'], + ); + SwiftPackageManagerUtils.addDependency(appDirectoryPath: appDirectoryPath, plugin: integrationTestPlugin); + await SwiftPackageManagerUtils.buildApp( + flutterBin, + appDirectoryPath, + options: [platformName, '--debug', '-v'], + expectedLines: SwiftPackageManagerUtils.expectedLines( + platform: platformName, + appDirectoryPath: appDirectoryPath, + cocoaPodsPlugin: integrationTestPlugin, + ), + unexpectedLines: SwiftPackageManagerUtils.unexpectedLines( + platform: platformName, + appDirectoryPath: appDirectoryPath, + cocoaPodsPlugin: integrationTestPlugin, + ), + ); + expect( + fileSystem + .directory(appDirectoryPath) + .childDirectory(platformName) + .childFile('Podfile') + .existsSync(), + isTrue, + ); + expect( + fileSystem + .directory(appDirectoryPath) + .childDirectory(platformName) + .childDirectory('Flutter') + .childDirectory('ephemeral') + .childDirectory('Packages') + .childDirectory('FlutterGeneratedPluginSwiftPackage') + .existsSync(), + isFalse, + ); + + final SwiftPackageManagerPlugin createdCocoaPodsPlugin = await SwiftPackageManagerUtils.createPlugin( + flutterBin, + workingDirectoryPath, + platform: platformName, + iosLanguage: iosLanguage, + ); + + // Rebuild app with Swift Package Manager enabled, migrating the app and using the Swift Package Manager version of + // integration_test. + await SwiftPackageManagerUtils.enableSwiftPackageManager(flutterBin, workingDirectoryPath); + await SwiftPackageManagerUtils.buildApp( + flutterBin, + appDirectoryPath, + options: [platformName, '--debug', '-v'], + expectedLines: SwiftPackageManagerUtils.expectedLines( + platform: platformName, + appDirectoryPath: appDirectoryPath, + swiftPackageMangerEnabled: true, + swiftPackagePlugin: integrationTestPlugin, + migrated: true, + ), + unexpectedLines: SwiftPackageManagerUtils.unexpectedLines( + platform: platformName, + appDirectoryPath: appDirectoryPath, + swiftPackageMangerEnabled: true, + swiftPackagePlugin: integrationTestPlugin, + migrated: true, + ), + ); + + expect( + fileSystem + .directory(appDirectoryPath) + .childDirectory(platformName) + .childFile('Podfile') + .existsSync(), + isTrue, + ); + expect( + fileSystem + .directory(appDirectoryPath) + .childDirectory(platformName) + .childDirectory('Flutter') + .childDirectory('ephemeral') + .childDirectory('Packages') + .childDirectory('FlutterGeneratedPluginSwiftPackage') + .existsSync(), + isTrue, + ); + + // Build an app using both a CocoaPods and Swift Package Manager plugin. + SwiftPackageManagerUtils.addDependency( + appDirectoryPath: appDirectoryPath, + plugin: createdCocoaPodsPlugin, + ); + await SwiftPackageManagerUtils.buildApp( + flutterBin, + appDirectoryPath, + options: [platformName, '--debug', '-v'], + expectedLines: SwiftPackageManagerUtils.expectedLines( + platform: platformName, + appDirectoryPath: appDirectoryPath, + cocoaPodsPlugin: createdCocoaPodsPlugin, + swiftPackageMangerEnabled: true, + swiftPackagePlugin: integrationTestPlugin, + ), + unexpectedLines: SwiftPackageManagerUtils.unexpectedLines( + platform: platformName, + appDirectoryPath: appDirectoryPath, + cocoaPodsPlugin: createdCocoaPodsPlugin, + swiftPackageMangerEnabled: true, + swiftPackagePlugin: integrationTestPlugin, + ), + ); + + expect( + fileSystem + .directory(appDirectoryPath) + .childDirectory(platformName) + .childFile('Podfile') + .existsSync(), + isTrue, + ); + expect( + fileSystem + .directory(appDirectoryPath) + .childDirectory(platformName) + .childDirectory('Flutter') + .childDirectory('ephemeral') + .childDirectory('Packages') + .childDirectory('FlutterGeneratedPluginSwiftPackage') + .existsSync(), + isTrue, + ); + + // Build app again but with Swift Package Manager disabled by config. + // App will now use CocoaPods version of integration_test plugin. + await SwiftPackageManagerUtils.disableSwiftPackageManager(flutterBin, workingDirectoryPath); + await SwiftPackageManagerUtils.cleanApp(flutterBin, appDirectoryPath); + await SwiftPackageManagerUtils.buildApp( + flutterBin, + appDirectoryPath, + options: [platformName, '--debug', '-v'], + expectedLines: SwiftPackageManagerUtils.expectedLines( + platform: platformName, + appDirectoryPath: appDirectoryPath, + cocoaPodsPlugin: integrationTestPlugin, + ), + unexpectedLines: SwiftPackageManagerUtils.unexpectedLines( + platform: platformName, + appDirectoryPath: appDirectoryPath, + cocoaPodsPlugin: integrationTestPlugin, + ), + ); + + // Build app again but with Swift Package Manager disabled by pubspec. + // App will still use CocoaPods version of integration_test plugin. + await SwiftPackageManagerUtils.enableSwiftPackageManager(flutterBin, workingDirectoryPath); + await SwiftPackageManagerUtils.cleanApp(flutterBin, appDirectoryPath); + SwiftPackageManagerUtils.disableSwiftPackageManagerByPubspec(appDirectoryPath: appDirectoryPath); + await SwiftPackageManagerUtils.buildApp( + flutterBin, + appDirectoryPath, + options: [platformName, '--debug', '-v'], + expectedLines: SwiftPackageManagerUtils.expectedLines( + platform: platformName, + appDirectoryPath: appDirectoryPath, + cocoaPodsPlugin: integrationTestPlugin, + ), + unexpectedLines: SwiftPackageManagerUtils.unexpectedLines( + platform: platformName, + appDirectoryPath: appDirectoryPath, + cocoaPodsPlugin: integrationTestPlugin, + ), + ); + } finally { + await SwiftPackageManagerUtils.disableSwiftPackageManager(flutterBin, workingDirectoryPath); + ErrorHandlingFileSystem.deleteIfExists( + workingDirectory, + recursive: true, + ); + } + }, skip: !platform.isMacOS); // [intended] Swift Package Manager only works on macos. + } + + test('Build $platformName-framework with non-module app uses CocoaPods', () async { + final Directory workingDirectory = fileSystem.systemTempDirectory + .createTempSync('swift_package_manager_build_framework.'); + final String workingDirectoryPath = workingDirectory.path; + try { + // Create and build an app using the Swift Package Manager version of + // integration_test. + await SwiftPackageManagerUtils.enableSwiftPackageManager(flutterBin, workingDirectoryPath); + + final String appDirectoryPath = await SwiftPackageManagerUtils.createApp( + flutterBin, + workingDirectoryPath, + iosLanguage: 'swift', + platform: platformName, + usesSwiftPackageManager: true, + options: ['--platforms=$platformName'], + ); + SwiftPackageManagerUtils.addDependency(appDirectoryPath: appDirectoryPath, plugin: integrationTestPlugin); + + await SwiftPackageManagerUtils.buildApp( + flutterBin, + appDirectoryPath, + options: [platformName, '--config-only', '-v'], + ); + + expect( + fileSystem + .directory(appDirectoryPath) + .childDirectory(platformName) + .childFile('Podfile') + .existsSync(), + isFalse, + ); + expect( + fileSystem + .directory(appDirectoryPath) + .childDirectory(platformName) + .childDirectory('Flutter') + .childDirectory('ephemeral') + .childDirectory('Packages') + .childDirectory('FlutterGeneratedPluginSwiftPackage') + .existsSync(), + isTrue, + ); + + // Create and build framework using the CocoaPods version of + // integration_test even though Swift Package Manager is enabled. + await SwiftPackageManagerUtils.buildApp( + flutterBin, + appDirectoryPath, + options: [ + '$platformName-framework', + '--no-debug', + '--no-profile', + '-v', + ], + expectedLines: [ + 'Swift Package Manager does not yet support this command. CocoaPods will be used instead.' + ] + ); + + expect( + fileSystem + .directory(appDirectoryPath) + .childDirectory('build') + .childDirectory(platformName) + .childDirectory('framework') + .childDirectory('Release') + .childDirectory('${integrationTestPlugin.pluginName}.xcframework') + .existsSync(), + isTrue, + ); + } finally { + await SwiftPackageManagerUtils.disableSwiftPackageManager(flutterBin, workingDirectoryPath); + ErrorHandlingFileSystem.deleteIfExists( + workingDirectory, + recursive: true, + ); + } + }, skip: !platform.isMacOS); // [intended] Swift Package Manager only works on macos. + + test('Caches build targets between builds with Swift Package Manager on $platformName', () async { + final Directory workingDirectory = fileSystem.systemTempDirectory + .createTempSync('swift_package_manager_caching.'); + final String workingDirectoryPath = workingDirectory.path; + try { + // Create and build an app using the Swift Package Manager version of + // integration_test. + await SwiftPackageManagerUtils.enableSwiftPackageManager(flutterBin, workingDirectoryPath); + + final String appDirectoryPath = await SwiftPackageManagerUtils.createApp( + flutterBin, + workingDirectoryPath, + iosLanguage: 'swift', + platform: platformName, + usesSwiftPackageManager: true, + options: ['--platforms=$platformName'], + ); + SwiftPackageManagerUtils.addDependency(appDirectoryPath: appDirectoryPath, plugin: integrationTestPlugin); + + final String unpackTarget = 'debug_unpack_$platformName'; + final String bundleFlutterAssetsTarget = 'debug_${platformName}_bundle_flutter_assets'; + final bool noCodesign = platformName == 'ios'; + await SwiftPackageManagerUtils.buildApp( + flutterBin, + appDirectoryPath, + options: [ + platformName, + '--debug', + '-v', + if (noCodesign) + '--no-codesign', + ], + expectedLines: [ + r'SchemeAction Run\ Prepare\ Flutter\ Framework\ Script', + '$unpackTarget: Starting due to', + '-dPreBuildAction=PrepareFramework $unpackTarget', + ], + unexpectedLines: [], + ); + + await SwiftPackageManagerUtils.buildApp( + flutterBin, + appDirectoryPath, + options: [ + platformName, + '--debug', + '-v', + if (noCodesign) + '--no-codesign', + ], + expectedLines: [ + r'SchemeAction Run\ Prepare\ Flutter\ Framework\ Script', + 'Skipping target: $unpackTarget', + 'Skipping target: $bundleFlutterAssetsTarget', + ], + unexpectedLines: [ + 'Starting due to', + ], + ); + + } finally { + await SwiftPackageManagerUtils.disableSwiftPackageManager(flutterBin, workingDirectoryPath); + ErrorHandlingFileSystem.deleteIfExists( + workingDirectory, + recursive: true, + ); + } + }, skip: !platform.isMacOS); // [intended] Swift Package Manager only works on macos. + } + + test('Build ios-framework with module app uses CocoaPods', () async { + final Directory workingDirectory = fileSystem.systemTempDirectory + .createTempSync('swift_package_manager_build_framework_module.'); + final String workingDirectoryPath = workingDirectory.path; + try { + // Create and build module and framework using the CocoaPods version of + // integration_test even though Swift Package Manager is enabled. + await SwiftPackageManagerUtils.enableSwiftPackageManager(flutterBin, workingDirectoryPath); + + final String appDirectoryPath = await SwiftPackageManagerUtils.createApp( + flutterBin, + workingDirectoryPath, + iosLanguage: 'swift', + platform: 'ios', + usesSwiftPackageManager: true, + options: ['--template=module'], + ); + final SwiftPackageManagerPlugin integrationTestPlugin = SwiftPackageManagerUtils.integrationTestPlugin('ios'); + SwiftPackageManagerUtils.addDependency(appDirectoryPath: appDirectoryPath, plugin: integrationTestPlugin); + + await SwiftPackageManagerUtils.buildApp( + flutterBin, + appDirectoryPath, + options: ['ios', '--config-only', '-v'], + ); + + expect( + fileSystem + .directory(appDirectoryPath) + .childDirectory('.ios') + .childFile('Podfile') + .existsSync(), + isTrue, + ); + expect( + fileSystem + .directory(appDirectoryPath) + .childDirectory('.ios') + .childDirectory('Flutter') + .childDirectory('ephemeral') + .childDirectory('Packages') + .childDirectory('FlutterGeneratedPluginSwiftPackage') + .existsSync(), + isFalse, + ); + final File pbxprojFile = fileSystem + .directory(appDirectoryPath) + .childDirectory('.ios') + .childDirectory('Runner.xcodeproj') + .childFile('project.pbxproj'); + expect(pbxprojFile.existsSync(), isTrue); + expect( + pbxprojFile.readAsStringSync().contains('FlutterGeneratedPluginSwiftPackage'), + isFalse, + ); + final File xcschemeFile = fileSystem + .directory(appDirectoryPath) + .childDirectory('.ios') + .childDirectory('Runner.xcodeproj') + .childDirectory('xcshareddata') + .childDirectory('xcschemes') + .childFile('Runner.xcscheme'); + expect(xcschemeFile.existsSync(), isTrue); + expect( + xcschemeFile.readAsStringSync().contains('Run Prepare Flutter Framework Script'), + isFalse, + ); + + await SwiftPackageManagerUtils.buildApp( + flutterBin, + appDirectoryPath, + options: [ + 'ios-framework', + '--no-debug', + '--no-profile', + '-v', + ], + unexpectedLines: [ + 'Adding Swift Package Manager integration...', + 'Swift Package Manager does not yet support this command. CocoaPods will be used instead.' + ] + ); + + expect( + fileSystem + .directory(appDirectoryPath) + .childDirectory('build') + .childDirectory('ios') + .childDirectory('framework') + .childDirectory('Release') + .childDirectory('${integrationTestPlugin.pluginName}.xcframework') + .existsSync(), + isTrue, + ); + } finally { + await SwiftPackageManagerUtils.disableSwiftPackageManager(flutterBin, workingDirectoryPath); + ErrorHandlingFileSystem.deleteIfExists( + workingDirectory, + recursive: true, + ); + } + }, skip: !platform.isMacOS); // [intended] Swift Package Manager only works on macos. +} diff --git a/flutter/packages/flutter_tools/test/integration.shard/swift_package_manager_utils.dart b/flutter/packages/flutter_tools/test/integration.shard/swift_package_manager_utils.dart new file mode 100644 index 0000000000000000000000000000000000000000..1dc52e35465f772e3e87ed4b4de975678797b419 --- /dev/null +++ b/flutter/packages/flutter_tools/test/integration.shard/swift_package_manager_utils.dart @@ -0,0 +1,381 @@ +// 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:flutter_tools/src/base/file_system.dart'; +import 'package:flutter_tools/src/base/io.dart'; + +import '../src/common.dart'; +import 'test_utils.dart'; + +class SwiftPackageManagerUtils { + static Future enableSwiftPackageManager( + String flutterBin, + String workingDirectory, + ) async { + final ProcessResult result = await processManager.run( + [ + flutterBin, + ...getLocalEngineArguments(), + 'config', + '--enable-swift-package-manager', + '-v', + ], + workingDirectory: workingDirectory, + ); + expect( + result.exitCode, + 0, + reason: 'Failed to enable Swift Package Manager: \n' + 'stdout: \n${result.stdout}\n' + 'stderr: \n${result.stderr}\n', + verbose: true, + ); + } + + static Future disableSwiftPackageManager( + String flutterBin, + String workingDirectory, + ) async { + final ProcessResult result = await processManager.run( + [ + flutterBin, + ...getLocalEngineArguments(), + 'config', + '--no-enable-swift-package-manager', + '-v', + ], + workingDirectory: workingDirectory, + ); + expect( + result.exitCode, + 0, + reason: 'Failed to disable Swift Package Manager: \n' + 'stdout: \n${result.stdout}\n' + 'stderr: \n${result.stderr}\n', + verbose: true, + ); + } + + static Future createApp( + String flutterBin, + String workingDirectory, { + required String platform, + required String iosLanguage, + required List options, + bool usesSwiftPackageManager = false, + }) async { + final String appTemplateType = usesSwiftPackageManager ? 'spm' : 'default'; + + final String appName = '${platform}_${iosLanguage}_${appTemplateType}_app'; + final ProcessResult result = await processManager.run( + [ + flutterBin, + ...getLocalEngineArguments(), + 'create', + '--org', + 'io.flutter.devicelab', + '-i', + iosLanguage, + ...options, + appName, + ], + workingDirectory: workingDirectory, + ); + + expect( + result.exitCode, + 0, + reason: 'Failed to create app: \n' + 'stdout: \n${result.stdout}\n' + 'stderr: \n${result.stderr}\n', + ); + + return fileSystem.path.join( + workingDirectory, + appName, + ); + } + + static Future buildApp( + String flutterBin, + String workingDirectory, { + required List options, + List? expectedLines, + List? unexpectedLines, + }) async { + final List remainingExpectedLines = expectedLines ?? []; + final List unexpectedLinesFound = []; + final List command = [ + flutterBin, + ...getLocalEngineArguments(), + 'build', + ...options, + ]; + + final ProcessResult result = await processManager.run( + command, + workingDirectory: workingDirectory, + ); + + final List stdout = LineSplitter.split(result.stdout.toString()).toList(); + final List stderr = LineSplitter.split(result.stderr.toString()).toList(); + final List output = stdout + stderr; + for (final String line in output) { + // Remove "[ +3 ms] " prefix + String trimmedLine = line.trim(); + if (trimmedLine.startsWith('[')) { + final int prefixEndIndex = trimmedLine.indexOf(']'); + if (prefixEndIndex > 0) { + trimmedLine = trimmedLine + .substring(prefixEndIndex + 1, trimmedLine.length) + .trim(); + } + } + remainingExpectedLines.remove(trimmedLine); + remainingExpectedLines.removeWhere((Pattern expectedLine) => trimmedLine.contains(expectedLine)); + if (unexpectedLines != null) { + if (unexpectedLines.where((String unexpectedLine) => trimmedLine.contains(unexpectedLine)).firstOrNull != null) { + unexpectedLinesFound.add(trimmedLine); + } + } + } + expect( + result.exitCode, + 0, + reason: 'Failed to build app for "${command.join(' ')}":\n' + 'stdout: \n${result.stdout}\n' + 'stderr: \n${result.stderr}\n', + ); + expect( + remainingExpectedLines, + isEmpty, + reason: 'Did not find expected lines for "${command.join(' ')}":\n' + 'stdout: \n${result.stdout}\n' + 'stderr: \n${result.stderr}\n', + ); + expect( + unexpectedLinesFound, + isEmpty, + reason: 'Found unexpected lines for "${command.join(' ')}":\n' + 'stdout: \n${result.stdout}\n' + 'stderr: \n${result.stderr}\n', + ); + } + + static Future cleanApp(String flutterBin, String workingDirectory) async { + final ProcessResult result = await processManager.run( + [ + flutterBin, + ...getLocalEngineArguments(), + 'clean', + ], + workingDirectory: workingDirectory, + ); + expect( + result.exitCode, + 0, + reason: 'Failed to clean app: \n' + 'stdout: \n${result.stdout}\n' + 'stderr: \n${result.stderr}\n', + ); + } + + static Future createPlugin( + String flutterBin, + String workingDirectory, { + required String platform, + required String iosLanguage, + bool usesSwiftPackageManager = false, + }) async { + final String dependencyManager = usesSwiftPackageManager ? 'spm' : 'cocoapods'; + + // Create plugin + final String pluginName = '${platform}_${iosLanguage}_${dependencyManager}_plugin'; + final ProcessResult result = await processManager.run( + [ + flutterBin, + ...getLocalEngineArguments(), + 'create', + '--org', + 'io.flutter.devicelab', + '--template=plugin', + '--platforms=$platform', + '-i', + iosLanguage, + pluginName, + ], + workingDirectory: workingDirectory, + ); + + expect( + result.exitCode, + 0, + reason: 'Failed to create plugin: \n' + 'stdout: \n${result.stdout}\n' + 'stderr: \n${result.stderr}\n', + ); + + final Directory pluginDirectory = fileSystem.directory( + fileSystem.path.join(workingDirectory, pluginName), + ); + + return SwiftPackageManagerPlugin( + pluginName: pluginName, + pluginPath: pluginDirectory.path, + platform: platform, + ); + } + + static void addDependency({ + required SwiftPackageManagerPlugin plugin, + required String appDirectoryPath, + }) { + final File pubspec = fileSystem.file( + fileSystem.path.join(appDirectoryPath, 'pubspec.yaml'), + ); + final String pubspecContent = pubspec.readAsStringSync(); + pubspec.writeAsStringSync( + pubspecContent.replaceFirst( + '\ndependencies:\n', + '\ndependencies:\n ${plugin.pluginName}:\n path: ${plugin.pluginPath}\n', + ), + ); + } + + static void disableSwiftPackageManagerByPubspec({ + required String appDirectoryPath, + }) { + final File pubspec = fileSystem.file( + fileSystem.path.join(appDirectoryPath, 'pubspec.yaml'), + ); + final String pubspecContent = pubspec.readAsStringSync(); + pubspec.writeAsStringSync( + pubspecContent.replaceFirst( + '\n# The following section is specific to Flutter packages.\nflutter:\n', + '\n# The following section is specific to Flutter packages.\nflutter:\n disable-swift-package-manager: true', + ), + ); + } + + static SwiftPackageManagerPlugin integrationTestPlugin(String platform) { + final String flutterRoot = getFlutterRoot(); + return SwiftPackageManagerPlugin( + platform: platform, + pluginName: + (platform == 'ios') ? 'integration_test' : 'integration_test_macos', + pluginPath: (platform == 'ios') + ? fileSystem.path.join(flutterRoot, 'packages', 'integration_test') + : fileSystem.path.join(flutterRoot, 'packages', 'integration_test', 'integration_test_macos'), + ); + } + + static List expectedLines({ + required String platform, + required String appDirectoryPath, + SwiftPackageManagerPlugin? cocoaPodsPlugin, + SwiftPackageManagerPlugin? swiftPackagePlugin, + bool swiftPackageMangerEnabled = false, + bool migrated = false, + }) { + final String frameworkName = platform == 'ios' ? 'Flutter' : 'FlutterMacOS'; + final String appPlatformDirectoryPath = fileSystem.path.join( + appDirectoryPath, + platform, + ); + + final List expectedLines = []; + if (swiftPackageMangerEnabled) { + expectedLines.addAll([ + 'FlutterGeneratedPluginSwiftPackage: $appPlatformDirectoryPath/Flutter/ephemeral/Packages/FlutterGeneratedPluginSwiftPackage', + "➜ Explicit dependency on target 'FlutterGeneratedPluginSwiftPackage' in project 'FlutterGeneratedPluginSwiftPackage'", + ]); + } + if (swiftPackagePlugin != null) { + // If using a Swift Package plugin, but Swift Package Manager is not enabled, it falls back to being used as a CocoaPods plugin. + if (swiftPackageMangerEnabled) { + expectedLines.addAll([ + RegExp('${swiftPackagePlugin.pluginName}: [/private]*${swiftPackagePlugin.pluginPath}/$platform/${swiftPackagePlugin.pluginName} @ local'), + "➜ Explicit dependency on target '${swiftPackagePlugin.pluginName}' in project '${swiftPackagePlugin.pluginName}'", + ]); + } else { + expectedLines.addAll([ + '-> Installing ${swiftPackagePlugin.pluginName} (0.0.1)', + "➜ Explicit dependency on target '${swiftPackagePlugin.pluginName}' in project 'Pods'", + ]); + } + } + if (cocoaPodsPlugin != null) { + expectedLines.addAll([ + 'Running pod install...', + '-> Installing $frameworkName (1.0.0)', + '-> Installing ${cocoaPodsPlugin.pluginName} (0.0.1)', + "Target 'Pods-Runner' in project 'Pods'", + "➜ Explicit dependency on target '$frameworkName' in project 'Pods'", + "➜ Explicit dependency on target '${cocoaPodsPlugin.pluginName}' in project 'Pods'", + ]); + } + if (migrated) { + expectedLines.addAll([ + 'Adding Swift Package Manager integration...', + 'Running pod install...', + "Target 'Pods-Runner' in project 'Pods'", + ]); + } + return expectedLines; + } + + static List unexpectedLines({ + required String platform, + required String appDirectoryPath, + SwiftPackageManagerPlugin? cocoaPodsPlugin, + SwiftPackageManagerPlugin? swiftPackagePlugin, + bool swiftPackageMangerEnabled = false, + bool migrated = false, + }) { + final String frameworkName = platform == 'ios' ? 'Flutter' : 'FlutterMacOS'; + final List unexpectedLines = []; + if (cocoaPodsPlugin == null && !migrated) { + unexpectedLines.addAll([ + 'Running pod install...', + '-> Installing $frameworkName (1.0.0)', + "Target 'Pods-Runner' in project 'Pods'", + ]); + } + if (swiftPackagePlugin != null) { + if (swiftPackageMangerEnabled) { + unexpectedLines.addAll([ + '-> Installing ${swiftPackagePlugin.pluginName} (0.0.1)', + "➜ Explicit dependency on target '${swiftPackagePlugin.pluginName}' in project 'Pods'", + ]); + } else { + unexpectedLines.addAll([ + '${swiftPackagePlugin.pluginName}: ${swiftPackagePlugin.pluginPath}/$platform/${swiftPackagePlugin.pluginName} @ local', + "➜ Explicit dependency on target '${swiftPackagePlugin.pluginName}' in project '${swiftPackagePlugin.pluginName}'", + ]); + } + } + if (!migrated) { + unexpectedLines.addAll([ + 'Adding Swift Package Manager integration...', + ]); + } + return unexpectedLines; + } +} + +class SwiftPackageManagerPlugin { + SwiftPackageManagerPlugin({ + required this.pluginName, + required this.pluginPath, + required this.platform, + }); + + final String pluginName; + final String pluginPath; + final String platform; + String get exampleAppPath => fileSystem.path.join(pluginPath, 'example'); + String get exampleAppPlatformPath => fileSystem.path.join(exampleAppPath, platform); +} diff --git a/flutter/packages/flutter_tools/test/integration.shard/template_manifest_test.dart b/flutter/packages/flutter_tools/test/integration.shard/template_manifest_test.dart new file mode 100644 index 0000000000000000000000000000000000000000..80741f70c32cf9926c6caf0551be61746bee166f --- /dev/null +++ b/flutter/packages/flutter_tools/test/integration.shard/template_manifest_test.dart @@ -0,0 +1,32 @@ +// 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/convert.dart'; +import '../src/common.dart'; +import 'test_utils.dart'; + +/// Checks that all active template files are defined in the template_manifest.json file. +void main() { + testWithoutContext('Check template manifest is up to date', () { + final Map manifest = json.decode( + fileSystem.file('templates/template_manifest.json').readAsStringSync(), + ) as Map; + final Set declaredFileList = Set.from( + (manifest['files']! as List).cast().map(fileSystem.path.toUri)); + + final Set activeTemplateList = fileSystem.directory('templates') + .listSync(recursive: true) + .whereType() + .where((File file) => fileSystem.path.basename(file.path) != 'template_manifest.json' && + fileSystem.path.basename(file.path) != 'README.md' && + fileSystem.path.basename(file.path) != '.DS_Store') + .map((File file) => file.uri) + .toSet(); + + final Set difference = activeTemplateList.difference(declaredFileList); + + expect(difference, isEmpty, reason: 'manifest and template directory should be in-sync'); + }); +} diff --git a/flutter/packages/flutter_tools/test/integration.shard/test_driver.dart b/flutter/packages/flutter_tools/test/integration.shard/test_driver.dart new file mode 100644 index 0000000000000000000000000000000000000000..6be229d2d5e91d8400c5fa42c8effeeea91c116e --- /dev/null +++ b/flutter/packages/flutter_tools/test/integration.shard/test_driver.dart @@ -0,0 +1,914 @@ +// Copyright 2014 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +import 'dart:async'; +import 'dart:convert'; +import 'dart:io' as io; // flutter_ignore: dart_io_import + +import 'package:file/file.dart'; +import 'package:flutter_tools/src/base/file_system.dart'; +import 'package:flutter_tools/src/base/io.dart'; +import 'package:flutter_tools/src/base/utils.dart'; +import 'package:process/process.dart'; +import 'package:vm_service/vm_service.dart'; +import 'package:vm_service/vm_service_io.dart'; + +import '../src/common.dart'; +import 'test_utils.dart'; + +// Set this to true for debugging to get verbose logs written to stdout. +// The logs include the following: +// <=stdout= data that the flutter tool running in --verbose mode wrote to stdout. +// <=stderr= data that the flutter tool running in --verbose mode wrote to stderr. +// =stdin=> data that the test sent to the flutter tool over stdin. +// =vm=> data that was sent over the VM service channel to the app running on the test device. +// <=vm= data that was sent from the app on the test device over the VM service channel. +// Messages regarding what the test is doing. +// If this is false, then only critical errors and logs when things appear to be +// taking a long time are printed to the console. +const bool _printDebugOutputToStdOut = false; + +final DateTime startTime = DateTime.now(); + +const Duration defaultTimeout = Duration(seconds: 5); +const Duration appStartTimeout = Duration(seconds: 120); +const Duration quitTimeout = Duration(seconds: 10); + +abstract class FlutterTestDriver { + FlutterTestDriver( + this._projectFolder, { + String? logPrefix, + }) : _logPrefix = logPrefix != null ? '$logPrefix: ' : ''; + + final Directory _projectFolder; + final String _logPrefix; + Process? _process; + int? _processPid; + final StreamController _stdout = StreamController.broadcast(); + final StreamController _stderr = StreamController.broadcast(); + final StreamController _allMessages = StreamController.broadcast(); + final StringBuffer _errorBuffer = StringBuffer(); + String? _lastResponse; + Uri? _vmServiceWsUri; + int? _attachPort; + bool _hasExited = false; + + VmService? _vmService; + String get lastErrorInfo => _errorBuffer.toString(); + Stream get stdout => _stdout.stream; + Stream get stderr => _stderr.stream; + int? get vmServicePort => _vmServiceWsUri?.port; + bool get hasExited => _hasExited; + Uri? get vmServiceWsUri => _vmServiceWsUri; + + String lastTime = ''; + void _debugPrint(String message, { String topic = '' }) { + const int maxLength = 2500; + final String truncatedMessage = message.length > maxLength ? '${message.substring(0, maxLength)}...' : message; + final String line = '${topic.padRight(10)} $truncatedMessage'; + _allMessages.add(line); + final int timeInSeconds = DateTime.now().difference(startTime).inSeconds; + String time = '${timeInSeconds.toString().padLeft(5)}s '; + if (time == lastTime) { + time = ' ' * time.length; + } else { + lastTime = time; + } + if (_printDebugOutputToStdOut) { + // This is the one place in this file that can call print. It is gated by + // _printDebugOutputToStdOut which should not be set to true in CI; it is + // intended only for use in local debugging. + // ignore: avoid_print + print('$time$_logPrefix$line'); + } else { + printOnFailure('$time$_logPrefix$line'); + } + } + + Future _setupProcess( + List arguments, { + String? script, + bool withDebugger = false, + }) async { + final String flutterBin = fileSystem.path.join(getFlutterRoot(), 'bin', 'flutter'); + if (withDebugger) { + arguments.add('--start-paused'); + } + if (_printDebugOutputToStdOut) { + arguments.add('--verbose'); + } + if (script != null) { + arguments.add(script); + } + _debugPrint('Spawning flutter $arguments in ${_projectFolder.path}'); + + const ProcessManager processManager = LocalProcessManager(); + _process = await processManager.start( + [flutterBin] + .followedBy(arguments) + .toList(), + workingDirectory: _projectFolder.path, + // The web environment variable has the same effect as `flutter config --enable-web`. + environment: { + 'FLUTTER_TEST': 'true', + 'FLUTTER_WEB': 'true', + }, + ); + + // This class doesn't use the result of the future. It's made available + // via a getter for external uses. + unawaited(_process!.exitCode.then((int code) { + _debugPrint('Process exited ($code)'); + _hasExited = true; + })); + transformToLines(_process!.stdout).listen(_stdout.add); + transformToLines(_process!.stderr).listen(_stderr.add); + + // Capture stderr to a buffer so we can show it all if any requests fail. + _stderr.stream.listen(_errorBuffer.writeln); + + // This is just debug printing to aid running/debugging tests locally. + _stdout.stream.listen((String message) => _debugPrint(message, topic: '<=stdout=')); + _stderr.stream.listen((String message) => _debugPrint(message, topic: '<=stderr=')); + } + + Future get done async => _process?.exitCode; + + Future connectToVmService({ bool pauseOnExceptions = false }) async { + _vmService = await vmServiceConnectUri('$_vmServiceWsUri'); + _vmService!.onSend.listen((String s) => _debugPrint(s, topic: '=vm=>')); + _vmService!.onReceive.listen((String s) => _debugPrint(s, topic: '<=vm=')); + + final Completer isolateStarted = Completer(); + _vmService!.onIsolateEvent.listen((Event event) { + if (event.kind == EventKind.kIsolateStart) { + isolateStarted.complete(); + } else if (event.kind == EventKind.kIsolateExit && event.isolate?.id == _flutterIsolateId) { + // Hot restarts cause all the isolates to exit, so we need to refresh + // our idea of what the Flutter isolate ID is. + _flutterIsolateId = null; + } + }); + + await Future.wait(>[ + _vmService!.streamListen('Isolate'), + _vmService!.streamListen('Debug'), + ]); + + if ((await _vmService!.getVM()).isolates?.isEmpty ?? true) { + await isolateStarted.future; + } + + await waitForPause(); + if (pauseOnExceptions) { + await _vmService!.setIsolatePauseMode( + await _getFlutterIsolateId(), + exceptionPauseMode: ExceptionPauseMode.kUnhandled, + ); + } + } + + Future callServiceExtension( + String extension, { + Map args = const {}, + }) async { + final int? port = _vmServiceWsUri != null ? vmServicePort : _attachPort; + final VmService vmService = await vmServiceConnectUri('ws://localhost:$port/ws'); + final Isolate isolate = await waitForExtension(vmService, extension); + return vmService.callServiceExtension( + extension, + isolateId: isolate.id, + args: args, + ); + } + + Future quit() => _killGracefully(); + + Future _killGracefully() async { + if (_processPid == null) { + return -1; + } + // If we try to kill the process while it's paused, we'll end up terminating + // it forcefully and it won't terminate child processes, so we need to ensure + // it's running before terminating. + await resume().timeout(defaultTimeout) + .then( + (Isolate? isolate) => isolate, + onError: (Object e) { + _debugPrint('Ignoring failure to resume during shutdown'); + return null; + }, + ); + + _debugPrint('Sending SIGTERM to $_processPid..'); + io.Process.killPid(_processPid!); + return _process!.exitCode.timeout(quitTimeout, onTimeout: _killForcefully); + } + + Future _killForcefully() { + _debugPrint('Sending SIGKILL to $_processPid..'); + ProcessSignal.sigkill.send(_processPid!); + return _process!.exitCode; + } + + String? _flutterIsolateId; + Future _getFlutterIsolateId() async { + // Currently these tests only have a single isolate. If this + // ceases to be the case, this code will need changing. + if (_flutterIsolateId == null) { + final VM vm = await _vmService!.getVM(); + _flutterIsolateId = vm.isolates!.single.id; + } + return _flutterIsolateId!; + } + + Future getFlutterIsolate() async { + final Isolate isolate = await _vmService!.getIsolate(await _getFlutterIsolateId()); + return isolate; + } + + /// Add a breakpoint and wait for it to trip the program execution. + /// + /// Only call this when you are absolutely sure that the program under test + /// will hit the breakpoint _in the future_. + /// + /// In particular, do not call this if the program is currently racing to pass + /// the line of code you are breaking on. Pretend that calling this will take + /// an hour before setting the breakpoint. Would the code still eventually hit + /// the breakpoint and stop? + Future breakAt(Uri uri, int line) async { + final String isolateId = await _getFlutterIsolateId(); + final Future event = subscribeToPauseEvent(isolateId); + await addBreakpoint(uri, line); + await waitForPauseEvent(isolateId, event); + } + + Future addBreakpoint(Uri uri, int line) async { + _debugPrint('Sending breakpoint for: $uri:$line'); + await _vmService!.addBreakpointWithScriptUri( + await _getFlutterIsolateId(), + uri.toString(), + line, + ); + } + + Future subscribeToPauseEvent(String isolateId) => subscribeToDebugEvent('Pause', isolateId); + Future subscribeToResumeEvent(String isolateId) => subscribeToDebugEvent('Resume', isolateId); + + Future waitForPauseEvent(String isolateId, Future event) => + waitForDebugEvent('Pause', isolateId, event); + Future waitForResumeEvent(String isolateId, Future event) => + waitForDebugEvent('Resume', isolateId, event); + + Future waitForPause() async => subscribeAndWaitForDebugEvent('Pause', await _getFlutterIsolateId()); + Future waitForResume() async => subscribeAndWaitForDebugEvent('Resume', await _getFlutterIsolateId()); + + + Future subscribeAndWaitForDebugEvent(String kind, String isolateId) { + final Future event = subscribeToDebugEvent(kind, isolateId); + return waitForDebugEvent(kind, isolateId, event); + } + + /// Subscribes to debug events containing [kind]. + /// + /// Returns a future that completes when the [kind] event is received. + /// + /// This method should be called before the command that triggers + /// the event to subscribe to the event in time, for example: + /// + /// ```dart + /// var event = subscribeToDebugEvent('Pause', id); // Subscribe to 'pause' events. + /// ... // Code that pauses the app. + /// await waitForDebugEvent('Pause', id, event); // Isolate is paused now. + /// ``` + Future subscribeToDebugEvent(String kind, String isolateId) { + _debugPrint('Start listening for $kind events'); + + return _vmService!.onDebugEvent + .where((Event event) { + return event.isolate?.id == isolateId + && (event.kind?.startsWith(kind) ?? false); + }).first; + } + + /// Wait for the [event] if needed. + /// + /// Return immediately if the isolate is already in the desired state. + Future waitForDebugEvent(String kind, String isolateId, Future event) { + return _timeoutWithMessages( + () async { + // But also check if the isolate was already at the state we need (only after we've + // set up the subscription) to avoid races. If it already in the desired state, we + // don't need to wait for the event. + final VmService vmService = _vmService!; + final Isolate isolate = await vmService.getIsolate(isolateId); + if (isolate.pauseEvent?.kind?.startsWith(kind) ?? false) { + _debugPrint('Isolate was already at "$kind" (${isolate.pauseEvent!.kind}).'); + event.ignore(); + } else { + _debugPrint('Waiting for "$kind" event to arrive...'); + await event; + } + + return vmService.getIsolate(isolateId); + }, + task: 'Waiting for isolate to $kind', + ); + } + + Future resume({ bool waitForNextPause = false }) => _resume(null, waitForNextPause); + Future stepOver({ bool waitForNextPause = true }) => _resume(StepOption.kOver, waitForNextPause); + Future stepOverAsync({ bool waitForNextPause = true }) => _resume(StepOption.kOverAsyncSuspension, waitForNextPause); + Future stepInto({ bool waitForNextPause = true }) => _resume(StepOption.kInto, waitForNextPause); + Future stepOut({ bool waitForNextPause = true }) => _resume(StepOption.kOut, waitForNextPause); + + Future isAtAsyncSuspension() async { + final Isolate isolate = await getFlutterIsolate(); + return isolate.pauseEvent?.atAsyncSuspension ?? false; + } + + Future stepOverOrOverAsyncSuspension({ bool waitForNextPause = true }) async { + if (await isAtAsyncSuspension()) { + return stepOverAsync(waitForNextPause: waitForNextPause); + } + return stepOver(waitForNextPause: waitForNextPause); + } + + Future _resume(String? step, bool waitForNextPause) async { + final String isolateId = await _getFlutterIsolateId(); + + final Future resume = subscribeToResumeEvent(isolateId); + final Future pause = subscribeToPauseEvent(isolateId); + + await _timeoutWithMessages( + () async => _vmService!.resume(isolateId, step: step), + task: 'Resuming isolate (step=$step)', + ); + await waitForResumeEvent(isolateId, resume); + return waitForNextPause ? waitForPauseEvent(isolateId, pause) : null; + } + + Future evaluateInFrame(String expression) async { + return _timeoutWithMessages( + () async => await _vmService!.evaluateInFrame(await _getFlutterIsolateId(), 0, expression) as ObjRef, + task: 'Evaluating expression ($expression)', + ); + } + + Future evaluate(String targetId, String expression) async { + return _timeoutWithMessages( + () async => await _vmService!.evaluate(await _getFlutterIsolateId(), targetId, expression) as ObjRef, + task: 'Evaluating expression ($expression for $targetId)', + ); + } + + Future getTopStackFrame() async { + final String flutterIsolateId = await _getFlutterIsolateId(); + final Stack stack = await _vmService!.getStack(flutterIsolateId); + final List? frames = stack.frames; + if (frames == null || frames.isEmpty) { + throw Exception('Stack is empty'); + } + return frames.first; + } + + Future getSourceLocation() async { + final String flutterIsolateId = await _getFlutterIsolateId(); + final Frame frame = await getTopStackFrame(); + final Script script = await _vmService!.getObject(flutterIsolateId, frame.location!.script!.id!) as Script; + return _lookupTokenPos(script.tokenPosTable!, frame.location!.tokenPos!); + } + + SourcePosition? _lookupTokenPos(List> table, int tokenPos) { + for (final List row in table) { + final int lineNumber = row[0]; + int index = 1; + + for (index = 1; index < row.length - 1; index += 2) { + if (row[index] == tokenPos) { + return SourcePosition(lineNumber, row[index + 1]); + } + } + } + + return null; + } + + Future> _waitFor({ + String? event, + int? id, + Duration timeout = defaultTimeout, + bool ignoreAppStopEvent = false, + }) async { + assert(event != null || id != null); + assert(event == null || id == null); + final String interestingOccurrence = event != null ? '$event event' : 'response to request $id'; + final Completer> response = Completer>(); + StreamSubscription? subscription; + subscription = _stdout.stream.listen((String line) async { + final Map? json = parseFlutterResponse(line); + _lastResponse = line; + if (json == null) { + return; + } + if ((event != null && json['event'] == event) || + (id != null && json['id'] == id)) { + await subscription?.cancel(); + _debugPrint('OK ($interestingOccurrence)'); + response.complete(json); + } else if (!ignoreAppStopEvent && json['event'] == 'app.stop') { + await subscription?.cancel(); + final StringBuffer error = StringBuffer(); + error.write('Received app.stop event while waiting for $interestingOccurrence\n\n$_errorBuffer'); + final Object? jsonParams = json['params']; + if (jsonParams is Map) { + if (jsonParams['error'] != null) { + error.write('${jsonParams['error']}\n\n'); + } + final Object? trace = jsonParams['trace']; + if (trace != null) { + error.write('$trace\n\n'); + } + } + response.completeError(Exception(error.toString())); + } + }); + + return _timeoutWithMessages( + () => response.future, + timeout: timeout, + task: 'Expecting $interestingOccurrence', + ).whenComplete(subscription.cancel); + } + + Future _timeoutWithMessages( + Future Function() callback, { + required String task, + Duration timeout = defaultTimeout, + }) { + + if (_printDebugOutputToStdOut) { + _debugPrint('$task...'); + final Timer longWarning = Timer(timeout, () => _debugPrint('$task is taking longer than usual...')); + return callback().whenComplete(longWarning.cancel); + } + + // We're not showing all output to the screen, so let's capture the output + // that we would have printed if we were, and output it if we take longer + // than the timeout or if we get an error. + final StringBuffer messages = StringBuffer('$task\n'); + final DateTime start = DateTime.now(); + bool timeoutExpired = false; + void logMessage(String logLine) { + final int ms = DateTime.now().difference(start).inMilliseconds; + final String formattedLine = '[+ ${ms.toString().padLeft(5)}] $logLine'; + messages.writeln(formattedLine); + } + final StreamSubscription subscription = _allMessages.stream.listen(logMessage); + + final Timer longWarning = Timer(timeout, () { + _debugPrint(messages.toString()); + timeoutExpired = true; + _debugPrint('$task is taking longer than usual...'); + }); + final Future future = callback().whenComplete(longWarning.cancel); + + return future.then( + (T t) => t, + onError: (Object error) { + if (!timeoutExpired) { + timeoutExpired = true; + _debugPrint(messages.toString()); + } + throw error; // ignore: only_throw_errors + }, + ).whenComplete(() => subscription.cancel()); + } +} + +class FlutterRunTestDriver extends FlutterTestDriver { + FlutterRunTestDriver( + super.projectFolder, { + super.logPrefix, + this.spawnDdsInstance = true, + }); + + String? _currentRunningAppId; + String? _currentRunningDeviceId; + String? _currentRunningMode; + + String? get currentRunningDeviceId => _currentRunningDeviceId; + String? get currentRunningMode => _currentRunningMode; + + Future run({ + bool withDebugger = false, + bool startPaused = false, + bool pauseOnExceptions = false, + bool chrome = false, + bool expressionEvaluation = true, + bool structuredErrors = false, + bool serveObservatory = false, + String? script, + List? additionalCommandArgs, + }) async { + await _setupProcess( + [ + 'run', + if (!chrome) + '--disable-service-auth-codes', + '--machine', + if (!spawnDdsInstance) '--no-dds', + '--${serveObservatory ? '' : 'no-'}serve-observatory', + ...getLocalEngineArguments(), + '-d', + if (chrome) + ...[ + 'chrome', + '--web-run-headless', + if (!expressionEvaluation) '--no-web-enable-expression-evaluation', + ] + else + 'flutter-tester', + if (structuredErrors) + '--dart-define=flutter.inspector.structuredErrors=true', + ...?additionalCommandArgs, + ], + withDebugger: withDebugger, + startPaused: startPaused, + pauseOnExceptions: pauseOnExceptions, + script: script, + ); + } + + Future attach( + int port, { + bool withDebugger = false, + bool startPaused = false, + bool pauseOnExceptions = false, + bool serveObservatory = false, + List? additionalCommandArgs, + }) async { + _attachPort = port; + await _setupProcess( + [ + 'attach', + ...getLocalEngineArguments(), + '--machine', + if (!spawnDdsInstance) + '--no-dds', + '--${serveObservatory ? '' : 'no-'}serve-observatory', + '-d', + 'flutter-tester', + '--debug-port', + '$port', + ...?additionalCommandArgs, + ], + withDebugger: withDebugger, + startPaused: startPaused, + pauseOnExceptions: pauseOnExceptions, + attachPort: port, + ); + } + + @override + Future _setupProcess( + List args, { + String? script, + bool withDebugger = false, + bool startPaused = false, + bool pauseOnExceptions = false, + int? attachPort, + }) async { + assert(!startPaused || withDebugger); + await super._setupProcess( + args, + script: script, + withDebugger: withDebugger, + ); + + final Completer prematureExitGuard = Completer(); + + // If the process exits before all of the `await`s below are done, then it + // exited prematurely. This causes the currently suspended `await` to + // deadlock until the test times out. Instead, this causes the test to fail + // fast. + unawaited(_process?.exitCode.then((_) { + if (!prematureExitGuard.isCompleted) { + prematureExitGuard.completeError(Exception('Process exited prematurely: ${args.join(' ')}: $_errorBuffer')); + } + })); + + unawaited(() async { + try { + // Stash the PID so that we can terminate the VM more reliably than using + // _process.kill() (`flutter` is a shell script so _process itself is a + // shell, not the flutter tool's Dart process). + final Map connected = await _waitFor(event: 'daemon.connected'); + _processPid = (connected['params'] as Map?)?['pid'] as int?; + + // Set this up now, but we don't wait it yet. We want to make sure we don't + // miss it while waiting for debugPort below. + final Future> start = _waitFor(event: 'app.start', timeout: appStartTimeout); + final Future> started = _waitFor(event: 'app.started', timeout: appStartTimeout); + + if (withDebugger) { + final Map debugPort = await _waitFor(event: 'app.debugPort', timeout: appStartTimeout); + final String wsUriString = (debugPort['params']! as Map)['wsUri']! as String; + _vmServiceWsUri = Uri.parse(wsUriString); + await connectToVmService(pauseOnExceptions: pauseOnExceptions); + if (!startPaused) { + await resume(); + } + } + + // In order to call service extensions from test runners started with + // attach, we need to store the port that the test runner was attached + // to. + if (_vmServiceWsUri == null && attachPort != null) { + _attachPort = attachPort; + } + + // Now await the start/started events; if it had already happened the future will + // have already completed. + final Map? startParams = (await start)['params'] as Map?; + final Map? startedParams = (await started)['params'] as Map?; + _currentRunningAppId = startedParams?['appId'] as String?; + _currentRunningDeviceId = startParams?['deviceId'] as String?; + _currentRunningMode = startParams?['mode'] as String?; + prematureExitGuard.complete(); + } on Exception catch (error, stackTrace) { + prematureExitGuard.completeError(Exception(error.toString()), stackTrace); + } + }()); + + return prematureExitGuard.future; + } + + Future hotRestart({ bool pause = false, bool debounce = false}) => _restart(fullRestart: true, pause: pause); + Future hotReload({ bool debounce = false, int? debounceDurationOverrideMs }) => + _restart(debounce: debounce, debounceDurationOverrideMs: debounceDurationOverrideMs); + + Future scheduleFrame() async { + if (_currentRunningAppId == null) { + throw Exception('App has not started yet'); + } + await _sendRequest( + 'app.callServiceExtension', + {'appId': _currentRunningAppId, 'methodName': 'ext.ui.window.scheduleFrame'}, + ); + } + + Future _restart({ bool fullRestart = false, bool pause = false, bool debounce = false, int? debounceDurationOverrideMs }) async { + if (_currentRunningAppId == null) { + throw Exception('App has not started yet'); + } + + _debugPrint('Performing ${ pause ? "paused " : "" }${ fullRestart ? "hot restart" : "hot reload" }...'); + final Map? hotReloadResponse = await _sendRequest( + 'app.restart', + {'appId': _currentRunningAppId, 'fullRestart': fullRestart, 'pause': pause, 'debounce': debounce, 'debounceDurationOverrideMs': debounceDurationOverrideMs}, + ) as Map?; + _debugPrint('${fullRestart ? "Hot restart" : "Hot reload"} complete.'); + + if (hotReloadResponse == null || hotReloadResponse['code'] != 0) { + _throwErrorResponse('Hot ${fullRestart ? 'restart' : 'reload'} request failed'); + } + } + + Future detach() async { + final Process? process = _process; + if (process == null) { + return 0; + } + final VmService? vmService = _vmService; + if (vmService != null) { + _debugPrint('Closing VM service...'); + await vmService.dispose(); + } + if (_currentRunningAppId != null) { + _debugPrint('Detaching from app...'); + await Future.any(>[ + process.exitCode, + _sendRequest( + 'app.detach', + {'appId': _currentRunningAppId}, + ), + ]).timeout( + quitTimeout, + onTimeout: () { _debugPrint('app.detach did not return within $quitTimeout'); }, + ); + _currentRunningAppId = null; + } + _debugPrint('Waiting for process to end...'); + return process.exitCode.timeout(quitTimeout, onTimeout: _killGracefully); + } + + Future stop() async { + final VmService? vmService = _vmService; + if (vmService != null) { + _debugPrint('Closing VM service...'); + await vmService.dispose(); + } + final Process? process = _process; + if (_currentRunningAppId != null) { + _debugPrint('Stopping application...'); + await Future.any(>[ + process!.exitCode, + _sendRequest( + 'app.stop', + {'appId': _currentRunningAppId}, + ), + ]).timeout( + quitTimeout, + onTimeout: () { _debugPrint('app.stop did not return within $quitTimeout'); }, + ); + _currentRunningAppId = null; + } + if (process != null) { + _debugPrint('Waiting for process to end...'); + return process.exitCode.timeout(quitTimeout, onTimeout: _killGracefully); + } + return 0; + } + + int id = 1; + Future _sendRequest(String method, Object? params) async { + final int requestId = id++; + final Map request = { + 'id': requestId, + 'method': method, + 'params': params, + }; + final String jsonEncoded = json.encode(>[request]); + _debugPrint(jsonEncoded, topic: '=stdin=>'); + + // Set up the response future before we send the request to avoid any + // races. If the method we're calling is app.stop then we tell _waitFor not + // to throw if it sees an app.stop event before the response to this request. + final Future> responseFuture = _waitFor( + id: requestId, + ignoreAppStopEvent: method == 'app.stop' || method == 'app.detach', + ); + _process?.stdin.writeln(jsonEncoded); + final Map response = await responseFuture; + + if (response['error'] != null || response['result'] == null) { + _throwErrorResponse('Unexpected error response'); + } + + return response['result']; + } + + void _throwErrorResponse(String message) { + throw Exception('$message\n\n$_lastResponse\n\n$_errorBuffer'.trim()); + } + + final bool spawnDdsInstance; +} + +class FlutterTestTestDriver extends FlutterTestDriver { + FlutterTestTestDriver(super.projectFolder, {super.logPrefix}); + + Future test({ + String testFile = 'test/test.dart', + String? deviceId, + bool withDebugger = false, + bool pauseOnExceptions = false, + bool coverage = false, + Future Function()? beforeStart, + }) async { + await _setupProcess([ + 'test', + ...getLocalEngineArguments(), + '--disable-service-auth-codes', + '--machine', + if (coverage) + '--coverage', + if (deviceId != null) + ...['-d', deviceId], + ], script: testFile, withDebugger: withDebugger, pauseOnExceptions: pauseOnExceptions, beforeStart: beforeStart); + } + + @override + Future _setupProcess( + List args, { + String? script, + bool withDebugger = false, + bool pauseOnExceptions = false, + Future Function()? beforeStart, + }) async { + await super._setupProcess( + args, + script: script, + withDebugger: withDebugger, + ); + + // Stash the PID so that we can terminate the VM more reliably than using + // _proc.kill() (because _proc is a shell, because `flutter` is a shell + // script). + final Map? version = await _waitForJson(); + _processPid = version?['pid'] as int?; + + if (withDebugger) { + final Map startedProcessParams = + (await _waitFor(event: 'test.startedProcess', timeout: appStartTimeout))['params']! as Map; + final String vmServiceHttpString = startedProcessParams['vmServiceUri']! as String; + _vmServiceWsUri = Uri.parse(vmServiceHttpString).replace(scheme: 'ws', path: '/ws'); + await connectToVmService(pauseOnExceptions: pauseOnExceptions); + // Allow us to run code before we start, eg. to set up breakpoints. + if (beforeStart != null) { + await beforeStart(); + } + await resume(); + } + } + + Future?> _waitForJson({ + Duration timeout = defaultTimeout, + }) async { + return _timeoutWithMessages?>( + () => _stdout.stream.map?>(_parseJsonResponse) + .firstWhere((Map? output) => output != null), + timeout: timeout, + task: 'Waiting for JSON', + ); + } + + Map? _parseJsonResponse(String line) { + try { + return castStringKeyedMap(json.decode(line)); + } on Exception { + // Not valid JSON, so likely some other output. + return null; + } + } + + Future waitForCompletion() async { + final Completer done = Completer(); + // Waiting for `{"success":true,"type":"done",...}` line indicating + // end of test run. + final StreamSubscription subscription = _stdout.stream.listen( + (String line) async { + final Map? json = _parseJsonResponse(line); + if (json != null && json['type'] != null && json['success'] != null) { + done.complete(json['type'] == 'done' && json['success'] == true); + } + }); + + await resume(); + + final Future timeoutFuture = + Future.delayed(defaultTimeout); + await Future.any(>[done.future, timeoutFuture]); + await subscription.cancel(); + if (!done.isCompleted) { + await quit(); + } + } +} + +Stream transformToLines(Stream> byteStream) { + return byteStream.transform(utf8.decoder).transform(const LineSplitter()); +} + +Map? parseFlutterResponse(String line) { + if (line.startsWith('[') && line.endsWith(']') && line.length > 2) { + try { + final Map? response = castStringKeyedMap((json.decode(line) as List)[0]); + return response; + } on FormatException { + // Not valid JSON, so likely some other output that was surrounded by [brackets] + return null; + } + } + return null; +} + +class SourcePosition { + SourcePosition(this.line, this.column); + + final int line; + final int column; +} + +Future waitForExtension(VmService vmService, String extension) async { + final Completer completer = Completer(); + try { + await vmService.streamListen(EventStreams.kExtension); + } on RPCError { + // Do nothing, already subscribed. + } + vmService.onExtensionEvent.listen((Event event) { + if (event.json?['extensionKind'] == 'Flutter.FrameworkInitialization') { + completer.complete(); + } + }); + final IsolateRef isolateRef = (await vmService.getVM()).isolates!.first; + final Isolate isolate = await vmService.getIsolate(isolateRef.id!); + if (isolate.extensionRPCs!.contains(extension)) { + return isolate; + } + await completer.future; + return isolate; +} diff --git a/flutter/packages/flutter_web_plugins/lib/flutter_web_plugins.dart b/flutter/packages/flutter_web_plugins/lib/flutter_web_plugins.dart new file mode 100644 index 0000000000000000000000000000000000000000..3b27fff155881a030ed53b93c7cef809a9bd16aa --- /dev/null +++ b/flutter/packages/flutter_web_plugins/lib/flutter_web_plugins.dart @@ -0,0 +1,21 @@ +// 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. + +/// The platform channels and plugin registry implementations for +/// the web implementations of Flutter plugins. +/// +/// This library provides the [Registrar] class, which is used in the +/// `registerWith` method that is itself called by the code generated +/// by the `flutter` tool for web applications. +/// +/// See also: +/// +/// * [How to Write a Flutter Web Plugin](https://medium.com/flutter/how-to-write-a-flutter-web-plugin-5e26c689ea1), a Medium article +/// describing how the `url_launcher` package was created using [flutter_web_plugins]. +library flutter_web_plugins; + +export 'src/navigation/url_strategy.dart'; +export 'src/navigation/utils.dart'; +export 'src/plugin_event_channel.dart'; +export 'src/plugin_registry.dart'; diff --git a/flutter/packages/flutter_web_plugins/lib/src/plugin_event_channel.dart b/flutter/packages/flutter_web_plugins/lib/src/plugin_event_channel.dart new file mode 100644 index 0000000000000000000000000000000000000000..d679e24caee0b247402091488fb524476a75064c --- /dev/null +++ b/flutter/packages/flutter_web_plugins/lib/src/plugin_event_channel.dart @@ -0,0 +1,149 @@ +// 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/services.dart'; + +import 'plugin_registry.dart'; + +/// A named channel for sending events to the framework-side using streams. +/// +/// This is the platform-side equivalent of [EventChannel]. Whereas +/// [EventChannel] receives a stream of events from platform plugins, this +/// channel sends a stream of events to the handler listening on the +/// framework-side. +/// +/// If no [codec] is provided, then [StandardMethodCodec] is used. If no +/// [binaryMessenger] is provided, then [pluginBinaryMessenger], which sends +/// messages to the framework-side, is used. +/// +/// Channels created using this class implement two methods for +/// subscribing to the event stream. The methods use the encoding of +/// the specified [codec]. +/// +/// The first method is `listen`. When called, it begins forwarding +/// messages to the framework side when they are added to the +/// `controller`. This triggers the [StreamController.onListen] callback +/// on the `controller`. +/// +/// The other method is `cancel`. When called, it stops forwarding +/// events to the framework. This triggers the [StreamController.onCancel] +/// callback on the `controller`. +/// +/// Events added to the `controller` when the framework is not +/// subscribed are silently discarded. +class PluginEventChannel { + /// Creates a new plugin event channel. + const PluginEventChannel( + this.name, [ + this.codec = const StandardMethodCodec(), + this.binaryMessenger, + ]); + + /// The logical channel on which communication happens. + final String name; + + /// The message codec used by this channel. + /// + /// Defaults to [StandardMethodCodec]. + final MethodCodec codec; + + /// The messenger used by this channel to send platform messages. + /// + /// When this is null, the [pluginBinaryMessenger] is used instead, + /// which sends messages from the platform-side to the + /// framework-side. + final BinaryMessenger? binaryMessenger; + + /// Use [setController] instead. + /// + /// This setter is deprecated because it has no corresponding getter, + /// and providing a getter would require making this class non-const. + @Deprecated( + 'Replace calls to the "controller" setter with calls to the "setController" method. ' + 'This feature was deprecated after v1.23.0-7.0.pre.' + ) + set controller(StreamController controller) { // ignore: avoid_setters_without_getters + setController(controller); + } + + /// Changes the stream controller for this event channel. + /// + /// Setting the controller to null disconnects from the channel (setting + /// the message handler on the [binaryMessenger] to null). + void setController(StreamController? controller) { + final BinaryMessenger messenger = binaryMessenger ?? pluginBinaryMessenger; + if (controller == null) { + messenger.setMessageHandler(name, null); + } else { + // The handler object is kept alive via its handle() method + // keeping a reference to itself. Ideally we would keep a + // reference to it so that there was a clear ownership model, + // but that would require making this class non-const. Having + // this class be const is convenient since it allows references + // to be obtained by using the constructor rather than having + // to literally pass references around. + final _EventChannelHandler handler = _EventChannelHandler( + name, + codec, + controller, + messenger, + ); + messenger.setMessageHandler(name, handler.handle); + } + } +} + +class _EventChannelHandler { + _EventChannelHandler( + this.name, + this.codec, + this.controller, + this.messenger, + ); + + final String name; + final MethodCodec codec; + final StreamController controller; + final BinaryMessenger messenger; + + StreamSubscription? subscription; + + Future? handle(ByteData? message) { + final MethodCall call = codec.decodeMethodCall(message); + switch (call.method) { + case 'listen': + assert(call.arguments == null); + return _listen(); + case 'cancel': + assert(call.arguments == null); + return _cancel(); + } + return null; + } + + Future _listen() async { + // Cancel any existing subscription. + await subscription?.cancel(); + subscription = controller.stream.listen((dynamic event) { + messenger.send(name, codec.encodeSuccessEnvelope(event)); + }, onError: (dynamic error) { + messenger.send(name, codec.encodeErrorEnvelope(code: 'error', message: '$error')); + }); + return codec.encodeSuccessEnvelope(null); + } + + Future _cancel() async { + if (subscription == null) { + return codec.encodeErrorEnvelope( + code: 'error', + message: 'No active subscription to cancel.', + ); + } + await subscription!.cancel(); + subscription = null; + return codec.encodeSuccessEnvelope(null); + } +} diff --git a/flutter/packages/flutter_web_plugins/lib/src/plugin_registry.dart b/flutter/packages/flutter_web_plugins/lib/src/plugin_registry.dart new file mode 100644 index 0000000000000000000000000000000000000000..a6ff602a43220bd1c0c3c6388ac07490bfa3ee35 --- /dev/null +++ b/flutter/packages/flutter_web_plugins/lib/src/plugin_registry.dart @@ -0,0 +1,224 @@ +// Copyright 2014 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +import 'dart:async'; +import 'dart:ui' as ui; +import 'dart:ui_web' as ui_web; + +import 'package:flutter/foundation.dart'; +import 'package:flutter/services.dart'; + +// Examples can assume: +// import 'package:flutter_web_plugins/flutter_web_plugins.dart'; +// import 'package:flutter/services.dart'; +// import 'dart:ui_web' as ui_web; +// void handleFrameworkMessage(String name, ByteData? data, PlatformMessageResponseCallback? callback) { } + +/// A registrar for Flutter plugins implemented in Dart. +/// +/// Plugins for the web platform are implemented in Dart and are +/// registered with this class by code generated by the `flutter` tool +/// when compiling the application. +/// +/// This class implements [BinaryMessenger] to route messages from the +/// framework to registered plugins. +/// +/// Use this [BinaryMessenger] when creating platform channels in order for +/// them to receive messages from the platform side. For example: +/// +/// ```dart +/// class MyPlugin { +/// static void registerWith(Registrar registrar) { +/// final MethodChannel channel = MethodChannel( +/// 'com.my_plugin/my_plugin', +/// const StandardMethodCodec(), +/// registrar, // the registrar is used as the BinaryMessenger +/// ); +/// final MyPlugin instance = MyPlugin(); +/// channel.setMethodCallHandler(instance.handleMethodCall); +/// } +/// +/// Future handleMethodCall(MethodCall call) async { +/// // ... +/// } +/// +/// // ... +/// } +/// ``` +class Registrar extends BinaryMessenger { + /// Creates a [Registrar]. + /// + /// The argument is ignored. To create a test [Registrar] with custom behavior, + /// subclass the [Registrar] class and override methods as appropriate. + Registrar([ + @Deprecated( + 'This argument is ignored. ' + 'This feature was deprecated after v1.24.0-7.0.pre.' + ) + BinaryMessenger? binaryMessenger, + ]); + + /// Registers the registrar's message handler + /// ([handlePlatformMessage]) with the engine, so that plugin + /// messages are correctly dispatched to the relevant registered + /// plugin. + /// + /// Only one handler can be registered at a time. Calling this + /// method a second time silently unregisters any + /// previously-registered handler and replaces it with the handler + /// from this object. + /// + /// This method uses a function called `setPluginHandler` in + /// the [dart:ui_web] library. That function is only available when + /// compiling for the web. + void registerMessageHandler() { + ui_web.setPluginHandler(handleFrameworkMessage); + } + + /// Receives a platform message from the framework. + /// + /// This method has been replaced with the more clearly-named [handleFrameworkMessage]. + @Deprecated( + 'Use handleFrameworkMessage instead. ' + 'This feature was deprecated after v1.24.0-7.0.pre.' + ) + @override + Future handlePlatformMessage( + String channel, + ByteData? data, + ui.PlatformMessageResponseCallback? callback, + ) => handleFrameworkMessage(channel, data, callback); + + /// Message handler for web plugins. + /// + /// This method is called when handling messages from the framework. + /// + /// If a handler has been registered for the given `channel`, it is + /// invoked, and the value it returns is passed to `callback` (if that + /// is non-null). Then, the method's future is completed. + /// + /// If no handler has been registered for that channel, then the + /// callback (if any) is invoked with null, then the method's future + /// is completed. + /// + /// Messages are not buffered (unlike platform messages headed to + /// the framework, which are managed by [ChannelBuffers]). + /// + /// This method is registered as the message handler by code + /// autogenerated by the `flutter` tool when the application is + /// compiled, if any web plugins are used. The code in question is + /// the following: + /// + /// ```dart + /// ui_web.setPluginHandler(handleFrameworkMessage); + /// ``` + Future handleFrameworkMessage( + String channel, + ByteData? data, + ui.PlatformMessageResponseCallback? callback, + ) async { + ByteData? response; + try { + final MessageHandler? handler = _handlers[channel]; + if (handler != null) { + response = await handler(data); + } + } catch (exception, stack) { + FlutterError.reportError(FlutterErrorDetails( + exception: exception, + stack: stack, + library: 'flutter web plugins', + context: ErrorDescription('during a framework-to-plugin message'), + )); + } finally { + if (callback != null) { + callback(response); + } + } + } + + /// Returns `this`. + @Deprecated( + 'This property is redundant. It returns the object on which it is called. ' + 'This feature was deprecated after v1.24.0-7.0.pre.' + ) + BinaryMessenger get messenger => this; + + final Map _handlers = {}; + + /// Sends a platform message from the platform side back to the framework. + @override + Future send(String channel, ByteData? message) { + final Completer completer = Completer(); + ui.channelBuffers.push(channel, message, (ByteData? reply) { + try { + completer.complete(reply); + } catch (exception, stack) { + FlutterError.reportError(FlutterErrorDetails( + exception: exception, + stack: stack, + library: 'flutter web plugins', + context: ErrorDescription('during a plugin-to-framework message'), + )); + } + }); + return completer.future; + } + + @override + void setMessageHandler(String channel, MessageHandler? handler) { + if (handler == null) { + _handlers.remove(channel); + } else { + _handlers[channel] = handler; + } + } +} + +/// This class was previously separate from [Registrar] but was merged into it +/// as part of a simplification of the web plugins API. +@Deprecated( + 'Use Registrar instead. ' + 'This feature was deprecated after v1.26.0-18.0.pre.' +) +class PluginRegistry extends Registrar { + /// Creates a [Registrar]. + /// + /// The argument is ignored. + @Deprecated( + 'Use Registrar instead. ' + 'This feature was deprecated after v1.26.0-18.0.pre.' + ) + PluginRegistry([ + @Deprecated( + 'This argument is ignored. ' + 'This feature was deprecated after v1.26.0-18.0.pre.' + ) + BinaryMessenger? binaryMessenger, + ]) : super(); + + /// Returns `this`. The argument is ignored. + @Deprecated( + 'This method is redundant. It returns the object on which it is called. ' + 'This feature was deprecated after v1.26.0-18.0.pre.' + ) + Registrar registrarFor(Type key) => this; +} + +/// The default plugin registrar for the web. +final Registrar webPluginRegistrar = PluginRegistry(); + +/// A deprecated alias for [webPluginRegistrar]. +@Deprecated( + 'Use webPluginRegistrar instead. ' + 'This feature was deprecated after v1.24.0-7.0.pre.' +) +PluginRegistry get webPluginRegistry => webPluginRegistrar as PluginRegistry; + +/// A deprecated alias for [webPluginRegistrar]. +@Deprecated( + 'Use webPluginRegistrar instead. ' + 'This feature was deprecated after v1.24.0-7.0.pre.' +) +BinaryMessenger get pluginBinaryMessenger => webPluginRegistrar; diff --git a/flutter/packages/flutter_web_plugins/lib/url_strategy.dart b/flutter/packages/flutter_web_plugins/lib/url_strategy.dart new file mode 100644 index 0000000000000000000000000000000000000000..79cc9265c27f0e5bddf6e6fc73d341336631bf55 --- /dev/null +++ b/flutter/packages/flutter_web_plugins/lib/url_strategy.dart @@ -0,0 +1,6 @@ +// 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. + +export 'src/navigation_non_web/url_strategy.dart' + if (dart.library.ui_web) 'src/navigation/url_strategy.dart'; diff --git a/flutter/packages/flutter_web_plugins/pubspec.lock b/flutter/packages/flutter_web_plugins/pubspec.lock new file mode 100644 index 0000000000000000000000000000000000000000..2d3f6c8c4454cc1d7407a2d0755161ed06822cc8 --- /dev/null +++ b/flutter/packages/flutter_web_plugins/pubspec.lock @@ -0,0 +1,188 @@ +# Generated by pub +# See https://dart.dev/tools/pub/glossary#lockfile +packages: + async: + dependency: "direct dev" + description: + name: async + sha256: "947bfcf187f74dbc5e146c9eb9c0f10c9f8b30743e341481c1e2ed3ecc18c20c" + url: "https://pub.dev" + source: hosted + version: "2.11.0" + boolean_selector: + dependency: "direct dev" + 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 dev" + 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 dev" + description: + name: fake_async + sha256: "511392330127add0b769b75a987850d136345d9227c6b94c96a04cf4a391bf78" + url: "https://pub.dev" + source: hosted + version: "1.3.1" + flutter: + dependency: "direct main" + description: flutter + source: sdk + version: "0.0.0" + flutter_test: + dependency: "direct dev" + description: flutter + source: sdk + version: "0.0.0" + leak_tracker: + dependency: "direct dev" + description: + name: leak_tracker + sha256: "78eb209deea09858f5269f5a5b02be4049535f568c07b275096836f01ea323fa" + url: "https://pub.dev" + source: hosted + version: "10.0.0" + leak_tracker_flutter_testing: + dependency: "direct dev" + description: + name: leak_tracker_flutter_testing + sha256: b46c5e37c19120a8a01918cfaf293547f47269f7cb4b0058f21531c2465d6ef0 + url: "https://pub.dev" + source: hosted + version: "2.0.1" + leak_tracker_testing: + dependency: "direct dev" + description: + name: leak_tracker_testing + sha256: a597f72a664dbd293f3bfc51f9ba69816f84dcd403cdac7066cb3f6003f3ab47 + url: "https://pub.dev" + source: hosted + version: "2.0.1" + matcher: + dependency: "direct dev" + 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 dev" + 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 dev" + description: + name: source_span + sha256: "53e943d4206a5e30df338fd4c6e7a077e02254531b138a15aec3bd143c1a8b3c" + url: "https://pub.dev" + source: hosted + version: "1.10.0" + stack_trace: + dependency: "direct dev" + description: + name: stack_trace + sha256: "73713990125a6d93122541237550ee3352a2d84baad52d375a4cad2eb9b7ce0b" + url: "https://pub.dev" + source: hosted + version: "1.11.1" + stream_channel: + dependency: "direct dev" + description: + name: stream_channel + sha256: ba2aa5d8cc609d96bbb2899c28934f9e1af5cddbd60a827822ea467161eb54e7 + url: "https://pub.dev" + source: hosted + version: "2.1.2" + string_scanner: + dependency: "direct dev" + description: + name: string_scanner + sha256: "556692adab6cfa87322a115640c11f13cb77b3f076ddcc5d6ae3c20242bedcde" + url: "https://pub.dev" + source: hosted + version: "1.2.0" + term_glyph: + dependency: "direct dev" + description: + name: term_glyph + sha256: a29248a84fbb7c79282b40b8c72a1209db169a2e0542bce341da992fe1bc7e84 + url: "https://pub.dev" + source: hosted + version: "1.2.1" + test_api: + dependency: "direct dev" + 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 dev" + 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" diff --git a/flutter/packages/flutter_web_plugins/pubspec.yaml b/flutter/packages/flutter_web_plugins/pubspec.yaml new file mode 100644 index 0000000000000000000000000000000000000000..b49ee6a235e1721e67cecebe77994c4aedaf488f --- /dev/null +++ b/flutter/packages/flutter_web_plugins/pubspec.yaml @@ -0,0 +1,39 @@ +name: flutter_web_plugins +description: Library to register Flutter Web plugins +homepage: https://flutter.dev + +environment: + sdk: '>=3.2.0-0 <4.0.0' + +dependencies: + flutter: + sdk: flutter + + 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" + 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" + vector_math: 2.1.4 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" + +dev_dependencies: + flutter_test: + sdk: flutter + + 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" + clock: 1.1.1 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" + fake_async: 1.3.1 # 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_flutter_testing: 2.0.1 # 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" + matcher: 0.12.16+1 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" + path: 1.9.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" + stack_trace: 1.11.1 # 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" + test_api: 0.6.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" + +# PUBSPEC CHECKSUM: 8023 diff --git a/flutter/packages/flutter_web_plugins/test/navigation/common.dart b/flutter/packages/flutter_web_plugins/test/navigation/common.dart new file mode 100644 index 0000000000000000000000000000000000000000..e01616bf64c880d6f8d16621695748fb05471270 --- /dev/null +++ b/flutter/packages/flutter_web_plugins/test/navigation/common.dart @@ -0,0 +1,47 @@ +// 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_web_plugins/url_strategy.dart'; + +/// A mock implementation of [PlatformLocation] that doesn't access the browser. +class TestPlatformLocation implements PlatformLocation { + @override + String pathname = ''; + + @override + String search = ''; + + @override + String hash = ''; + + @override + Object? get state => null; + + /// Mocks the base href of the document. + String baseHref = ''; + + @override + void addPopStateListener(EventListener fn) { + throw UnimplementedError(); + } + + @override + void removePopStateListener(EventListener fn) { + throw UnimplementedError(); + } + + @override + void pushState(Object? state, String title, String url) {} + + @override + void replaceState(Object? state, String title, String url) {} + + @override + void go(int count) { + throw UnimplementedError(); + } + + @override + String getBaseHref() => baseHref; +} diff --git a/flutter/packages/flutter_web_plugins/test/navigation/non_web_url_strategy_test.dart b/flutter/packages/flutter_web_plugins/test/navigation/non_web_url_strategy_test.dart new file mode 100644 index 0000000000000000000000000000000000000000..6f16105c044fea8375178e7b114822a4dc4d95d0 --- /dev/null +++ b/flutter/packages/flutter_web_plugins/test/navigation/non_web_url_strategy_test.dart @@ -0,0 +1,41 @@ +// 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. + +@TestOn('!chrome') +library; + +import 'package:flutter_test/flutter_test.dart'; +import 'package:flutter_web_plugins/url_strategy.dart'; + +import 'common.dart'; + +void main() { + group('Non-web UrlStrategy', () { + late TestPlatformLocation location; + + setUp(() { + location = TestPlatformLocation(); + }); + + test('Can create and set a $HashUrlStrategy', () { + expect(() { + final HashUrlStrategy strategy = HashUrlStrategy(location); + setUrlStrategy(strategy); + }, returnsNormally); + }); + + test('Can create and set a $PathUrlStrategy', () { + expect(() { + final PathUrlStrategy strategy = PathUrlStrategy(location); + setUrlStrategy(strategy); + }, returnsNormally); + }); + + test('Can usePathUrlStrategy', () { + expect(() { + usePathUrlStrategy(); + }, returnsNormally); + }); + }); +} diff --git a/flutter/packages/flutter_web_plugins/test/navigation/url_strategy_test.dart b/flutter/packages/flutter_web_plugins/test/navigation/url_strategy_test.dart new file mode 100644 index 0000000000000000000000000000000000000000..d9e0a4d453595315257713ce43ef17a112964911 --- /dev/null +++ b/flutter/packages/flutter_web_plugins/test/navigation/url_strategy_test.dart @@ -0,0 +1,146 @@ +// 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. + +@TestOn('chrome') // Uses web-only Flutter SDK +library; + +import 'package:flutter_test/flutter_test.dart'; +import 'package:flutter_web_plugins/url_strategy.dart'; + +import 'common.dart'; + +void main() { + group('$PathUrlStrategy', () { + late TestPlatformLocation location; + + setUp(() { + location = TestPlatformLocation(); + location.baseHref = '/'; + }); + + test('allows null state', () { + final PathUrlStrategy strategy = PathUrlStrategy(location); + expect(() => strategy.pushState(null, '', '/'), returnsNormally); + expect(() => strategy.replaceState(null, '', '/'), returnsNormally); + }); + + test('validates base href', () { + expect( + () => PathUrlStrategy(location), + returnsNormally, + ); + + location.baseHref = '/foo/'; + expect( + () => PathUrlStrategy(location), + returnsNormally, + ); + + location.baseHref = ''; + expect( + () => PathUrlStrategy(location), + throwsException, + ); + + location.baseHref = 'foo'; + expect( + () => PathUrlStrategy(location), + throwsException, + ); + + location.baseHref = '/foo'; + expect( + () => PathUrlStrategy(location), + throwsException, + ); + }); + + test('leading slash is always prepended', () { + final PathUrlStrategy strategy = PathUrlStrategy(location); + + location.pathname = ''; + expect(strategy.getPath(), '/'); + + location.pathname = 'foo'; + expect(strategy.getPath(), '/foo'); + }); + + test('gets path correctly in the presence of basePath', () { + location.baseHref = 'https://example.com/foo/'; + final PathUrlStrategy strategy = PathUrlStrategy(location); + + location.pathname = '/foo/'; + expect(strategy.getPath(), '/'); + + location.pathname = '/foo'; + expect(strategy.getPath(), '/'); + + location.pathname = '/foo/bar'; + expect(strategy.getPath(), '/bar'); + }); + + test('gets path correctly in the presence of query params and omits fragment if no flag specified', () { + location.baseHref = 'https://example.com/foo/'; + location.pathname = '/foo/bar'; + final PathUrlStrategy strategy = PathUrlStrategy(location); + + location.search = '?q=1'; + expect(strategy.getPath(), '/bar?q=1'); + + location.search = '?q=1&t=r'; + expect(strategy.getPath(), '/bar?q=1&t=r'); + + location.hash = '#fragment=1'; + expect(strategy.getPath(), '/bar?q=1&t=r'); + }); + + test('gets path correctly in the presence of query params and fragment', () { + location.baseHref = 'https://example.com/foo/'; + location.pathname = '/foo/bar'; + final PathUrlStrategy strategy = PathUrlStrategy(location, true); + + location.search = '?q=1'; + expect(strategy.getPath(), '/bar?q=1'); + + location.search = '?q=1&t=r'; + expect(strategy.getPath(), '/bar?q=1&t=r'); + + location.hash = '#fragment=1'; + expect(strategy.getPath(), '/bar?q=1&t=r#fragment=1'); + }); + + test('empty route name is ok', () { + final PathUrlStrategy strategy = PathUrlStrategy(location); + expect(strategy.prepareExternalUrl(''), '/'); + expect(() => strategy.pushState(null, '', ''), returnsNormally); + expect(() => strategy.replaceState(null, '', ''), returnsNormally); + }); + + test('route names must start with /', () { + final PathUrlStrategy strategy = PathUrlStrategy(location); + + expect(() => strategy.prepareExternalUrl('foo'), throwsAssertionError); + expect(() => strategy.prepareExternalUrl('foo/'), throwsAssertionError); + expect(() => strategy.prepareExternalUrl('foo/bar'), throwsAssertionError); + + expect(() => strategy.pushState(null, '', 'foo'), throwsAssertionError); + expect(() => strategy.pushState(null, '', 'foo/'), throwsAssertionError); + expect(() => strategy.pushState(null, '', 'foo/bar'), throwsAssertionError); + + expect(() => strategy.replaceState(null, '', 'foo'), throwsAssertionError); + expect(() => strategy.replaceState(null, '', 'foo/'), throwsAssertionError); + expect(() => strategy.replaceState(null, '', 'foo/bar'), throwsAssertionError); + }); + + test('generates external path correctly in the presence of basePath', () { + location.baseHref = 'https://example.com/foo/'; + final PathUrlStrategy strategy = PathUrlStrategy(location); + + expect(strategy.prepareExternalUrl(''), '/foo/'); + expect(strategy.prepareExternalUrl('/'), '/foo/'); + expect(strategy.prepareExternalUrl('/bar'), '/foo/bar'); + expect(strategy.prepareExternalUrl('/bar/'), '/foo/bar/'); + }); + }); +} diff --git a/flutter/packages/flutter_web_plugins/test/navigation/utils_test.dart b/flutter/packages/flutter_web_plugins/test/navigation/utils_test.dart new file mode 100644 index 0000000000000000000000000000000000000000..0bfc64594ecfc02797f1bc2c62d694b63ee5cd2f --- /dev/null +++ b/flutter/packages/flutter_web_plugins/test/navigation/utils_test.dart @@ -0,0 +1,41 @@ +// 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. + +@TestOn('browser') // Uses web-only Flutter SDK +library; + +import 'package:flutter_test/flutter_test.dart'; +import 'package:flutter_web_plugins/src/navigation/utils.dart'; + +void main() { + test('checks base href', () { + expect(() => checkBaseHref(null), throwsException); + expect(() => checkBaseHref('foo'), throwsException); + expect(() => checkBaseHref('/foo'), throwsException); + expect(() => checkBaseHref('foo/bar'), throwsException); + expect(() => checkBaseHref('/foo/bar'), throwsException); + + expect(() => checkBaseHref('/'), returnsNormally); + expect(() => checkBaseHref('/foo/'), returnsNormally); + expect(() => checkBaseHref('/foo/bar/'), returnsNormally); + }); + + test('extracts pathname from URL', () { + expect(extractPathname('/'), '/'); + expect(extractPathname('/foo'), '/foo'); + expect(extractPathname('/foo/'), '/foo/'); + expect(extractPathname('/foo/bar'), '/foo/bar'); + expect(extractPathname('/foo/bar/'), '/foo/bar/'); + + expect(extractPathname('https://example.com'), '/'); + expect(extractPathname('https://example.com/'), '/'); + expect(extractPathname('https://example.com/foo'), '/foo'); + expect(extractPathname('https://example.com/foo#bar'), '/foo'); + expect(extractPathname('https://example.com/foo/#bar'), '/foo/'); + + // URL encoding. + expect(extractPathname('/foo bar'), '/foo%20bar'); + expect(extractPathname('https://example.com/foo bar'), '/foo%20bar'); + }); +} diff --git a/flutter/packages/flutter_web_plugins/test/plugin_event_channel_test.dart b/flutter/packages/flutter_web_plugins/test/plugin_event_channel_test.dart new file mode 100644 index 0000000000000000000000000000000000000000..b43a841bf116c5adad885d26783c8e2d740ccccd --- /dev/null +++ b/flutter/packages/flutter_web_plugins/test/plugin_event_channel_test.dart @@ -0,0 +1,165 @@ +// 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. + +@TestOn('chrome') // Uses web-only Flutter SDK +library; + +import 'dart:async'; +import 'dart:ui_web' as ui_web; + +import 'package:flutter/services.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:flutter_web_plugins/flutter_web_plugins.dart'; + +void main() { + // Disabling tester emulation because this test relies on real message channel communication. + ui_web.debugEmulateFlutterTesterEnvironment = false; + + group('Plugin Event Channel', () { + setUp(() { + TestWidgetsFlutterBinding.ensureInitialized(); + webPluginRegistry.registerMessageHandler(); + }); + + test('can send events to an $EventChannel (deprecated API)', () async { + const EventChannel listeningChannel = EventChannel('test'); + const PluginEventChannel sendingChannel = + PluginEventChannel('test'); + + final StreamController controller = StreamController(); + sendingChannel.setController(controller); + + expect(listeningChannel.receiveBroadcastStream(), + emitsInOrder(['hello', 'world'])); + + controller.add('hello'); + controller.add('world'); + await controller.close(); + }); + + test('can send events to an $EventChannel', () async { + const EventChannel listeningChannel = EventChannel('test'); + const PluginEventChannel sendingChannel = + PluginEventChannel('test'); + + final StreamController controller = StreamController(); + sendingChannel.setController(controller); + + expect(listeningChannel.receiveBroadcastStream(), + emitsInOrder(['hello', 'world'])); + + controller.add('hello'); + controller.add('world'); + await controller.close(); + }); + + test('can send errors to an $EventChannel (deprecated API)', () async { + const EventChannel listeningChannel = EventChannel('test2'); + const PluginEventChannel sendingChannel = + PluginEventChannel('test2'); + + final StreamController controller = StreamController(); + sendingChannel.setController(controller); + + expect( + listeningChannel.receiveBroadcastStream(), + emitsError(predicate((dynamic e) => + e is PlatformException && e.message == 'Test error'))); + + controller.addError('Test error'); + await controller.close(); + }); + + test('can send errors to an $EventChannel', () async { + const EventChannel listeningChannel = EventChannel('test2'); + const PluginEventChannel sendingChannel = + PluginEventChannel('test2'); + + final StreamController controller = StreamController(); + sendingChannel.setController(controller); + + expect( + listeningChannel.receiveBroadcastStream(), + emitsError(predicate((dynamic e) => + e is PlatformException && e.message == 'Test error'))); + + controller.addError('Test error'); + await controller.close(); + }); + + test('receives a listen event (deprecated API)', () async { + const EventChannel listeningChannel = EventChannel('test3'); + const PluginEventChannel sendingChannel = + PluginEventChannel('test3'); + + final StreamController controller = StreamController( + onListen: expectAsync0(() {})); + sendingChannel.setController(controller); + + expect(listeningChannel.receiveBroadcastStream(), + emitsInOrder(['hello'])); + + controller.add('hello'); + await controller.close(); + }); + + test('receives a listen event', () async { + const EventChannel listeningChannel = EventChannel('test3'); + const PluginEventChannel sendingChannel = + PluginEventChannel('test3'); + + final StreamController controller = StreamController( + onListen: expectAsync0(() {})); + sendingChannel.setController(controller); + + expect(listeningChannel.receiveBroadcastStream(), + emitsInOrder(['hello'])); + + controller.add('hello'); + await controller.close(); + }); + + test('receives a cancel event (deprecated API)', () async { + const EventChannel listeningChannel = EventChannel('test4'); + const PluginEventChannel sendingChannel = + PluginEventChannel('test4'); + + final StreamController controller = + StreamController(onCancel: expectAsync0(() {})); + sendingChannel.setController(controller); + + final Stream eventStream = + listeningChannel.receiveBroadcastStream(); + late StreamSubscription subscription; + subscription = + eventStream.listen(expectAsync1((dynamic x) { + expect(x, equals('hello')); + subscription.cancel(); + })); + + controller.add('hello'); + }); + + test('receives a cancel event', () async { + const EventChannel listeningChannel = EventChannel('test4'); + const PluginEventChannel sendingChannel = + PluginEventChannel('test4'); + + final StreamController controller = + StreamController(onCancel: expectAsync0(() {})); + sendingChannel.setController(controller); + + final Stream eventStream = + listeningChannel.receiveBroadcastStream(); + late StreamSubscription subscription; + subscription = + eventStream.listen(expectAsync1((dynamic x) { + expect(x, equals('hello')); + subscription.cancel(); + })); + + controller.add('hello'); + }); + }); +} diff --git a/flutter/packages/flutter_web_plugins/test/plugin_registry_test.dart b/flutter/packages/flutter_web_plugins/test/plugin_registry_test.dart new file mode 100644 index 0000000000000000000000000000000000000000..43d724527e94ab88cfa67a54f07db9097d94caf3 --- /dev/null +++ b/flutter/packages/flutter_web_plugins/test/plugin_registry_test.dart @@ -0,0 +1,76 @@ +// 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. + +@TestOn('chrome') // Uses web-only Flutter SDK +library; + +import 'dart:ui_web' as ui_web; + +import 'package:flutter/services.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:flutter_web_plugins/flutter_web_plugins.dart'; + +class TestPlugin { + static void registerWith(Registrar registrar) { + final MethodChannel channel = MethodChannel( + 'test_plugin', + const StandardMethodCodec(), + registrar.messenger, + ); + final TestPlugin testPlugin = TestPlugin(); + channel.setMethodCallHandler(testPlugin.handleMethodCall); + } + + static final List calledMethods = []; + + Future handleMethodCall(MethodCall call) async { + calledMethods.add(call.method); + } +} + +void main() { + // Disabling tester emulation because this test relies on real message channel communication. + ui_web.debugEmulateFlutterTesterEnvironment = false; + + group('Plugin Registry', () { + setUp(() { + TestWidgetsFlutterBinding.ensureInitialized(); + webPluginRegistry.registerMessageHandler(); + final Registrar registrar = webPluginRegistry.registrarFor(TestPlugin); + TestPlugin.registerWith(registrar); + }); + + test('can register a plugin', () { + TestPlugin.calledMethods.clear(); + + const MethodChannel frameworkChannel = + MethodChannel('test_plugin'); + frameworkChannel.invokeMethod('test1'); + + expect(TestPlugin.calledMethods, equals(['test1'])); + }); + + test('can send a message from the plugin to the framework', () async { + const StandardMessageCodec codec = StandardMessageCodec(); + + final List loggedMessages = []; + ServicesBinding.instance.defaultBinaryMessenger + .setMessageHandler('test_send', (ByteData? data) { + loggedMessages.add(codec.decodeMessage(data)! as String); + return Future.value(); + }); + + await pluginBinaryMessenger.send( + 'test_send', codec.encodeMessage('hello')); + expect(loggedMessages, equals(['hello'])); + + await pluginBinaryMessenger.send( + 'test_send', codec.encodeMessage('world')); + expect(loggedMessages, equals(['hello', 'world'])); + + ServicesBinding.instance.defaultBinaryMessenger + .setMessageHandler('test_send', null); + }); + }); +} diff --git a/flutter/packages/fuchsia_remote_debug_protocol/lib/fuchsia_remote_debug_protocol.dart b/flutter/packages/fuchsia_remote_debug_protocol/lib/fuchsia_remote_debug_protocol.dart new file mode 100644 index 0000000000000000000000000000000000000000..14a193b736a5b9db7d548eb0735fbb6d9a2ea6fa --- /dev/null +++ b/flutter/packages/fuchsia_remote_debug_protocol/lib/fuchsia_remote_debug_protocol.dart @@ -0,0 +1,22 @@ +// 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. + +/// Provides an API to test/debug Flutter applications on remote Fuchsia devices +/// and emulators. +/// +/// The application typically runs in a separate process from the actual +/// test, wherein the user can supply the process with various events to test +/// the behavior of said application. +/// +/// The API will provide methods to connect to one or more instances of the +/// Dart VM and operate on Isolates and Flutter Views, including affordances to +/// subscribe to creation and destruction of Dart VM instances, Isolates, and +/// Flutter Views. Not all of these features are yet implemented, as this +/// library is a work in progress. +library fuchsia_remote_debug_protocol; + +export 'src/common/network.dart'; +export 'src/dart/dart_vm.dart'; +export 'src/fuchsia_remote_connection.dart'; +export 'src/runners/ssh_command_runner.dart'; diff --git a/flutter/packages/fuchsia_remote_debug_protocol/lib/logging.dart b/flutter/packages/fuchsia_remote_debug_protocol/lib/logging.dart new file mode 100644 index 0000000000000000000000000000000000000000..6e665da37db36cd78aa81c97da98f29331cf2790 --- /dev/null +++ b/flutter/packages/fuchsia_remote_debug_protocol/lib/logging.dart @@ -0,0 +1,12 @@ +// 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. + +/// Library for logging the remote debug protocol internals. +/// +/// Useful for determining connection issues and the like. This is included as a +/// separate library so that it can be imported under a separate namespace in +/// the event that you are using a logging package with similar class names. +library logging; + +export 'src/common/logging.dart'; diff --git a/flutter/packages/fuchsia_remote_debug_protocol/lib/src/common/logging.dart b/flutter/packages/fuchsia_remote_debug_protocol/lib/src/common/logging.dart new file mode 100644 index 0000000000000000000000000000000000000000..b2250a745d6e866fdd243a647fbf7c1059bcf80d --- /dev/null +++ b/flutter/packages/fuchsia_remote_debug_protocol/lib/src/common/logging.dart @@ -0,0 +1,149 @@ +// 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:core'; +import 'dart:io'; + +/// Determines the level of logging. +/// +/// Verbosity is increasing from one (none) to five (fine). The sixth level +/// (all) logs everything. +enum LoggingLevel { + /// Logs no logs. + none, + + /// Logs severe messages at the most (severe messages are always logged). + /// + /// Severe means that the process has encountered a critical level of failure + /// in which it cannot recover and will terminate as a result. + severe, + + /// Logs warning messages at the most. + /// + /// Warning implies that an error was encountered, but the process will + /// attempt to continue, and may/may not succeed. + warning, + + /// Logs info messages at the most. + /// + /// An info message is for determining information about the state of the + /// application as it runs through execution. + info, + + /// Logs fine logs at the most. + /// + /// A fine message is one that is not important for logging outside of + /// debugging potential issues in the application. + fine, + + /// Logs everything. + all, +} + +/// Signature of a function that logs a [LogMessage]. +typedef LoggingFunction = void Function(LogMessage log); + +/// The default logging function. +/// +/// Runs the [print] function using the format string: +/// '[${log.levelName}]::${log.tag}--${log.time}: ${log.message}' +/// +/// Exits with status code 1 if the `log` is [LoggingLevel.severe]. +void defaultLoggingFunction(LogMessage log) { + // ignore: avoid_print + print('[${log.levelName}]::${log.tag}--${log.time}: ${log.message}'); + if (log.level == LoggingLevel.severe) { + exit(1); + } +} + +/// Represents a logging message created by the logger. +/// +/// Includes a message, the time the message was created, the level of the log +/// as an enum, the name of the level as a string, and a tag. This class is used +/// to print from the global logging function defined in +/// [Logger.loggingFunction] (a function that can be user-defined). +class LogMessage { + /// Creates a log, including the level of the log, the time it was created, + /// and the actual log message. + /// + /// When this message is created, it sets its [time] to [DateTime.now]. + LogMessage(this.message, this.tag, this.level) + : levelName = level.toString().substring(level.toString().indexOf('.') + 1), + time = DateTime.now(); + + /// The actual log message. + final String message; + + /// The time the log message was created. + final DateTime time; + + /// The level of this log. + final LoggingLevel level; + + /// The human readable level of this log. + final String levelName; + + /// The tag associated with the message. This is set to [Logger.tag] when + /// emitted by a [Logger] object. + final String tag; +} + +/// Logs messages using the global [LoggingFunction] and logging level. +/// +/// Example of setting log level to [LoggingLevel.warning] and creating a +/// logging function: +/// +/// ```dart +/// Logger.globalLevel = LoggingLevel.warning; +/// ``` +class Logger { + /// Creates a logger with the given [tag]. + Logger(this.tag); + + /// The tag associated with the log message (usable in the logging function). + /// [LogMessage] objects emitted by this class will have [LogMessage.tag] set + /// to this value. + final String tag; + + /// Determines what to do when the [Logger] creates and attempts to log a + /// [LogMessage] object. + /// + /// This function can be reassigned to whatever functionality of your + /// choosing, so long as it has the same signature of [LoggingFunction] (it + /// can also be an asynchronous function, if doing file I/O, for + /// example). + static LoggingFunction loggingFunction = defaultLoggingFunction; + + /// Determines the logging level all [Logger] instances use. + static LoggingLevel globalLevel = LoggingLevel.none; + + /// Logs a [LoggingLevel.severe] level `message`. + /// + /// Severe messages are always logged, regardless of what level is set. + void severe(String message) { + loggingFunction(LogMessage(message, tag, LoggingLevel.severe)); + } + + /// Logs a [LoggingLevel.warning] level `message`. + void warning(String message) { + if (globalLevel.index >= LoggingLevel.warning.index) { + loggingFunction(LogMessage(message, tag, LoggingLevel.warning)); + } + } + + /// Logs a [LoggingLevel.info] level `message`. + void info(String message) { + if (globalLevel.index >= LoggingLevel.info.index) { + loggingFunction(LogMessage(message, tag, LoggingLevel.info)); + } + } + + /// Logs a [LoggingLevel.fine] level `message`. + void fine(String message) { + if (globalLevel.index >= LoggingLevel.fine.index) { + loggingFunction(LogMessage(message, tag, LoggingLevel.fine)); + } + } +} diff --git a/flutter/packages/fuchsia_remote_debug_protocol/lib/src/common/network.dart b/flutter/packages/fuchsia_remote_debug_protocol/lib/src/common/network.dart new file mode 100644 index 0000000000000000000000000000000000000000..8033361357e30b9f35af95e1f8705de79a0a488a --- /dev/null +++ b/flutter/packages/fuchsia_remote_debug_protocol/lib/src/common/network.dart @@ -0,0 +1,38 @@ +// 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:core'; + +/// Determines whether `address` is a valid IPv6 or IPv4 address. +/// +/// Throws an [ArgumentError] if the address is neither. +void validateAddress(String address) { + if (!(isIpV4Address(address) || isIpV6Address(address))) { + throw ArgumentError( + '"$address" is neither a valid IPv4 nor IPv6 address'); + } +} + +/// Returns true if `address` is a valid IPv6 address. +bool isIpV6Address(String address) { + try { + // parseIpv6Address fails if there's a zone ID. Since this is still a valid + // IP, remove any zone ID before parsing. + final List addressParts = address.split('%'); + Uri.parseIPv6Address(addressParts[0]); + return true; + } on FormatException { + return false; + } +} + +/// Returns true if `address` is a valid IPv4 address. +bool isIpV4Address(String address) { + try { + Uri.parseIPv4Address(address); + return true; + } on FormatException { + return false; + } +} diff --git a/flutter/packages/fuchsia_remote_debug_protocol/lib/src/dart/dart_vm.dart b/flutter/packages/fuchsia_remote_debug_protocol/lib/src/dart/dart_vm.dart new file mode 100644 index 0000000000000000000000000000000000000000..fe421ad818f70140bb2e9f859a331915597efb19 --- /dev/null +++ b/flutter/packages/fuchsia_remote_debug_protocol/lib/src/dart/dart_vm.dart @@ -0,0 +1,250 @@ +// Copyright 2014 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +import 'dart:async'; +import 'dart:io'; + +import 'package:vm_service/vm_service.dart' as vms; + +import '../common/logging.dart'; + +const Duration _kConnectTimeout = Duration(seconds: 3); +final Logger _log = Logger('DartVm'); + +/// Signature of an asynchronous function for establishing a [vms.VmService] +/// connection to a [Uri]. +typedef RpcPeerConnectionFunction = Future Function( + Uri uri, { + required Duration timeout, +}); + +/// [DartVm] uses this function to connect to the Dart VM on Fuchsia. +/// +/// This function can be assigned to a different one in the event that a +/// custom connection function is needed. +RpcPeerConnectionFunction fuchsiaVmServiceConnectionFunction = _waitAndConnect; + +/// Attempts to connect to a Dart VM service. +/// +/// Gives up after `timeout` has elapsed. +Future _waitAndConnect( + Uri uri, { + Duration timeout = _kConnectTimeout, +}) async { + int attempts = 0; + late WebSocket socket; + while (true) { + try { + socket = await WebSocket.connect(uri.toString()); + final StreamController controller = StreamController(); + final Completer streamClosedCompleter = Completer(); + socket.listen( + (dynamic data) => controller.add(data), + onDone: () => streamClosedCompleter.complete(), + ); + final vms.VmService service = vms.VmService( + controller.stream, + socket.add, + disposeHandler: () => socket.close(), + streamClosed: streamClosedCompleter.future + ); + // This call is to ensure we are able to establish a connection instead of + // keeping on trucking and failing farther down the process. + await service.getVersion(); + return service; + } catch (e) { + // We should not be catching all errors arbitrarily here, this might hide real errors. + // TODO(ianh): Determine which exceptions to catch here. + await socket.close(); + if (attempts > 5) { + _log.warning('It is taking an unusually long time to connect to the VM...'); + } + attempts += 1; + await Future.delayed(timeout); + } + } +} + +/// Restores the VM service connection function to the default implementation. +void restoreVmServiceConnectionFunction() { + fuchsiaVmServiceConnectionFunction = _waitAndConnect; +} + +/// An error raised when a malformed RPC response is received from the Dart VM. +/// +/// A more detailed description of the error is found within the [message] +/// field. +class RpcFormatError extends Error { + /// Basic constructor outlining the reason for the format error. + RpcFormatError(this.message); + + /// The reason for format error. + final String message; + + @override + String toString() { + return '$RpcFormatError: $message\n${super.stackTrace}'; + } +} + +/// Handles JSON RPC-2 communication with a Dart VM service. +/// +/// Either wraps existing RPC calls to the Dart VM service, or runs raw RPC +/// function calls via [invokeRpc]. +class DartVm { + DartVm._(this._vmService, this.uri); + + final vms.VmService _vmService; + + /// The URL through which this DartVM instance is connected. + final Uri uri; + + /// Attempts to connect to the given [Uri]. + /// + /// Throws an error if unable to connect. + static Future connect( + Uri uri, { + Duration timeout = _kConnectTimeout, + }) async { + if (uri.scheme == 'http') { + uri = uri.replace(scheme: 'ws', path: '/ws'); + } + + final vms.VmService service = await fuchsiaVmServiceConnectionFunction(uri, timeout: timeout); + return DartVm._(service, uri); + } + + /// Returns a [List] of [IsolateRef] objects whose name matches `pattern`. + /// + /// This is not limited to Isolates running Flutter, but to any Isolate on the + /// VM. Therefore, the [pattern] argument should be written to exclude + /// matching unintended isolates. + Future> getMainIsolatesByPattern(Pattern pattern) async { + final vms.VM vmRef = await _vmService.getVM(); + final List result = []; + for (final vms.IsolateRef isolateRef in vmRef.isolates!) { + if (pattern.matchAsPrefix(isolateRef.name!) != null) { + _log.fine('Found Isolate matching "$pattern": "${isolateRef.name}"'); + result.add(IsolateRef._fromJson(isolateRef.json!, this)); + } + } + return result; + } + + + /// Returns a list of [FlutterView] objects running across all Dart VM's. + /// + /// If there is no associated isolate with the flutter view (used to determine + /// the flutter view's name), then the flutter view's ID will be added + /// instead. If none of these things can be found (isolate has no name or the + /// flutter view has no ID), then the result will not be added to the list. + Future> getAllFlutterViews() async { + final List views = []; + final vms.Response rpcResponse = await _vmService.callMethod('_flutter.listViews'); + for (final Map jsonView in (rpcResponse.json!['views'] as List).cast>()) { + views.add(FlutterView._fromJson(jsonView)); + } + return views; + } + + /// Tests that the connection to the [vms.VmService] is valid. + Future ping() async { + final vms.Version version = await _vmService.getVersion(); + _log.fine('DartVM($uri) version check result: $version'); + } + + /// Disconnects from the Dart VM Service. + /// + /// After this function completes this object is no longer usable. + Future stop() async { + await _vmService.dispose(); + await _vmService.onDone; + } +} + +/// Represents an instance of a Flutter view running on a Fuchsia device. +class FlutterView { + FlutterView._(this._name, this._id); + + /// Attempts to construct a [FlutterView] from a json representation. + /// + /// If there is no isolate and no ID for the view, throws an [RpcFormatError]. + /// If there is an associated isolate, and there is no name for said isolate, + /// also throws an [RpcFormatError]. + /// + /// All other cases return a [FlutterView] instance. The name of the + /// view may be null, but the id will always be set. + factory FlutterView._fromJson(Map json) { + final Map? isolate = json['isolate'] as Map?; + final String? id = json['id'] as String?; + String? name; + if (id == null) { + throw RpcFormatError( + 'Unable to find view name for the following JSON structure "$json"'); + } + if (isolate != null) { + name = isolate['name'] as String?; + if (name == null) { + throw RpcFormatError('Unable to find name for isolate "$isolate"'); + } + } + return FlutterView._(name, id); + } + + /// Determines the name of the isolate associated with this view. If there is + /// no associated isolate, this will be set to the view's ID. + final String? _name; + + /// The ID of the Flutter view. + final String _id; + + /// The ID of the [FlutterView]. + String get id => _id; + + /// Returns the name of the [FlutterView]. + /// + /// May be null if there is no associated isolate. + String? get name => _name; +} + +/// This is a wrapper class for the `@Isolate` RPC object. +/// +/// See: +/// https://github.com/dart-lang/sdk/blob/main/runtime/vm/service/service.md#isolate +/// +/// This class contains information about the Isolate like its name and ID, as +/// well as a reference to the parent DartVM on which it is running. +class IsolateRef { + IsolateRef._(this.name, this.number, this.dartVm); + + factory IsolateRef._fromJson(Map json, DartVm dartVm) { + final String? number = json['number'] as String?; + final String? name = json['name'] as String?; + final String? type = json['type'] as String?; + if (type == null) { + throw RpcFormatError('Unable to find type within JSON "$json"'); + } + if (type != '@Isolate') { + throw RpcFormatError('Type "$type" does not match for IsolateRef'); + } + if (number == null) { + throw RpcFormatError( + 'Unable to find number for isolate ref within JSON "$json"'); + } + if (name == null) { + throw RpcFormatError( + 'Unable to find name for isolate ref within JSON "$json"'); + } + return IsolateRef._(name, int.parse(number), dartVm); + } + + /// The full name of this Isolate (not guaranteed to be unique). + final String name; + + /// The unique number ID of this isolate. + final int number; + + /// The parent [DartVm] on which this Isolate lives. + final DartVm dartVm; +} diff --git a/flutter/packages/fuchsia_remote_debug_protocol/lib/src/fuchsia_remote_connection.dart b/flutter/packages/fuchsia_remote_debug_protocol/lib/src/fuchsia_remote_connection.dart new file mode 100644 index 0000000000000000000000000000000000000000..d71af2146812d62c0a5dcc04487f6c364f274362 --- /dev/null +++ b/flutter/packages/fuchsia_remote_debug_protocol/lib/src/fuchsia_remote_connection.dart @@ -0,0 +1,715 @@ +// Copyright 2014 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +import 'dart:async'; +import 'dart:convert'; +import 'dart:io'; + +import 'package:process/process.dart'; + +import 'common/logging.dart'; +import 'common/network.dart'; +import 'dart/dart_vm.dart'; +import 'runners/ssh_command_runner.dart'; + +final String _ipv4Loopback = InternetAddress.loopbackIPv4.address; + +final String _ipv6Loopback = InternetAddress.loopbackIPv6.address; + +const ProcessManager _processManager = LocalProcessManager(); + +const Duration _kIsolateFindTimeout = Duration(minutes: 1); + +const Duration _kDartVmConnectionTimeout = Duration(seconds: 9); + +const Duration _kVmPollInterval = Duration(milliseconds: 1500); + +final Logger _log = Logger('FuchsiaRemoteConnection'); + +/// A function for forwarding ports on the local machine to a remote device. +/// +/// Takes a remote `address`, the target device's port, and an optional +/// `interface` and `configFile`. The config file is used primarily for the +/// default SSH port forwarding configuration. +typedef PortForwardingFunction = Future Function( + String address, + int remotePort, [ + String? interface, + String? configFile, +]); + +/// The function for forwarding the local machine's ports to a remote Fuchsia +/// device. +/// +/// Can be overwritten in the event that a different method is required. +/// Defaults to using SSH port forwarding. +PortForwardingFunction fuchsiaPortForwardingFunction = _SshPortForwarder.start; + +/// Sets [fuchsiaPortForwardingFunction] back to the default SSH port forwarding +/// implementation. +void restoreFuchsiaPortForwardingFunction() { + fuchsiaPortForwardingFunction = _SshPortForwarder.start; +} + +/// A general error raised when something fails within a +/// [FuchsiaRemoteConnection]. +class FuchsiaRemoteConnectionError extends Error { + /// Basic constructor outlining the reason for the failure in `message`. + FuchsiaRemoteConnectionError(this.message); + + /// The reason for the failure. + final String message; + + @override + String toString() { + return '$FuchsiaRemoteConnectionError: $message'; + } +} + +/// An enum specifying a Dart VM's state. +enum DartVmEventType { + /// The Dart VM has started. + started, + + /// The Dart VM has stopped. + /// + /// This can mean either the host machine cannot be connect to, the VM service + /// has shut down cleanly, or the VM service has crashed. + stopped, +} + +/// An event regarding the Dart VM. +/// +/// Specifies the type of the event (whether the VM has started or has stopped), +/// and contains the service port of the VM as well as a URL to connect to it. +class DartVmEvent { + DartVmEvent._({required this.eventType, required this.servicePort, required this.uri}); + + /// The URL used to connect to the Dart VM. + final Uri uri; + + /// The type of event regarding this instance of the Dart VM. + final DartVmEventType eventType; + + /// The port on the host machine that the Dart VM service is/was running on. + final int servicePort; +} + +/// Manages a remote connection to a Fuchsia Device. +/// +/// Provides affordances to observe and connect to Flutter views, isolates, and +/// perform actions on the Fuchsia device's various VM services. +/// +/// This class can be connected to several instances of the Fuchsia device's +/// Dart VM at any given time. +class FuchsiaRemoteConnection { + FuchsiaRemoteConnection._(this._useIpV6, this._sshCommandRunner) + : _pollDartVms = false; + + bool _pollDartVms; + final List _forwardedVmServicePorts = []; + final SshCommandRunner _sshCommandRunner; + final bool _useIpV6; + + /// A mapping of Dart VM ports (as seen on the target machine), to + /// [PortForwarder] instances mapping from the local machine to the target + /// machine. + final Map _dartVmPortMap = {}; + + /// Tracks stale ports so as not to reconnect while polling. + final Set _stalePorts = {}; + + /// A broadcast stream that emits events relating to Dart VM's as they update. + Stream get onDartVmEvent => _onDartVmEvent; + late Stream _onDartVmEvent; + final StreamController _dartVmEventController = + StreamController(); + + /// VM service cache to avoid repeating handshakes across function + /// calls. Keys a URI to a DartVm connection instance. + final Map _dartVmCache = {}; + + /// Same as [FuchsiaRemoteConnection.connect] albeit with a provided + /// [SshCommandRunner] instance. + static Future connectWithSshCommandRunner(SshCommandRunner commandRunner) async { + final FuchsiaRemoteConnection connection = FuchsiaRemoteConnection._( + isIpV6Address(commandRunner.address), commandRunner); + await connection._forwardOpenPortsToDeviceServicePorts(); + + Stream dartVmStream() { + Future listen() async { + while (connection._pollDartVms) { + await connection._pollVms(); + await Future.delayed(_kVmPollInterval); + } + connection._dartVmEventController.close(); + } + + connection._dartVmEventController.onListen = listen; + return connection._dartVmEventController.stream.asBroadcastStream(); + } + + connection._onDartVmEvent = dartVmStream(); + return connection; + } + + /// Opens a connection to a Fuchsia device. + /// + /// Accepts an `address` to a Fuchsia device, and optionally a `sshConfigPath` + /// in order to open the associated ssh_config for port forwarding. + /// + /// Will throw an [ArgumentError] if `address` is malformed. + /// + /// Once this function is called, the instance of [FuchsiaRemoteConnection] + /// returned will keep all associated DartVM connections opened over the + /// lifetime of the object. + /// + /// At its current state Dart VM connections will not be added or removed over + /// the lifetime of this object. + /// + /// Throws an [ArgumentError] if the supplied `address` is not valid IPv6 or + /// IPv4. + /// + /// If `address` is IPv6 link local (usually starts with `fe80::`), then + /// `interface` will probably need to be set in order to connect successfully + /// (that being the outgoing interface of your machine, not the interface on + /// the target machine). + /// + /// Attempts to set `address` via the environment variable + /// `FUCHSIA_DEVICE_URL` in the event that the argument is not passed. + /// If `address` is not supplied, `interface` is also ignored, as the format + /// is expected to contain the interface as well (in the event that it is + /// link-local), like the following: + /// + /// ``` + /// fe80::1%eth0 + /// ``` + /// + /// In the event that `FUCHSIA_SSH_CONFIG` is set in the environment, that + /// will be used when `sshConfigPath` isn't supplied. + static Future connect([ + String? address, + String interface = '', + String? sshConfigPath, + ]) async { + address ??= Platform.environment['FUCHSIA_DEVICE_URL']; + sshConfigPath ??= Platform.environment['FUCHSIA_SSH_CONFIG']; + if (address == null) { + throw FuchsiaRemoteConnectionError( + r'No address supplied, and $FUCHSIA_DEVICE_URL not found.'); + } + const String interfaceDelimiter = '%'; + if (address.contains(interfaceDelimiter)) { + final List addressAndInterface = + address.split(interfaceDelimiter); + address = addressAndInterface[0]; + interface = addressAndInterface[1]; + } + + return FuchsiaRemoteConnection.connectWithSshCommandRunner( + SshCommandRunner( + address: address, + interface: interface, + sshConfigPath: sshConfigPath, + ), + ); + } + + /// Closes all open connections. + /// + /// Any objects that this class returns (including any child objects from + /// those objects) will subsequently have its connection closed as well, so + /// behavior for them will be undefined. + Future stop() async { + for (final PortForwarder pf in _forwardedVmServicePorts) { + // Closes VM service first to ensure that the connection is closed cleanly + // on the target before shutting down the forwarding itself. + final Uri uri = _getDartVmUri(pf); + final DartVm? vmService = _dartVmCache[uri]; + _dartVmCache[uri] = null; + await vmService?.stop(); + await pf.stop(); + } + for (final PortForwarder pf in _dartVmPortMap.values) { + final Uri uri = _getDartVmUri(pf); + final DartVm? vmService = _dartVmCache[uri]; + _dartVmCache[uri] = null; + await vmService?.stop(); + await pf.stop(); + } + _dartVmCache.clear(); + _forwardedVmServicePorts.clear(); + _dartVmPortMap.clear(); + _pollDartVms = false; + } + + /// Helper method for [getMainIsolatesByPattern]. + /// + /// Called when either there are no Isolates that exist that match + /// `pattern`, or there are not yet any active Dart VM's on the system + /// (possible when the Isolate we're attempting to connect to is in the only + /// instance of the Dart VM and its service port has not yet opened). + Future> _waitForMainIsolatesByPattern([ + Pattern? pattern, + Duration timeout = _kIsolateFindTimeout, + Duration vmConnectionTimeout = _kDartVmConnectionTimeout, + ]) async { + final Completer> completer = Completer>(); + _onDartVmEvent.listen( + (DartVmEvent event) async { + if (event.eventType == DartVmEventType.started) { + _log.fine('New VM found on port: ${event.servicePort}. Searching ' + 'for Isolate: $pattern'); + final DartVm? vmService = await _getDartVm(event.uri); + // If the VM service is null, set the result to the empty list. + final List result = await vmService?.getMainIsolatesByPattern(pattern!) ?? []; + if (result.isNotEmpty) { + if (!completer.isCompleted) { + completer.complete(result); + } else { + _log.warning('Found more than one Dart VM containing Isolates ' + 'that match the pattern "$pattern".'); + } + } + } + }, + onDone: () { + if (!completer.isCompleted) { + _log.warning('Terminating isolate search for "$pattern"' + ' before timeout reached.'); + } + }, + ); + return completer.future.timeout(timeout); + } + + /// Returns all Isolates running `main()` as matched by the [Pattern]. + /// + /// If there are no live Dart VM's or the Isolate cannot be found, waits until + /// either `timeout` is reached, or a Dart VM starts up with a name that + /// matches `pattern`. + Future> getMainIsolatesByPattern( + Pattern pattern, { + Duration timeout = _kIsolateFindTimeout, + Duration vmConnectionTimeout = _kDartVmConnectionTimeout, + }) async { + // If for some reason there are no Dart VM's that are alive, wait for one to + // start with the Isolate in question. + if (_dartVmPortMap.isEmpty) { + _log.fine('No live Dart VMs found. Awaiting new VM startup'); + return _waitForMainIsolatesByPattern( + pattern, timeout, vmConnectionTimeout); + } + // Accumulate a list of eventual IsolateRef lists so that they can be loaded + // simultaneously via Future.wait. + final List>> isolates = + >>[]; + for (final PortForwarder fp in _dartVmPortMap.values) { + final DartVm? vmService = + await _getDartVm(_getDartVmUri(fp), timeout: vmConnectionTimeout); + if (vmService == null) { + continue; + } + isolates.add(vmService.getMainIsolatesByPattern(pattern)); + } + final List result = + await Future.wait>(isolates) + .timeout(timeout) + .then>((List> listOfLists) { + final List> mutableListOfLists = + List>.from(listOfLists) + ..retainWhere((List list) => list.isNotEmpty); + // Folds the list of lists into one flat list. + return mutableListOfLists.fold>( + [], + (List accumulator, List element) { + accumulator.addAll(element); + return accumulator; + }, + ); + }); + + // If no VM instance anywhere has this, it's possible it hasn't spun up + // anywhere. + // + // For the time being one Flutter Isolate runs at a time in each VM, so for + // now this will wait until the timer runs out or a new Dart VM starts that + // contains the Isolate in question. + // + // TODO(awdavies): Set this up to handle multiple Isolates per Dart VM. + if (result.isEmpty) { + _log.fine('No instance of the Isolate found. Awaiting new VM startup'); + return _waitForMainIsolatesByPattern( + pattern, timeout, vmConnectionTimeout); + } + return result; + } + + /// Returns a list of [FlutterView] objects. + /// + /// This is run across all connected Dart VM connections that this class is + /// managing. + Future> getFlutterViews() async { + if (_dartVmPortMap.isEmpty) { + return []; + } + final List> flutterViewLists = + await _invokeForAllVms>((DartVm vmService) async { + return vmService.getAllFlutterViews(); + }); + final List results = flutterViewLists.fold>( + [], (List acc, List element) { + acc.addAll(element); + return acc; + }); + return List.unmodifiable(results); + } + + // Calls all Dart VM's, returning a list of results. + // + // A side effect of this function is that internally tracked port forwarding + // will be updated in the event that ports are found to be broken/stale: they + // will be shut down and removed from tracking. + Future> _invokeForAllVms( + Future Function(DartVm vmService) vmFunction, [ + bool queueEvents = true, + ]) async { + final List result = []; + + // Helper function loop. + Future shutDownPortForwarder(PortForwarder pf) async { + await pf.stop(); + _stalePorts.add(pf.remotePort); + if (queueEvents) { + _dartVmEventController.add(DartVmEvent._( + eventType: DartVmEventType.stopped, + servicePort: pf.remotePort, + uri: _getDartVmUri(pf), + )); + } + } + + for (final PortForwarder pf in _dartVmPortMap.values) { + final DartVm? service = await _getDartVm(_getDartVmUri(pf)); + if (service == null) { + await shutDownPortForwarder(pf); + } else { + result.add(await vmFunction(service)); + } + } + _stalePorts.forEach(_dartVmPortMap.remove); + return result; + } + + Uri _getDartVmUri(PortForwarder pf) { + String? addr; + if (pf.openPortAddress == null) { + addr = _useIpV6 ? '[$_ipv6Loopback]' : _ipv4Loopback; + } else { + addr = isIpV6Address(pf.openPortAddress!) + ? '[${pf.openPortAddress}]' + : pf.openPortAddress; + } + final Uri uri = Uri.http('$addr:${pf.port}', '/'); + return uri; + } + + /// Attempts to create a connection to a Dart VM. + /// + /// Returns null if either there is an [HttpException] or a + /// [TimeoutException], else a [DartVm] instance. + Future _getDartVm( + Uri uri, { + Duration timeout = _kDartVmConnectionTimeout, + }) async { + if (!_dartVmCache.containsKey(uri)) { + // When raising an HttpException this means that there is no instance of + // the Dart VM to communicate with. The TimeoutException is raised when + // the Dart VM instance is shut down in the middle of communicating. + try { + final DartVm dartVm = await DartVm.connect(uri, timeout: timeout); + _dartVmCache[uri] = dartVm; + } on HttpException { + _log.warning('HTTP Exception encountered connecting to new VM'); + return null; + } on TimeoutException { + _log.warning('TimeoutException encountered connecting to new VM'); + return null; + } + } + return _dartVmCache[uri]; + } + + /// Checks for changes in the list of Dart VM instances. + /// + /// If there are new instances of the Dart VM, then connections will be + /// attempted (after clearing out stale connections). + Future _pollVms() async { + await _checkPorts(); + final List servicePorts = await getDeviceServicePorts(); + for (final int servicePort in servicePorts) { + if (!_stalePorts.contains(servicePort) && + !_dartVmPortMap.containsKey(servicePort)) { + _dartVmPortMap[servicePort] = await fuchsiaPortForwardingFunction( + _sshCommandRunner.address, + servicePort, + _sshCommandRunner.interface, + _sshCommandRunner.sshConfigPath); + + _dartVmEventController.add(DartVmEvent._( + eventType: DartVmEventType.started, + servicePort: servicePort, + uri: _getDartVmUri(_dartVmPortMap[servicePort]!), + )); + } + } + } + + /// Runs a dummy heartbeat command on all Dart VM instances. + /// + /// Removes any failing ports from the cache. + Future _checkPorts([ bool queueEvents = true ]) async { + // Filters out stale ports after connecting. Ignores results. + await _invokeForAllVms( + (DartVm vmService) async { + await vmService.ping(); + }, + queueEvents, + ); + } + + /// Forwards a series of open ports to the remote device. + /// + /// When this function is run, all existing forwarded ports and connections + /// are reset by way of [stop]. + Future _forwardOpenPortsToDeviceServicePorts() async { + await stop(); + final List servicePorts = await getDeviceServicePorts(); + final List forwardedVmServicePorts = + await Future.wait( + servicePorts.map>((int deviceServicePort) { + return fuchsiaPortForwardingFunction( + _sshCommandRunner.address, + deviceServicePort, + _sshCommandRunner.interface, + _sshCommandRunner.sshConfigPath); + })); + + for (final PortForwarder? pf in forwardedVmServicePorts) { + // TODO(awdavies): Handle duplicates. + _dartVmPortMap[pf!.remotePort] = pf; + } + + // Don't queue events, since this is the initial forwarding. + await _checkPorts(false); + + _pollDartVms = true; + } + + /// Helper for getDeviceServicePorts() to extract the vm_service_port from + /// json response. + List getVmServicePortFromInspectSnapshot(dynamic inspectSnapshot) { + final List> snapshot = + List>.from(inspectSnapshot as List); + final List ports = []; + + for (final Map item in snapshot) { + if (!item.containsKey('payload') || item['payload'] == null) { + continue; + } + final Map payload = + Map.from(item['payload'] as Map); + + if (!payload.containsKey('root') || payload['root'] == null) { + continue; + } + final Map root = + Map.from(payload['root'] as Map); + + if (!root.containsKey('vm_service_port') || + root['vm_service_port'] == null) { + continue; + } + + final int? port = int.tryParse(root['vm_service_port'] as String); + if (port != null) { + ports.add(port); + } + } + return ports; + } + + /// Gets the open Dart VM service ports on a remote Fuchsia device. + /// + /// The method attempts to get service ports through an SSH connection. Upon + /// successfully getting the VM service ports, returns them as a list of + /// integers. If an empty list is returned, then no Dart VM instances could be + /// found. An exception is thrown in the event of an actual error when + /// attempting to acquire the ports. + Future> getDeviceServicePorts() async { + final List inspectResult = await _sshCommandRunner + .run("iquery --format json show '**:root:vm_service_port'"); + final dynamic inspectOutputJson = jsonDecode(inspectResult.join('\n')); + final List ports = + getVmServicePortFromInspectSnapshot(inspectOutputJson); + + if (ports.length > 1) { + throw StateError('More than one Flutter observatory port found'); + } + return ports; + } +} + +/// Defines an interface for port forwarding. +/// +/// When a port forwarder is initialized, it is intended to save a port through +/// which a connection is persisted along the lifetime of this object. +/// +/// To shut down a port forwarder you must call the [stop] function. +abstract class PortForwarder { + /// Determines the port which is being forwarded. + int get port; + + /// The address on which the open port is accessible. Defaults to null to + /// indicate local loopback. + String? get openPortAddress => null; + + /// The destination port on the other end of the port forwarding tunnel. + int get remotePort; + + /// Shuts down and cleans up port forwarding. + Future stop(); +} + +/// Instances of this class represent a running SSH tunnel. +/// +/// The SSH tunnel is from the host to a VM service running on a Fuchsia device. +class _SshPortForwarder implements PortForwarder { + _SshPortForwarder._( + this._remoteAddress, + this._remotePort, + this._localSocket, + this._interface, + this._sshConfigPath, + this._ipV6, + ); + + final String _remoteAddress; + final int _remotePort; + final ServerSocket _localSocket; + final String? _sshConfigPath; + final String? _interface; + final bool _ipV6; + + @override + int get port => _localSocket.port; + + @override + String get openPortAddress => _ipV6 ? _ipv6Loopback : _ipv4Loopback; + + @override + int get remotePort => _remotePort; + + /// Starts SSH forwarding through a subprocess, and returns an instance of + /// [_SshPortForwarder]. + static Future<_SshPortForwarder> start( + String address, + int remotePort, [ + String? interface, + String? sshConfigPath, + ]) async { + final bool isIpV6 = isIpV6Address(address); + final ServerSocket? localSocket = await _createLocalSocket(); + if (localSocket == null || localSocket.port == 0) { + _log.warning('_SshPortForwarder failed to find a local port for ' + '$address:$remotePort'); + throw StateError('Unable to create a socket or no available ports.'); + } + // TODO(awdavies): The square-bracket enclosure for using the IPv6 loopback + // didn't appear to work, but when assigning to the IPv4 loopback device, + // netstat shows that the local port is actually being used on the IPv6 + // loopback (::1). Therefore, while the IPv4 loopback can be used for + // forwarding to the destination IPv6 interface, when connecting to the + // websocket, the IPV6 loopback should be used. + final String formattedForwardingUrl = + '${localSocket.port}:$_ipv4Loopback:$remotePort'; + final String targetAddress = + isIpV6 && interface!.isNotEmpty ? '$address%$interface' : address; + const String dummyRemoteCommand = 'true'; + final List command = [ + 'ssh', + if (isIpV6) '-6', + if (sshConfigPath != null) + ...['-F', sshConfigPath], + '-nNT', + '-f', + '-L', + formattedForwardingUrl, + targetAddress, + dummyRemoteCommand, + ]; + _log.fine("_SshPortForwarder running '${command.join(' ')}'"); + // Must await for the port forwarding function to completer here, as + // forwarding must be completed before surfacing VM events (as the user may + // want to connect immediately after an event is surfaced). + final ProcessResult processResult = await _processManager.run(command); + _log.fine("'${command.join(' ')}' exited with exit code " + '${processResult.exitCode}'); + if (processResult.exitCode != 0) { + throw StateError('Unable to start port forwarding'); + } + final _SshPortForwarder result = _SshPortForwarder._( + address, remotePort, localSocket, interface, sshConfigPath, isIpV6); + _log.fine('Set up forwarding from ${localSocket.port} ' + 'to $address port $remotePort'); + return result; + } + + /// Kills the SSH forwarding command, then to ensure no ports are forwarded, + /// runs the SSH 'cancel' command to shut down port forwarding completely. + @override + Future stop() async { + // Cancel the forwarding request. See [start] for commentary about why this + // uses the IPv4 loopback. + final String formattedForwardingUrl = + '${_localSocket.port}:$_ipv4Loopback:$_remotePort'; + final String targetAddress = _ipV6 && _interface!.isNotEmpty + ? '$_remoteAddress%$_interface' + : _remoteAddress; + final String? sshConfigPath = _sshConfigPath; + final List command = [ + 'ssh', + if (sshConfigPath != null) + ...['-F', sshConfigPath], + '-O', + 'cancel', + '-L', + formattedForwardingUrl, + targetAddress, + ]; + _log.fine( + 'Shutting down SSH forwarding with command: ${command.join(' ')}'); + final ProcessResult result = await _processManager.run(command); + if (result.exitCode != 0) { + _log.warning('Command failed:\nstdout: ${result.stdout}' + '\nstderr: ${result.stderr}'); + } + _localSocket.close(); + } + + /// Attempts to find an available port. + /// + /// If successful returns a valid [ServerSocket] (which must be disconnected + /// later). + static Future _createLocalSocket() async { + try { + return await ServerSocket.bind(_ipv4Loopback, 0); + } catch (e) { + // We should not be catching all errors arbitrarily here, this might hide real errors. + // TODO(ianh): Determine which exceptions to catch here. + _log.warning('_createLocalSocket failed: $e'); + return null; + } + } +} diff --git a/flutter/packages/fuchsia_remote_debug_protocol/lib/src/runners/ssh_command_runner.dart b/flutter/packages/fuchsia_remote_debug_protocol/lib/src/runners/ssh_command_runner.dart new file mode 100644 index 0000000000000000000000000000000000000000..23e27ad366099ffca29421579e2919adc1530891 --- /dev/null +++ b/flutter/packages/fuchsia_remote_debug_protocol/lib/src/runners/ssh_command_runner.dart @@ -0,0 +1,103 @@ +// 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:io' show ProcessResult; + +import 'package:meta/meta.dart'; +import 'package:process/process.dart'; + +import '../common/logging.dart'; +import '../common/network.dart'; + +/// An error raised when a command fails to run within the [SshCommandRunner]. +/// +/// This occurs for both connection failures, and for failure to +/// run the command on the remote device. This error is raised when the +/// subprocess running the SSH command returns a nonzero exit code. +class SshCommandError extends Error { + /// Basic constructor outlining the reason for the SSH command failure through + /// the message string. + SshCommandError(this.message); + + /// The reason for the command failure. + final String message; + + @override + String toString() { + return '$SshCommandError: $message\n${super.stackTrace}'; + } +} + +/// Runs commands remotely on a Fuchsia device. +/// +/// Requires a Fuchsia root and build type (to load the ssh config), +/// and the address of the Fuchsia device. +class SshCommandRunner { + /// Instantiates the command runner, pointing to an `address` as well as + /// an optional SSH config file path. + /// + /// If the SSH config path is supplied as an empty string, behavior is + /// undefined. + /// + /// [ArgumentError] is thrown in the event that `address` is neither valid + /// IPv4 nor IPv6. When connecting to a link local address (`fe80::` is + /// usually at the start of the address), an interface should be supplied. + SshCommandRunner({ + required this.address, + this.interface = '', + this.sshConfigPath, + }) : _processManager = const LocalProcessManager() { + validateAddress(address); + } + + /// Private constructor for dependency injection of the process manager. + @visibleForTesting + SshCommandRunner.withProcessManager( + this._processManager, { + required this.address, + this.interface = '', + this.sshConfigPath, + }) { + validateAddress(address); + } + + final Logger _log = Logger('SshCommandRunner'); + + final ProcessManager _processManager; + + /// The IPv4 address to access the Fuchsia machine over SSH. + final String address; + + /// The path to the SSH config (optional). + final String? sshConfigPath; + + /// The name of the machine's network interface (for use with IPv6 + /// connections. Ignored otherwise). + final String interface; + + /// Runs a command on a Fuchsia device through an SSH tunnel. + /// + /// If the subprocess creating the SSH tunnel returns a nonzero exit status, + /// then an [SshCommandError] is raised. + Future> run(String command) async { + final List args = [ + 'ssh', + if (sshConfigPath != null) + ...['-F', sshConfigPath!], + if (isIpV6Address(address)) + ...['-6', if (interface.isEmpty) address else '$address%$interface'] + else + address, + command, + ]; + _log.fine('Running command through SSH: ${args.join(' ')}'); + final ProcessResult result = await _processManager.run(args); + if (result.exitCode != 0) { + throw SshCommandError( + 'Command failed: $command\nstdout: ${result.stdout}\nstderr: ${result.stderr}'); + } + _log.fine('SSH command stdout in brackets:[${result.stdout}]'); + return (result.stdout as String).split('\n'); + } +} diff --git a/flutter/packages/fuchsia_remote_debug_protocol/pubspec.lock b/flutter/packages/fuchsia_remote_debug_protocol/pubspec.lock new file mode 100644 index 0000000000000000000000000000000000000000..48b5a40a957c3d119d595ac157cce7abb26c3e07 --- /dev/null +++ b/flutter/packages/fuchsia_remote_debug_protocol/pubspec.lock @@ -0,0 +1,389 @@ +# Generated by pub +# See https://dart.dev/tools/pub/glossary#lockfile +packages: + _fe_analyzer_shared: + dependency: "direct dev" + description: + name: _fe_analyzer_shared + sha256: "36a321c3d2cbe01cbcb3540a87b8843846e0206df3e691fa7b23e19e78de6d49" + url: "https://pub.dev" + source: hosted + version: "65.0.0" + analyzer: + dependency: "direct dev" + description: + name: analyzer + sha256: dfe03b90ec022450e22513b5e5ca1f01c0c01de9c3fba2f7fd233cb57a6b9a07 + url: "https://pub.dev" + source: hosted + version: "6.3.0" + args: + dependency: "direct dev" + description: + name: args + sha256: eef6c46b622e0494a36c5a12d10d77fb4e855501a91c1b9ef9339326e58f0596 + url: "https://pub.dev" + source: hosted + version: "2.4.2" + async: + dependency: "direct dev" + description: + name: async + sha256: "947bfcf187f74dbc5e146c9eb9c0f10c9f8b30743e341481c1e2ed3ecc18c20c" + url: "https://pub.dev" + source: hosted + version: "2.11.0" + boolean_selector: + dependency: "direct dev" + description: + name: boolean_selector + sha256: "6cfb5af12253eaf2b368f07bacc5a80d1301a071c73360d746b7f2e32d762c66" + url: "https://pub.dev" + source: hosted + version: "2.1.1" + collection: + dependency: "direct dev" + description: + name: collection + sha256: ee67cb0715911d28db6bf4af1026078bd6f0128b07a5f66fb2ed94ec6783c09a + url: "https://pub.dev" + source: hosted + version: "1.18.0" + convert: + dependency: "direct dev" + description: + name: convert + sha256: "0f08b14755d163f6e2134cb58222dd25ea2a2ee8a195e53983d57c075324d592" + url: "https://pub.dev" + source: hosted + version: "3.1.1" + coverage: + dependency: "direct dev" + description: + name: coverage + sha256: "8acabb8306b57a409bf4c83522065672ee13179297a6bb0cb9ead73948df7c76" + url: "https://pub.dev" + source: hosted + version: "1.7.2" + crypto: + dependency: "direct dev" + description: + name: crypto + sha256: ff625774173754681d66daaf4a448684fb04b78f902da9cb3d308c19cc5e8bab + url: "https://pub.dev" + source: hosted + version: "3.0.3" + file: + dependency: "direct main" + description: + name: file + sha256: "5fc22d7c25582e38ad9a8515372cd9a93834027aacf1801cf01164dac0ffa08c" + url: "https://pub.dev" + source: hosted + version: "7.0.0" + frontend_server_client: + dependency: "direct dev" + description: + name: frontend_server_client + sha256: "408e3ca148b31c20282ad6f37ebfa6f4bdc8fede5b74bc2f08d9d92b55db3612" + url: "https://pub.dev" + source: hosted + version: "3.2.0" + glob: + dependency: "direct dev" + description: + name: glob + sha256: "0e7014b3b7d4dac1ca4d6114f82bf1782ee86745b9b42a92c9289c23d8a0ab63" + url: "https://pub.dev" + source: hosted + version: "2.1.2" + http_multi_server: + dependency: "direct dev" + description: + name: http_multi_server + sha256: "97486f20f9c2f7be8f514851703d0119c3596d14ea63227af6f7a481ef2b2f8b" + url: "https://pub.dev" + source: hosted + version: "3.2.1" + http_parser: + dependency: "direct dev" + description: + name: http_parser + sha256: "2aa08ce0341cc9b354a498388e30986515406668dbcc4f7c950c3e715496693b" + url: "https://pub.dev" + source: hosted + version: "4.0.2" + io: + dependency: "direct dev" + description: + name: io + sha256: "2ec25704aba361659e10e3e5f5d672068d332fc8ac516421d483a11e5cbd061e" + url: "https://pub.dev" + source: hosted + version: "1.0.4" + js: + dependency: "direct dev" + description: + name: js + sha256: f2c445dce49627136094980615a031419f7f3eb393237e4ecd97ac15dea343f3 + url: "https://pub.dev" + source: hosted + version: "0.6.7" + logging: + dependency: "direct dev" + description: + name: logging + sha256: "623a88c9594aa774443aa3eb2d41807a48486b5613e67599fb4c41c0ad47c340" + url: "https://pub.dev" + source: hosted + version: "1.2.0" + matcher: + dependency: "direct dev" + 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 dev" + description: + name: mime + sha256: e4ff8e8564c03f255408decd16e7899da1733852a9110a58fe6d1b817684a63e + url: "https://pub.dev" + source: hosted + version: "1.0.4" + 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 dev" + 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" + platform: + dependency: "direct main" + description: + name: platform + sha256: "12220bb4b65720483f8fa9450b4332347737cf8213dd2840d8b2c823e47243ec" + url: "https://pub.dev" + source: hosted + version: "3.1.4" + pool: + dependency: "direct dev" + 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 dev" + description: + name: pub_semver + sha256: "40d3ab1bbd474c4c2328c91e3a7df8c6dd629b79ece4c4bd04bee496a224fb0c" + url: "https://pub.dev" + source: hosted + version: "2.1.4" + shelf: + dependency: "direct dev" + description: + name: shelf + sha256: ad29c505aee705f41a4d8963641f91ac4cee3c8fad5947e033390a7bd8180fa4 + url: "https://pub.dev" + source: hosted + version: "1.4.1" + shelf_packages_handler: + dependency: "direct dev" + description: + name: shelf_packages_handler + sha256: "89f967eca29607c933ba9571d838be31d67f53f6e4ee15147d5dc2934fee1b1e" + url: "https://pub.dev" + source: hosted + version: "3.0.2" + shelf_static: + dependency: "direct dev" + description: + name: shelf_static + sha256: a41d3f53c4adf0f57480578c1d61d90342cd617de7fc8077b1304643c2d85c1e + url: "https://pub.dev" + source: hosted + version: "1.1.2" + shelf_web_socket: + dependency: "direct dev" + description: + name: shelf_web_socket + sha256: "9ca081be41c60190ebcb4766b2486a7d50261db7bd0f5d9615f2d653637a84c1" + url: "https://pub.dev" + source: hosted + version: "1.0.4" + source_map_stack_trace: + dependency: "direct dev" + description: + name: source_map_stack_trace + sha256: "84cf769ad83aa6bb61e0aa5a18e53aea683395f196a6f39c4c881fb90ed4f7ae" + url: "https://pub.dev" + source: hosted + version: "2.1.1" + source_maps: + dependency: "direct dev" + description: + name: source_maps + sha256: "708b3f6b97248e5781f493b765c3337db11c5d2c81c3094f10904bfa8004c703" + url: "https://pub.dev" + source: hosted + version: "0.10.12" + source_span: + dependency: "direct dev" + description: + name: source_span + sha256: "53e943d4206a5e30df338fd4c6e7a077e02254531b138a15aec3bd143c1a8b3c" + url: "https://pub.dev" + source: hosted + version: "1.10.0" + stack_trace: + dependency: "direct dev" + description: + name: stack_trace + sha256: "73713990125a6d93122541237550ee3352a2d84baad52d375a4cad2eb9b7ce0b" + url: "https://pub.dev" + source: hosted + version: "1.11.1" + stream_channel: + dependency: "direct dev" + description: + name: stream_channel + sha256: ba2aa5d8cc609d96bbb2899c28934f9e1af5cddbd60a827822ea467161eb54e7 + url: "https://pub.dev" + source: hosted + version: "2.1.2" + string_scanner: + dependency: "direct dev" + description: + name: string_scanner + sha256: "556692adab6cfa87322a115640c11f13cb77b3f076ddcc5d6ae3c20242bedcde" + url: "https://pub.dev" + source: hosted + version: "1.2.0" + term_glyph: + dependency: "direct dev" + 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 dev" + description: + name: test_api + sha256: "5c2f730018264d276c20e4f1503fd1308dfbbae39ec8ee63c5236311ac06954b" + url: "https://pub.dev" + source: hosted + version: "0.6.1" + test_core: + dependency: "direct dev" + description: + name: test_core + sha256: a757b14fc47507060a162cc2530d9a4a2f92f5100a952c7443b5cad5ef5b106a + url: "https://pub.dev" + source: hosted + version: "0.5.9" + typed_data: + dependency: "direct dev" + description: + name: typed_data + sha256: facc8d6582f16042dd49f2463ff1bd6e2c9ef9f3d5da3d9b087e244a7b564b3c + url: "https://pub.dev" + source: hosted + version: "1.3.2" + vm_service: + dependency: "direct main" + description: + name: vm_service + sha256: b3d56ff4341b8f182b96aceb2fa20e3dcb336b9f867bc0eafc0de10f1048e957 + url: "https://pub.dev" + source: hosted + version: "13.0.0" + watcher: + dependency: "direct dev" + description: + name: watcher + sha256: "3d2ad6751b3c16cf07c7fca317a1413b3f26530319181b37e3b9039b84fc01d8" + url: "https://pub.dev" + source: hosted + version: "1.1.0" + web: + dependency: "direct dev" + description: + name: web + sha256: edc8a9573dd8c5a83a183dae1af2b6fd4131377404706ca4e5420474784906fa + url: "https://pub.dev" + source: hosted + version: "0.4.0" + web_socket_channel: + dependency: "direct dev" + description: + name: web_socket_channel + sha256: "045ec2137c27bf1a32e6ffa0e734d532a6677bf9016a0d1a406c54e499ff945b" + url: "https://pub.dev" + source: hosted + version: "2.4.1" + webkit_inspection_protocol: + dependency: "direct dev" + description: + name: webkit_inspection_protocol + sha256: "87d3f2333bb240704cd3f1c6b5b7acd8a10e7f0bc28c28dcf14e782014f4a572" + url: "https://pub.dev" + source: hosted + version: "1.2.1" + yaml: + dependency: "direct dev" + description: + name: yaml + sha256: "75769501ea3489fca56601ff33454fe45507ea3bfb014161abc3b43ae25989d5" + url: "https://pub.dev" + source: hosted + version: "3.1.2" +sdks: + dart: ">=3.2.0 <4.0.0" diff --git a/flutter/packages/fuchsia_remote_debug_protocol/pubspec.yaml b/flutter/packages/fuchsia_remote_debug_protocol/pubspec.yaml new file mode 100644 index 0000000000000000000000000000000000000000..13d2cf7d6a20631490a807c63135ef80df4bb134 --- /dev/null +++ b/flutter/packages/fuchsia_remote_debug_protocol/pubspec.yaml @@ -0,0 +1,67 @@ +name: fuchsia_remote_debug_protocol +publish_to: none +description: Provides an API to test/debug Flutter applications on remote Fuchsia devices and emulators. +homepage: https://flutter.dev + +environment: + sdk: '>=3.2.0-0 <4.0.0' + +dependencies: + process: 5.0.2 + vm_service: 13.0.0 + + file: 7.0.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" + path: 1.9.0 # 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" + +dev_dependencies: + test: 1.24.9 + + _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" + args: 2.4.2 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" + 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" + collection: 1.18.0 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" + convert: 3.1.1 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" + coverage: 1.7.2 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" + crypto: 3.0.3 # 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_multi_server: 3.2.1 # 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" + logging: 1.2.0 # 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" + mime: 1.0.4 # 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" + package_config: 2.1.0 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" + pool: 1.5.1 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" + pub_semver: 2.1.4 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" + shelf: 1.4.1 # 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_static: 1.1.2 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" + shelf_web_socket: 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" + stack_trace: 1.11.1 # 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" + test_api: 0.6.1 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" + test_core: 0.5.9 # 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" + 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" + web_socket_channel: 2.4.1 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" + webkit_inspection_protocol: 1.2.1 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" + yaml: 3.1.2 # 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: 1c68 diff --git a/flutter/packages/fuchsia_remote_debug_protocol/test/fuchsia_remote_connection_test.dart b/flutter/packages/fuchsia_remote_debug_protocol/test/fuchsia_remote_connection_test.dart new file mode 100644 index 0000000000000000000000000000000000000000..d9c9ea2aa5b4fa02333aba2ab38795c2bfee9d72 --- /dev/null +++ b/flutter/packages/fuchsia_remote_debug_protocol/test/fuchsia_remote_connection_test.dart @@ -0,0 +1,411 @@ +// 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:fuchsia_remote_debug_protocol/fuchsia_remote_debug_protocol.dart'; +import 'package:test/fake.dart'; +import 'package:test/test.dart'; +import 'package:vm_service/vm_service.dart' as vms; + +void main() { + group('FuchsiaRemoteConnection.connect', () { + late List forwardedPorts; + List fakeVmServices; + late List uriConnections; + + setUp(() { + final List> flutterViewCannedResponses = + >[ + { + 'views': >[ + { + 'type': 'FlutterView', + 'id': 'flutterView0', + }, + ], + }, + { + 'views': >[ + { + 'type': 'FlutterView', + 'id': 'flutterView1', + 'isolate': { + 'type': '@Isolate', + 'fixedId': 'true', + 'id': 'isolates/1', + 'name': 'file://flutterBinary1', + 'number': '1', + }, + }, + ], + }, + { + 'views': >[ + { + 'type': 'FlutterView', + 'id': 'flutterView2', + 'isolate': { + 'type': '@Isolate', + 'fixedId': 'true', + 'id': 'isolates/2', + 'name': 'file://flutterBinary2', + 'number': '2', + }, + }, + ], + }, + ]; + + forwardedPorts = []; + fakeVmServices = []; + uriConnections = []; + Future fakeVmConnectionFunction( + Uri uri, { + Duration? timeout, + }) { + return Future(() async { + final FakeVmService service = FakeVmService(); + fakeVmServices.add(service); + uriConnections.add(uri); + service.flutterListViews = vms.Response.parse(flutterViewCannedResponses[uri.port]); + return service; + }); + } + + fuchsiaVmServiceConnectionFunction = fakeVmConnectionFunction; + }); + + tearDown(() { + /// Most tests will fake out the port forwarding and connection + /// functions. + restoreFuchsiaPortForwardingFunction(); + restoreVmServiceConnectionFunction(); + }); + + test('end-to-end with one vm connection and flutter view query', () async { + int port = 0; + Future fakePortForwardingFunction( + String address, + int remotePort, [ + String? interface = '', + String? configFile, + ]) { + return Future(() { + final FakePortForwarder pf = FakePortForwarder(); + forwardedPorts.add(pf); + pf.port = port++; + pf.remotePort = remotePort; + return pf; + }); + } + + fuchsiaPortForwardingFunction = fakePortForwardingFunction; + final FakeSshCommandRunner fakeRunner = FakeSshCommandRunner(); + // Adds some extra junk to make sure the strings will be cleaned up. + fakeRunner.iqueryResponse = [ + '[', + ' {', + ' "data_source": "Inspect",', + ' "metadata": {', + ' "filename": "fuchsia.inspect.Tree",', + ' "component_url": "fuchsia-pkg://fuchsia.com/flutter_runner#meta/flutter_runner.cm",', + ' "timestamp": 12345678901234', + ' },', + ' "moniker": "core/session-manager/session/flutter_runner",', + ' "payload": {', + ' "root": {', + ' "vm_service_port": "12345",', + ' "16859221": {', + ' "empty_tree": "this semantic tree is empty"', + ' },', + ' "build_info": {', + ' "dart_sdk_git_revision": "77e83fcc14fa94049f363d554579f48fbd6bb7a1",', + ' "dart_sdk_semantic_version": "2.19.0-317.0.dev",', + ' "flutter_engine_git_revision": "563b8e830c697a543bf0a8a9f4ae3edfad86ea86",', + ' "fuchsia_sdk_version": "10.20221018.0.1"', + ' },', + ' "vm": {', + ' "dst_status": 1,', + ' "get_profile_status": 0,', + ' "num_get_profile_calls": 1,', + ' "num_intl_provider_errors": 0,', + ' "num_on_change_calls": 0,', + ' "timezone_content_status": 0,', + ' "tz_data_close_status": -1,', + ' "tz_data_status": -1', + ' }', + ' }', + ' },', + ' "version": 1', + ' }', + ' ]' + ]; + fakeRunner.address = 'fe80::8eae:4cff:fef4:9247'; + fakeRunner.interface = 'eno1'; + + final FuchsiaRemoteConnection connection = + await FuchsiaRemoteConnection.connectWithSshCommandRunner(fakeRunner); + + expect(forwardedPorts.length, 1); + expect(forwardedPorts[0].remotePort, 12345); + + // VMs should be accessed via localhost ports given by + // [fakePortForwardingFunction]. + expect(uriConnections[0], + Uri(scheme: 'ws', host: '[::1]', port: 0, path: '/ws')); + + final List views = await connection.getFlutterViews(); + expect(views, isNot(null)); + expect(views.length, 1); + // Since name can be null, check for the ID on all of them. + expect(views[0].id, 'flutterView0'); + + expect(views[0].name, equals(null)); + + // Ensure the ports are all closed after stop was called. + await connection.stop(); + expect(forwardedPorts[0].stopped, true); + }); + + test('end-to-end with one vm and remote open port', () async { + int port = 0; + Future fakePortForwardingFunction( + String address, + int remotePort, [ + String? interface = '', + String? configFile, + ]) { + return Future(() { + final FakePortForwarder pf = FakePortForwarder(); + forwardedPorts.add(pf); + pf.port = port++; + pf.remotePort = remotePort; + pf.openPortAddress = 'fe80::1:2%eno2'; + return pf; + }); + } + + fuchsiaPortForwardingFunction = fakePortForwardingFunction; + final FakeSshCommandRunner fakeRunner = FakeSshCommandRunner(); + // Adds some extra junk to make sure the strings will be cleaned up. + fakeRunner.iqueryResponse = [ + '[', + ' {', + ' "data_source": "Inspect",', + ' "metadata": {', + ' "filename": "fuchsia.inspect.Tree",', + ' "component_url": "fuchsia-pkg://fuchsia.com/flutter_runner#meta/flutter_runner.cm",', + ' "timestamp": 12345678901234', + ' },', + ' "moniker": "core/session-manager/session/flutter_runner",', + ' "payload": {', + ' "root": {', + ' "vm_service_port": "12345",', + ' "16859221": {', + ' "empty_tree": "this semantic tree is empty"', + ' },', + ' "build_info": {', + ' "dart_sdk_git_revision": "77e83fcc14fa94049f363d554579f48fbd6bb7a1",', + ' "dart_sdk_semantic_version": "2.19.0-317.0.dev",', + ' "flutter_engine_git_revision": "563b8e830c697a543bf0a8a9f4ae3edfad86ea86",', + ' "fuchsia_sdk_version": "10.20221018.0.1"', + ' },', + ' "vm": {', + ' "dst_status": 1,', + ' "get_profile_status": 0,', + ' "num_get_profile_calls": 1,', + ' "num_intl_provider_errors": 0,', + ' "num_on_change_calls": 0,', + ' "timezone_content_status": 0,', + ' "tz_data_close_status": -1,', + ' "tz_data_status": -1', + ' }', + ' }', + ' },', + ' "version": 1', + ' }', + ' ]' + ]; + fakeRunner.address = 'fe80::8eae:4cff:fef4:9247'; + fakeRunner.interface = 'eno1'; + final FuchsiaRemoteConnection connection = + await FuchsiaRemoteConnection.connectWithSshCommandRunner(fakeRunner); + + expect(forwardedPorts.length, 1); + expect(forwardedPorts[0].remotePort, 12345); + + // VMs should be accessed via the alternate address given by + // [fakePortForwardingFunction]. + expect(uriConnections[0], + Uri(scheme: 'ws', host: '[fe80::1:2%25eno2]', port: 0, path: '/ws')); + + final List views = await connection.getFlutterViews(); + expect(views, isNot(null)); + expect(views.length, 1); + // Since name can be null, check for the ID on all of them. + expect(views[0].id, 'flutterView0'); + + expect(views[0].name, equals(null)); + + // Ensure the ports are all closed after stop was called. + await connection.stop(); + expect(forwardedPorts[0].stopped, true); + }); + + test('end-to-end with one vm and ipv4', () async { + int port = 0; + Future fakePortForwardingFunction( + String address, + int remotePort, [ + String? interface = '', + String? configFile, + ]) { + return Future(() { + final FakePortForwarder pf = FakePortForwarder(); + forwardedPorts.add(pf); + pf.port = port++; + pf.remotePort = remotePort; + return pf; + }); + } + + fuchsiaPortForwardingFunction = fakePortForwardingFunction; + final FakeSshCommandRunner fakeRunner = FakeSshCommandRunner(); + // Adds some extra junk to make sure the strings will be cleaned up. + fakeRunner.iqueryResponse = [ + '[', + ' {', + ' "data_source": "Inspect",', + ' "metadata": {', + ' "filename": "fuchsia.inspect.Tree",', + ' "component_url": "fuchsia-pkg://fuchsia.com/flutter_runner#meta/flutter_runner.cm",', + ' "timestamp": 12345678901234', + ' },', + ' "moniker": "core/session-manager/session/flutter_runner",', + ' "payload": {', + ' "root": {', + ' "vm_service_port": "12345",', + ' "16859221": {', + ' "empty_tree": "this semantic tree is empty"', + ' },', + ' "build_info": {', + ' "dart_sdk_git_revision": "77e83fcc14fa94049f363d554579f48fbd6bb7a1",', + ' "dart_sdk_semantic_version": "2.19.0-317.0.dev",', + ' "flutter_engine_git_revision": "563b8e830c697a543bf0a8a9f4ae3edfad86ea86",', + ' "fuchsia_sdk_version": "10.20221018.0.1"', + ' },', + ' "vm": {', + ' "dst_status": 1,', + ' "get_profile_status": 0,', + ' "num_get_profile_calls": 1,', + ' "num_intl_provider_errors": 0,', + ' "num_on_change_calls": 0,', + ' "timezone_content_status": 0,', + ' "tz_data_close_status": -1,', + ' "tz_data_status": -1', + ' }', + ' }', + ' },', + ' "version": 1', + ' }', + ' ]' + ]; + fakeRunner.address = '196.168.1.4'; + + final FuchsiaRemoteConnection connection = + await FuchsiaRemoteConnection.connectWithSshCommandRunner(fakeRunner); + + expect(forwardedPorts.length, 1); + expect(forwardedPorts[0].remotePort, 12345); + + // VMs should be accessed via the ipv4 loopback. + expect(uriConnections[0], + Uri(scheme: 'ws', host: '127.0.0.1', port: 0, path: '/ws')); + + final List views = await connection.getFlutterViews(); + expect(views, isNot(null)); + expect(views.length, 1); + // Since name can be null, check for the ID on all of them. + expect(views[0].id, 'flutterView0'); + + expect(views[0].name, equals(null)); + + // Ensure the ports are all closed after stop was called. + await connection.stop(); + expect(forwardedPorts[0].stopped, true); + }); + + test('env variable test without remote addr', () async { + Future failingFunction() async { + await FuchsiaRemoteConnection.connect(); + } + + // Should fail as no env variable has been passed. + expect(failingFunction, + throwsA(isA())); + }); + }); +} + +class FakeSshCommandRunner extends Fake implements SshCommandRunner { + List? iqueryResponse; + @override + Future> run(String command) async { + if (command.startsWith('iquery --format json show')) { + return iqueryResponse!; + } + throw UnimplementedError(command); + } + + @override + String interface = ''; + + @override + String address = ''; + + @override + String get sshConfigPath => '~/.ssh'; +} + +class FakePortForwarder extends Fake implements PortForwarder { + @override + int port = 0; + + @override + int remotePort = 0; + + @override + String? openPortAddress; + + bool stopped = false; + @override + Future stop() async { + stopped = true; + } +} + +class FakeVmService extends Fake implements vms.VmService { + bool disposed = false; + vms.Response? flutterListViews; + + @override + Future dispose() async { + disposed = true; + } + + @override + Future callMethod(String method, {String? isolateId, Map? args}) async { + if (method == '_flutter.listViews') { + return flutterListViews!; + } + throw UnimplementedError(method); + } + + @override + Future onDone = Future.value(); + + @override + Future getVersion() async { + return vms.Version(major: -1, minor: -1); + } +} diff --git a/flutter/packages/fuchsia_remote_debug_protocol/test/src/common/network_test.dart b/flutter/packages/fuchsia_remote_debug_protocol/test/src/common/network_test.dart new file mode 100644 index 0000000000000000000000000000000000000000..bb75c7206f923439a12517b69560b6c1204064ca --- /dev/null +++ b/flutter/packages/fuchsia_remote_debug_protocol/test/src/common/network_test.dart @@ -0,0 +1,28 @@ +// 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:fuchsia_remote_debug_protocol/src/common/network.dart'; + +import 'package:test/test.dart'; + +void main() { + final List ipv4Addresses = ['127.0.0.1', '8.8.8.8']; + final List ipv6Addresses = [ + '::1', + 'fe80::8eae:4cff:fef4:9247', + 'fe80::8eae:4cff:fef4:9247%e0', + ]; + + group('test validation', () { + test('isIpV4Address', () { + expect(ipv4Addresses.map(isIpV4Address), everyElement(isTrue)); + expect(ipv6Addresses.map(isIpV4Address), everyElement(isFalse)); + }); + + test('isIpV6Address', () { + expect(ipv4Addresses.map(isIpV6Address), everyElement(isFalse)); + expect(ipv6Addresses.map(isIpV6Address), everyElement(isTrue)); + }); + }); +} diff --git a/flutter/packages/fuchsia_remote_debug_protocol/test/src/dart/dart_vm_test.dart b/flutter/packages/fuchsia_remote_debug_protocol/test/src/dart/dart_vm_test.dart new file mode 100644 index 0000000000000000000000000000000000000000..21bbb0513089125a840e62744a25a6952f10e730 --- /dev/null +++ b/flutter/packages/fuchsia_remote_debug_protocol/test/src/dart/dart_vm_test.dart @@ -0,0 +1,334 @@ +// 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:fuchsia_remote_debug_protocol/src/dart/dart_vm.dart'; +import 'package:test/fake.dart'; +import 'package:test/test.dart'; +import 'package:vm_service/vm_service.dart' as vms; + +void main() { + group('DartVm.connect', () { + tearDown(() { + restoreVmServiceConnectionFunction(); + }); + + test('disconnect closes peer', () async { + final FakeVmService service = FakeVmService(); + Future fakeServiceFunction( + Uri uri, { + Duration? timeout, + }) { + return Future(() => service); + } + + fuchsiaVmServiceConnectionFunction = fakeServiceFunction; + final DartVm vm = + await DartVm.connect(Uri.parse('http://this.whatever/ws')); + expect(vm, isNot(null)); + await vm.stop(); + expect(service.disposed, true); + }); + }); + + group('DartVm.getAllFlutterViews', () { + late FakeVmService fakeService; + + setUp(() { + fakeService = FakeVmService(); + }); + + tearDown(() { + restoreVmServiceConnectionFunction(); + }); + + test('basic flutter view parsing', () async { + final Map flutterViewCannedResponses = { + 'views': >[ + { + 'type': 'FlutterView', + 'id': 'flutterView0', + }, + { + 'type': 'FlutterView', + 'id': 'flutterView1', + 'isolate': { + 'type': '@Isolate', + 'fixedId': 'true', + 'id': 'isolates/1', + 'name': 'file://flutterBinary1', + 'number': '1', + }, + }, + { + 'type': 'FlutterView', + 'id': 'flutterView2', + 'isolate': { + 'type': '@Isolate', + 'fixedId': 'true', + 'id': 'isolates/2', + 'name': 'file://flutterBinary2', + 'number': '2', + }, + }, + ], + }; + + Future fakeVmConnectionFunction( + Uri uri, { + Duration? timeout, + }) { + fakeService.flutterListViews = + vms.Response.parse(flutterViewCannedResponses); + return Future(() => fakeService); + } + + fuchsiaVmServiceConnectionFunction = fakeVmConnectionFunction; + final DartVm vm = + await DartVm.connect(Uri.parse('http://whatever.com/ws')); + expect(vm, isNot(null)); + final List views = await vm.getAllFlutterViews(); + expect(views.length, 3); + // Check ID's as they cannot be null. + expect(views[0].id, 'flutterView0'); + expect(views[1].id, 'flutterView1'); + expect(views[2].id, 'flutterView2'); + + // Verify names. + expect(views[0].name, equals(null)); + expect(views[1].name, 'file://flutterBinary1'); + expect(views[2].name, 'file://flutterBinary2'); + }); + + test('basic flutter view parsing with casting checks', () async { + final Map flutterViewCannedResponses = { + 'views': [ + { + 'type': 'FlutterView', + 'id': 'flutterView0', + }, + { + 'type': 'FlutterView', + 'id': 'flutterView1', + 'isolate': { + 'type': '@Isolate', + 'fixedId': 'true', + 'id': 'isolates/1', + 'name': 'file://flutterBinary1', + 'number': '1', + }, + }, + { + 'type': 'FlutterView', + 'id': 'flutterView2', + 'isolate': { + 'type': '@Isolate', + 'fixedId': 'true', + 'id': 'isolates/2', + 'name': 'file://flutterBinary2', + 'number': '2', + }, + }, + ], + }; + + Future fakeVmConnectionFunction( + Uri uri, { + Duration? timeout, + }) { + fakeService.flutterListViews = + vms.Response.parse(flutterViewCannedResponses); + return Future(() => fakeService); + } + + fuchsiaVmServiceConnectionFunction = fakeVmConnectionFunction; + final DartVm vm = + await DartVm.connect(Uri.parse('http://whatever.com/ws')); + expect(vm, isNot(null)); + final List views = await vm.getAllFlutterViews(); + expect(views.length, 3); + // Check ID's as they cannot be null. + expect(views[0].id, 'flutterView0'); + expect(views[1].id, 'flutterView1'); + expect(views[2].id, 'flutterView2'); + + // Verify names. + expect(views[0].name, equals(null)); + expect(views[1].name, 'file://flutterBinary1'); + expect(views[2].name, 'file://flutterBinary2'); + }); + + test('invalid flutter view missing ID', () async { + final Map flutterViewCannedResponseMissingId = + { + 'views': >[ + // Valid flutter view. + { + 'type': 'FlutterView', + 'id': 'flutterView1', + 'isolate': { + 'type': '@Isolate', + 'name': 'IsolateThing', + 'fixedId': 'true', + 'id': 'isolates/1', + 'number': '1', + }, + }, + + // Missing ID. + { + 'type': 'FlutterView', + }, + ], + }; + + Future fakeVmConnectionFunction( + Uri uri, { + Duration? timeout, + }) { + fakeService.flutterListViews = + vms.Response.parse(flutterViewCannedResponseMissingId); + return Future(() => fakeService); + } + + fuchsiaVmServiceConnectionFunction = fakeVmConnectionFunction; + final DartVm vm = + await DartVm.connect(Uri.parse('http://whatever.com/ws')); + expect(vm, isNot(null)); + Future failingFunction() async { + await vm.getAllFlutterViews(); + } + + // Both views should be invalid as they were missing required fields. + expect(failingFunction, throwsA(isA())); + }); + + test('get isolates by pattern', () async { + final List isolates = [ + vms.IsolateRef.parse({ + 'type': '@Isolate', + 'fixedId': 'true', + 'id': 'isolates/1', + 'name': 'file://thingThatWillNotMatch:main()', + 'number': '1', + })!, + vms.IsolateRef.parse({ + 'type': '@Isolate', + 'fixedId': 'true', + 'id': 'isolates/2', + 'name': '0:dart_name_pattern()', + 'number': '2', + })!, + vms.IsolateRef.parse({ + 'type': '@Isolate', + 'fixedId': 'true', + 'id': 'isolates/3', + 'name': 'flutterBinary.cm', + 'number': '3', + })!, + vms.IsolateRef.parse({ + 'type': '@Isolate', + 'fixedId': 'true', + 'id': 'isolates/4', + 'name': '0:some_other_dart_name_pattern()', + 'number': '4', + })!, + ]; + + Future fakeVmConnectionFunction( + Uri uri, { + Duration? timeout, + }) { + fakeService.vm = FakeVM(isolates: isolates); + return Future(() => fakeService); + } + + fuchsiaVmServiceConnectionFunction = fakeVmConnectionFunction; + final DartVm vm = + await DartVm.connect(Uri.parse('http://whatever.com/ws')); + expect(vm, isNot(null)); + final List matchingFlutterIsolates = + await vm.getMainIsolatesByPattern('flutterBinary.cm'); + expect(matchingFlutterIsolates.length, 1); + final List allIsolates = + await vm.getMainIsolatesByPattern(''); + expect(allIsolates.length, 4); + }); + + test('invalid flutter view missing ID', () async { + final Map flutterViewCannedResponseMissingIsolateName = + { + 'views': >[ + // Missing isolate name. + { + 'type': 'FlutterView', + 'id': 'flutterView1', + 'isolate': { + 'type': '@Isolate', + 'fixedId': 'true', + 'id': 'isolates/1', + 'number': '1', + }, + }, + ], + }; + + Future fakeVmConnectionFunction( + Uri uri, { + Duration? timeout, + }) { + fakeService.flutterListViews = + vms.Response.parse(flutterViewCannedResponseMissingIsolateName); + return Future(() => fakeService); + } + + fuchsiaVmServiceConnectionFunction = fakeVmConnectionFunction; + final DartVm vm = + await DartVm.connect(Uri.parse('http://whatever.com/ws')); + expect(vm, isNot(null)); + Future failingFunction() async { + await vm.getAllFlutterViews(); + } + + // Both views should be invalid as they were missing required fields. + expect(failingFunction, throwsA(isA())); + }); + }); +} + +class FakeVmService extends Fake implements vms.VmService { + bool disposed = false; + vms.Response? flutterListViews; + vms.VM? vm; + + @override + Future getVM() async => vm!; + + @override + Future dispose() async { + disposed = true; + } + + @override + Future callMethod(String method, + {String? isolateId, Map? args}) async { + if (method == '_flutter.listViews') { + return flutterListViews!; + } + throw UnimplementedError(method); + } + + @override + Future onDone = Future.value(); +} + +class FakeVM extends Fake implements vms.VM { + FakeVM({ + this.isolates = const [], + }); + + @override + List? isolates; +} diff --git a/flutter/packages/fuchsia_remote_debug_protocol/test/src/runners/ssh_command_runner_test.dart b/flutter/packages/fuchsia_remote_debug_protocol/test/src/runners/ssh_command_runner_test.dart new file mode 100644 index 0000000000000000000000000000000000000000..7cb70aedd7ae5d3218778fb720a1d0db890feda1 --- /dev/null +++ b/flutter/packages/fuchsia_remote_debug_protocol/test/src/runners/ssh_command_runner_test.dart @@ -0,0 +1,146 @@ +// 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 'dart:io' show ProcessResult, systemEncoding; + +import 'package:fuchsia_remote_debug_protocol/src/runners/ssh_command_runner.dart'; +import 'package:process/process.dart'; +import 'package:test/fake.dart'; + +import 'package:test/test.dart'; + +void main() { + group('SshCommandRunner.constructors', () { + test('throws exception with invalid address', () async { + SshCommandRunner newCommandRunner() { + return SshCommandRunner(address: 'sillyaddress.what'); + } + + expect(newCommandRunner, throwsArgumentError); + }); + + test('throws exception from injection constructor with invalid addr', () async { + SshCommandRunner newCommandRunner() { + return SshCommandRunner.withProcessManager( + const LocalProcessManager(), + address: '192.168.1.1.1'); + } + + expect(newCommandRunner, throwsArgumentError); + }); + }); + + group('SshCommandRunner.run', () { + late FakeProcessManager fakeProcessManager; + SshCommandRunner runner; + + setUp(() { + fakeProcessManager = FakeProcessManager(); + }); + + test('verify interface is appended to ipv6 address', () async { + const String ipV6Addr = 'fe80::8eae:4cff:fef4:9247'; + const String interface = 'eno1'; + runner = SshCommandRunner.withProcessManager( + fakeProcessManager, + address: ipV6Addr, + interface: interface, + sshConfigPath: '/whatever', + ); + fakeProcessManager.fakeResult = ProcessResult(23, 0, 'somestuff', null); + await runner.run('ls /whatever'); + expect(fakeProcessManager.runCommands.single, contains('$ipV6Addr%$interface')); + }); + + test('verify no percentage symbol is added when no ipv6 interface', () async { + const String ipV6Addr = 'fe80::8eae:4cff:fef4:9247'; + runner = SshCommandRunner.withProcessManager( + fakeProcessManager, + address: ipV6Addr, + ); + fakeProcessManager.fakeResult = ProcessResult(23, 0, 'somestuff', null); + await runner.run('ls /whatever'); + expect(fakeProcessManager.runCommands.single, contains(ipV6Addr)); + }); + + test('verify commands are split into multiple lines', () async { + const String addr = '192.168.1.1'; + runner = SshCommandRunner.withProcessManager(fakeProcessManager, + address: addr); + fakeProcessManager.fakeResult = ProcessResult( + 23, + 0, + ''' + this + has + four + lines''', + null); + final List result = await runner.run('oihaw'); + expect(result, hasLength(4)); + }); + + test('verify exception on nonzero process result exit code', () async { + const String addr = '192.168.1.1'; + runner = SshCommandRunner.withProcessManager(fakeProcessManager, + address: addr); + fakeProcessManager.fakeResult = ProcessResult(23, 1, 'whatever', null); + Future failingFunction() async { + await runner.run('oihaw'); + } + + expect(failingFunction, throwsA(isA())); + }); + + test('verify correct args with config', () async { + const String addr = 'fe80::8eae:4cff:fef4:9247'; + const String config = '/this/that/this/and/uh'; + runner = SshCommandRunner.withProcessManager( + fakeProcessManager, + address: addr, + sshConfigPath: config, + ); + fakeProcessManager.fakeResult = ProcessResult(23, 0, 'somestuff', null); + await runner.run('ls /whatever'); + final List passedCommand = fakeProcessManager.runCommands.single as List; + expect(passedCommand, contains('-F')); + final int indexOfFlag = passedCommand.indexOf('-F'); + final String? passedConfig = passedCommand[indexOfFlag + 1]; + expect(passedConfig, config); + }); + + test('verify config is excluded correctly', () async { + const String addr = 'fe80::8eae:4cff:fef4:9247'; + runner = SshCommandRunner.withProcessManager( + fakeProcessManager, + address: addr, + ); + fakeProcessManager.fakeResult = ProcessResult(23, 0, 'somestuff', null); + await runner.run('ls /whatever'); + final List passedCommand = fakeProcessManager.runCommands.single as List; + final int indexOfFlag = passedCommand.indexOf('-F'); + expect(indexOfFlag, equals(-1)); + }); + }); +} + +class FakeProcessManager extends Fake implements ProcessManager { + ProcessResult? fakeResult; + + List> runCommands = >[]; + + @override + Future run(List command, { + String? workingDirectory, + Map? environment, + bool includeParentEnvironment = true, + bool runInShell = false, + Encoding? stdoutEncoding = systemEncoding, + Encoding? stderrEncoding = systemEncoding, + }) async { + runCommands.add(command); + return fakeResult!; + } +} diff --git a/flutter/packages/integration_test/CHANGELOG.md b/flutter/packages/integration_test/CHANGELOG.md new file mode 100644 index 0000000000000000000000000000000000000000..d92de4f2494bcc81c4334b6d6350252f2d544ad4 --- /dev/null +++ b/flutter/packages/integration_test/CHANGELOG.md @@ -0,0 +1,228 @@ +# CHANGELOG + +This changelog was discontinued after version 0.9.2+2, when the package started +to vend from the Flutter SDK rather than pub. + +It is maintained here for historical purposes only. + +## 0.9.2+2 + +* Broaden the constraint on vm_service. + +## 0.9.2+1 + +* Update android compileSdkVersion to 29. + +## 0.9.2 + +* Add `watchPerformance` for performance test. + +## 0.9.1 + +* Keep handling deprecated Android v1 classes for backward compatibility. + +## 0.9.0 + +* Add screenshot capability to web tests. + +## 0.8.2 + +* Add support to get timeline. + +## 0.8.1 + +* Show stack trace of widget test errors on the platform side +* Fix method channel name for iOS + +## 0.8.0 + +* Rename plugin to integration_test. + +## 0.7.0 + +* Move utilities for tracking frame performance in an e2e test to `flutter_test`. + +## 0.6.3 + +* Add customizable `flutter_driver` adaptor. +* Add utilities for tracking frame performance in an e2e test. + +## 0.6.2+1 + +* Fix incorrect test results when one test passes then another fails + +## 0.6.2 + +* Fix `setSurfaceSize` for e2e tests + +## 0.6.1 + +* Added `data` in the reported json. + +## 0.6.0 + +* **Breaking change** `E2EPlugin` exports a `Future` for `testResults`. + +## 0.5.0+1 + +* Fixed the device pixel ratio problem. + +## 0.5.0 + +* **Breaking change** by default, tests will use the device window size. + Tests can still override the window size by using the `setSurfaceSize` method. +* **Breaking change** If using Flutter 1.19.0-2.0.pre.196 or greater, the + `testTextInput` will no longer automatically register. +* **Breaking change** If using Flutter 1.19.0-2.0.pre.196 or greater, the + `HttpOverrides` will no longer be set by default. +* Minor formatting changes to Dart code. + +## 0.4.3+3 + +* Fixed code snippet in readme that referenced a non-existent `result` variable. + +## 0.4.3+2 + +* Bumps AGP to 3.6.3 +* Changes android-retrofuture dependency type to "implementation" + +## 0.4.3+1 + +* Post-v2 Android embedding cleanup. + +## 0.4.3 + +* Uses CompletableFuture from android-retrofuture allow compatibility with API < 24. + +## 0.4.2 + +* Adds support for Android E2E tests that utilize other @Rule's, like GrantPermissionRule. +* Fix CocoaPods podspec lint warnings. + +## 0.4.1 + +* Remove Android dependencies fallback. +* Require Flutter SDK 1.12.13+hotfix.5 or greater. + +## 0.4.0 + +* **Breaking change** Driver request_data call's response has changed to + encapsulate the failure details. +* Details for failure cases are added: failed method name, stack trace. + +## 0.3.0+1 + +* Replace deprecated `getFlutterEngine` call on Android. + +## 0.3.0 + +* Updates documentation to instruct developers not to launch the activity since + we are doing it for them. +* Renames `FlutterRunner` to `FlutterTestRunner` to avoid conflict with Fuchsia. + +## 0.2.4+4 + +* Fixed a hang that occurred on platforms that don't have a `MethodChannel` listener registered.. + +## 0.2.4+3 + +* Fixed code snippet in the readme under the "Using Flutter driver to run tests" section. + +## 0.2.4+2 + +* Make the pedantic dev_dependency explicit. + +## 0.2.4+1 + +* Registering web service extension for using e2e with web. + +## 0.2.4 + +* Fixed problem with XCTest in XCode 11.3 where the testing bundles were getting + opened multiple times which interfered with the singleton logic for E2EPlugin. + +## 0.2.3+1 + +* Added a driver test for failure behavior. + +## 0.2.3 + +* Updates `E2EPlugin` and add skeleton iOS test case `E2EIosTest`. +* Adds instructions to README.md about e2e testing on iOS devices. +* Adds iOS e2e testing to example. + +## 0.2.2+3 + +* Remove the deprecated `author:` field from pubspec.yaml +* Migrate the plugin to the pubspec platforms manifest. +* Require Flutter SDK 1.10.0 or greater. + +## 0.2.2+2 + +* Adds an android dummy project to silence warnings and removes unnecessary + .gitignore files. + +## 0.2.2+1 + +* Fix pedantic lints. Adds a missing await in the example test and some missing + documentation. + +## 0.2.2 + +* Added a stub macos implementation +* Added a macos example + +## 0.2.1+1 + +* Updated README. + +## 0.2.1 + +* Support the v2 Android embedder. +* Print a warning if the plugin is not registered. +* Updated method channel name. +* Set a Flutter minimum SDK version. + +## 0.2.0+1 + +* Updated README. + +## 0.2.0 + +* Renamed package from instrumentation_adapter to e2e. +* Refactored example app test. +* **Breaking change**. Renamed `InstrumentationAdapterFlutterBinding` to + `IntegrationTestWidgetsFlutterBinding`. +* Updated README. + +## 0.1.4 + +* Migrate example to AndroidX. +* Define clang module for iOS. + +## 0.1.3 + +* Added example app. +* Added stub iOS implementation. +* Updated README. +* No longer throws errors when running tests on the host. + +## 0.1.2 + +* Added support for running tests using Flutter driver. + +## 0.1.1 + +* Updates about using *androidx* library. + +## 0.1.0 + +* Update boilerplate test to use `@Rule` instead of `FlutterTest`. + +## 0.0.2 + +* Document current usage instructions, which require adding a Java test file. + +## 0.0.1 + +* Initial release diff --git a/flutter/packages/integration_test/README.md b/flutter/packages/integration_test/README.md new file mode 100644 index 0000000000000000000000000000000000000000..305fad32417f4b2ffdd8c4bad2aba2c59abe2d3d --- /dev/null +++ b/flutter/packages/integration_test/README.md @@ -0,0 +1,348 @@ +# integration_test + +This package enables self-driving testing of Flutter code on devices and emulators. +It adapts flutter_test results into a format that is compatible with `flutter drive` +and native Android instrumentation testing. + +## Usage + +Add a dependency on the `integration_test` and `flutter_test` package in the +`dev_dependencies` section of `pubspec.yaml`. For plugins, do this in the +`pubspec.yaml` of the example app: + +```yaml +dev_dependencies: + integration_test: + sdk: flutter + flutter_test: + sdk: flutter +``` + +Create a `integration_test/` directory for your package. In this directory, +create a `_test.dart`, using the following as a starting point to make +assertions. + +```dart +import 'package:flutter_test/flutter_test.dart'; +import 'package:integration_test/integration_test.dart'; + +void main() { + IntegrationTestWidgetsFlutterBinding.ensureInitialized(); + + testWidgets("failing test example", (WidgetTester tester) async { + expect(2 + 2, equals(5)); + }); +} +``` + +### Driver Entrypoint + +An accompanying driver script will be needed that can be shared across all +integration tests. Create a file named `integration_test.dart` in the +`test_driver/` directory with the following contents: + +```dart +import 'package:integration_test/integration_test_driver.dart'; + +Future main() => integrationDriver(); +``` + +You can also use different driver scripts to customize the behavior of the app +under test. For example, `FlutterDriver` can also be parameterized with +different [options](https://api.flutter.dev/flutter/flutter_driver/FlutterDriver/connect.html). +See the [extended driver](https://github.com/flutter/flutter/blob/master/packages/integration_test/example/test_driver/extended_integration_test.dart) for an example. + +### Package Structure + +Your package should have a structure that looks like this: + +``` +lib/ + ... +integration_test/ + foo_test.dart + bar_test.dart +test/ + # Other unit tests go here. +test_driver/ + integration_test.dart +``` + +[Example](https://github.com/flutter/flutter/tree/master/packages/integration_test/example) + +## Using Flutter Driver to Run Tests + +These tests can be launched with the `flutter drive` command. + +To run the `integration_test/foo_test.dart` test with the +`test_driver/integration_test.dart` driver, use the following command: + +```sh +flutter drive \ + --driver=test_driver/integration_test.dart \ + --target=integration_test/foo_test.dart +``` + +### Web + +Make sure you have [enabled web support](https://flutter.dev/docs/get-started/web#set-up) +then [download and run](https://docs.flutter.dev/cookbook/testing/integration/introduction#5b-web) +the web driver in another process. + +Use following command to execute the tests: + +```sh +flutter drive \ + --driver=test_driver/integration_test.dart \ + --target=integration_test/foo_test.dart \ + -d web-server +``` + +### Screenshots + +You can use `integration_test` to take screenshots of the UI rendered on the mobile device or +Web browser at a specific time during the test. + +This feature is currently supported on Android, iOS, and Web. + +#### Android and iOS + +**integration_test/screenshot_test.dart** + +```dart +void main() { + final binding = IntegrationTestWidgetsFlutterBinding.ensureInitialized() + as IntegrationTestWidgetsFlutterBinding; + + testWidgets('screenshot', (WidgetTester tester) async { + // Build the app. + app.main(); + + // This is required prior to taking the screenshot (Android only). + await binding.convertFlutterSurfaceToImage(); + + // Trigger a frame. + await tester.pumpAndSettle(); + await binding.takeScreenshot('screenshot-1'); + }); +} +``` + +You can use a driver script to pull in the screenshot from the device. +This way, you can store the images locally on your computer. On iOS, the +screenshot will also be available in Xcode test results. + +**test_driver/integration_test.dart** + +```dart +import 'dart:io'; +import 'package:integration_test/integration_test_driver_extended.dart'; + +Future main() async { + await integrationDriver( + onScreenshot: (String screenshotName, List screenshotBytes, [Map? args]) async { + final File image = File('$screenshotName.png'); + image.writeAsBytesSync(screenshotBytes); + // Return false if the screenshot is invalid. + return true; + }, + ); +} +``` + +#### Web + +**integration_test/screenshot_test.dart** + +```dart +void main() { + final binding = IntegrationTestWidgetsFlutterBinding.ensureInitialized() + as IntegrationTestWidgetsFlutterBinding; + + testWidgets('screenshot', (WidgetTester tester) async { + // Build the app. + app.main(); + + // Trigger a frame. + await tester.pumpAndSettle(); + await binding.takeScreenshot('screenshot-1'); + }); +} +``` + +## Android Device Testing + +Create an instrumentation test file in your application's +**android/app/src/androidTest/java/com/example/myapp/** directory (replacing +com, example, and myapp with values from your app's package name). You can name +this test file `MainActivityTest.java` or another name of your choice. + +```java +package com.example.myapp; + +import androidx.test.rule.ActivityTestRule; +import dev.flutter.plugins.integration_test.FlutterTestRunner; +import org.junit.Rule; +import org.junit.runner.RunWith; + +@RunWith(FlutterTestRunner.class) +public class MainActivityTest { + @Rule + public ActivityTestRule rule = new ActivityTestRule<>(MainActivity.class, true, false); +} +``` + +Update your application's **myapp/android/app/build.gradle** to make sure it +uses androidx's version of `AndroidJUnitRunner` and has androidx libraries as a +dependency. + +```gradle +android { + ... + defaultConfig { + ... + testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner" + } +} + +dependencies { + testImplementation 'junit:junit:4.12' + + // https://developer.android.com/jetpack/androidx/releases/test/#1.2.0 + androidTestImplementation 'androidx.test:runner:1.2.0' + androidTestImplementation 'androidx.test.espresso:espresso-core:3.2.0' +} +``` + +To run `integration_test/foo_test.dart` on a local Android device (emulated or +physical): + +```sh +./gradlew app:connectedAndroidTest -Ptarget=`pwd`/../integration_test/foo_test.dart +``` + +Note: +To use `--dart-define` with `gradlew` you must `base64` encode all parameters, +and pass them to gradle in a comma separated list: +```bash +./gradlew project:task -Pdart-defines="{base64(key=value)},[...]" +``` + +## Firebase Test Lab + +If this is your first time testing with Firebase Test Lab, you'll need to follow +the guides in the [Firebase test lab +documentation](https://firebase.google.com/docs/test-lab/?gclid=EAIaIQobChMIs5qVwqW25QIV8iCtBh3DrwyUEAAYASAAEgLFU_D_BwE) +to set up a project. + +To run a test on Android devices using Firebase Test Lab, use gradle commands to build an +instrumentation test for Android, after creating `androidTest` as suggested in the last section. + +```bash +pushd android +# flutter build generates files in android/ for building the app +flutter build apk +./gradlew app:assembleAndroidTest +./gradlew app:assembleDebug -Ptarget=.dart +popd +``` + +Upload the build apks Firebase Test Lab, making sure to replace , +, , and with your values. + +```bash +gcloud auth activate-service-account --key-file= +gcloud --quiet config set project +gcloud firebase test android run --type instrumentation \ + --app build/app/outputs/apk/debug/app-debug.apk \ + --test build/app/outputs/apk/androidTest/debug/app-debug-androidTest.apk\ + --timeout 2m \ + --results-bucket= \ + --results-dir= +``` + +You can pass additional parameters on the command line, such as the +devices you want to test on. See +[gcloud firebase test android run](https://cloud.google.com/sdk/gcloud/reference/firebase/test/android/run). + +## iOS Device Testing + +Open `ios/Runner.xcworkspace` in Xcode. Create a test target if you +do not already have one via `File > New > Target...` and select `Unit Testing Bundle`. +Change the `Product Name` to `RunnerTests`. Make sure `Target to be Tested` is set to `Runner` and language is set to `Objective-C`. +Select `Finish`. +Make sure that the **iOS Deployment Target** of `RunnerTests` within the **Build Settings** section is the same as `Runner`. + +Add the new test target to `ios/Podfile` by embedding in the existing `Runner` target. + +```ruby +target 'Runner' do + # Do not change existing lines. + ... + + target 'RunnerTests' do + inherit! :search_paths + end +end +``` + +To build `integration_test/foo_test.dart` from the command line, run: + +```sh +flutter build ios --config-only integration_test/foo_test.dart +``` + +In Xcode, add a test file called `RunnerTests.m` (or any name of your choice) to the new target and +replace the file: + +```objective-c +@import XCTest; +@import integration_test; + +INTEGRATION_TEST_IOS_RUNNER(RunnerTests) +``` + +Run `Product > Test` to run the integration tests on your selected device. + +To deploy it to Firebase Test Lab you can follow these steps: + +Execute this script at the root of your Flutter app: + +```sh +output="../build/ios_integ" +product="build/ios_integ/Build/Products" +dev_target="14.3" + +# Pass --simulator if building for the simulator. +flutter build ios integration_test/foo_test.dart --release + +pushd ios +xcodebuild build-for-testing \ + -workspace Runner.xcworkspace \ + -scheme Runner \ + -xcconfig Flutter/Release.xcconfig \ + -configuration Release \ + -derivedDataPath \ + $output -sdk iphoneos +popd + +pushd $product +zip -r "ios_tests.zip" "Release-iphoneos" "Runner_iphoneos$dev_target-arm64.xctestrun" +popd +``` + +You can verify locally that your tests are successful by running the following command: + +```sh +xcodebuild test-without-building \ + -xctestrun "build/ios_integ/Build/Products/Runner_iphoneos14.3-arm64.xctestrun" \ + -destination id= +``` + +Once everything is ok, you can upload the resulting zip to Firebase Test Lab (change the model with your values): + +```sh +gcloud firebase test ios run \ + --test "build/ios_integ/Build/Products/ios_tests.zip" \ + --device model=iphone11pro,version=14.1,locale=fr_FR,orientation=portrait +``` diff --git a/flutter/packages/integration_test/analysis_options.yaml b/flutter/packages/integration_test/analysis_options.yaml new file mode 100644 index 0000000000000000000000000000000000000000..e61f982d45eb553b34c11630b746f0a798cd5b8d --- /dev/null +++ b/flutter/packages/integration_test/analysis_options.yaml @@ -0,0 +1,5 @@ +include: ../analysis_options.yaml + +analyzer: + exclude: + - "test_fixes/**" diff --git a/flutter/packages/integration_test/android/build.gradle b/flutter/packages/integration_test/android/build.gradle new file mode 100644 index 0000000000000000000000000000000000000000..2323c87695254d298a68293a32e480fa196b8be7 --- /dev/null +++ b/flutter/packages/integration_test/android/build.gradle @@ -0,0 +1,64 @@ +// 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. + +group 'dev.flutter.plugins.integration_test' +version '1.0-SNAPSHOT' + +buildscript { + repositories { + google() + mavenCentral() + } + + dependencies { + classpath 'com.android.tools.build:gradle:7.3.1' + } +} + +rootProject.allprojects { + repositories { + google() + mavenCentral() + } +} + +// project.getTasks().withType(JavaCompile){ +// options.compilerArgs << "-Xlint:all" << "-Werror" +// } + +apply plugin: 'com.android.library' + +android { + // Conditional for compatibility with AGP <4.2. + if (project.android.hasProperty("namespace")) { + namespace 'dev.flutter.integration_test' + } + + compileSdk 34 + + compileOptions { + sourceCompatibility JavaVersion.VERSION_1_8 + targetCompatibility JavaVersion.VERSION_1_8 + } + + defaultConfig { + minSdkVersion 19 + testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner" + consumerProguardFiles 'lib-proguard-rules.txt' + } + + dependencies { + // TODO(egarciad): These dependencies should not be added to release builds. + // https://github.com/flutter/flutter/issues/56591 + testImplementation 'junit:junit:4.12' + testImplementation 'org.mockito:mockito-inline:5.0.0' + + // https://developer.android.com/jetpack/androidx/releases/test/#1.2.0 + api 'androidx.test:runner:1.2.0' + api 'androidx.test:rules:1.2.0' + api 'androidx.test.espresso:espresso-core:3.2.0' + + implementation 'com.google.guava:guava:28.1-android' + } +} diff --git a/flutter/packages/integration_test/android/gradle.properties b/flutter/packages/integration_test/android/gradle.properties new file mode 100644 index 0000000000000000000000000000000000000000..95b4763a84734b3e3051bec5b9dfd02825c5cb14 --- /dev/null +++ b/flutter/packages/integration_test/android/gradle.properties @@ -0,0 +1 @@ +org.gradle.jvmargs=-Xmx4G diff --git a/flutter/packages/integration_test/android/lib-proguard-rules.txt b/flutter/packages/integration_test/android/lib-proguard-rules.txt new file mode 100644 index 0000000000000000000000000000000000000000..fb96b5604097bc0c86f7c12cce20fd85c264e127 --- /dev/null +++ b/flutter/packages/integration_test/android/lib-proguard-rules.txt @@ -0,0 +1,5 @@ +# For some reason org.kxml2.io.KXmlParser and org.kxml2.io.KXmlSerializer +# are missing and not marked correctly by dependencies. +# Possibly related to https://github.com/flutter/flutter/issues/56591 +# See https://github.com/flutter/flutter/issues/127388 for more context. +-dontwarn org.kxml2.io.KXmlParser**,org.kxml2.io.KXmlSerializer** \ No newline at end of file diff --git a/flutter/packages/integration_test/android/settings.gradle b/flutter/packages/integration_test/android/settings.gradle new file mode 100644 index 0000000000000000000000000000000000000000..29941fd33e6e63217198e4478b5c10d3b3db78a1 --- /dev/null +++ b/flutter/packages/integration_test/android/settings.gradle @@ -0,0 +1,5 @@ +// 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. + +rootProject.name = 'integrationTest' diff --git a/flutter/packages/integration_test/android/src/main/AndroidManifest.xml b/flutter/packages/integration_test/android/src/main/AndroidManifest.xml new file mode 100644 index 0000000000000000000000000000000000000000..76ada4d34cdad097c8f6a8d51a7c012be43525d8 --- /dev/null +++ b/flutter/packages/integration_test/android/src/main/AndroidManifest.xml @@ -0,0 +1,7 @@ + + + + diff --git a/flutter/packages/integration_test/android/src/main/java/dev/flutter/plugins/integration_test/FlutterDeviceScreenshot.java b/flutter/packages/integration_test/android/src/main/java/dev/flutter/plugins/integration_test/FlutterDeviceScreenshot.java new file mode 100644 index 0000000000000000000000000000000000000000..5b376b0277be2f4cb20a6df6440280a38d68f6a6 --- /dev/null +++ b/flutter/packages/integration_test/android/src/main/java/dev/flutter/plugins/integration_test/FlutterDeviceScreenshot.java @@ -0,0 +1,272 @@ +// 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. + +package dev.flutter.plugins.integration_test; + +import android.annotation.TargetApi; +import android.app.Activity; +import android.graphics.Bitmap; +import android.graphics.Canvas; +import android.graphics.Rect; +import android.os.Build; +import android.os.Handler; +import android.os.HandlerThread; +import android.os.Looper; +import android.view.Choreographer; +import android.view.PixelCopy; +import android.view.View; +import android.view.ViewGroup; +import androidx.annotation.NonNull; +import androidx.annotation.Nullable; +import androidx.annotation.VisibleForTesting; + +import io.flutter.embedding.android.FlutterActivity; +import io.flutter.embedding.android.FlutterFragment; +import io.flutter.embedding.android.FlutterFragmentActivity; +import io.flutter.embedding.android.FlutterSurfaceView; +import io.flutter.embedding.android.FlutterView; +import io.flutter.plugin.common.MethodChannel; +import io.flutter.plugin.common.MethodChannel.Result; +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.lang.StringBuilder; + +/** + * FlutterDeviceScreenshot is a utility class that allows to capture a screenshot + * that includes both Android views and the Flutter UI. + * + * To take screenshots, the rendering surface must be changed to {@code FlutterImageView}, + * since surfaces like {@code FlutterSurfaceView} and {@code FlutterTextureView} are opaque + * when the view hierarchy is rendered to a bitmap. + * + * It's also necessary to ask the framework to schedule a frame, and then add a listener + * that waits for that frame to be presented by the Android framework. + */ +@TargetApi(19) +class FlutterDeviceScreenshot { + /** + * Finds the {@code FlutterView} added to the {@code activity} view hierarchy. + * + *

This assumes that there's only one {@code FlutterView} per activity, which + * is always the case. + * + * @param activity typically, {code FlutterActivity}. + * @return the Flutter view. + */ + @Nullable + @VisibleForTesting + public static FlutterView getFlutterView(@NonNull Activity activity) { + if (activity instanceof FlutterActivity) { + return (FlutterView)activity.findViewById(FlutterActivity.FLUTTER_VIEW_ID); + } else if (activity instanceof FlutterFragmentActivity) { + return (FlutterView)activity.findViewById(FlutterFragment.FLUTTER_VIEW_ID); + } else { + return null; + } + } + + /** + * Whether the app is run with instrumentation. + * + * @return true if the app is running with instrumentation. + */ + static boolean hasInstrumentation() { + // TODO(egarciad): InstrumentationRegistry requires the uiautomator dependency. + // However, Flutter adds test dependencies to release builds. + // As a result, disable screenshots with instrumentation until the issue is fixed. + // https://github.com/flutter/flutter/issues/56591 + return false; + } + + /** + * Captures a screenshot using ui automation. + * + * @return byte array containing the screenshot. + */ + static byte[] captureWithUiAutomation() throws IOException { + return new byte[0]; + } + + // Whether the flutter surface is already converted to an image. + private static boolean flutterSurfaceConvertedToImage = false; + + /** + * Converts the Flutter surface to an image view. + * This allows to render the view hierarchy to a bitmap since + * {@code FlutterSurfaceView} and {@code FlutterTextureView} cannot be rendered to a bitmap. + * + * @param activity typically {@code FlutterActivity}. + */ + static void convertFlutterSurfaceToImage(@NonNull Activity activity) { + final FlutterView flutterView = getFlutterView(activity); + if (flutterView != null && !flutterSurfaceConvertedToImage) { + flutterView.convertToImageView(); + flutterSurfaceConvertedToImage = true; + } + } + + /** + * Restores the original Flutter surface. + * The new surface will either be {@code FlutterSurfaceView} or {@code FlutterTextureView}. + * + * @param activity typically {@code FlutterActivity}. + */ + static void revertFlutterImage(@NonNull Activity activity) { + final FlutterView flutterView = getFlutterView(activity); + if (flutterView != null && flutterSurfaceConvertedToImage) { + flutterView.revertImageView(() -> { + flutterSurfaceConvertedToImage = false; + }); + } + } + + // Handlers used to capture a view. + private static Handler backgroundHandler; + private static Handler mainHandler; + + /** + * Captures a screenshot by drawing the view to a Canvas. + * + *

{@code convertFlutterSurfaceToImage} must be called prior to capturing the view, + * otherwise the result is an error. + * + * @param activity this is {@link FlutterActivity}. + * @param methodChannel the method channel to call into Dart. + * @param result the result for the method channel that will contain the byte array. + */ + static void captureView( + @NonNull Activity activity, @NonNull MethodChannel methodChannel, @NonNull Result result) { + final FlutterView flutterView = getFlutterView(activity); + if (flutterView == null) { + result.error("Could not copy the pixels", "FlutterView is null", null); + return; + } + if (!flutterSurfaceConvertedToImage) { + result.error("Could not copy the pixels", "Flutter surface must be converted to image first", null); + return; + } + + // Ask the framework to schedule a new frame. + methodChannel.invokeMethod("scheduleFrame", null); + + if (backgroundHandler == null) { + final HandlerThread screenshotBackgroundThread = new HandlerThread("screenshot"); + screenshotBackgroundThread.start(); + backgroundHandler = new Handler(screenshotBackgroundThread.getLooper()); + } + if (mainHandler == null) { + mainHandler = new Handler(Looper.getMainLooper()); + } + takeScreenshot(backgroundHandler, mainHandler, flutterView, result); + } + + /** + * Waits for the next Android frame. + * + * @param r a callback. + */ + private static void waitForAndroidFrame(Runnable r) { + Choreographer.getInstance() + .postFrameCallback( + new Choreographer.FrameCallback() { + @Override + public void doFrame(long frameTimeNanos) { + r.run(); + } + }); + } + + /** + * Waits until a Flutter frame is rendered by the Android OS. + * + * @param backgroundHandler the handler associated to a background thread. + * @param mainHandler the handler associated to the platform thread. + * @param view the flutter view. + * @param result the result that contains the byte array. + */ + private static void takeScreenshot( + @NonNull Handler backgroundHandler, + @NonNull Handler mainHandler, + @NonNull FlutterView view, + @NonNull Result result) { + final boolean acquired = view.acquireLatestImageViewFrame(); + // The next frame may already have already been committed. + // The next frame is guaranteed to have the Flutter image. + waitForAndroidFrame( + () -> { + waitForAndroidFrame( + () -> { + if (acquired) { + FlutterDeviceScreenshot.convertViewToBitmap(view, result, backgroundHandler); + } else { + takeScreenshot(backgroundHandler, mainHandler, view, result); + } + }); + }); + } + + /** + * Renders {@code FlutterView} to a Bitmap. + * + * If successful, The byte array is provided in the result. + * + * @param flutterView the Flutter view. + * @param result the result that contains the byte array. + * @param backgroundHandler a background handler to avoid blocking the platform thread. + */ + private static void convertViewToBitmap( + @NonNull FlutterView flutterView, @NonNull Result result, @NonNull Handler backgroundHandler) { + if (Build.VERSION.SDK_INT < Build.VERSION_CODES.O) { + final Bitmap bitmap = + Bitmap.createBitmap( + flutterView.getWidth(), flutterView.getHeight(), Bitmap.Config.RGB_565); + final Canvas canvas = new Canvas(bitmap); + flutterView.draw(canvas); + + final ByteArrayOutputStream output = new ByteArrayOutputStream(); + bitmap.compress(Bitmap.CompressFormat.PNG, /*quality=*/ 100, output); + result.success(output.toByteArray()); + return; + } + + final Bitmap bitmap = + Bitmap.createBitmap( + flutterView.getWidth(), flutterView.getHeight(), Bitmap.Config.ARGB_8888); + + final int[] flutterViewLocation = new int[2]; + flutterView.getLocationInWindow(flutterViewLocation); + final int flutterViewLeft = flutterViewLocation[0]; + final int flutterViewTop = flutterViewLocation[1]; + + final Rect flutterViewRect = + new Rect( + flutterViewLeft, + flutterViewTop, + flutterViewLeft + flutterView.getWidth(), + flutterViewTop + flutterView.getHeight()); + + final Activity flutterActivity = (Activity) flutterView.getContext(); + PixelCopy.request( + flutterActivity.getWindow(), + flutterViewRect, + bitmap, + (int copyResult) -> { + final Handler mainHandler = new Handler(Looper.getMainLooper()); + if (copyResult == PixelCopy.SUCCESS) { + final ByteArrayOutputStream output = new ByteArrayOutputStream(); + bitmap.compress(Bitmap.CompressFormat.PNG, /*quality=*/ 100, output); + mainHandler.post( + () -> { + result.success(output.toByteArray()); + }); + } else { + mainHandler.post( + () -> { + result.error("Could not copy the pixels", "result was " + copyResult, null); + }); + } + }, + backgroundHandler); + } +} diff --git a/flutter/packages/integration_test/android/src/main/java/dev/flutter/plugins/integration_test/FlutterTestRunner.java b/flutter/packages/integration_test/android/src/main/java/dev/flutter/plugins/integration_test/FlutterTestRunner.java new file mode 100644 index 0000000000000000000000000000000000000000..84a9b2353eeab153a0ca5eda7b44b4460e036365 --- /dev/null +++ b/flutter/packages/integration_test/android/src/main/java/dev/flutter/plugins/integration_test/FlutterTestRunner.java @@ -0,0 +1,90 @@ +// 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. + +package dev.flutter.plugins.integration_test; + +import android.util.Log; +import androidx.test.rule.ActivityTestRule; +import java.lang.reflect.Field; +import java.lang.reflect.InvocationTargetException; +import java.util.Map; +import java.util.concurrent.ExecutionException; +import org.junit.Rule; +import org.junit.rules.TestRule; +import org.junit.runner.Description; +import org.junit.runner.Runner; +import org.junit.runner.notification.Failure; +import org.junit.runner.notification.RunNotifier; + +public class FlutterTestRunner extends Runner { + + private static final String TAG = "FlutterTestRunner"; + + final Class testClass; + TestRule rule = null; + + public FlutterTestRunner(Class testClass) { + super(); + this.testClass = testClass; + + // Look for an `ActivityTestRule` annotated `@Rule` and invoke `launchActivity()` + Field[] fields = testClass.getDeclaredFields(); + for (Field field : fields) { + if (field.isAnnotationPresent(Rule.class)) { + try { + Object instance = testClass.getDeclaredConstructor().newInstance(); + if (field.get(instance) instanceof ActivityTestRule) { + rule = (TestRule) field.get(instance); + break; + } + } catch (InvocationTargetException | NoSuchMethodException e) { + throw new RuntimeException("Unable to contruct " + testClass.getName() + " object for testing"); + } catch (InstantiationException | IllegalAccessException e) { + // This might occur if the developer did not make the rule public. + // We could call field.setAccessible(true) but it seems better to throw. + throw new RuntimeException("Unable to access activity rule", e); + } + } + } + } + + @Override + public Description getDescription() { + return Description.createTestDescription(testClass, "Flutter Tests"); + } + + @Override + public void run(RunNotifier notifier) { + if (rule == null) { + throw new RuntimeException("Unable to run tests due to missing activity rule"); + } + try { + if (rule instanceof ActivityTestRule) { + ((ActivityTestRule) rule).launchActivity(null); + } + } catch (RuntimeException e) { + Log.v(TAG, "launchActivity failed, possibly because the activity was already running. " + e); + Log.v( + TAG, + "Try disabling auto-launch of the activity, e.g. ActivityTestRule<>(MainActivity.class, true, false);"); + } + Map results = null; + try { + results = IntegrationTestPlugin.testResults.get(); + } catch (ExecutionException | InterruptedException e) { + throw new IllegalThreadStateException("Unable to get test results"); + } + + for (String name : results.keySet()) { + Description d = Description.createTestDescription(testClass, name); + notifier.fireTestStarted(d); + String outcome = results.get(name); + if (!outcome.equals("success")) { + Exception dummyException = new Exception(outcome); + notifier.fireTestFailure(new Failure(d, dummyException)); + } + notifier.fireTestFinished(d); + } + } +} diff --git a/flutter/packages/integration_test/android/src/main/java/dev/flutter/plugins/integration_test/IntegrationTestPlugin.java b/flutter/packages/integration_test/android/src/main/java/dev/flutter/plugins/integration_test/IntegrationTestPlugin.java new file mode 100644 index 0000000000000000000000000000000000000000..7a230f0ead0edc2c82c155efb4bcbb5ee3388b28 --- /dev/null +++ b/flutter/packages/integration_test/android/src/main/java/dev/flutter/plugins/integration_test/IntegrationTestPlugin.java @@ -0,0 +1,121 @@ +// 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. + +package dev.flutter.plugins.integration_test; + +import android.app.Activity; +import android.content.Context; +import com.google.common.util.concurrent.SettableFuture; +import io.flutter.embedding.engine.plugins.FlutterPlugin; +import io.flutter.embedding.engine.plugins.activity.ActivityAware; +import io.flutter.embedding.engine.plugins.activity.ActivityPluginBinding; +import io.flutter.plugin.common.BinaryMessenger; +import io.flutter.plugin.common.MethodCall; +import io.flutter.plugin.common.MethodChannel; +import io.flutter.plugin.common.MethodChannel.MethodCallHandler; +import io.flutter.plugin.common.MethodChannel.Result; +import java.io.IOException; +import java.util.Map; +import java.util.concurrent.Future; + +/** IntegrationTestPlugin */ +public class IntegrationTestPlugin implements MethodCallHandler, FlutterPlugin, ActivityAware { + private static final String CHANNEL = "plugins.flutter.io/integration_test"; + private static final SettableFuture> testResultsSettable = + SettableFuture.create(); + + private MethodChannel methodChannel; + private Activity flutterActivity; + public static final Future> testResults = testResultsSettable; + + /** Plugin registration. */ + @SuppressWarnings("deprecation") + public static void registerWith(io.flutter.plugin.common.PluginRegistry.Registrar registrar) { + final IntegrationTestPlugin instance = new IntegrationTestPlugin(); + instance.onAttachedToEngine(registrar.context(), registrar.messenger()); + } + + @Override + public void onAttachedToEngine(FlutterPluginBinding binding) { + onAttachedToEngine(binding.getApplicationContext(), binding.getBinaryMessenger()); + } + + private void onAttachedToEngine(Context unusedApplicationContext, BinaryMessenger messenger) { + methodChannel = new MethodChannel(messenger, CHANNEL); + methodChannel.setMethodCallHandler(this); + } + + @Override + public void onDetachedFromEngine(FlutterPluginBinding binding) { + methodChannel.setMethodCallHandler(null); + methodChannel = null; + } + + @Override + public void onAttachedToActivity(ActivityPluginBinding binding) { + flutterActivity = binding.getActivity(); + } + + @Override + public void onReattachedToActivityForConfigChanges(ActivityPluginBinding binding) { + flutterActivity = binding.getActivity(); + } + + @Override + public void onDetachedFromActivity() { + flutterActivity = null; + } + + @Override + public void onDetachedFromActivityForConfigChanges() { + flutterActivity = null; + } + + @Override + public void onMethodCall(MethodCall call, Result result) { + switch (call.method) { + case "allTestsFinished": + final Map results = call.argument("results"); + testResultsSettable.set(results); + result.success(null); + return; + case "convertFlutterSurfaceToImage": + if (flutterActivity == null) { + result.error("Could not convert to image", "Activity not initialized", null); + return; + } + FlutterDeviceScreenshot.convertFlutterSurfaceToImage(flutterActivity); + result.success(null); + return; + case "revertFlutterImage": + if (flutterActivity == null) { + result.error("Could not revert Flutter image", "Activity not initialized", null); + return; + } + FlutterDeviceScreenshot.revertFlutterImage(flutterActivity); + result.success(null); + return; + case "captureScreenshot": + if (FlutterDeviceScreenshot.hasInstrumentation()) { + byte[] image; + try { + image = FlutterDeviceScreenshot.captureWithUiAutomation(); + } catch (IOException exception) { + result.error("Could not capture screenshot", "UiAutomation failed", exception); + return; + } + result.success(image); + return; + } + if (flutterActivity == null) { + result.error("Could not capture screenshot", "Activity not initialized", null); + return; + } + FlutterDeviceScreenshot.captureView(flutterActivity, methodChannel, result); + return; + default: + result.notImplemented(); + } + } +} diff --git a/flutter/packages/integration_test/android/src/test/java/dev/flutter/plugins/integration_test/FlutterDeviceScreenshotTest.java b/flutter/packages/integration_test/android/src/test/java/dev/flutter/plugins/integration_test/FlutterDeviceScreenshotTest.java new file mode 100644 index 0000000000000000000000000000000000000000..15dfad615ea7a8c5f48f3071a4cc0e24a1d6dcda --- /dev/null +++ b/flutter/packages/integration_test/android/src/test/java/dev/flutter/plugins/integration_test/FlutterDeviceScreenshotTest.java @@ -0,0 +1,52 @@ +// 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. + +package dev.flutter.plugins.integration_test; + +import androidx.test.runner.AndroidJUnitRunner; + +import org.junit.Test; + +import static org.junit.Assert.*; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +import android.app.Activity; + +import io.flutter.embedding.android.FlutterActivity; +import io.flutter.embedding.android.FlutterFragment; +import io.flutter.embedding.android.FlutterFragmentActivity; +import io.flutter.embedding.android.FlutterView; + +public class FlutterDeviceScreenshotTest extends AndroidJUnitRunner { + @Test + public void getFlutterView_returnsNullForNonFlutterActivity() { + Activity mockActivity = mock(Activity.class); + assertNull(FlutterDeviceScreenshot.getFlutterView(mockActivity)); + } + + @Test + public void getFlutterView_returnsFlutterViewForFlutterActivity() { + FlutterView mockFlutterView = mock(FlutterView.class); + FlutterActivity mockFlutterActivity = mock(FlutterActivity.class); + when(mockFlutterActivity.findViewById(FlutterActivity.FLUTTER_VIEW_ID)) + .thenReturn(mockFlutterView); + assertEquals( + FlutterDeviceScreenshot.getFlutterView(mockFlutterActivity), + mockFlutterView + ); + } + + @Test + public void getFlutterView_returnsFlutterViewForFlutterFragmentActivity() { + FlutterView mockFlutterView = mock(FlutterView.class); + FlutterFragmentActivity mockFlutterFragmentActivity = mock(FlutterFragmentActivity.class); + when(mockFlutterFragmentActivity.findViewById(FlutterFragment.FLUTTER_VIEW_ID)) + .thenReturn(mockFlutterView); + assertEquals( + FlutterDeviceScreenshot.getFlutterView(mockFlutterFragmentActivity), + mockFlutterView + ); + } +} diff --git a/flutter/packages/integration_test/example/README.md b/flutter/packages/integration_test/example/README.md new file mode 100644 index 0000000000000000000000000000000000000000..8b2c03573b1650c42ce5d3bd5a936eece10df043 --- /dev/null +++ b/flutter/packages/integration_test/example/README.md @@ -0,0 +1,31 @@ +# integration_test_example + +Demonstrates how to use the `package:integration_test`. + +To run `integration_test/example_test.dart`, + +## Android / iOS + +```sh +flutter drive \ + --driver=test_driver/integration_test.dart \ + --target=integration_test/example_test.dart +``` + +## Web + +In one shell, run Chromedriver ([download +here](https://chromedriver.chromium.org/downloads)): + +``` +chromedriver --port 8444 +``` + +Then, in another shell, run `flutter drive`: + +```sh +flutter drive \ + --driver=test_driver/integration_test.dart \ + --target=integration_test/example_test.dart \ + -d web-server +``` diff --git a/flutter/packages/integration_test/example/android/app/build.gradle b/flutter/packages/integration_test/example/android/app/build.gradle new file mode 100644 index 0000000000000000000000000000000000000000..bf10634d1f88d827c83184f9f007062be51ff9a5 --- /dev/null +++ b/flutter/packages/integration_test/example/android/app/build.gradle @@ -0,0 +1,71 @@ +// 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. + +def localProperties = new Properties() +def localPropertiesFile = rootProject.file('local.properties') +if (localPropertiesFile.exists()) { + localPropertiesFile.withReader('UTF-8') { reader -> + localProperties.load(reader) + } +} + +def flutterRoot = localProperties.getProperty('flutter.sdk') +if (flutterRoot == null) { + throw new GradleException("Flutter SDK not found. Define location with flutter.sdk in the local.properties file.") +} + +def flutterVersionCode = localProperties.getProperty('flutter.versionCode') +if (flutterVersionCode == null) { + flutterVersionCode = '1' +} + +def flutterVersionName = localProperties.getProperty('flutter.versionName') +if (flutterVersionName == null) { + flutterVersionName = '1.0' +} + +apply plugin: 'com.android.application' +apply from: "$flutterRoot/packages/flutter_tools/gradle/flutter.gradle" + +android { + // Conditional for compatibility with AGP <4.2. + if (project.android.hasProperty("namespace")) { + namespace 'com.example.integration_test_example' + } + compileSdk flutter.compileSdkVersion + + compileOptions { + sourceCompatibility JavaVersion.VERSION_1_8 + targetCompatibility JavaVersion.VERSION_1_8 + } + + defaultConfig { + // TODO: Specify your own unique Application ID (https://developer.android.com/studio/build/application-id.html). + applicationId "com.example.integration_test_example" + minSdkVersion flutter.minSdkVersion + targetSdkVersion flutter.targetSdkVersion + versionCode flutterVersionCode.toInteger() + versionName flutterVersionName + testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner" + } + + 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 + proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' + } + } +} + +flutter { + source '../..' +} + +dependencies { + testImplementation 'junit:junit:4.13.2' + androidTestImplementation 'androidx.test:runner:1.5.2' + androidTestImplementation 'androidx.test.espresso:espresso-core:3.5.1' +} diff --git a/flutter/packages/integration_test/example/android/app/proguard-rules.pro b/flutter/packages/integration_test/example/android/app/proguard-rules.pro new file mode 100644 index 0000000000000000000000000000000000000000..800c5c2adc6afb059714a89b0414954d49483cf8 --- /dev/null +++ b/flutter/packages/integration_test/example/android/app/proguard-rules.pro @@ -0,0 +1 @@ +# Intentionally empty. Validation is that apps can set their own proguard files. diff --git a/flutter/packages/integration_test/example/android/app/src/androidTest/java/com/example/integration_test_example/FlutterActivityTest.java b/flutter/packages/integration_test/example/android/app/src/androidTest/java/com/example/integration_test_example/FlutterActivityTest.java new file mode 100644 index 0000000000000000000000000000000000000000..6bac4a92f753009cd38508b155233ec7422a2d9c --- /dev/null +++ b/flutter/packages/integration_test/example/android/app/src/androidTest/java/com/example/integration_test_example/FlutterActivityTest.java @@ -0,0 +1,18 @@ +// 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. + +package com.example.integration_test_example; + +import androidx.test.rule.ActivityTestRule; +import dev.flutter.plugins.integration_test.FlutterTestRunner; +import io.flutter.embedding.android.FlutterActivity; +import org.junit.Rule; +import org.junit.runner.RunWith; + +@RunWith(FlutterTestRunner.class) +public class FlutterActivityTest { + @Rule + public ActivityTestRule rule = + new ActivityTestRule<>(FlutterActivity.class, true, false); +} diff --git a/flutter/packages/integration_test/example/android/app/src/androidTest/java/com/example/integration_test_example/FlutterActivityWithPermissionTest.java b/flutter/packages/integration_test/example/android/app/src/androidTest/java/com/example/integration_test_example/FlutterActivityWithPermissionTest.java new file mode 100644 index 0000000000000000000000000000000000000000..e3ed9effc57dd0cee4f7224b369e66b803b90894 --- /dev/null +++ b/flutter/packages/integration_test/example/android/app/src/androidTest/java/com/example/integration_test_example/FlutterActivityWithPermissionTest.java @@ -0,0 +1,30 @@ +// 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. + +package com.example.integration_test_example; + +import android.Manifest.permission; +import androidx.test.rule.ActivityTestRule; +import androidx.test.rule.GrantPermissionRule; +import dev.flutter.plugins.integration_test.FlutterTestRunner; +import io.flutter.embedding.android.FlutterActivity; +import org.junit.Rule; +import org.junit.runner.RunWith; + +/** + * Demonstrates how an integration test on Android can be run with permissions already granted. This + * is helpful if developers want to test native App behavior that depends on certain system service + * results which are guarded with permissions. + */ +@RunWith(FlutterTestRunner.class) +public class FlutterActivityWithPermissionTest { + + @Rule + public GrantPermissionRule permissionRule = + GrantPermissionRule.grant(permission.ACCESS_COARSE_LOCATION); + + @Rule + public ActivityTestRule rule = + new ActivityTestRule<>(FlutterActivity.class, true, false); +} diff --git a/flutter/packages/integration_test/example/android/app/src/debug/AndroidManifest.xml b/flutter/packages/integration_test/example/android/app/src/debug/AndroidManifest.xml new file mode 100644 index 0000000000000000000000000000000000000000..fa9a400b91ac4a9c1b4799bb897385e99b15e511 --- /dev/null +++ b/flutter/packages/integration_test/example/android/app/src/debug/AndroidManifest.xml @@ -0,0 +1,11 @@ + + + + + + diff --git a/flutter/packages/integration_test/example/android/app/src/main/AndroidManifest.xml b/flutter/packages/integration_test/example/android/app/src/main/AndroidManifest.xml new file mode 100644 index 0000000000000000000000000000000000000000..f36b7764e62b898360642ba27aac1d08b2a90256 --- /dev/null +++ b/flutter/packages/integration_test/example/android/app/src/main/AndroidManifest.xml @@ -0,0 +1,31 @@ + + + + + + + + + + + + + + + diff --git a/flutter/packages/integration_test/example/android/app/src/main/res/drawable/launch_background.xml b/flutter/packages/integration_test/example/android/app/src/main/res/drawable/launch_background.xml new file mode 100644 index 0000000000000000000000000000000000000000..3727f9e00a029f25d630f317fcb835328d0e78b4 --- /dev/null +++ b/flutter/packages/integration_test/example/android/app/src/main/res/drawable/launch_background.xml @@ -0,0 +1,16 @@ + + + + + + + + + + diff --git a/flutter/packages/integration_test/example/android/app/src/main/res/mipmap-hdpi/ic_launcher.png b/flutter/packages/integration_test/example/android/app/src/main/res/mipmap-hdpi/ic_launcher.png new file mode 100644 index 0000000000000000000000000000000000000000..db77bb4b7b0906d62b1847e87f15cdcacf6a4f29 Binary files /dev/null and b/flutter/packages/integration_test/example/android/app/src/main/res/mipmap-hdpi/ic_launcher.png differ diff --git a/flutter/packages/integration_test/example/android/app/src/main/res/mipmap-mdpi/ic_launcher.png b/flutter/packages/integration_test/example/android/app/src/main/res/mipmap-mdpi/ic_launcher.png new file mode 100644 index 0000000000000000000000000000000000000000..17987b79bb8a35cc66c3c1fd44f5a5526c1b78be Binary files /dev/null and b/flutter/packages/integration_test/example/android/app/src/main/res/mipmap-mdpi/ic_launcher.png differ diff --git a/flutter/packages/integration_test/example/android/app/src/main/res/mipmap-xhdpi/ic_launcher.png b/flutter/packages/integration_test/example/android/app/src/main/res/mipmap-xhdpi/ic_launcher.png new file mode 100644 index 0000000000000000000000000000000000000000..09d4391482be68e9e4a07fab769b5de337d16eb1 Binary files /dev/null and b/flutter/packages/integration_test/example/android/app/src/main/res/mipmap-xhdpi/ic_launcher.png differ diff --git a/flutter/packages/integration_test/example/android/app/src/main/res/mipmap-xxhdpi/ic_launcher.png b/flutter/packages/integration_test/example/android/app/src/main/res/mipmap-xxhdpi/ic_launcher.png new file mode 100644 index 0000000000000000000000000000000000000000..d5f1c8d34e7a88e3f88bea192c3a370d44689c3c Binary files /dev/null and b/flutter/packages/integration_test/example/android/app/src/main/res/mipmap-xxhdpi/ic_launcher.png differ diff --git a/flutter/packages/integration_test/example/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png b/flutter/packages/integration_test/example/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png new file mode 100644 index 0000000000000000000000000000000000000000..4d6372eebdb28e45604e46eeda8dd24651419bc0 Binary files /dev/null and b/flutter/packages/integration_test/example/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png differ diff --git a/flutter/packages/integration_test/example/android/app/src/main/res/values/styles.xml b/flutter/packages/integration_test/example/android/app/src/main/res/values/styles.xml new file mode 100644 index 0000000000000000000000000000000000000000..97fa79160336902831acf3a5cf1b2c96a66d71f5 --- /dev/null +++ b/flutter/packages/integration_test/example/android/app/src/main/res/values/styles.xml @@ -0,0 +1,9 @@ + + + + + diff --git a/flutter/packages/integration_test/example/android/app/src/profile/AndroidManifest.xml b/flutter/packages/integration_test/example/android/app/src/profile/AndroidManifest.xml new file mode 100644 index 0000000000000000000000000000000000000000..fa9a400b91ac4a9c1b4799bb897385e99b15e511 --- /dev/null +++ b/flutter/packages/integration_test/example/android/app/src/profile/AndroidManifest.xml @@ -0,0 +1,11 @@ + + + + + + diff --git a/flutter/packages/integration_test/example/android/build.gradle b/flutter/packages/integration_test/example/android/build.gradle new file mode 100644 index 0000000000000000000000000000000000000000..79e0589e545535bc4b790b1e775b4375387f8cbc --- /dev/null +++ b/flutter/packages/integration_test/example/android/build.gradle @@ -0,0 +1,51 @@ +// Copyright 2014 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +// This file is auto generated. +// To update all the build.gradle files in the Flutter repo, +// See dev/tools/bin/generate_gradle_lockfiles.dart. + +buildscript { + ext.kotlin_version = '1.8.21' + repositories { + google() + mavenCentral() + } + + dependencies { + classpath 'com.android.tools.build:gradle:8.0.0' + classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version" + } + + configurations.classpath { + resolutionStrategy.activateDependencyLocking() + } +} + +allprojects { + repositories { + google() + mavenCentral() + } +} + +rootProject.buildDir = '../build' + +subprojects { + project.buildDir = "${rootProject.buildDir}/${project.name}" +} +subprojects { + project.evaluationDependsOn(':app') + dependencyLocking { + ignoredDependencies.add('io.flutter:*') + lockFile = file("${rootProject.projectDir}/project-${project.name}.lockfile") + if (!project.hasProperty('local-engine-repo')) { + lockAllConfigurations() + } + } +} + +tasks.register("clean", Delete) { + delete rootProject.buildDir +} diff --git a/flutter/packages/integration_test/example/android/buildscript-gradle.lockfile b/flutter/packages/integration_test/example/android/buildscript-gradle.lockfile new file mode 100644 index 0000000000000000000000000000000000000000..c4752680eb0d4761e2b2d1731333d2747ad1a228 --- /dev/null +++ b/flutter/packages/integration_test/example/android/buildscript-gradle.lockfile @@ -0,0 +1,151 @@ +# This is a Gradle generated file for dependency locking. +# Manual edits can break the build and are not advised. +# This file is expected to be part of source control. +androidx.databinding:databinding-common:8.0.0=classpath +androidx.databinding:databinding-compiler-common:8.0.0=classpath +com.android.databinding:baseLibrary:8.0.0=classpath +com.android.tools.analytics-library:crash:31.0.0=classpath +com.android.tools.analytics-library:protos:31.0.0=classpath +com.android.tools.analytics-library:shared:31.0.0=classpath +com.android.tools.analytics-library:tracker:31.0.0=classpath +com.android.tools.build.jetifier:jetifier-core:1.0.0-beta10=classpath +com.android.tools.build.jetifier:jetifier-processor:1.0.0-beta10=classpath +com.android.tools.build:aapt2-proto:8.0.0-9289358=classpath +com.android.tools.build:aaptcompiler:8.0.0=classpath +com.android.tools.build:apksig:8.0.0=classpath +com.android.tools.build:apkzlib:8.0.0=classpath +com.android.tools.build:builder-model:8.0.0=classpath +com.android.tools.build:builder-test-api:8.0.0=classpath +com.android.tools.build:builder:8.0.0=classpath +com.android.tools.build:bundletool:1.13.2=classpath +com.android.tools.build:gradle-api:8.0.0=classpath +com.android.tools.build:gradle-settings-api:8.0.0=classpath +com.android.tools.build:gradle:8.0.0=classpath +com.android.tools.build:manifest-merger:31.0.0=classpath +com.android.tools.build:transform-api:2.0.0-deprecated-use-gradle-api=classpath +com.android.tools.ddms:ddmlib:31.0.0=classpath +com.android.tools.layoutlib:layoutlib-api:31.0.0=classpath +com.android.tools.lint:lint-model:31.0.0=classpath +com.android.tools.lint:lint-typedef-remover:31.0.0=classpath +com.android.tools.utp:android-device-provider-ddmlib-proto:31.0.0=classpath +com.android.tools.utp:android-device-provider-gradle-proto:31.0.0=classpath +com.android.tools.utp:android-test-plugin-host-additional-test-output-proto:31.0.0=classpath +com.android.tools.utp:android-test-plugin-host-coverage-proto:31.0.0=classpath +com.android.tools.utp:android-test-plugin-host-logcat-proto:31.0.0=classpath +com.android.tools.utp:android-test-plugin-host-retention-proto:31.0.0=classpath +com.android.tools.utp:android-test-plugin-result-listener-gradle-proto:31.0.0=classpath +com.android.tools:annotations:31.0.0=classpath +com.android.tools:common:31.0.0=classpath +com.android.tools:dvlib:31.0.0=classpath +com.android.tools:repository:31.0.0=classpath +com.android.tools:sdk-common:31.0.0=classpath +com.android.tools:sdklib:31.0.0=classpath +com.android:signflinger:8.0.0=classpath +com.android:zipflinger:8.0.0=classpath +com.google.android:annotations:4.1.1.4=classpath +com.google.api.grpc:proto-google-common-protos:2.0.1=classpath +com.google.auto.value:auto-value-annotations:1.6.2=classpath +com.google.code.findbugs:jsr305:3.0.2=classpath +com.google.code.gson:gson:2.8.9=classpath +com.google.crypto.tink:tink:1.7.0=classpath +com.google.dagger:dagger:2.28.3=classpath +com.google.errorprone:error_prone_annotations:2.10.0=classpath +com.google.flatbuffers:flatbuffers-java:1.12.0=classpath +com.google.guava:failureaccess:1.0.1=classpath +com.google.guava:guava:31.0.1-jre=classpath +com.google.guava:listenablefuture:9999.0-empty-to-avoid-conflict-with-guava=classpath +com.google.j2objc:j2objc-annotations:1.3=classpath +com.google.jimfs:jimfs:1.1=classpath +com.google.protobuf:protobuf-java-util:3.19.3=classpath +com.google.protobuf:protobuf-java:3.19.3=classpath +com.google.testing.platform:core-proto:0.0.8-alpha08=classpath +com.googlecode.juniversalchardet:juniversalchardet:1.0.3=classpath +com.squareup:javapoet:1.10.0=classpath +com.squareup:javawriter:2.5.0=classpath +com.sun.activation:javax.activation:1.2.0=classpath +com.sun.istack:istack-commons-runtime:3.0.8=classpath +com.sun.xml.fastinfoset:FastInfoset:1.2.16=classpath +commons-codec:commons-codec:1.11=classpath +commons-io:commons-io:2.4=classpath +commons-logging:commons-logging:1.2=classpath +io.grpc:grpc-api:1.45.1=classpath +io.grpc:grpc-context:1.45.1=classpath +io.grpc:grpc-core:1.45.1=classpath +io.grpc:grpc-netty:1.45.1=classpath +io.grpc:grpc-protobuf-lite:1.45.1=classpath +io.grpc:grpc-protobuf:1.45.1=classpath +io.grpc:grpc-stub:1.45.1=classpath +io.netty:netty-buffer:4.1.72.Final=classpath +io.netty:netty-codec-http2:4.1.72.Final=classpath +io.netty:netty-codec-http:4.1.72.Final=classpath +io.netty:netty-codec-socks:4.1.72.Final=classpath +io.netty:netty-codec:4.1.72.Final=classpath +io.netty:netty-common:4.1.72.Final=classpath +io.netty:netty-handler-proxy:4.1.72.Final=classpath +io.netty:netty-handler:4.1.72.Final=classpath +io.netty:netty-resolver:4.1.72.Final=classpath +io.netty:netty-tcnative-classes:2.0.46.Final=classpath +io.netty:netty-transport:4.1.72.Final=classpath +io.perfmark:perfmark-api:0.23.0=classpath +jakarta.activation:jakarta.activation-api:1.2.1=classpath +jakarta.xml.bind:jakarta.xml.bind-api:2.3.2=classpath +javax.annotation:javax.annotation-api:1.3.2=classpath +javax.inject:javax.inject:1=classpath +net.java.dev.jna:jna-platform:5.6.0=classpath +net.java.dev.jna:jna:5.6.0=classpath +net.sf.jopt-simple:jopt-simple:4.9=classpath +net.sf.kxml:kxml2:2.3.0=classpath +org.apache.commons:commons-compress:1.20=classpath +org.apache.httpcomponents:httpclient:4.5.13=classpath +org.apache.httpcomponents:httpcore:4.4.15=classpath +org.apache.httpcomponents:httpmime:4.5.6=classpath +org.bitbucket.b_c:jose4j:0.7.0=classpath +org.bouncycastle:bcpkix-jdk15on:1.67=classpath +org.bouncycastle:bcprov-jdk15on:1.67=classpath +org.checkerframework:checker-qual:3.12.0=classpath +org.codehaus.mojo:animal-sniffer-annotations:1.19=classpath +org.glassfish.jaxb:jaxb-runtime:2.3.2=classpath +org.glassfish.jaxb:txw2:2.3.2=classpath +org.jdom:jdom2:2.0.6=classpath +org.jetbrains.intellij.deps:trove4j:1.0.20200330=classpath +org.jetbrains.kotlin:kotlin-android-extensions:1.8.21=classpath +org.jetbrains.kotlin:kotlin-annotation-processing-gradle:1.8.21=classpath +org.jetbrains.kotlin:kotlin-compiler-embeddable:1.8.21=classpath +org.jetbrains.kotlin:kotlin-compiler-runner:1.8.21=classpath +org.jetbrains.kotlin:kotlin-daemon-client:1.8.21=classpath +org.jetbrains.kotlin:kotlin-daemon-embeddable:1.8.21=classpath +org.jetbrains.kotlin:kotlin-gradle-plugin-annotations:1.8.21=classpath +org.jetbrains.kotlin:kotlin-gradle-plugin-api:1.8.21=classpath +org.jetbrains.kotlin:kotlin-gradle-plugin-idea-proto:1.8.21=classpath +org.jetbrains.kotlin:kotlin-gradle-plugin-idea:1.8.21=classpath +org.jetbrains.kotlin:kotlin-gradle-plugin-model:1.8.21=classpath +org.jetbrains.kotlin:kotlin-gradle-plugin:1.8.21=classpath +org.jetbrains.kotlin:kotlin-gradle-plugins-bom:1.8.21=classpath +org.jetbrains.kotlin:kotlin-klib-commonizer-api:1.8.21=classpath +org.jetbrains.kotlin:kotlin-native-utils:1.8.21=classpath +org.jetbrains.kotlin:kotlin-project-model:1.8.21=classpath +org.jetbrains.kotlin:kotlin-reflect:1.7.10=classpath +org.jetbrains.kotlin:kotlin-scripting-common:1.8.21=classpath +org.jetbrains.kotlin:kotlin-scripting-compiler-embeddable:1.8.21=classpath +org.jetbrains.kotlin:kotlin-scripting-compiler-impl-embeddable:1.8.21=classpath +org.jetbrains.kotlin:kotlin-scripting-jvm:1.8.21=classpath +org.jetbrains.kotlin:kotlin-stdlib-common:1.7.10=classpath +org.jetbrains.kotlin:kotlin-stdlib-jdk7:1.7.10=classpath +org.jetbrains.kotlin:kotlin-stdlib-jdk8:1.7.10=classpath +org.jetbrains.kotlin:kotlin-stdlib:1.7.10=classpath +org.jetbrains.kotlin:kotlin-tooling-core:1.8.21=classpath +org.jetbrains.kotlin:kotlin-util-io:1.8.21=classpath +org.jetbrains.kotlin:kotlin-util-klib:1.8.21=classpath +org.jetbrains.kotlinx:kotlinx-coroutines-core-jvm:1.5.0=classpath +org.jetbrains:annotations:13.0=classpath +org.jvnet.staxex:stax-ex:1.8.1=classpath +org.ow2.asm:asm-analysis:9.2=classpath +org.ow2.asm:asm-commons:9.2=classpath +org.ow2.asm:asm-tree:9.2=classpath +org.ow2.asm:asm-util:9.2=classpath +org.ow2.asm:asm:9.2=classpath +org.slf4j:slf4j-api:1.7.30=classpath +org.tensorflow:tensorflow-lite-metadata:0.1.0-rc2=classpath +xerces:xercesImpl:2.12.0=classpath +xml-apis:xml-apis:1.4.01=classpath +empty= diff --git a/flutter/packages/integration_test/example/android/gradle.properties b/flutter/packages/integration_test/example/android/gradle.properties new file mode 100644 index 0000000000000000000000000000000000000000..d513e21975fc154cd506fce70c15e67d091043c9 --- /dev/null +++ b/flutter/packages/integration_test/example/android/gradle.properties @@ -0,0 +1,7 @@ +org.gradle.jvmargs=-Xmx4G + +android.useAndroidX=true +android.enableJetifier=true +android.defaults.buildfeatures.buildconfig=true +android.nonTransitiveRClass=false +android.nonFinalResIds=false diff --git a/flutter/packages/integration_test/example/android/gradle/wrapper/gradle-wrapper.properties b/flutter/packages/integration_test/example/android/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 0000000000000000000000000000000000000000..8bc9958ab0cfe54c122c0baf33acbc7ab9adc545 --- /dev/null +++ b/flutter/packages/integration_test/example/android/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,5 @@ +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-8.0-all.zip diff --git a/flutter/packages/integration_test/example/android/project-app.lockfile b/flutter/packages/integration_test/example/android/project-app.lockfile new file mode 100644 index 0000000000000000000000000000000000000000..0fed2919fad7d5e90d9b4538ecca9a4f217a1f69 --- /dev/null +++ b/flutter/packages/integration_test/example/android/project-app.lockfile @@ -0,0 +1,137 @@ +# This is a Gradle generated file for dependency locking. +# Manual edits can break the build and are not advised. +# This file is expected to be part of source control. +androidx.activity:activity:1.0.0=debugAndroidTestCompileClasspath,debugCompileClasspath,debugRuntimeClasspath,debugUnitTestCompileClasspath,debugUnitTestRuntimeClasspath,profileCompileClasspath,profileRuntimeClasspath,profileUnitTestCompileClasspath,profileUnitTestRuntimeClasspath,releaseCompileClasspath,releaseRuntimeClasspath,releaseUnitTestCompileClasspath,releaseUnitTestRuntimeClasspath +androidx.annotation:annotation-experimental:1.1.0=debugAndroidTestCompileClasspath,debugCompileClasspath,debugRuntimeClasspath,debugUnitTestCompileClasspath,debugUnitTestRuntimeClasspath,profileCompileClasspath,profileRuntimeClasspath,profileUnitTestCompileClasspath,profileUnitTestRuntimeClasspath,releaseCompileClasspath,releaseRuntimeClasspath,releaseUnitTestCompileClasspath,releaseUnitTestRuntimeClasspath +androidx.annotation:annotation:1.2.0=debugAndroidTestCompileClasspath,debugAndroidTestRuntimeClasspath,debugCompileClasspath,debugRuntimeClasspath,debugUnitTestCompileClasspath,debugUnitTestRuntimeClasspath,profileCompileClasspath,profileRuntimeClasspath,profileUnitTestCompileClasspath,profileUnitTestRuntimeClasspath,releaseCompileClasspath,releaseRuntimeClasspath,releaseUnitTestCompileClasspath,releaseUnitTestRuntimeClasspath +androidx.arch.core:core-common:2.1.0=debugAndroidTestCompileClasspath,debugCompileClasspath,debugRuntimeClasspath,debugUnitTestCompileClasspath,debugUnitTestRuntimeClasspath,profileCompileClasspath,profileRuntimeClasspath,profileUnitTestCompileClasspath,profileUnitTestRuntimeClasspath,releaseCompileClasspath,releaseRuntimeClasspath,releaseUnitTestCompileClasspath,releaseUnitTestRuntimeClasspath +androidx.arch.core:core-runtime:2.0.0=debugAndroidTestCompileClasspath,debugCompileClasspath,debugRuntimeClasspath,debugUnitTestCompileClasspath,debugUnitTestRuntimeClasspath,profileCompileClasspath,profileRuntimeClasspath,profileUnitTestCompileClasspath,profileUnitTestRuntimeClasspath,releaseCompileClasspath,releaseRuntimeClasspath,releaseUnitTestCompileClasspath,releaseUnitTestRuntimeClasspath +androidx.collection:collection:1.1.0=debugAndroidTestCompileClasspath,debugCompileClasspath,debugRuntimeClasspath,debugUnitTestCompileClasspath,debugUnitTestRuntimeClasspath,profileCompileClasspath,profileRuntimeClasspath,profileUnitTestCompileClasspath,profileUnitTestRuntimeClasspath,releaseCompileClasspath,releaseRuntimeClasspath,releaseUnitTestCompileClasspath,releaseUnitTestRuntimeClasspath +androidx.concurrent:concurrent-futures:1.1.0=debugAndroidTestCompileClasspath +androidx.core:core:1.6.0=debugAndroidTestCompileClasspath,debugCompileClasspath,debugRuntimeClasspath,debugUnitTestCompileClasspath,debugUnitTestRuntimeClasspath,profileCompileClasspath,profileRuntimeClasspath,profileUnitTestCompileClasspath,profileUnitTestRuntimeClasspath,releaseCompileClasspath,releaseRuntimeClasspath,releaseUnitTestCompileClasspath,releaseUnitTestRuntimeClasspath +androidx.customview:customview:1.0.0=debugAndroidTestCompileClasspath,debugCompileClasspath,debugRuntimeClasspath,debugUnitTestCompileClasspath,debugUnitTestRuntimeClasspath,profileCompileClasspath,profileRuntimeClasspath,profileUnitTestCompileClasspath,profileUnitTestRuntimeClasspath,releaseCompileClasspath,releaseRuntimeClasspath,releaseUnitTestCompileClasspath,releaseUnitTestRuntimeClasspath +androidx.fragment:fragment:1.1.0=debugAndroidTestCompileClasspath,debugCompileClasspath,debugRuntimeClasspath,debugUnitTestCompileClasspath,debugUnitTestRuntimeClasspath,profileCompileClasspath,profileRuntimeClasspath,profileUnitTestCompileClasspath,profileUnitTestRuntimeClasspath,releaseCompileClasspath,releaseRuntimeClasspath,releaseUnitTestCompileClasspath,releaseUnitTestRuntimeClasspath +androidx.lifecycle:lifecycle-common-java8:2.2.0=debugAndroidTestCompileClasspath,debugCompileClasspath,debugRuntimeClasspath,debugUnitTestCompileClasspath,debugUnitTestRuntimeClasspath,profileCompileClasspath,profileRuntimeClasspath,profileUnitTestCompileClasspath,profileUnitTestRuntimeClasspath,releaseCompileClasspath,releaseRuntimeClasspath,releaseUnitTestCompileClasspath,releaseUnitTestRuntimeClasspath +androidx.lifecycle:lifecycle-common:2.2.0=debugAndroidTestCompileClasspath,debugCompileClasspath,debugRuntimeClasspath,debugUnitTestCompileClasspath,debugUnitTestRuntimeClasspath,profileCompileClasspath,profileRuntimeClasspath,profileUnitTestCompileClasspath,profileUnitTestRuntimeClasspath,releaseCompileClasspath,releaseRuntimeClasspath,releaseUnitTestCompileClasspath,releaseUnitTestRuntimeClasspath +androidx.lifecycle:lifecycle-livedata-core:2.0.0=debugAndroidTestCompileClasspath,debugCompileClasspath,debugRuntimeClasspath,debugUnitTestCompileClasspath,debugUnitTestRuntimeClasspath,profileCompileClasspath,profileRuntimeClasspath,profileUnitTestCompileClasspath,profileUnitTestRuntimeClasspath,releaseCompileClasspath,releaseRuntimeClasspath,releaseUnitTestCompileClasspath,releaseUnitTestRuntimeClasspath +androidx.lifecycle:lifecycle-livedata:2.0.0=debugAndroidTestCompileClasspath,debugCompileClasspath,debugRuntimeClasspath,debugUnitTestCompileClasspath,debugUnitTestRuntimeClasspath,profileCompileClasspath,profileRuntimeClasspath,profileUnitTestCompileClasspath,profileUnitTestRuntimeClasspath,releaseCompileClasspath,releaseRuntimeClasspath,releaseUnitTestCompileClasspath,releaseUnitTestRuntimeClasspath +androidx.lifecycle:lifecycle-runtime:2.2.0=debugAndroidTestCompileClasspath,debugCompileClasspath,debugRuntimeClasspath,debugUnitTestCompileClasspath,debugUnitTestRuntimeClasspath,profileCompileClasspath,profileRuntimeClasspath,profileUnitTestCompileClasspath,profileUnitTestRuntimeClasspath,releaseCompileClasspath,releaseRuntimeClasspath,releaseUnitTestCompileClasspath,releaseUnitTestRuntimeClasspath +androidx.lifecycle:lifecycle-viewmodel:2.1.0=debugAndroidTestCompileClasspath,debugCompileClasspath,debugRuntimeClasspath,debugUnitTestCompileClasspath,debugUnitTestRuntimeClasspath,profileCompileClasspath,profileRuntimeClasspath,profileUnitTestCompileClasspath,profileUnitTestRuntimeClasspath,releaseCompileClasspath,releaseRuntimeClasspath,releaseUnitTestCompileClasspath,releaseUnitTestRuntimeClasspath +androidx.loader:loader:1.0.0=debugAndroidTestCompileClasspath,debugCompileClasspath,debugRuntimeClasspath,debugUnitTestCompileClasspath,debugUnitTestRuntimeClasspath,profileCompileClasspath,profileRuntimeClasspath,profileUnitTestCompileClasspath,profileUnitTestRuntimeClasspath,releaseCompileClasspath,releaseRuntimeClasspath,releaseUnitTestCompileClasspath,releaseUnitTestRuntimeClasspath +androidx.savedstate:savedstate:1.0.0=debugAndroidTestCompileClasspath,debugCompileClasspath,debugRuntimeClasspath,debugUnitTestCompileClasspath,debugUnitTestRuntimeClasspath,profileCompileClasspath,profileRuntimeClasspath,profileUnitTestCompileClasspath,profileUnitTestRuntimeClasspath,releaseCompileClasspath,releaseRuntimeClasspath,releaseUnitTestCompileClasspath,releaseUnitTestRuntimeClasspath +androidx.test.espresso:espresso-core:3.2.0=debugAndroidTestRuntimeClasspath,debugCompileClasspath,debugRuntimeClasspath,debugUnitTestCompileClasspath,debugUnitTestRuntimeClasspath,profileCompileClasspath,profileRuntimeClasspath,profileUnitTestCompileClasspath,profileUnitTestRuntimeClasspath,releaseCompileClasspath,releaseRuntimeClasspath,releaseUnitTestCompileClasspath,releaseUnitTestRuntimeClasspath +androidx.test.espresso:espresso-core:3.5.1=debugAndroidTestCompileClasspath +androidx.test.espresso:espresso-idling-resource:3.2.0=debugAndroidTestCompileClasspath,debugAndroidTestRuntimeClasspath,debugCompileClasspath,debugRuntimeClasspath,debugUnitTestCompileClasspath,debugUnitTestRuntimeClasspath,profileCompileClasspath,profileRuntimeClasspath,profileUnitTestCompileClasspath,profileUnitTestRuntimeClasspath,releaseCompileClasspath,releaseRuntimeClasspath,releaseUnitTestCompileClasspath,releaseUnitTestRuntimeClasspath +androidx.test.services:storage:1.4.2=debugAndroidTestCompileClasspath +androidx.test:annotation:1.0.1=debugAndroidTestCompileClasspath +androidx.test:core:1.5.0=debugAndroidTestCompileClasspath +androidx.test:monitor:1.2.0=debugAndroidTestCompileClasspath,debugAndroidTestRuntimeClasspath,debugCompileClasspath,debugRuntimeClasspath,debugUnitTestCompileClasspath,debugUnitTestRuntimeClasspath,profileCompileClasspath,profileRuntimeClasspath,profileUnitTestCompileClasspath,profileUnitTestRuntimeClasspath,releaseCompileClasspath,releaseRuntimeClasspath,releaseUnitTestCompileClasspath,releaseUnitTestRuntimeClasspath +androidx.test:rules:1.2.0=debugAndroidTestCompileClasspath,debugCompileClasspath,debugRuntimeClasspath,debugUnitTestCompileClasspath,debugUnitTestRuntimeClasspath,profileCompileClasspath,profileRuntimeClasspath,profileUnitTestCompileClasspath,profileUnitTestRuntimeClasspath,releaseCompileClasspath,releaseRuntimeClasspath,releaseUnitTestCompileClasspath,releaseUnitTestRuntimeClasspath +androidx.test:runner:1.2.0=debugAndroidTestRuntimeClasspath,debugCompileClasspath,debugRuntimeClasspath,debugUnitTestCompileClasspath,debugUnitTestRuntimeClasspath,profileCompileClasspath,profileRuntimeClasspath,profileUnitTestCompileClasspath,profileUnitTestRuntimeClasspath,releaseCompileClasspath,releaseRuntimeClasspath,releaseUnitTestCompileClasspath,releaseUnitTestRuntimeClasspath +androidx.test:runner:1.5.2=debugAndroidTestCompileClasspath +androidx.tracing:tracing:1.0.0=debugAndroidTestCompileClasspath,debugCompileClasspath,debugRuntimeClasspath,debugUnitTestCompileClasspath,debugUnitTestRuntimeClasspath,profileCompileClasspath,profileRuntimeClasspath,profileUnitTestCompileClasspath,profileUnitTestRuntimeClasspath,releaseCompileClasspath,releaseRuntimeClasspath,releaseUnitTestCompileClasspath,releaseUnitTestRuntimeClasspath +androidx.versionedparcelable:versionedparcelable:1.1.1=debugAndroidTestCompileClasspath,debugCompileClasspath,debugRuntimeClasspath,debugUnitTestCompileClasspath,debugUnitTestRuntimeClasspath,profileCompileClasspath,profileRuntimeClasspath,profileUnitTestCompileClasspath,profileUnitTestRuntimeClasspath,releaseCompileClasspath,releaseRuntimeClasspath,releaseUnitTestCompileClasspath,releaseUnitTestRuntimeClasspath +androidx.viewpager:viewpager:1.0.0=debugAndroidTestCompileClasspath,debugCompileClasspath,debugRuntimeClasspath,debugUnitTestCompileClasspath,debugUnitTestRuntimeClasspath,profileCompileClasspath,profileRuntimeClasspath,profileUnitTestCompileClasspath,profileUnitTestRuntimeClasspath,releaseCompileClasspath,releaseRuntimeClasspath,releaseUnitTestCompileClasspath,releaseUnitTestRuntimeClasspath +androidx.window:window-java:1.0.0-beta04=debugAndroidTestCompileClasspath,debugCompileClasspath,debugRuntimeClasspath,debugUnitTestCompileClasspath,debugUnitTestRuntimeClasspath,profileCompileClasspath,profileRuntimeClasspath,profileUnitTestCompileClasspath,profileUnitTestRuntimeClasspath,releaseCompileClasspath,releaseRuntimeClasspath,releaseUnitTestCompileClasspath,releaseUnitTestRuntimeClasspath +androidx.window:window:1.0.0-beta04=debugAndroidTestCompileClasspath,debugCompileClasspath,debugRuntimeClasspath,debugUnitTestCompileClasspath,debugUnitTestRuntimeClasspath,profileCompileClasspath,profileRuntimeClasspath,profileUnitTestCompileClasspath,profileUnitTestRuntimeClasspath,releaseCompileClasspath,releaseRuntimeClasspath,releaseUnitTestCompileClasspath,releaseUnitTestRuntimeClasspath +com.android.tools.analytics-library:protos:27.1.3=lintClassPath +com.android.tools.analytics-library:shared:27.1.3=lintClassPath +com.android.tools.analytics-library:tracker:27.1.3=lintClassPath +com.android.tools.build:aapt2-proto:4.1.0-alpha01-6193524=lintClassPath +com.android.tools.build:aapt2:4.1.3-6503028=_internal_aapt2_binary +com.android.tools.build:apksig:4.1.3=lintClassPath +com.android.tools.build:apkzlib:4.1.3=lintClassPath +com.android.tools.build:builder-model:4.1.3=lintClassPath +com.android.tools.build:builder-test-api:4.1.3=lintClassPath +com.android.tools.build:builder:4.1.3=lintClassPath +com.android.tools.build:gradle-api:4.1.3=lintClassPath +com.android.tools.build:manifest-merger:27.1.3=lintClassPath +com.android.tools.ddms:ddmlib:27.1.3=lintClassPath +com.android.tools.external.com-intellij:intellij-core:27.1.3=lintClassPath +com.android.tools.external.com-intellij:kotlin-compiler:27.1.3=lintClassPath +com.android.tools.external.org-jetbrains:uast:27.1.3=lintClassPath +com.android.tools.layoutlib:layoutlib-api:27.1.3=lintClassPath +com.android.tools.lint:lint-api:27.1.3=lintClassPath +com.android.tools.lint:lint-checks:27.1.3=lintClassPath +com.android.tools.lint:lint-gradle-api:27.1.3=lintClassPath +com.android.tools.lint:lint-gradle:27.1.3=lintClassPath +com.android.tools.lint:lint-model:27.1.3=lintClassPath +com.android.tools.lint:lint:27.1.3=lintClassPath +com.android.tools:annotations:27.1.3=lintClassPath +com.android.tools:common:27.1.3=lintClassPath +com.android.tools:dvlib:27.1.3=lintClassPath +com.android.tools:repository:27.1.3=lintClassPath +com.android.tools:sdk-common:27.1.3=lintClassPath +com.android.tools:sdklib:27.1.3=lintClassPath +com.android:signflinger:4.1.3=lintClassPath +com.android:zipflinger:4.1.3=lintClassPath +com.google.code.findbugs:jsr305:3.0.2=debugAndroidTestCompileClasspath,debugAndroidTestRuntimeClasspath,debugCompileClasspath,debugRuntimeClasspath,debugUnitTestCompileClasspath,debugUnitTestRuntimeClasspath,lintClassPath,profileCompileClasspath,profileRuntimeClasspath,profileUnitTestCompileClasspath,profileUnitTestRuntimeClasspath,releaseCompileClasspath,releaseRuntimeClasspath,releaseUnitTestCompileClasspath,releaseUnitTestRuntimeClasspath +com.google.code.gson:gson:2.8.5=lintClassPath +com.google.errorprone:error_prone_annotations:2.3.2=debugRuntimeClasspath,debugUnitTestRuntimeClasspath,lintClassPath,profileRuntimeClasspath,profileUnitTestRuntimeClasspath,releaseRuntimeClasspath,releaseUnitTestRuntimeClasspath +com.google.guava:failureaccess:1.0.1=debugRuntimeClasspath,debugUnitTestRuntimeClasspath,lintClassPath,profileRuntimeClasspath,profileUnitTestRuntimeClasspath,releaseRuntimeClasspath,releaseUnitTestRuntimeClasspath +com.google.guava:guava:28.1-android=debugRuntimeClasspath,debugUnitTestRuntimeClasspath,profileRuntimeClasspath,profileUnitTestRuntimeClasspath,releaseRuntimeClasspath,releaseUnitTestRuntimeClasspath +com.google.guava:guava:28.1-jre=lintClassPath +com.google.guava:listenablefuture:9999.0-empty-to-avoid-conflict-with-guava=debugAndroidTestCompileClasspath,debugRuntimeClasspath,debugUnitTestRuntimeClasspath,lintClassPath,profileRuntimeClasspath,profileUnitTestRuntimeClasspath,releaseRuntimeClasspath,releaseUnitTestRuntimeClasspath +com.google.j2objc:j2objc-annotations:1.3=debugRuntimeClasspath,debugUnitTestRuntimeClasspath,lintClassPath,profileRuntimeClasspath,profileUnitTestRuntimeClasspath,releaseRuntimeClasspath,releaseUnitTestRuntimeClasspath +com.google.jimfs:jimfs:1.1=lintClassPath +com.google.protobuf:protobuf-java:3.10.0=lintClassPath +com.googlecode.json-simple:json-simple:1.1=lintClassPath +com.squareup:javawriter:2.1.1=debugAndroidTestCompileClasspath,debugAndroidTestRuntimeClasspath,debugCompileClasspath,debugRuntimeClasspath,debugUnitTestCompileClasspath,debugUnitTestRuntimeClasspath,profileCompileClasspath,profileRuntimeClasspath,profileUnitTestCompileClasspath,profileUnitTestRuntimeClasspath,releaseCompileClasspath,releaseRuntimeClasspath,releaseUnitTestCompileClasspath,releaseUnitTestRuntimeClasspath +com.squareup:javawriter:2.5.0=lintClassPath +com.sun.activation:javax.activation:1.2.0=lintClassPath +com.sun.istack:istack-commons-runtime:3.0.7=lintClassPath +com.sun.xml.fastinfoset:FastInfoset:1.2.15=lintClassPath +commons-codec:commons-codec:1.10=lintClassPath +commons-logging:commons-logging:1.2=lintClassPath +it.unimi.dsi:fastutil:7.2.0=lintClassPath +javax.activation:javax.activation-api:1.2.0=lintClassPath +javax.inject:javax.inject:1=debugAndroidTestCompileClasspath,debugAndroidTestRuntimeClasspath,debugCompileClasspath,debugRuntimeClasspath,debugUnitTestCompileClasspath,debugUnitTestRuntimeClasspath,lintClassPath,profileCompileClasspath,profileRuntimeClasspath,profileUnitTestCompileClasspath,profileUnitTestRuntimeClasspath,releaseCompileClasspath,releaseRuntimeClasspath,releaseUnitTestCompileClasspath,releaseUnitTestRuntimeClasspath +javax.xml.bind:jaxb-api:2.3.1=lintClassPath +junit:junit:4.12=debugAndroidTestCompileClasspath,debugAndroidTestRuntimeClasspath,debugCompileClasspath,debugRuntimeClasspath,profileCompileClasspath,profileRuntimeClasspath,releaseCompileClasspath,releaseRuntimeClasspath +junit:junit:4.13.2=debugUnitTestCompileClasspath,debugUnitTestRuntimeClasspath,profileUnitTestCompileClasspath,profileUnitTestRuntimeClasspath,releaseUnitTestCompileClasspath,releaseUnitTestRuntimeClasspath +net.sf.jopt-simple:jopt-simple:4.9=lintClassPath +net.sf.kxml:kxml2:2.3.0=debugAndroidTestRuntimeClasspath,debugCompileClasspath,debugRuntimeClasspath,debugUnitTestCompileClasspath,debugUnitTestRuntimeClasspath,lintClassPath,profileCompileClasspath,profileRuntimeClasspath,profileUnitTestCompileClasspath,profileUnitTestRuntimeClasspath,releaseCompileClasspath,releaseRuntimeClasspath,releaseUnitTestCompileClasspath,releaseUnitTestRuntimeClasspath +org.apache.commons:commons-compress:1.12=lintClassPath +org.apache.httpcomponents:httpclient:4.5.6=lintClassPath +org.apache.httpcomponents:httpcore:4.4.10=lintClassPath +org.apache.httpcomponents:httpmime:4.5.6=lintClassPath +org.bouncycastle:bcpkix-jdk15on:1.56=lintClassPath +org.bouncycastle:bcprov-jdk15on:1.56=lintClassPath +org.checkerframework:checker-compat-qual:2.5.5=debugRuntimeClasspath,debugUnitTestRuntimeClasspath,profileRuntimeClasspath,profileUnitTestRuntimeClasspath,releaseRuntimeClasspath,releaseUnitTestRuntimeClasspath +org.checkerframework:checker-qual:2.8.1=lintClassPath +org.codehaus.groovy:groovy-all:2.4.15=lintClassPath +org.codehaus.mojo:animal-sniffer-annotations:1.18=debugRuntimeClasspath,debugUnitTestRuntimeClasspath,lintClassPath,profileRuntimeClasspath,profileUnitTestRuntimeClasspath,releaseRuntimeClasspath,releaseUnitTestRuntimeClasspath +org.glassfish.jaxb:jaxb-runtime:2.3.1=lintClassPath +org.glassfish.jaxb:txw2:2.3.1=lintClassPath +org.hamcrest:hamcrest-core:1.3=debugAndroidTestCompileClasspath,debugAndroidTestRuntimeClasspath,debugCompileClasspath,debugRuntimeClasspath,debugUnitTestCompileClasspath,debugUnitTestRuntimeClasspath,profileCompileClasspath,profileRuntimeClasspath,profileUnitTestCompileClasspath,profileUnitTestRuntimeClasspath,releaseCompileClasspath,releaseRuntimeClasspath,releaseUnitTestCompileClasspath,releaseUnitTestRuntimeClasspath +org.hamcrest:hamcrest-integration:1.3=debugAndroidTestCompileClasspath,debugAndroidTestRuntimeClasspath,debugCompileClasspath,debugRuntimeClasspath,debugUnitTestCompileClasspath,debugUnitTestRuntimeClasspath,profileCompileClasspath,profileRuntimeClasspath,profileUnitTestCompileClasspath,profileUnitTestRuntimeClasspath,releaseCompileClasspath,releaseRuntimeClasspath,releaseUnitTestCompileClasspath,releaseUnitTestRuntimeClasspath +org.hamcrest:hamcrest-library:1.3=debugAndroidTestCompileClasspath,debugAndroidTestRuntimeClasspath,debugCompileClasspath,debugRuntimeClasspath,debugUnitTestCompileClasspath,debugUnitTestRuntimeClasspath,profileCompileClasspath,profileRuntimeClasspath,profileUnitTestCompileClasspath,profileUnitTestRuntimeClasspath,releaseCompileClasspath,releaseRuntimeClasspath,releaseUnitTestCompileClasspath,releaseUnitTestRuntimeClasspath +org.jacoco:org.jacoco.agent:0.8.8=androidJacocoAnt +org.jacoco:org.jacoco.ant:0.8.8=androidJacocoAnt +org.jacoco:org.jacoco.core:0.8.8=androidJacocoAnt +org.jacoco:org.jacoco.report:0.8.8=androidJacocoAnt +org.jetbrains.kotlin:kotlin-reflect:1.3.72=lintClassPath +org.jetbrains.kotlin:kotlin-stdlib-common:1.3.72=lintClassPath +org.jetbrains.kotlin:kotlin-stdlib-common:1.5.31=debugAndroidTestCompileClasspath,debugCompileClasspath,debugRuntimeClasspath,debugUnitTestCompileClasspath,debugUnitTestRuntimeClasspath,profileCompileClasspath,profileRuntimeClasspath,profileUnitTestCompileClasspath,profileUnitTestRuntimeClasspath,releaseCompileClasspath,releaseRuntimeClasspath,releaseUnitTestCompileClasspath,releaseUnitTestRuntimeClasspath +org.jetbrains.kotlin:kotlin-stdlib-jdk7:1.3.72=lintClassPath +org.jetbrains.kotlin:kotlin-stdlib-jdk7:1.5.30=debugAndroidTestCompileClasspath,debugCompileClasspath,debugRuntimeClasspath,debugUnitTestCompileClasspath,debugUnitTestRuntimeClasspath,profileCompileClasspath,profileRuntimeClasspath,profileUnitTestCompileClasspath,profileUnitTestRuntimeClasspath,releaseCompileClasspath,releaseRuntimeClasspath,releaseUnitTestCompileClasspath,releaseUnitTestRuntimeClasspath +org.jetbrains.kotlin:kotlin-stdlib-jdk8:1.3.72=lintClassPath +org.jetbrains.kotlin:kotlin-stdlib-jdk8:1.5.30=debugAndroidTestCompileClasspath,debugCompileClasspath,debugRuntimeClasspath,debugUnitTestCompileClasspath,debugUnitTestRuntimeClasspath,profileCompileClasspath,profileRuntimeClasspath,profileUnitTestCompileClasspath,profileUnitTestRuntimeClasspath,releaseCompileClasspath,releaseRuntimeClasspath,releaseUnitTestCompileClasspath,releaseUnitTestRuntimeClasspath +org.jetbrains.kotlin:kotlin-stdlib:1.3.72=lintClassPath +org.jetbrains.kotlin:kotlin-stdlib:1.5.31=debugAndroidTestCompileClasspath,debugCompileClasspath,debugRuntimeClasspath,debugUnitTestCompileClasspath,debugUnitTestRuntimeClasspath,profileCompileClasspath,profileRuntimeClasspath,profileUnitTestCompileClasspath,profileUnitTestRuntimeClasspath,releaseCompileClasspath,releaseRuntimeClasspath,releaseUnitTestCompileClasspath,releaseUnitTestRuntimeClasspath +org.jetbrains.kotlinx:kotlinx-coroutines-android:1.5.2=debugAndroidTestCompileClasspath,debugCompileClasspath,debugRuntimeClasspath,debugUnitTestCompileClasspath,debugUnitTestRuntimeClasspath,profileCompileClasspath,profileRuntimeClasspath,profileUnitTestCompileClasspath,profileUnitTestRuntimeClasspath,releaseCompileClasspath,releaseRuntimeClasspath,releaseUnitTestCompileClasspath,releaseUnitTestRuntimeClasspath +org.jetbrains.kotlinx:kotlinx-coroutines-core-jvm:1.5.2=debugAndroidTestCompileClasspath,debugCompileClasspath,debugRuntimeClasspath,debugUnitTestCompileClasspath,debugUnitTestRuntimeClasspath,profileCompileClasspath,profileRuntimeClasspath,profileUnitTestCompileClasspath,profileUnitTestRuntimeClasspath,releaseCompileClasspath,releaseRuntimeClasspath,releaseUnitTestCompileClasspath,releaseUnitTestRuntimeClasspath +org.jetbrains.kotlinx:kotlinx-coroutines-core:1.5.2=debugAndroidTestCompileClasspath,debugCompileClasspath,debugRuntimeClasspath,debugUnitTestCompileClasspath,debugUnitTestRuntimeClasspath,profileCompileClasspath,profileRuntimeClasspath,profileUnitTestCompileClasspath,profileUnitTestRuntimeClasspath,releaseCompileClasspath,releaseRuntimeClasspath,releaseUnitTestCompileClasspath,releaseUnitTestRuntimeClasspath +org.jetbrains.trove4j:trove4j:20160824=lintClassPath +org.jetbrains:annotations:13.0=debugAndroidTestCompileClasspath,debugCompileClasspath,debugRuntimeClasspath,debugUnitTestCompileClasspath,debugUnitTestRuntimeClasspath,lintClassPath,profileCompileClasspath,profileRuntimeClasspath,profileUnitTestCompileClasspath,profileUnitTestRuntimeClasspath,releaseCompileClasspath,releaseRuntimeClasspath,releaseUnitTestCompileClasspath,releaseUnitTestRuntimeClasspath +org.jvnet.staxex:stax-ex:1.8=lintClassPath +org.ow2.asm:asm-analysis:7.0=lintClassPath +org.ow2.asm:asm-analysis:9.2=androidJacocoAnt +org.ow2.asm:asm-commons:7.0=lintClassPath +org.ow2.asm:asm-commons:9.2=androidJacocoAnt +org.ow2.asm:asm-tree:7.0=lintClassPath +org.ow2.asm:asm-tree:9.2=androidJacocoAnt +org.ow2.asm:asm-util:7.0=lintClassPath +org.ow2.asm:asm:7.0=lintClassPath +org.ow2.asm:asm:9.2=androidJacocoAnt +empty=androidApis,androidJdkImage,androidTestUtil,compile,coreLibraryDesugaring,debugAndroidTestAnnotationProcessorClasspath,debugAnnotationProcessorClasspath,debugReverseMetadataValues,debugUnitTestAnnotationProcessorClasspath,debugWearBundling,lintChecks,lintPublish,profileAnnotationProcessorClasspath,profileReverseMetadataValues,profileUnitTestAnnotationProcessorClasspath,profileWearBundling,releaseAnnotationProcessorClasspath,releaseReverseMetadataValues,releaseUnitTestAnnotationProcessorClasspath,releaseWearBundling,testCompile diff --git a/flutter/packages/integration_test/example/ios/Runner/Assets.xcassets/LaunchImage.imageset/Contents.json b/flutter/packages/integration_test/example/ios/Runner/Assets.xcassets/LaunchImage.imageset/Contents.json new file mode 100644 index 0000000000000000000000000000000000000000..0bedcf2fd46788ae3a01a423467513ff59b5c120 --- /dev/null +++ b/flutter/packages/integration_test/example/ios/Runner/Assets.xcassets/LaunchImage.imageset/Contents.json @@ -0,0 +1,23 @@ +{ + "images" : [ + { + "idiom" : "universal", + "filename" : "LaunchImage.png", + "scale" : "1x" + }, + { + "idiom" : "universal", + "filename" : "LaunchImage@2x.png", + "scale" : "2x" + }, + { + "idiom" : "universal", + "filename" : "LaunchImage@3x.png", + "scale" : "3x" + } + ], + "info" : { + "version" : 1, + "author" : "xcode" + } +} diff --git a/flutter/packages/integration_test/example/ios/Runner/Assets.xcassets/LaunchImage.imageset/LaunchImage.png b/flutter/packages/integration_test/example/ios/Runner/Assets.xcassets/LaunchImage.imageset/LaunchImage.png new file mode 100644 index 0000000000000000000000000000000000000000..9da19eacad3b03bb08bbddbbf4ac48dd78b3d838 Binary files /dev/null and b/flutter/packages/integration_test/example/ios/Runner/Assets.xcassets/LaunchImage.imageset/LaunchImage.png differ diff --git a/flutter/packages/integration_test/example/ios/Runner/Assets.xcassets/LaunchImage.imageset/LaunchImage@2x.png b/flutter/packages/integration_test/example/ios/Runner/Assets.xcassets/LaunchImage.imageset/LaunchImage@2x.png new file mode 100644 index 0000000000000000000000000000000000000000..9da19eacad3b03bb08bbddbbf4ac48dd78b3d838 Binary files /dev/null and b/flutter/packages/integration_test/example/ios/Runner/Assets.xcassets/LaunchImage.imageset/LaunchImage@2x.png differ diff --git a/flutter/packages/integration_test/example/ios/Runner/Assets.xcassets/LaunchImage.imageset/LaunchImage@3x.png b/flutter/packages/integration_test/example/ios/Runner/Assets.xcassets/LaunchImage.imageset/LaunchImage@3x.png new file mode 100644 index 0000000000000000000000000000000000000000..9da19eacad3b03bb08bbddbbf4ac48dd78b3d838 Binary files /dev/null and b/flutter/packages/integration_test/example/ios/Runner/Assets.xcassets/LaunchImage.imageset/LaunchImage@3x.png differ diff --git a/flutter/packages/integration_test/example/ios/Runner/Assets.xcassets/LaunchImage.imageset/README.md b/flutter/packages/integration_test/example/ios/Runner/Assets.xcassets/LaunchImage.imageset/README.md new file mode 100644 index 0000000000000000000000000000000000000000..89c2725b70f1882be97f5214fafe22d27a0ec01e --- /dev/null +++ b/flutter/packages/integration_test/example/ios/Runner/Assets.xcassets/LaunchImage.imageset/README.md @@ -0,0 +1,5 @@ +# Launch Screen Assets + +You can customize the launch screen with your own desired assets by replacing the image files in this directory. + +You can also do it by opening your Flutter project's Xcode project with `open ios/Runner.xcworkspace`, selecting `Runner/Assets.xcassets` in the Project Navigator and dropping in the desired images. \ No newline at end of file diff --git a/flutter/packages/integration_test/example/pubspec.lock b/flutter/packages/integration_test/example/pubspec.lock new file mode 100644 index 0000000000000000000000000000000000000000..9c1188a01f6f749c4c9d9559a04cb7c99c4b23ee --- /dev/null +++ b/flutter/packages/integration_test/example/pubspec.lock @@ -0,0 +1,523 @@ +# Generated by pub +# See https://dart.dev/tools/pub/glossary#lockfile +packages: + _fe_analyzer_shared: + dependency: "direct dev" + description: + name: _fe_analyzer_shared + sha256: "36a321c3d2cbe01cbcb3540a87b8843846e0206df3e691fa7b23e19e78de6d49" + url: "https://pub.dev" + source: hosted + version: "65.0.0" + analyzer: + dependency: "direct dev" + description: + name: analyzer + sha256: dfe03b90ec022450e22513b5e5ca1f01c0c01de9c3fba2f7fd233cb57a6b9a07 + url: "https://pub.dev" + source: hosted + version: "6.3.0" + args: + dependency: "direct dev" + description: + name: args + sha256: eef6c46b622e0494a36c5a12d10d77fb4e855501a91c1b9ef9339326e58f0596 + url: "https://pub.dev" + source: hosted + version: "2.4.2" + async: + dependency: "direct dev" + description: + name: async + sha256: "947bfcf187f74dbc5e146c9eb9c0f10c9f8b30743e341481c1e2ed3ecc18c20c" + url: "https://pub.dev" + source: hosted + version: "2.11.0" + boolean_selector: + dependency: "direct dev" + 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 dev" + 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" + convert: + dependency: "direct dev" + description: + name: convert + sha256: "0f08b14755d163f6e2134cb58222dd25ea2a2ee8a195e53983d57c075324d592" + url: "https://pub.dev" + source: hosted + version: "3.1.1" + coverage: + dependency: "direct dev" + description: + name: coverage + sha256: "8acabb8306b57a409bf4c83522065672ee13179297a6bb0cb9ead73948df7c76" + url: "https://pub.dev" + source: hosted + version: "1.7.2" + crypto: + dependency: "direct dev" + description: + name: crypto + sha256: ff625774173754681d66daaf4a448684fb04b78f902da9cb3d308c19cc5e8bab + url: "https://pub.dev" + source: hosted + version: "3.0.3" + cupertino_icons: + dependency: "direct main" + description: + name: cupertino_icons + sha256: d57953e10f9f8327ce64a508a355f0b1ec902193f66288e8cb5070e7c47eeb2d + url: "https://pub.dev" + source: hosted + version: "1.0.6" + fake_async: + dependency: "direct dev" + 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" + flutter_driver: + dependency: "direct dev" + description: flutter + source: sdk + version: "0.0.0" + flutter_test: + dependency: "direct dev" + description: flutter + source: sdk + version: "0.0.0" + frontend_server_client: + dependency: "direct dev" + description: + name: frontend_server_client + sha256: "408e3ca148b31c20282ad6f37ebfa6f4bdc8fede5b74bc2f08d9d92b55db3612" + url: "https://pub.dev" + source: hosted + version: "3.2.0" + fuchsia_remote_debug_protocol: + dependency: transitive + description: flutter + source: sdk + version: "0.0.0" + glob: + dependency: "direct dev" + description: + name: glob + sha256: "0e7014b3b7d4dac1ca4d6114f82bf1782ee86745b9b42a92c9289c23d8a0ab63" + url: "https://pub.dev" + source: hosted + version: "2.1.2" + http_multi_server: + dependency: "direct dev" + description: + name: http_multi_server + sha256: "97486f20f9c2f7be8f514851703d0119c3596d14ea63227af6f7a481ef2b2f8b" + url: "https://pub.dev" + source: hosted + version: "3.2.1" + http_parser: + dependency: "direct dev" + description: + name: http_parser + sha256: "2aa08ce0341cc9b354a498388e30986515406668dbcc4f7c950c3e715496693b" + url: "https://pub.dev" + source: hosted + version: "4.0.2" + integration_test: + dependency: "direct dev" + description: flutter + source: sdk + version: "0.0.0" + integration_test_macos: + dependency: "direct dev" + description: + path: "../integration_test_macos" + relative: true + source: path + version: "0.0.1+1" + io: + dependency: "direct dev" + description: + name: io + sha256: "2ec25704aba361659e10e3e5f5d672068d332fc8ac516421d483a11e5cbd061e" + url: "https://pub.dev" + source: hosted + version: "1.0.4" + js: + dependency: "direct dev" + description: + name: js + sha256: f2c445dce49627136094980615a031419f7f3eb393237e4ecd97ac15dea343f3 + url: "https://pub.dev" + source: hosted + version: "0.6.7" + leak_tracker: + dependency: "direct dev" + description: + name: leak_tracker + sha256: "78eb209deea09858f5269f5a5b02be4049535f568c07b275096836f01ea323fa" + url: "https://pub.dev" + source: hosted + version: "10.0.0" + leak_tracker_flutter_testing: + dependency: "direct dev" + description: + name: leak_tracker_flutter_testing + sha256: b46c5e37c19120a8a01918cfaf293547f47269f7cb4b0058f21531c2465d6ef0 + url: "https://pub.dev" + source: hosted + version: "2.0.1" + leak_tracker_testing: + dependency: "direct dev" + description: + name: leak_tracker_testing + sha256: a597f72a664dbd293f3bfc51f9ba69816f84dcd403cdac7066cb3f6003f3ab47 + url: "https://pub.dev" + source: hosted + version: "2.0.1" + logging: + dependency: "direct dev" + description: + name: logging + sha256: "623a88c9594aa774443aa3eb2d41807a48486b5613e67599fb4c41c0ad47c340" + url: "https://pub.dev" + source: hosted + version: "1.2.0" + matcher: + dependency: "direct dev" + 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" + mime: + dependency: "direct dev" + description: + name: mime + sha256: e4ff8e8564c03f255408decd16e7899da1733852a9110a58fe6d1b817684a63e + url: "https://pub.dev" + source: hosted + version: "1.0.4" + 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 dev" + description: + name: package_config + sha256: "1c5b77ccc91e4823a5af61ee74e6b972db1ef98c2ff5a18d3161c982a55448bd" + url: "https://pub.dev" + source: hosted + version: "2.1.0" + path: + dependency: "direct dev" + description: + name: path + sha256: "087ce49c3f0dc39180befefc60fdb4acd8f8620e5682fe2476afd0b3688bb4af" + url: "https://pub.dev" + source: hosted + version: "1.9.0" + pedantic: + dependency: "direct dev" + description: + name: pedantic + sha256: "67fc27ed9639506c856c840ccce7594d0bdcd91bc8d53d6e52359449a1d50602" + url: "https://pub.dev" + source: hosted + version: "1.11.1" + platform: + dependency: transitive + description: + name: platform + sha256: "12220bb4b65720483f8fa9450b4332347737cf8213dd2840d8b2c823e47243ec" + url: "https://pub.dev" + source: hosted + version: "3.1.4" + pool: + dependency: "direct dev" + description: + name: pool + sha256: "20fe868b6314b322ea036ba325e6fc0711a22948856475e2c2b6306e8ab39c2a" + url: "https://pub.dev" + source: hosted + version: "1.5.1" + process: + dependency: transitive + description: + name: process + sha256: "21e54fd2faf1b5bdd5102afd25012184a6793927648ea81eea80552ac9405b32" + url: "https://pub.dev" + source: hosted + version: "5.0.2" + pub_semver: + dependency: "direct dev" + description: + name: pub_semver + sha256: "40d3ab1bbd474c4c2328c91e3a7df8c6dd629b79ece4c4bd04bee496a224fb0c" + url: "https://pub.dev" + source: hosted + version: "2.1.4" + shelf: + dependency: "direct dev" + description: + name: shelf + sha256: ad29c505aee705f41a4d8963641f91ac4cee3c8fad5947e033390a7bd8180fa4 + url: "https://pub.dev" + source: hosted + version: "1.4.1" + shelf_packages_handler: + dependency: "direct dev" + description: + name: shelf_packages_handler + sha256: "89f967eca29607c933ba9571d838be31d67f53f6e4ee15147d5dc2934fee1b1e" + url: "https://pub.dev" + source: hosted + version: "3.0.2" + shelf_static: + dependency: "direct dev" + description: + name: shelf_static + sha256: a41d3f53c4adf0f57480578c1d61d90342cd617de7fc8077b1304643c2d85c1e + url: "https://pub.dev" + source: hosted + version: "1.1.2" + shelf_web_socket: + dependency: "direct dev" + description: + name: shelf_web_socket + sha256: "9ca081be41c60190ebcb4766b2486a7d50261db7bd0f5d9615f2d653637a84c1" + url: "https://pub.dev" + source: hosted + version: "1.0.4" + sky_engine: + dependency: transitive + description: flutter + source: sdk + version: "0.0.99" + source_map_stack_trace: + dependency: "direct dev" + description: + name: source_map_stack_trace + sha256: "84cf769ad83aa6bb61e0aa5a18e53aea683395f196a6f39c4c881fb90ed4f7ae" + url: "https://pub.dev" + source: hosted + version: "2.1.1" + source_maps: + dependency: "direct dev" + description: + name: source_maps + sha256: "708b3f6b97248e5781f493b765c3337db11c5d2c81c3094f10904bfa8004c703" + url: "https://pub.dev" + source: hosted + version: "0.10.12" + source_span: + dependency: "direct dev" + description: + name: source_span + sha256: "53e943d4206a5e30df338fd4c6e7a077e02254531b138a15aec3bd143c1a8b3c" + url: "https://pub.dev" + source: hosted + version: "1.10.0" + stack_trace: + dependency: "direct dev" + description: + name: stack_trace + sha256: "73713990125a6d93122541237550ee3352a2d84baad52d375a4cad2eb9b7ce0b" + url: "https://pub.dev" + source: hosted + version: "1.11.1" + stream_channel: + dependency: "direct dev" + description: + name: stream_channel + sha256: ba2aa5d8cc609d96bbb2899c28934f9e1af5cddbd60a827822ea467161eb54e7 + url: "https://pub.dev" + source: hosted + version: "2.1.2" + string_scanner: + dependency: "direct dev" + description: + name: string_scanner + sha256: "556692adab6cfa87322a115640c11f13cb77b3f076ddcc5d6ae3c20242bedcde" + url: "https://pub.dev" + source: hosted + version: "1.2.0" + sync_http: + dependency: "direct dev" + description: + name: sync_http + sha256: "7f0cd72eca000d2e026bcd6f990b81d0ca06022ef4e32fb257b30d3d1014a961" + url: "https://pub.dev" + source: hosted + version: "0.3.1" + term_glyph: + dependency: "direct dev" + 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 dev" + description: + name: test_api + sha256: "5c2f730018264d276c20e4f1503fd1308dfbbae39ec8ee63c5236311ac06954b" + url: "https://pub.dev" + source: hosted + version: "0.6.1" + test_core: + dependency: "direct dev" + description: + name: test_core + sha256: a757b14fc47507060a162cc2530d9a4a2f92f5100a952c7443b5cad5ef5b106a + url: "https://pub.dev" + source: hosted + version: "0.5.9" + typed_data: + dependency: "direct dev" + description: + name: typed_data + sha256: facc8d6582f16042dd49f2463ff1bd6e2c9ef9f3d5da3d9b087e244a7b564b3c + url: "https://pub.dev" + source: hosted + version: "1.3.2" + 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 dev" + description: + name: vm_service + sha256: b3d56ff4341b8f182b96aceb2fa20e3dcb336b9f867bc0eafc0de10f1048e957 + url: "https://pub.dev" + source: hosted + version: "13.0.0" + watcher: + dependency: "direct dev" + description: + name: watcher + sha256: "3d2ad6751b3c16cf07c7fca317a1413b3f26530319181b37e3b9039b84fc01d8" + url: "https://pub.dev" + source: hosted + version: "1.1.0" + web: + dependency: "direct dev" + description: + name: web + sha256: edc8a9573dd8c5a83a183dae1af2b6fd4131377404706ca4e5420474784906fa + url: "https://pub.dev" + source: hosted + version: "0.4.0" + web_socket_channel: + dependency: "direct dev" + description: + name: web_socket_channel + sha256: "045ec2137c27bf1a32e6ffa0e734d532a6677bf9016a0d1a406c54e499ff945b" + url: "https://pub.dev" + source: hosted + version: "2.4.1" + webdriver: + dependency: "direct dev" + description: + name: webdriver + sha256: "003d7da9519e1e5f329422b36c4dcdf18d7d2978d1ba099ea4e45ba490ed845e" + url: "https://pub.dev" + source: hosted + version: "3.0.3" + webkit_inspection_protocol: + dependency: "direct dev" + description: + name: webkit_inspection_protocol + sha256: "87d3f2333bb240704cd3f1c6b5b7acd8a10e7f0bc28c28dcf14e782014f4a572" + url: "https://pub.dev" + source: hosted + version: "1.2.1" + yaml: + dependency: "direct dev" + description: + name: yaml + sha256: "75769501ea3489fca56601ff33454fe45507ea3bfb014161abc3b43ae25989d5" + url: "https://pub.dev" + source: hosted + version: "3.1.2" +sdks: + dart: ">=3.2.0 <4.0.0" + flutter: ">=1.6.7" diff --git a/flutter/packages/integration_test/example/pubspec.yaml b/flutter/packages/integration_test/example/pubspec.yaml new file mode 100644 index 0000000000000000000000000000000000000000..158bcd7ea30bae074f73c27b71a9d509e1c4331f --- /dev/null +++ b/flutter/packages/integration_test/example/pubspec.yaml @@ -0,0 +1,90 @@ +name: integration_test_example +description: Demonstrates how to use the integration_test plugin. +publish_to: 'none' + +environment: + sdk: '>=3.2.0-0 <4.0.0' + flutter: ">=1.6.7" + +dependencies: + flutter: + sdk: flutter + + cupertino_icons: 1.0.6 + + 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" + 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" + vector_math: 2.1.4 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" + +dev_dependencies: + flutter_test: + sdk: flutter + flutter_driver: + sdk: flutter + integration_test: + sdk: flutter + integration_test_macos: + path: ../integration_test_macos + test: 1.24.9 + pedantic: 1.11.1 + +# For information on the generic Dart part of this file, see the +# following page: https://dart.dev/tools/pub/pubspec + + _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" + args: 2.4.2 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" + 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" + clock: 1.1.1 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" + convert: 3.1.1 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" + coverage: 1.7.2 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" + crypto: 3.0.3 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" + fake_async: 1.3.1 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" + file: 7.0.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_multi_server: 3.2.1 # 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" + leak_tracker: 10.0.0 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" + leak_tracker_flutter_testing: 2.0.1 # 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" + logging: 1.2.0 # 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" + mime: 1.0.4 # 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" + package_config: 2.1.0 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" + path: 1.9.0 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" + pool: 1.5.1 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" + pub_semver: 2.1.4 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" + shelf: 1.4.1 # 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_static: 1.1.2 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" + shelf_web_socket: 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" + stack_trace: 1.11.1 # 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" + 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" + test_api: 0.6.1 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" + test_core: 0.5.9 # 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: 13.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" + web_socket_channel: 2.4.1 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" + webdriver: 3.0.3 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" + webkit_inspection_protocol: 1.2.1 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" + yaml: 3.1.2 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" + +flutter: + uses-material-design: true + +# PUBSPEC CHECKSUM: b58f diff --git a/flutter/packages/integration_test/integration_test_macos/CHANGELOG.md b/flutter/packages/integration_test/integration_test_macos/CHANGELOG.md new file mode 100644 index 0000000000000000000000000000000000000000..ab4bac1a3f3fbd1099d2702f952252229fd269f9 --- /dev/null +++ b/flutter/packages/integration_test/integration_test_macos/CHANGELOG.md @@ -0,0 +1,11 @@ +## 0.0.2 + +* Renames package to integration_test_macos. + +## 0.0.1+1 + +* Remove Android folder from `e2e_macos`. + +## 0.0.1 + +* Initial release diff --git a/flutter/packages/integration_test/integration_test_macos/ios/integration_test_macos.podspec b/flutter/packages/integration_test/integration_test_macos/ios/integration_test_macos.podspec new file mode 100644 index 0000000000000000000000000000000000000000..6034ec28510d03cd1d3baf4cb02bc67bd46b2ed9 --- /dev/null +++ b/flutter/packages/integration_test/integration_test_macos/ios/integration_test_macos.podspec @@ -0,0 +1,21 @@ +# +# To learn more about a Podspec see http://guides.cocoapods.org/syntax/podspec.html +# +Pod::Spec.new do |s| + s.name = 'IntegrationTestMacOS' + s.version = '0.0.1' + s.summary = 'No-op implementation of the integration_test desktop plugin to avoid build issues on iOS' + s.description = <<-DESC + No-op implementation of integration to avoid build issues on iOS. + See https://github.com/flutter/flutter/issues/39659 + DESC + s.homepage = 'https://github.com/flutter/flutter/tree/master/packages/integration_test/integration_test_macos' + s.license = { :file => '../LICENSE' } + s.author = { 'Flutter Team' => 'flutter-dev@googlegroups.com' } + s.source = { :path => '.' } + s.source_files = 'Classes/**/*' + s.public_header_files = 'Classes/**/*.h' + s.dependency 'Flutter' + + s.ios.deployment_target = '8.0' +end diff --git a/flutter/packages/integration_test/integration_test_macos/macos/Classes/IntegrationTestPlugin.swift b/flutter/packages/integration_test/integration_test_macos/macos/Classes/IntegrationTestPlugin.swift new file mode 100644 index 0000000000000000000000000000000000000000..cb3127f007aad4d76e7240fa9d905bd13f4b708e --- /dev/null +++ b/flutter/packages/integration_test/integration_test_macos/macos/Classes/IntegrationTestPlugin.swift @@ -0,0 +1,26 @@ +// 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 FlutterMacOS + +public class IntegrationTestPlugin: NSObject, FlutterPlugin { + + public static func register(with registrar: FlutterPluginRegistrar) { + let channel = FlutterMethodChannel( + name: "plugins.flutter.io/integration_test", + binaryMessenger: registrar.messenger) + + let instance = IntegrationTestPlugin() + registrar.addMethodCallDelegate(instance, channel: channel) + } + + public func handle(_ call: FlutterMethodCall, result: @escaping FlutterResult) { + switch call.method { + case "allTestsFinished": + result(nil) + default: + result(FlutterMethodNotImplemented) + } + } +} diff --git a/flutter/packages/integration_test/integration_test_macos/macos/integration_test_macos.podspec b/flutter/packages/integration_test/integration_test_macos/macos/integration_test_macos.podspec new file mode 100644 index 0000000000000000000000000000000000000000..a8b6e233901abebace9177f2bce268416fb91869 --- /dev/null +++ b/flutter/packages/integration_test/integration_test_macos/macos/integration_test_macos.podspec @@ -0,0 +1,24 @@ +# +# To learn more about a Podspec see http://guides.cocoapods.org/syntax/podspec.html +# +Pod::Spec.new do |s| + s.name = 'integration_test_macos' + s.version = '0.0.1' + s.summary = 'Adapter for integration tests.' + s.description = <<-DESC +Runs tests that use the flutter_test API as integration tests on macOS. + DESC + s.homepage = 'https://github.com/flutter/flutter/tree/master/packages/integration_test/integration_test_macos' + s.license = { :type => 'BSD', :text => <<-LICENSE +Use of this source code is governed by a BSD-style license that can be found in the LICENSE file. +LICENSE + } + s.author = { 'Flutter Team' => 'flutter-dev@googlegroups.com' } + s.source = { :http => 'https://github.com/flutter/flutter/tree/master/packages/integration_test/integration_test_macos' } + s.source_files = 'Classes/**/*' + s.dependency 'FlutterMacOS' + + s.platform = :osx, '10.11' + s.swift_version = '5.0' + s.pod_target_xcconfig = { 'DEFINES_MODULE' => 'YES' } +end diff --git a/flutter/packages/integration_test/integration_test_macos/macos/integration_test_macos/Package.swift b/flutter/packages/integration_test/integration_test_macos/macos/integration_test_macos/Package.swift new file mode 100644 index 0000000000000000000000000000000000000000..9ef9c76b9b261019c1f021d2165d99b2b00ada93 --- /dev/null +++ b/flutter/packages/integration_test/integration_test_macos/macos/integration_test_macos/Package.swift @@ -0,0 +1,22 @@ +// swift-tools-version: 5.9 +// The swift-tools-version declares the minimum version of Swift required to build this package. + +import PackageDescription + +let package = Package( + name: "integration_test_macos", + platforms: [ + .macOS("10.14"), + ], + products: [ + .library(name: "integration-test-macos", targets: ["integration_test_macos"]), + ], + targets: [ + .target( + name: "integration_test_macos", + resources: [ + .process("Resources"), + ] + ), + ] +) diff --git a/flutter/packages/integration_test/integration_test_macos/macos/integration_test_macos/Sources/integration_test_macos/IntegrationTestPlugin.swift b/flutter/packages/integration_test/integration_test_macos/macos/integration_test_macos/Sources/integration_test_macos/IntegrationTestPlugin.swift new file mode 100644 index 0000000000000000000000000000000000000000..cb3127f007aad4d76e7240fa9d905bd13f4b708e --- /dev/null +++ b/flutter/packages/integration_test/integration_test_macos/macos/integration_test_macos/Sources/integration_test_macos/IntegrationTestPlugin.swift @@ -0,0 +1,26 @@ +// 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 FlutterMacOS + +public class IntegrationTestPlugin: NSObject, FlutterPlugin { + + public static func register(with registrar: FlutterPluginRegistrar) { + let channel = FlutterMethodChannel( + name: "plugins.flutter.io/integration_test", + binaryMessenger: registrar.messenger) + + let instance = IntegrationTestPlugin() + registrar.addMethodCallDelegate(instance, channel: channel) + } + + public func handle(_ call: FlutterMethodCall, result: @escaping FlutterResult) { + switch call.method { + case "allTestsFinished": + result(nil) + default: + result(FlutterMethodNotImplemented) + } + } +} diff --git a/flutter/packages/integration_test/integration_test_macos/pubspec.lock b/flutter/packages/integration_test/integration_test_macos/pubspec.lock new file mode 100644 index 0000000000000000000000000000000000000000..a75541058df815ebe6acda386c6801c8fd4d964a --- /dev/null +++ b/flutter/packages/integration_test/integration_test_macos/pubspec.lock @@ -0,0 +1,63 @@ +# Generated by pub +# See https://dart.dev/tools/pub/glossary#lockfile +packages: + characters: + dependency: "direct main" + description: + name: characters + sha256: "04a925763edad70e8443c99234dc3328f442e811f1d8fd1a72f1c8ad0f69a605" + url: "https://pub.dev" + source: hosted + version: "1.3.0" + collection: + dependency: "direct main" + description: + name: collection + sha256: ee67cb0715911d28db6bf4af1026078bd6f0128b07a5f66fb2ed94ec6783c09a + url: "https://pub.dev" + source: hosted + version: "1.18.0" + flutter: + dependency: "direct main" + description: flutter + source: sdk + version: "0.0.0" + 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" + pedantic: + dependency: "direct dev" + description: + name: pedantic + sha256: "67fc27ed9639506c856c840ccce7594d0bdcd91bc8d53d6e52359449a1d50602" + url: "https://pub.dev" + source: hosted + version: "1.11.1" + sky_engine: + dependency: transitive + description: flutter + source: sdk + version: "0.0.99" + vector_math: + dependency: "direct main" + description: + name: vector_math + sha256: "80b3257d1492ce4d091729e3a67a60407d227c27241d6927be0130c98e741803" + url: "https://pub.dev" + source: hosted + version: "2.1.4" +sdks: + dart: ">=3.2.0-0 <4.0.0" diff --git a/flutter/packages/integration_test/integration_test_macos/pubspec.yaml b/flutter/packages/integration_test/integration_test_macos/pubspec.yaml new file mode 100644 index 0000000000000000000000000000000000000000..b5c03f869d4cbe4884012337d087647d7be33667 --- /dev/null +++ b/flutter/packages/integration_test/integration_test_macos/pubspec.yaml @@ -0,0 +1,28 @@ +name: integration_test_macos +description: Desktop implementation of integration_test plugin +version: 0.0.1+1 +homepage: https://github.com/flutter/flutter/tree/master/packages/integration_test/integration_test_macos + +flutter: + plugin: + platforms: + macos: + pluginClass: IntegrationTestPlugin + +environment: + sdk: '>=3.2.0-0 <4.0.0' + +dependencies: + flutter: + sdk: flutter + + 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" + 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" + vector_math: 2.1.4 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" + +dev_dependencies: + pedantic: 1.11.1 + +# PUBSPEC CHECKSUM: d95b diff --git a/flutter/packages/integration_test/ios/Classes/FLTIntegrationTestRunner.h b/flutter/packages/integration_test/ios/Classes/FLTIntegrationTestRunner.h new file mode 100644 index 0000000000000000000000000000000000000000..65568fc71173d970e14ca0806a452125d8bfce84 --- /dev/null +++ b/flutter/packages/integration_test/ios/Classes/FLTIntegrationTestRunner.h @@ -0,0 +1,36 @@ +// 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 Foundation; + +@class UIImage; + +NS_ASSUME_NONNULL_BEGIN + +typedef void (^FLTIntegrationTestResults)(SEL nativeTestSelector, BOOL success, NSString *_Nullable failureMessage); + +@interface FLTIntegrationTestRunner : NSObject + +/** + * Any screenshots captured by the plugin. + */ +@property (copy, readonly) NSDictionary *capturedScreenshotsByName; + +/** + * Starts dart tests and waits for results. + * + * @param testResult Will be called once per every completed dart test. + */ +- (void)testIntegrationTestWithResults:(NS_NOESCAPE FLTIntegrationTestResults)testResult; + +/** + * An appropriate XCTest method name based on the dart test name. + * + * Example: dart test "verify widget-ABC123" becomes "testVerifyWidgetABC123" + */ ++ (NSString *)testCaseNameFromDartTestName:(NSString *)dartTestName; + +@end + +NS_ASSUME_NONNULL_END diff --git a/flutter/packages/integration_test/ios/Classes/FLTIntegrationTestRunner.m b/flutter/packages/integration_test/ios/Classes/FLTIntegrationTestRunner.m new file mode 100644 index 0000000000000000000000000000000000000000..a6c57dff78977df60e22ee626ea689fc62b0d407 --- /dev/null +++ b/flutter/packages/integration_test/ios/Classes/FLTIntegrationTestRunner.m @@ -0,0 +1,70 @@ +// 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 "FLTIntegrationTestRunner.h" + +#import "IntegrationTestPlugin.h" + +@import ObjectiveC.runtime; +@import UIKit; + +@interface FLTIntegrationTestRunner () + +@property IntegrationTestPlugin *integrationTestPlugin; + +@end + +@implementation FLTIntegrationTestRunner + +- (instancetype)init { + self = [super init]; + _integrationTestPlugin = [IntegrationTestPlugin instance]; + + return self; +} + +- (void)testIntegrationTestWithResults:(NS_NOESCAPE FLTIntegrationTestResults)testResult { + IntegrationTestPlugin *integrationTestPlugin = self.integrationTestPlugin; + // Spin the runloop. + while (!integrationTestPlugin.testResults) { + [NSRunLoop.currentRunLoop runUntilDate:[NSDate dateWithTimeIntervalSinceNow:1.0]]; + } + + NSMutableSet *testCaseNames = [[NSMutableSet alloc] init]; + + [integrationTestPlugin.testResults enumerateKeysAndObjectsUsingBlock:^(NSString *test, NSString *result, BOOL *stop) { + NSString *testSelectorName = [[self class] testCaseNameFromDartTestName:test]; + + // Validate Objective-C test names are unique after sanitization. + if ([testCaseNames containsObject:testSelectorName]) { + NSString *reason = [NSString stringWithFormat:@"Cannot test \"%@\", duplicate XCTestCase tests named %@", test, testSelectorName]; + testResult(NSSelectorFromString(@"testDuplicateTestNames"), NO, reason); + *stop = YES; + return; + } + [testCaseNames addObject:testSelectorName]; + SEL testSelector = NSSelectorFromString(testSelectorName); + + if ([result isEqualToString:@"success"]) { + testResult(testSelector, YES, nil); + } else { + testResult(testSelector, NO, result); + } + }]; +} + +- (NSDictionary *)capturedScreenshotsByName { + return self.integrationTestPlugin.capturedScreenshotsByName; +} + ++ (NSString *)testCaseNameFromDartTestName:(NSString *)dartTestName { + NSString *capitalizedString = dartTestName.localizedCapitalizedString; + // Objective-C method names must be alphanumeric. + NSCharacterSet *disallowedCharacters = NSCharacterSet.alphanumericCharacterSet.invertedSet; + // Remove disallowed characters. + NSString *upperCamelTestName = [[capitalizedString componentsSeparatedByCharactersInSet:disallowedCharacters] componentsJoinedByString:@""]; + return [NSString stringWithFormat:@"test%@", upperCamelTestName]; +} + +@end diff --git a/flutter/packages/integration_test/ios/Classes/IntegrationTestIosTest.h b/flutter/packages/integration_test/ios/Classes/IntegrationTestIosTest.h new file mode 100644 index 0000000000000000000000000000000000000000..33aaea52a10ce02fe27bf683473b2bc58cf09b85 --- /dev/null +++ b/flutter/packages/integration_test/ios/Classes/IntegrationTestIosTest.h @@ -0,0 +1,68 @@ +// 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 Foundation; +@import ObjectiveC.runtime; + +NS_ASSUME_NONNULL_BEGIN + +DEPRECATED_MSG_ATTRIBUTE("Use FLTIntegrationTestRunner instead.") +@interface IntegrationTestIosTest : NSObject + +/** + * Initiate dart tests and wait for results. @c testResult will be set to a string describing the results. + * + * @return @c YES if all tests succeeded. + */ +- (BOOL)testIntegrationTest:(NSString *_Nullable *_Nullable)testResult; + +@end + +// For every Flutter dart test, dynamically generate an Objective-C method mirroring the test results +// so it is reported as a native XCTest run result. +// If the Flutter dart tests have captured screenshots, add them to the XCTest bundle. +#define INTEGRATION_TEST_IOS_RUNNER(__test_class) \ + @interface __test_class : XCTestCase \ + @end \ + \ + @implementation __test_class \ + \ + + (NSArray *)testInvocations { \ + FLTIntegrationTestRunner *integrationTestRunner = [[FLTIntegrationTestRunner alloc] init]; \ + NSMutableArray *testInvocations = [[NSMutableArray alloc] init]; \ + [integrationTestRunner testIntegrationTestWithResults:^(SEL testSelector, BOOL success, NSString *failureMessage) { \ + IMP assertImplementation = imp_implementationWithBlock(^(id _self) { \ + XCTAssertTrue(success, @"%@", failureMessage); \ + }); \ + class_addMethod(self, testSelector, assertImplementation, "v@:"); \ + NSMethodSignature *signature = [self instanceMethodSignatureForSelector:testSelector]; \ + NSInvocation *invocation = [NSInvocation invocationWithMethodSignature:signature]; \ + invocation.selector = testSelector; \ + [testInvocations addObject:invocation]; \ + }]; \ + NSDictionary *capturedScreenshotsByName = integrationTestRunner.capturedScreenshotsByName; \ + if (capturedScreenshotsByName.count > 0) { \ + IMP screenshotImplementation = imp_implementationWithBlock(^(id _self) { \ + [capturedScreenshotsByName enumerateKeysAndObjectsUsingBlock:^(NSString *name, UIImage *screenshot, BOOL *stop) { \ + XCTAttachment *attachment = [XCTAttachment attachmentWithImage:screenshot]; \ + attachment.lifetime = XCTAttachmentLifetimeKeepAlways; \ + if (name != nil) { \ + attachment.name = name; \ + } \ + [_self addAttachment:attachment]; \ + }]; \ + }); \ + SEL attachmentSelector = NSSelectorFromString(@"screenshotPlaceholder"); \ + class_addMethod(self, attachmentSelector, screenshotImplementation, "v@:"); \ + NSMethodSignature *attachmentSignature = [self instanceMethodSignatureForSelector:attachmentSelector]; \ + NSInvocation *attachmentInvocation = [NSInvocation invocationWithMethodSignature:attachmentSignature]; \ + attachmentInvocation.selector = attachmentSelector; \ + [testInvocations addObject:attachmentInvocation]; \ + } \ + return testInvocations; \ + } \ + \ + @end + +NS_ASSUME_NONNULL_END diff --git a/flutter/packages/integration_test/ios/Classes/IntegrationTestIosTest.m b/flutter/packages/integration_test/ios/Classes/IntegrationTestIosTest.m new file mode 100644 index 0000000000000000000000000000000000000000..808fa94eac0f2ec464e0d948971c03a312f92a0e --- /dev/null +++ b/flutter/packages/integration_test/ios/Classes/IntegrationTestIosTest.m @@ -0,0 +1,42 @@ +// 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 "IntegrationTestIosTest.h" + +#import "IntegrationTestPlugin.h" +#import "FLTIntegrationTestRunner.h" + +#pragma mark - Deprecated + +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wdeprecated-implementations" + +@implementation IntegrationTestIosTest + +- (BOOL)testIntegrationTest:(NSString **)testResult { + NSLog(@"==================== Test Results ====================="); + NSMutableArray *failedTests = [NSMutableArray array]; + NSMutableArray *testNames = [NSMutableArray array]; + [[FLTIntegrationTestRunner new] testIntegrationTestWithResults:^(SEL testSelector, BOOL success, NSString *message) { + NSString *testName = NSStringFromSelector(testSelector); + [testNames addObject:testName]; + if (success) { + NSLog(@"%@ passed.", testName); + } else { + NSLog(@"%@ failed: %@", testName, message); + [failedTests addObject:testName]; + } + }]; + NSLog(@"================== Test Results End ===================="); + BOOL testPass = failedTests.count == 0; + if (!testPass && testResult != NULL) { + *testResult = + [NSString stringWithFormat:@"Detected failed integration test(s) %@ among %@", + failedTests.description, testNames.description]; + } + return testPass; +} + +@end +#pragma clang diagnostic pop diff --git a/flutter/packages/integration_test/ios/Classes/IntegrationTestPlugin.h b/flutter/packages/integration_test/ios/Classes/IntegrationTestPlugin.h new file mode 100644 index 0000000000000000000000000000000000000000..e9cbd663b8dae38b52cde1214aacd9235d34e13a --- /dev/null +++ b/flutter/packages/integration_test/ios/Classes/IntegrationTestPlugin.h @@ -0,0 +1,31 @@ +// 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 + +NS_ASSUME_NONNULL_BEGIN + +/** A Flutter plugin that's responsible for communicating the test results back + * to iOS XCTest. */ +@interface IntegrationTestPlugin : NSObject + +/** + * Test results that are sent from Dart when integration test completes. Before the + * completion, it is @c nil. + */ +@property(nonatomic, readonly, nullable) NSDictionary *testResults; + +/** + * Mapping of screenshot images by suggested names, captured by the dart tests. + */ +@property (copy, readonly) NSDictionary *capturedScreenshotsByName; + +/** Fetches the singleton instance of the plugin. */ ++ (instancetype)instance; + +- (instancetype)init NS_UNAVAILABLE; + +@end + +NS_ASSUME_NONNULL_END diff --git a/flutter/packages/integration_test/ios/Classes/IntegrationTestPlugin.m b/flutter/packages/integration_test/ios/Classes/IntegrationTestPlugin.m new file mode 100644 index 0000000000000000000000000000000000000000..b3ac58138f3def0858e4fb8ddd68590362aa7c33 --- /dev/null +++ b/flutter/packages/integration_test/ios/Classes/IntegrationTestPlugin.m @@ -0,0 +1,90 @@ +// 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 "IntegrationTestPlugin.h" + +@import UIKit; + +static NSString *const kIntegrationTestPluginChannel = @"plugins.flutter.io/integration_test"; +static NSString *const kMethodTestFinished = @"allTestsFinished"; +static NSString *const kMethodScreenshot = @"captureScreenshot"; +static NSString *const kMethodConvertSurfaceToImage = @"convertFlutterSurfaceToImage"; +static NSString *const kMethodRevertImage = @"revertFlutterImage"; + +@interface IntegrationTestPlugin () + +@property(nonatomic, readwrite) NSDictionary *testResults; + +- (instancetype)init NS_DESIGNATED_INITIALIZER; + +@end + +@implementation IntegrationTestPlugin { + NSDictionary *_testResults; + NSMutableDictionary *_capturedScreenshotsByName; +} + ++ (instancetype)instance { + static dispatch_once_t onceToken; + static IntegrationTestPlugin *sInstance; + dispatch_once(&onceToken, ^{ + sInstance = [[IntegrationTestPlugin alloc] initForRegistration]; + }); + return sInstance; +} + +- (instancetype)initForRegistration { + return [self init]; +} + +- (instancetype)init { + self = [super init]; + _capturedScreenshotsByName = [NSMutableDictionary new]; + return self; +} + ++ (void)registerWithRegistrar:(NSObject *)registrar { + FlutterMethodChannel *channel = [FlutterMethodChannel methodChannelWithName:kIntegrationTestPluginChannel + binaryMessenger:registrar.messenger]; + [registrar addMethodCallDelegate:[self instance] channel:channel]; +} + +- (void)handleMethodCall:(FlutterMethodCall *)call result:(FlutterResult)result { + if ([call.method isEqualToString:kMethodTestFinished]) { + self.testResults = call.arguments[@"results"]; + result(nil); + } else if ([call.method isEqualToString:kMethodScreenshot]) { + // If running as a native Xcode test, attach to test. + UIImage *screenshot = [self capturePngScreenshot]; + NSString *name = call.arguments[@"name"]; + _capturedScreenshotsByName[name] = screenshot; + + // Also pass back along the channel for the driver to handle. + NSData *pngData = UIImagePNGRepresentation(screenshot); + result([FlutterStandardTypedData typedDataWithBytes:pngData]); + } else if ([call.method isEqualToString:kMethodConvertSurfaceToImage] + || [call.method isEqualToString:kMethodRevertImage]) { + // Android only, no-op on iOS. + result(nil); + } else { + result(FlutterMethodNotImplemented); + } +} + +- (UIImage *)capturePngScreenshot { + UIWindow *window = [UIApplication.sharedApplication.windows + filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:@"keyWindow = YES"]].firstObject; + CGRect screenshotBounds = window.bounds; + UIImage *image; + + UIGraphicsImageRenderer *renderer = [[UIGraphicsImageRenderer alloc] initWithBounds:screenshotBounds]; + + image = [renderer imageWithActions:^(UIGraphicsImageRendererContext *rendererContext) { + [window drawViewHierarchyInRect:screenshotBounds afterScreenUpdates:YES]; + }]; + + return image; +} + +@end diff --git a/flutter/packages/integration_test/ios/integration_test.podspec b/flutter/packages/integration_test/ios/integration_test.podspec new file mode 100644 index 0000000000000000000000000000000000000000..0a67820711e0bb8e7fa36caa9e9c6bec564ebaa8 --- /dev/null +++ b/flutter/packages/integration_test/ios/integration_test.podspec @@ -0,0 +1,25 @@ +# +# To learn more about a Podspec see http://guides.cocoapods.org/syntax/podspec.html +# +Pod::Spec.new do |s| + s.name = 'integration_test' + s.version = '0.0.1' + s.summary = 'Adapter for integration tests.' + s.description = <<-DESC +Runs tests that use the flutter_test API as integration tests. + DESC + s.homepage = 'https://github.com/flutter/flutter/tree/master/packages/integration_test' + s.license = { :type => 'BSD', :text => <<-LICENSE +Use of this source code is governed by a BSD-style license that can be found in the LICENSE file. +LICENSE + } + s.author = { 'Flutter Team' => 'flutter-dev@googlegroups.com' } + s.source = { :http => 'https://github.com/flutter/flutter/tree/master/packages/integration_test' } + s.source_files = 'Classes/**/*' + s.public_header_files = 'Classes/**/*.h' + s.dependency 'Flutter' + s.ios.framework = 'UIKit' + + s.platform = :ios, '11.0' + s.pod_target_xcconfig = { 'DEFINES_MODULE' => 'YES', 'EXCLUDED_ARCHS[sdk=iphonesimulator*]' => 'i386' } +end diff --git a/flutter/packages/integration_test/ios/integration_test/Package.swift b/flutter/packages/integration_test/ios/integration_test/Package.swift new file mode 100644 index 0000000000000000000000000000000000000000..b9bd1a9a450772cf07c71391cc0548140a00bc0f --- /dev/null +++ b/flutter/packages/integration_test/ios/integration_test/Package.swift @@ -0,0 +1,25 @@ +// swift-tools-version: 5.9 +// The swift-tools-version declares the minimum version of Swift required to build this package. + +import PackageDescription + +let package = Package( + name: "integration_test", + platforms: [ + .iOS("12.0"), + ], + products: [ + .library(name: "integration-test", targets: ["integration_test"]), + ], + targets: [ + .target( + name: "integration_test", + resources: [ + .process("Resources"), + ], + cSettings: [ + .headerSearchPath("include/integration_test"), + ] + ), + ] +) diff --git a/flutter/packages/integration_test/ios/integration_test/Sources/integration_test/FLTIntegrationTestRunner.m b/flutter/packages/integration_test/ios/integration_test/Sources/integration_test/FLTIntegrationTestRunner.m new file mode 100644 index 0000000000000000000000000000000000000000..a6c57dff78977df60e22ee626ea689fc62b0d407 --- /dev/null +++ b/flutter/packages/integration_test/ios/integration_test/Sources/integration_test/FLTIntegrationTestRunner.m @@ -0,0 +1,70 @@ +// 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 "FLTIntegrationTestRunner.h" + +#import "IntegrationTestPlugin.h" + +@import ObjectiveC.runtime; +@import UIKit; + +@interface FLTIntegrationTestRunner () + +@property IntegrationTestPlugin *integrationTestPlugin; + +@end + +@implementation FLTIntegrationTestRunner + +- (instancetype)init { + self = [super init]; + _integrationTestPlugin = [IntegrationTestPlugin instance]; + + return self; +} + +- (void)testIntegrationTestWithResults:(NS_NOESCAPE FLTIntegrationTestResults)testResult { + IntegrationTestPlugin *integrationTestPlugin = self.integrationTestPlugin; + // Spin the runloop. + while (!integrationTestPlugin.testResults) { + [NSRunLoop.currentRunLoop runUntilDate:[NSDate dateWithTimeIntervalSinceNow:1.0]]; + } + + NSMutableSet *testCaseNames = [[NSMutableSet alloc] init]; + + [integrationTestPlugin.testResults enumerateKeysAndObjectsUsingBlock:^(NSString *test, NSString *result, BOOL *stop) { + NSString *testSelectorName = [[self class] testCaseNameFromDartTestName:test]; + + // Validate Objective-C test names are unique after sanitization. + if ([testCaseNames containsObject:testSelectorName]) { + NSString *reason = [NSString stringWithFormat:@"Cannot test \"%@\", duplicate XCTestCase tests named %@", test, testSelectorName]; + testResult(NSSelectorFromString(@"testDuplicateTestNames"), NO, reason); + *stop = YES; + return; + } + [testCaseNames addObject:testSelectorName]; + SEL testSelector = NSSelectorFromString(testSelectorName); + + if ([result isEqualToString:@"success"]) { + testResult(testSelector, YES, nil); + } else { + testResult(testSelector, NO, result); + } + }]; +} + +- (NSDictionary *)capturedScreenshotsByName { + return self.integrationTestPlugin.capturedScreenshotsByName; +} + ++ (NSString *)testCaseNameFromDartTestName:(NSString *)dartTestName { + NSString *capitalizedString = dartTestName.localizedCapitalizedString; + // Objective-C method names must be alphanumeric. + NSCharacterSet *disallowedCharacters = NSCharacterSet.alphanumericCharacterSet.invertedSet; + // Remove disallowed characters. + NSString *upperCamelTestName = [[capitalizedString componentsSeparatedByCharactersInSet:disallowedCharacters] componentsJoinedByString:@""]; + return [NSString stringWithFormat:@"test%@", upperCamelTestName]; +} + +@end diff --git a/flutter/packages/integration_test/ios/integration_test/Sources/integration_test/IntegrationTestIosTest.m b/flutter/packages/integration_test/ios/integration_test/Sources/integration_test/IntegrationTestIosTest.m new file mode 100644 index 0000000000000000000000000000000000000000..808fa94eac0f2ec464e0d948971c03a312f92a0e --- /dev/null +++ b/flutter/packages/integration_test/ios/integration_test/Sources/integration_test/IntegrationTestIosTest.m @@ -0,0 +1,42 @@ +// 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 "IntegrationTestIosTest.h" + +#import "IntegrationTestPlugin.h" +#import "FLTIntegrationTestRunner.h" + +#pragma mark - Deprecated + +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wdeprecated-implementations" + +@implementation IntegrationTestIosTest + +- (BOOL)testIntegrationTest:(NSString **)testResult { + NSLog(@"==================== Test Results ====================="); + NSMutableArray *failedTests = [NSMutableArray array]; + NSMutableArray *testNames = [NSMutableArray array]; + [[FLTIntegrationTestRunner new] testIntegrationTestWithResults:^(SEL testSelector, BOOL success, NSString *message) { + NSString *testName = NSStringFromSelector(testSelector); + [testNames addObject:testName]; + if (success) { + NSLog(@"%@ passed.", testName); + } else { + NSLog(@"%@ failed: %@", testName, message); + [failedTests addObject:testName]; + } + }]; + NSLog(@"================== Test Results End ===================="); + BOOL testPass = failedTests.count == 0; + if (!testPass && testResult != NULL) { + *testResult = + [NSString stringWithFormat:@"Detected failed integration test(s) %@ among %@", + failedTests.description, testNames.description]; + } + return testPass; +} + +@end +#pragma clang diagnostic pop diff --git a/flutter/packages/integration_test/ios/integration_test/Sources/integration_test/IntegrationTestPlugin.m b/flutter/packages/integration_test/ios/integration_test/Sources/integration_test/IntegrationTestPlugin.m new file mode 100644 index 0000000000000000000000000000000000000000..b3ac58138f3def0858e4fb8ddd68590362aa7c33 --- /dev/null +++ b/flutter/packages/integration_test/ios/integration_test/Sources/integration_test/IntegrationTestPlugin.m @@ -0,0 +1,90 @@ +// 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 "IntegrationTestPlugin.h" + +@import UIKit; + +static NSString *const kIntegrationTestPluginChannel = @"plugins.flutter.io/integration_test"; +static NSString *const kMethodTestFinished = @"allTestsFinished"; +static NSString *const kMethodScreenshot = @"captureScreenshot"; +static NSString *const kMethodConvertSurfaceToImage = @"convertFlutterSurfaceToImage"; +static NSString *const kMethodRevertImage = @"revertFlutterImage"; + +@interface IntegrationTestPlugin () + +@property(nonatomic, readwrite) NSDictionary *testResults; + +- (instancetype)init NS_DESIGNATED_INITIALIZER; + +@end + +@implementation IntegrationTestPlugin { + NSDictionary *_testResults; + NSMutableDictionary *_capturedScreenshotsByName; +} + ++ (instancetype)instance { + static dispatch_once_t onceToken; + static IntegrationTestPlugin *sInstance; + dispatch_once(&onceToken, ^{ + sInstance = [[IntegrationTestPlugin alloc] initForRegistration]; + }); + return sInstance; +} + +- (instancetype)initForRegistration { + return [self init]; +} + +- (instancetype)init { + self = [super init]; + _capturedScreenshotsByName = [NSMutableDictionary new]; + return self; +} + ++ (void)registerWithRegistrar:(NSObject *)registrar { + FlutterMethodChannel *channel = [FlutterMethodChannel methodChannelWithName:kIntegrationTestPluginChannel + binaryMessenger:registrar.messenger]; + [registrar addMethodCallDelegate:[self instance] channel:channel]; +} + +- (void)handleMethodCall:(FlutterMethodCall *)call result:(FlutterResult)result { + if ([call.method isEqualToString:kMethodTestFinished]) { + self.testResults = call.arguments[@"results"]; + result(nil); + } else if ([call.method isEqualToString:kMethodScreenshot]) { + // If running as a native Xcode test, attach to test. + UIImage *screenshot = [self capturePngScreenshot]; + NSString *name = call.arguments[@"name"]; + _capturedScreenshotsByName[name] = screenshot; + + // Also pass back along the channel for the driver to handle. + NSData *pngData = UIImagePNGRepresentation(screenshot); + result([FlutterStandardTypedData typedDataWithBytes:pngData]); + } else if ([call.method isEqualToString:kMethodConvertSurfaceToImage] + || [call.method isEqualToString:kMethodRevertImage]) { + // Android only, no-op on iOS. + result(nil); + } else { + result(FlutterMethodNotImplemented); + } +} + +- (UIImage *)capturePngScreenshot { + UIWindow *window = [UIApplication.sharedApplication.windows + filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:@"keyWindow = YES"]].firstObject; + CGRect screenshotBounds = window.bounds; + UIImage *image; + + UIGraphicsImageRenderer *renderer = [[UIGraphicsImageRenderer alloc] initWithBounds:screenshotBounds]; + + image = [renderer imageWithActions:^(UIGraphicsImageRendererContext *rendererContext) { + [window drawViewHierarchyInRect:screenshotBounds afterScreenUpdates:YES]; + }]; + + return image; +} + +@end diff --git a/flutter/packages/integration_test/ios/integration_test/Sources/integration_test/include/FLTIntegrationTestRunner.h b/flutter/packages/integration_test/ios/integration_test/Sources/integration_test/include/FLTIntegrationTestRunner.h new file mode 100644 index 0000000000000000000000000000000000000000..65568fc71173d970e14ca0806a452125d8bfce84 --- /dev/null +++ b/flutter/packages/integration_test/ios/integration_test/Sources/integration_test/include/FLTIntegrationTestRunner.h @@ -0,0 +1,36 @@ +// 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 Foundation; + +@class UIImage; + +NS_ASSUME_NONNULL_BEGIN + +typedef void (^FLTIntegrationTestResults)(SEL nativeTestSelector, BOOL success, NSString *_Nullable failureMessage); + +@interface FLTIntegrationTestRunner : NSObject + +/** + * Any screenshots captured by the plugin. + */ +@property (copy, readonly) NSDictionary *capturedScreenshotsByName; + +/** + * Starts dart tests and waits for results. + * + * @param testResult Will be called once per every completed dart test. + */ +- (void)testIntegrationTestWithResults:(NS_NOESCAPE FLTIntegrationTestResults)testResult; + +/** + * An appropriate XCTest method name based on the dart test name. + * + * Example: dart test "verify widget-ABC123" becomes "testVerifyWidgetABC123" + */ ++ (NSString *)testCaseNameFromDartTestName:(NSString *)dartTestName; + +@end + +NS_ASSUME_NONNULL_END diff --git a/flutter/packages/integration_test/ios/integration_test/Sources/integration_test/include/IntegrationTestIosTest.h b/flutter/packages/integration_test/ios/integration_test/Sources/integration_test/include/IntegrationTestIosTest.h new file mode 100644 index 0000000000000000000000000000000000000000..33aaea52a10ce02fe27bf683473b2bc58cf09b85 --- /dev/null +++ b/flutter/packages/integration_test/ios/integration_test/Sources/integration_test/include/IntegrationTestIosTest.h @@ -0,0 +1,68 @@ +// 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 Foundation; +@import ObjectiveC.runtime; + +NS_ASSUME_NONNULL_BEGIN + +DEPRECATED_MSG_ATTRIBUTE("Use FLTIntegrationTestRunner instead.") +@interface IntegrationTestIosTest : NSObject + +/** + * Initiate dart tests and wait for results. @c testResult will be set to a string describing the results. + * + * @return @c YES if all tests succeeded. + */ +- (BOOL)testIntegrationTest:(NSString *_Nullable *_Nullable)testResult; + +@end + +// For every Flutter dart test, dynamically generate an Objective-C method mirroring the test results +// so it is reported as a native XCTest run result. +// If the Flutter dart tests have captured screenshots, add them to the XCTest bundle. +#define INTEGRATION_TEST_IOS_RUNNER(__test_class) \ + @interface __test_class : XCTestCase \ + @end \ + \ + @implementation __test_class \ + \ + + (NSArray *)testInvocations { \ + FLTIntegrationTestRunner *integrationTestRunner = [[FLTIntegrationTestRunner alloc] init]; \ + NSMutableArray *testInvocations = [[NSMutableArray alloc] init]; \ + [integrationTestRunner testIntegrationTestWithResults:^(SEL testSelector, BOOL success, NSString *failureMessage) { \ + IMP assertImplementation = imp_implementationWithBlock(^(id _self) { \ + XCTAssertTrue(success, @"%@", failureMessage); \ + }); \ + class_addMethod(self, testSelector, assertImplementation, "v@:"); \ + NSMethodSignature *signature = [self instanceMethodSignatureForSelector:testSelector]; \ + NSInvocation *invocation = [NSInvocation invocationWithMethodSignature:signature]; \ + invocation.selector = testSelector; \ + [testInvocations addObject:invocation]; \ + }]; \ + NSDictionary *capturedScreenshotsByName = integrationTestRunner.capturedScreenshotsByName; \ + if (capturedScreenshotsByName.count > 0) { \ + IMP screenshotImplementation = imp_implementationWithBlock(^(id _self) { \ + [capturedScreenshotsByName enumerateKeysAndObjectsUsingBlock:^(NSString *name, UIImage *screenshot, BOOL *stop) { \ + XCTAttachment *attachment = [XCTAttachment attachmentWithImage:screenshot]; \ + attachment.lifetime = XCTAttachmentLifetimeKeepAlways; \ + if (name != nil) { \ + attachment.name = name; \ + } \ + [_self addAttachment:attachment]; \ + }]; \ + }); \ + SEL attachmentSelector = NSSelectorFromString(@"screenshotPlaceholder"); \ + class_addMethod(self, attachmentSelector, screenshotImplementation, "v@:"); \ + NSMethodSignature *attachmentSignature = [self instanceMethodSignatureForSelector:attachmentSelector]; \ + NSInvocation *attachmentInvocation = [NSInvocation invocationWithMethodSignature:attachmentSignature]; \ + attachmentInvocation.selector = attachmentSelector; \ + [testInvocations addObject:attachmentInvocation]; \ + } \ + return testInvocations; \ + } \ + \ + @end + +NS_ASSUME_NONNULL_END diff --git a/flutter/packages/integration_test/ios/integration_test/Sources/integration_test/include/IntegrationTestPlugin.h b/flutter/packages/integration_test/ios/integration_test/Sources/integration_test/include/IntegrationTestPlugin.h new file mode 100644 index 0000000000000000000000000000000000000000..e9cbd663b8dae38b52cde1214aacd9235d34e13a --- /dev/null +++ b/flutter/packages/integration_test/ios/integration_test/Sources/integration_test/include/IntegrationTestPlugin.h @@ -0,0 +1,31 @@ +// 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 + +NS_ASSUME_NONNULL_BEGIN + +/** A Flutter plugin that's responsible for communicating the test results back + * to iOS XCTest. */ +@interface IntegrationTestPlugin : NSObject + +/** + * Test results that are sent from Dart when integration test completes. Before the + * completion, it is @c nil. + */ +@property(nonatomic, readonly, nullable) NSDictionary *testResults; + +/** + * Mapping of screenshot images by suggested names, captured by the dart tests. + */ +@property (copy, readonly) NSDictionary *capturedScreenshotsByName; + +/** Fetches the singleton instance of the plugin. */ ++ (instancetype)instance; + +- (instancetype)init NS_UNAVAILABLE; + +@end + +NS_ASSUME_NONNULL_END diff --git a/flutter/packages/integration_test/lib/common.dart b/flutter/packages/integration_test/lib/common.dart new file mode 100644 index 0000000000000000000000000000000000000000..e148851b38c45b866de8e32f3bf64afc85524d6c --- /dev/null +++ b/flutter/packages/integration_test/lib/common.dart @@ -0,0 +1,325 @@ +// Copyright 2014 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +import 'dart:async'; +import 'dart:convert'; + +/// A callback to use with [integrationDriver]. +/// +/// The callback receives the name of screenshot passed to `binding.takeScreenshot()`, +/// a PNG byte buffer representing the screenshot, and an optional `Map` of arguments. +/// +/// The callback returns `true` if the test passes or `false` otherwise. +/// +/// You can use this callback to store the bytes locally in a file or upload them to a service +/// that compares the image against a gold or baseline version. +/// +/// The optional `Map` of arguments can be passed from the +/// `binding.takeScreenshot(, )` callsite in the integration test, +/// and then the arguments can be used in the `onScreenshot` handler that is defined by +/// the Flutter driver. This `Map` should only contain values that can be serialized +/// to JSON. +/// +/// Since the function is executed on the host driving the test, you can access any environment +/// variable from it. +typedef ScreenshotCallback = Future Function(String name, List image, [Map? args]); + +/// Classes shared between `integration_test.dart` and `flutter drive` based +/// adaptor (ex: `integration_test_driver.dart`). + +/// An object sent from integration_test back to the Flutter Driver in response to +/// `request_data` command. +class Response { + /// Constructor to use for positive response. + Response.allTestsPassed({this.data}) + : _allTestsPassed = true, + _failureDetails = null; + + /// Constructor for failure response. + Response.someTestsFailed(this._failureDetails, {this.data}) + : _allTestsPassed = false; + + /// Constructor for failure response. + Response.toolException({String? ex}) + : _allTestsPassed = false, + _failureDetails = [Failure('ToolException', ex)]; + + /// Constructor for web driver commands response. + Response.webDriverCommand({this.data}) + : _allTestsPassed = false, + _failureDetails = null; + + final List? _failureDetails; + + final bool _allTestsPassed; + + /// The extra information to be added along side the test result. + Map? data; + + /// Whether the test ran successfully or not. + bool get allTestsPassed => _allTestsPassed; + + /// If the result are failures get the formatted details. + String get formattedFailureDetails => + _allTestsPassed ? '' : formatFailures(_failureDetails!); + + /// Failure details as a list. + List? get failureDetails => _failureDetails; + + /// Serializes this message to a JSON map. + String toJson() => json.encode({ + 'result': allTestsPassed.toString(), + 'failureDetails': _failureDetailsAsString(), + if (data != null) 'data': data, + }); + + /// Deserializes the result from JSON. + static Response fromJson(String source) { + final Map responseJson = json.decode(source) as Map; + if ((responseJson['result'] as String?) == 'true') { + return Response.allTestsPassed(data: responseJson['data'] as Map?); + } else { + return Response.someTestsFailed( + _failureDetailsFromJson(responseJson['failureDetails'] as List), + data: responseJson['data'] as Map?, + ); + } + } + + /// Method for formatting the test failures' details. + String formatFailures(List failureDetails) { + if (failureDetails.isEmpty) { + return ''; + } + + final StringBuffer sb = StringBuffer(); + int failureCount = 1; + for (final Failure failure in failureDetails) { + sb.writeln('Failure in method: ${failure.methodName}'); + sb.writeln(failure.details); + sb.writeln('end of failure $failureCount\n\n'); + failureCount++; + } + return sb.toString(); + } + + /// Create a list of Strings from [_failureDetails]. + List _failureDetailsAsString() { + final List list = []; + if (_failureDetails == null || _failureDetails.isEmpty) { + return list; + } + + for (final Failure failure in _failureDetails) { + list.add(failure.toJson()); + } + + return list; + } + + /// Creates a [Failure] list using a json response. + static List _failureDetailsFromJson(List list) { + return list.map((dynamic s) { + return Failure.fromJsonString(s as String); + }).toList(); + } +} + +/// Representing a failure includes the method name and the failure details. +class Failure { + /// Constructor requiring all fields during initialization. + Failure(this.methodName, this.details); + + /// The name of the test method which failed. + final String methodName; + + /// The details of the failure such as stack trace. + final String? details; + + /// Serializes the object to JSON. + String toJson() { + return json.encode({ + 'methodName': methodName, + 'details': details, + }); + } + + @override + String toString() => toJson(); + + /// Decode a JSON string to create a Failure object. + static Failure fromJsonString(String jsonString) { + final Map failure = json.decode(jsonString) as Map; + return Failure(failure['methodName'] as String, failure['details'] as String?); + } +} + +/// Message used to communicate between app side tests and driver tests. +/// +/// Not all `integration_tests` use this message. They are only used when app +/// side tests are sending [WebDriverCommand]s to the driver side. +/// +/// These messages are used for the handshake since they carry information on +/// the driver side test such as: status pending or tests failed. +class DriverTestMessage { + /// When tests are failed on the driver side. + DriverTestMessage.error() + : _isSuccess = false, + _isPending = false; + + /// When driver side is waiting on [WebDriverCommand]s to be sent from the + /// app side. + DriverTestMessage.pending() + : _isSuccess = false, + _isPending = true; + + /// When driver side successfully completed executing the [WebDriverCommand]. + DriverTestMessage.complete() + : _isSuccess = true, + _isPending = false; + + final bool _isSuccess; + final bool _isPending; + + // /// Status of this message. + // /// + // /// The status will be use to notify `integration_test` of driver side's + // /// state. + // String get status => _status; + + /// Has the command completed successfully by the driver. + bool get isSuccess => _isSuccess; + + /// Is the driver waiting for a command. + bool get isPending => _isPending; + + /// Depending on the values of [isPending] and [isSuccess], returns a string + /// to represent the [DriverTestMessage]. + /// + /// Used as an alternative method to converting the object to json since + /// [RequestData] is only accepting string as `message`. + @override + String toString() { + if (isPending) { + return 'pending'; + } else if (isSuccess) { + return 'complete'; + } else { + return 'error'; + } + } + + /// Return a DriverTestMessage depending on `status`. + static DriverTestMessage fromString(String status) { + switch (status) { + case 'error': + return DriverTestMessage.error(); + case 'pending': + return DriverTestMessage.pending(); + case 'complete': + return DriverTestMessage.complete(); + default: + throw StateError('This type of status does not exist: $status'); + } + } +} + +/// Types of different WebDriver commands that can be used in web integration +/// tests. +/// +/// These commands are either commands that WebDriver can execute or used +/// for the communication between `integration_test` and the driver test. +enum WebDriverCommandType { + /// Acknowledgement for the previously sent message. + ack, + + /// No further WebDriver commands is requested by the app-side tests. + noop, + + /// Asking WebDriver to take a screenshot of the Web page. + screenshot, +} + +/// Command for WebDriver to execute. +/// +/// Only works on Web when tests are run via `flutter driver` command. +/// +/// See: https://www.w3.org/TR/webdriver/ +class WebDriverCommand { + /// Constructor for [WebDriverCommandType.noop] command. + WebDriverCommand.noop() + : type = WebDriverCommandType.noop, + values = {}; + + /// Constructor for [WebDriverCommandType.noop] screenshot. + WebDriverCommand.screenshot(String screenshotName, [Map? args]) + : type = WebDriverCommandType.screenshot, + values = { + 'screenshot_name': screenshotName, + if (args != null) 'args': args, + }; + + /// Type of the [WebDriverCommand]. + /// + /// Currently the only command that triggers a WebDriver API is `screenshot`. + /// + /// There are also `ack` and `noop` commands defined to manage the handshake + /// during the communication. + final WebDriverCommandType type; + + /// Used for adding extra values to the commands such as file name for + /// `screenshot`. + final Map values; + + /// Util method for converting [WebDriverCommandType] to a map entry. + /// + /// Used for converting messages to json format. + static Map typeToMap(WebDriverCommandType type) => { + 'web_driver_command': '$type', + }; +} + +/// Template methods each class that responses the driver side inputs must +/// implement. +/// +/// Depending on the platform the communication between `integration_tests` and +/// the `driver_tests` can be different. +abstract class CallbackManager { + /// The callback function to response the driver side input. + Future> callback( + Map params, IntegrationTestResults testRunner); + + /// Takes a screenshot of the application. + /// Returns the data that is sent back to the host. + Future> takeScreenshot(String screenshot, [Map? args]); + + /// Android only. Converts the Flutter surface to an image view. + Future convertFlutterSurfaceToImage(); + + /// Cleanup and completers or locks used during the communication. + void cleanup(); +} + +/// Interface that surfaces test results of integration tests. +/// +/// Implemented by [IntegrationTestWidgetsFlutterBinding]s. +/// +/// Any class which needs to access the test results but do not want to create +/// a cyclic dependency [IntegrationTestWidgetsFlutterBinding]s can use this +/// interface. Example [CallbackManager]. +abstract class IntegrationTestResults { + /// Stores failure details. + /// + /// Failed test method's names used as key. + List get failureMethodsDetails; + + /// The extra data for the reported result. + Map? get reportData; + + /// Whether all the test methods completed successfully. + /// + /// Completes when the tests have finished. The boolean value will be true if + /// all tests have passed, and false otherwise. + Completer get allTestsPassed; +} diff --git a/flutter/packages/integration_test/lib/fix_data/README.md b/flutter/packages/integration_test/lib/fix_data/README.md new file mode 100644 index 0000000000000000000000000000000000000000..748818fc6128406b8dfe7e85d10df870c15db69d --- /dev/null +++ b/flutter/packages/integration_test/lib/fix_data/README.md @@ -0,0 +1,45 @@ +## Directory contents + +The `.yaml` files in these directories are used to +define the [`dart fix` framework](https://dart.dev/tools/dart-fix) refactorings +used by `integration_test`. + +The number of fix rules defined in a file should not exceed 50 for better +maintainability. Searching for `title:` in a given `.yaml` file will account +for the number of fixes. Splitting out fix rules should be done by class. + +When adding a new `.yaml` file, make a copy of `template.yaml`. Each file should +be for a single class and named `fix_.yaml`. To make sure each file is +grouped with related classes, a `fix_` folder will contain all of the +fix files for the individual classes. + +See the flutter/packages/integration_test/test_fixes directory for the tests +that validate these fix rules. + +To run these tests locally, execute this command in the +flutter/packages/integration_test/test_fixes directory. +```sh +dart fix --compare-to-golden +``` + +For more documentation about Data Driven Fixes, see +https://dart.dev/go/data-driven-fixes#test-folder. + +To learn more about how fixes are authored in package:integration_test, see +https://github.com/flutter/flutter/wiki/Data-driven-Fixes + +## When making structural changes to this directory + +The tests in this directory are also invoked from external +repositories. Specifically, the CI system for the dart-lang/sdk repo +runs these tests in order to ensure that changes to the dart fix file +format do not break Flutter. + +See [tools/bots/flutter/analyze_flutter_flutter.sh](https://github.com/dart-lang/sdk/blob/main/tools/bots/flutter/analyze_flutter_flutter.sh) +for where the flutter fix tests are invoked for the dart repo. + +See [dev/bots/test.dart](https://github.com/flutter/flutter/blob/master/dev/bots/test.dart) +for where the flutter fix tests are invoked for the flutter/flutter repo. + +When possible, please coordinate changes to this directory that might affect the +`analyze_flutter_flutter.sh` script. diff --git a/flutter/packages/integration_test/lib/fix_data/fix_integration_test/fix_binding/fix_integration_test_widgets_flutter_binding.yaml b/flutter/packages/integration_test/lib/fix_data/fix_integration_test/fix_binding/fix_integration_test_widgets_flutter_binding.yaml new file mode 100644 index 0000000000000000000000000000000000000000..26092699f209168ee21facea6578a001e9c414c7 --- /dev/null +++ b/flutter/packages/integration_test/lib/fix_data/fix_integration_test/fix_binding/fix_integration_test_widgets_flutter_binding.yaml @@ -0,0 +1,33 @@ +# 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. + +# For details regarding the *Flutter Fix* feature, see +# https://flutter.dev/docs/development/tools/flutter-fix + +# Please add new fixes to the top of the file, separated by one blank line +# from other fixes. In a comment, include a link to the PR where the change +# requiring the fix was made. + +# Every fix must be tested. See the +# flutter/packages/integration_test/test_fixes/README.md file for instructions +# on testing these data driven fixes. + +# For documentation about this file format, see +# https://dart.dev/go/data-driven-fixes. + +# * Fixes in this file are for IntegrationTestWidgetsFlutterBinding from the +# integration_test/integration_test.dart file. * + +version: 1 +transforms: + # Changes made in https://github.com/flutter/flutter/pull/89952 + - title: "Remove timeout" + date: 2023-06-26 + element: + uris: [ 'integration_test.dart' ] + method: 'runTest' + inClass: 'IntegrationTestWidgetsFlutterBinding' + changes: + - kind: 'removeParameter' + name: 'timeout' diff --git a/flutter/packages/integration_test/lib/fix_data/template.yaml b/flutter/packages/integration_test/lib/fix_data/template.yaml new file mode 100644 index 0000000000000000000000000000000000000000..27c5d14a98c3a86e469f9cb1eafc1c90cb758935 --- /dev/null +++ b/flutter/packages/integration_test/lib/fix_data/template.yaml @@ -0,0 +1,25 @@ +# 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. + +# For details regarding the *Flutter Fix* feature, see +# https://flutter.dev/docs/development/tools/flutter-fix + +# Please add new fixes to the top of the file, separated by one blank line +# from other fixes. In a comment, include a link to the PR where the change +# requiring the fix was made. + +# Every fix must be tested. See the +# flutter/packages/integration_test/lib/fix_data/README.md file for instructions +# on testing these data driven fixes. + +# For documentation about this file format, see +# https://dart.dev/go/data-driven-fixes. + +# * Fixes in this file are [for CLASS] from the file. * + +# Uncomment version & transforms, and follow with fixes. +# version: 1 +# transforms: + +# Before adding a new fix: read instructions at the top of this file. diff --git a/flutter/packages/integration_test/lib/integration_test.dart b/flutter/packages/integration_test/lib/integration_test.dart new file mode 100644 index 0000000000000000000000000000000000000000..244cfbd98ea8453c7b0b32055f3c2997c4c84db0 --- /dev/null +++ b/flutter/packages/integration_test/lib/integration_test.dart @@ -0,0 +1,495 @@ +// Copyright 2014 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +import 'dart:async'; +import 'dart:developer' as developer; +import 'dart:io' show HttpClient, SocketException, WebSocket; +import 'dart:ui'; + +import 'package:flutter/foundation.dart'; +import 'package:flutter/rendering.dart'; +import 'package:flutter/services.dart'; +import 'package:flutter/widgets.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:vm_service/vm_service.dart' as vm; + +import 'common.dart'; +import 'src/callback.dart' as driver_actions; +import 'src/channel.dart'; +import 'src/extension.dart'; + +const String _success = 'success'; + +/// Whether results should be reported to the native side over the method +/// channel. +/// +/// This is enabled by default for use by native test frameworks like Android +/// instrumentation or XCTest. When running with the Flutter Tool through +/// `flutter test integration_test` though, it will be disabled as the Flutter +/// tool will be responsible for collection of test results. +const bool _shouldReportResultsToNative = bool.fromEnvironment( + 'INTEGRATION_TEST_SHOULD_REPORT_RESULTS_TO_NATIVE', + defaultValue: true, +); + +/// A subclass of [LiveTestWidgetsFlutterBinding] that reports tests results +/// on a channel to adapt them to native instrumentation test format. +class IntegrationTestWidgetsFlutterBinding extends LiveTestWidgetsFlutterBinding implements IntegrationTestResults { + /// Sets up a listener to report that the tests are finished when everything is + /// torn down. + IntegrationTestWidgetsFlutterBinding() { + tearDownAll(() async { + if (!_allTestsPassed.isCompleted) { + _allTestsPassed.complete(failureMethodsDetails.isEmpty); + } + callbackManager.cleanup(); + + // TODO(jiahaog): Print the message directing users to run with + // `flutter test` when Web is supported. + if (!_shouldReportResultsToNative || kIsWeb) { + return; + } + + try { + await integrationTestChannel.invokeMethod( + 'allTestsFinished', + { + 'results': results.map((String name, Object result) { + if (result is Failure) { + return MapEntry(name, result.details); + } + return MapEntry(name, result); + }), + }, + ); + } on MissingPluginException { + debugPrint(r''' +Warning: integration_test plugin was not detected. + +If you're running the tests with `flutter drive`, please make sure your tests +are in the `integration_test/` directory of your package and use +`flutter test $path_to_test` to run it instead. + +If you're running the tests with Android instrumentation or XCTest, this means +that you are not capturing test results properly! See the following link for +how to set up the integration_test plugin: + +https://flutter.dev/docs/testing/integration-tests#testing-on-firebase-test-lab +'''); + } + }); + + final TestExceptionReporter oldTestExceptionReporter = reportTestException; + reportTestException = + (FlutterErrorDetails details, String testDescription) { + results[testDescription] = Failure(testDescription, details.toString()); + oldTestExceptionReporter(details, testDescription); + }; + } + + @override + bool get overrideHttpClient => false; + + @override + bool get registerTestTextInput => false; + + Size? _surfaceSize; + + // This flag is used to print warning messages when tracking performance + // under debug mode. + static bool _firstRun = false; + + @override + Future setSurfaceSize(Size? size) { + return TestAsyncUtils.guard(() async { + assert(inTest); + if (_surfaceSize == size) { + return; + } + _surfaceSize = size; + handleMetricsChanged(); + }); + } + + @override + ViewConfiguration createViewConfigurationFor(RenderView renderView) { + final FlutterView view = renderView.flutterView; + final Size? surfaceSize = view == platformDispatcher.implicitView ? _surfaceSize : null; + return TestViewConfiguration.fromView( + size: surfaceSize ?? view.physicalSize / view.devicePixelRatio, + view: view, + ); + } + + @override + Completer get allTestsPassed => _allTestsPassed; + final Completer _allTestsPassed = Completer(); + + @override + List get failureMethodsDetails => results.values.whereType().toList(); + + @override + void initInstances() { + super.initInstances(); + _instance = this; + } + + /// The singleton instance of this object. + /// + /// Provides access to the features exposed by this class. The binding must + /// be initialized before using this getter; this is typically done by calling + /// [IntegrationTestWidgetsFlutterBinding.ensureInitialized]. + static IntegrationTestWidgetsFlutterBinding get instance => BindingBase.checkInstance(_instance); + static IntegrationTestWidgetsFlutterBinding? _instance; + + /// Returns an instance of the [IntegrationTestWidgetsFlutterBinding], creating and + /// initializing it if necessary. + /// + /// See also: + /// + /// * [WidgetsFlutterBinding.ensureInitialized], the equivalent in the widgets framework. + static IntegrationTestWidgetsFlutterBinding ensureInitialized() { + if (_instance == null) { + IntegrationTestWidgetsFlutterBinding(); + } + return _instance!; + } + + /// Test results that will be populated after the tests have completed. + /// + /// Keys are the test descriptions, and values are either [_success] or + /// a [Failure]. + @visibleForTesting + Map results = {}; + + /// The extra data for the reported result. + /// + /// The values in `reportData` must be json-serializable objects or `null`. + /// If it's `null`, no extra data is attached to the result. + /// + /// The default value is `null`. + @override + Map? reportData; + + /// Manages callbacks received from driver side and commands send to driver + /// side. + final CallbackManager callbackManager = driver_actions.callbackManager; + + /// Takes a screenshot. + /// + /// On Android, you need to call `convertFlutterSurfaceToImage()`, and + /// pump a frame before taking a screenshot. + Future> takeScreenshot(String screenshotName, [Map? args]) async { + reportData ??= {}; + reportData!['screenshots'] ??= []; + final Map data = await callbackManager.takeScreenshot(screenshotName, args); + assert(data.containsKey('bytes')); + + (reportData!['screenshots']! as List).add(data); + return data['bytes']! as List; + } + + /// Android only. Converts the Flutter surface to an image view. + /// Be aware that if you are conducting a perf test, you may not want to call + /// this method since the this is an expensive operation that affects the + /// rendering of a Flutter app. + /// + /// Once the screenshot is taken, call `revertFlutterImage()` to restore + /// the original Flutter surface. + Future convertFlutterSurfaceToImage() async { + await callbackManager.convertFlutterSurfaceToImage(); + } + + /// The callback function to response the driver side input. + @visibleForTesting + Future> callback(Map params) async { + return callbackManager.callback( + params, this /* as IntegrationTestResults */); + } + + // Emulates the Flutter driver extension, returning 'pass' or 'fail'. + @override + void initServiceExtensions() { + super.initServiceExtensions(); + + if (kIsWeb) { + registerWebServiceExtension(callback); + } + + registerServiceExtension(name: 'driver', callback: callback); + } + + @override + Future runTest( + Future Function() testBody, + VoidCallback invariantTester, { + String description = '', + @Deprecated( + 'This parameter has no effect. Use the `timeout` parameter on `testWidgets` instead. ' + 'This feature was deprecated after v2.6.0-1.0.pre.' + ) + Duration? timeout, + }) async { + await super.runTest( + testBody, + invariantTester, + description: description, + ); + results[description] ??= _success; + } + + vm.VmService? _vmService; + + /// Initialize the [vm.VmService] settings for the timeline. + @visibleForTesting + Future enableTimeline({ + List streams = const ['all'], + @visibleForTesting vm.VmService? vmService, + @visibleForTesting HttpClient? httpClient, + }) async { + assert(streams.isNotEmpty); + if (vmService != null) { + _vmService = vmService; + } + if (_vmService == null) { + final developer.ServiceProtocolInfo info = await developer.Service.getInfo(); + assert(info.serverUri != null); + final String address = 'ws://localhost:${info.serverUri!.port}${info.serverUri!.path}ws'; + try { + _vmService = await _vmServiceConnectUri(address, httpClient: httpClient); + } on SocketException catch (e, s) { + throw StateError( + 'Failed to connect to VM Service at $address.\n' + 'This may happen if DDS is enabled. If this test was launched via ' + '`flutter drive`, try adding `--no-dds`.\n' + 'The original exception was:\n' + '$e\n$s', + ); + } + } + await _vmService!.setVMTimelineFlags(streams); + } + + /// Runs [action] and returns a [vm.Timeline] trace for it. + /// + /// Waits for the `Future` returned by [action] to complete prior to stopping + /// the trace. + /// + /// The `streams` parameter limits the recorded timeline event streams to only + /// the ones listed. By default, all streams are recorded. + /// See `timeline_streams` in + /// [Dart-SDK/runtime/vm/timeline.cc](https://github.com/dart-lang/sdk/blob/main/runtime/vm/timeline.cc) + /// + /// If [retainPriorEvents] is true, retains events recorded prior to calling + /// [action]. Otherwise, prior events are cleared before calling [action]. By + /// default, prior events are cleared. + Future traceTimeline( + Future Function() action, { + List streams = const ['all'], + bool retainPriorEvents = false, + }) async { + await enableTimeline(streams: streams); + if (retainPriorEvents) { + await action(); + return _vmService!.getVMTimeline(); + } + + await _vmService!.clearVMTimeline(); + final vm.Timestamp startTime = await _vmService!.getVMTimelineMicros(); + await action(); + final vm.Timestamp endTime = await _vmService!.getVMTimelineMicros(); + return _vmService!.getVMTimeline( + timeOriginMicros: startTime.timestamp, + timeExtentMicros: endTime.timestamp, + ); + } + + /// This is a convenience method that calls [traceTimeline] and sends the + /// result back to the host for the [flutter_driver] style tests. + /// + /// This records the timeline during `action` and adds the result to + /// [reportData] with `reportKey`. The [reportData] contains extra information + /// from the test other than test success/fail. It will be passed back to the + /// host and be processed by the [ResponseDataCallback] defined in + /// [integration_test_driver.integrationDriver]. By default it will be written + /// to `build/integration_response_data.json` with the key `timeline`. + /// + /// For tests with multiple calls of this method, `reportKey` needs to be a + /// unique key, otherwise the later result will override earlier one. Tests + /// that call this multiple times must also provide a custom + /// [ResponseDataCallback] to decide where and how to write the output + /// timelines. For example, + /// + /// ```dart + /// import 'package:integration_test/integration_test_driver.dart'; + /// + /// Future main() { + /// return integrationDriver( + /// responseDataCallback: (Map? data) async { + /// if (data != null) { + /// for (final MapEntry entry in data.entries) { + /// print('Writing ${entry.key} to the disk.'); + /// await writeResponseData( + /// entry.value as Map, + /// testOutputFilename: entry.key, + /// ); + /// } + /// } + /// }, + /// ); + /// } + /// ``` + /// + /// The `streams` and `retainPriorEvents` parameters are passed as-is to + /// [traceTimeline]. + Future traceAction( + Future Function() action, { + List streams = const ['all'], + bool retainPriorEvents = false, + String reportKey = 'timeline', + }) async { + final vm.Timeline timeline = await traceTimeline( + action, + streams: streams, + retainPriorEvents: retainPriorEvents, + ); + reportData ??= {}; + reportData![reportKey] = timeline.toJson(); + } + + Future<_GarbageCollectionInfo> _runAndGetGCInfo(Future Function() action) async { + if (kIsWeb) { + await action(); + return const _GarbageCollectionInfo(); + } + + final vm.Timeline timeline = await traceTimeline( + action, + streams: ['GC'], + ); + + final int oldGenGCCount = timeline.traceEvents!.where((vm.TimelineEvent event) { + return event.json!['cat'] == 'GC' && event.json!['name'] == 'CollectOldGeneration'; + }).length; + final int newGenGCCount = timeline.traceEvents!.where((vm.TimelineEvent event) { + return event.json!['cat'] == 'GC' && event.json!['name'] == 'CollectNewGeneration'; + }).length; + return _GarbageCollectionInfo( + oldCount: oldGenGCCount, + newCount: newGenGCCount, + ); + } + + /// Watches the [FrameTiming] during `action` and report it to the binding + /// with key `reportKey`. + /// + /// This can be used to implement performance tests previously using + /// [traceAction] and [TimelineSummary] from [flutter_driver] + Future watchPerformance( + Future Function() action, { + String reportKey = 'performance', + }) async { + assert(() { + if (_firstRun) { + debugPrint(kDebugWarning); + _firstRun = false; + } + return true; + }()); + + // The engine could batch FrameTimings and send them only once per second. + // Delay for a sufficient time so either old FrameTimings are flushed and not + // interfering our measurements here, or new FrameTimings are all reported. + // TODO(CareF): remove this when flush FrameTiming is readily in engine. + // See https://github.com/flutter/flutter/issues/64808 + // and https://github.com/flutter/flutter/issues/67593 + final List frameTimings = []; + Future delayForFrameTimings() async { + int count = 0; + while (frameTimings.isEmpty) { + count++; + await Future.delayed(const Duration(seconds: 2)); + if (count > 20) { + debugPrint('delayForFrameTimings is taking longer than expected...'); + } + } + } + + await Future.delayed(const Duration(seconds: 2)); // flush old FrameTimings + final TimingsCallback watcher = frameTimings.addAll; + addTimingsCallback(watcher); + final _GarbageCollectionInfo gcInfo = await _runAndGetGCInfo(action); + + await delayForFrameTimings(); // make sure all FrameTimings are reported + removeTimingsCallback(watcher); + + final FrameTimingSummarizer frameTimes = FrameTimingSummarizer( + frameTimings, + newGenGCCount: gcInfo.newCount, + oldGenGCCount: gcInfo.oldCount, + ); + reportData ??= {}; + reportData![reportKey] = frameTimes.summary; + } + + @override + Timeout defaultTestTimeout = Timeout.none; + + @override + Widget wrapWithDefaultView(Widget rootWidget) { + // This is a workaround where screenshots of root widgets have incorrect + // bounds. + // TODO(jiahaog): Remove when https://github.com/flutter/flutter/issues/66006 is fixed. + return super.wrapWithDefaultView(RepaintBoundary(child: rootWidget)); + } + + @override + void reportExceptionNoticed(FlutterErrorDetails exception) { + // This method is called to log errors as they happen, and they will also + // be eventually logged again at the end of the tests. The superclass + // behavior is specific to the "live" execution semantics of + // [LiveTestWidgetsFlutterBinding] so users don't have to wait until tests + // finish to see the stack traces. + // + // Disable this because Integration Tests follow the semantics of + // [AutomatedTestWidgetsFlutterBinding] that does not log the stack traces + // live, and avoids the doubly logged stack trace. + // TODO(jiahaog): Integration test binding should not inherit from + // `LiveTestWidgetsFlutterBinding` https://github.com/flutter/flutter/issues/81534 + } +} + +@immutable +class _GarbageCollectionInfo { + const _GarbageCollectionInfo({this.oldCount = -1, this.newCount = -1}); + + final int oldCount; + final int newCount; +} + +// Connect to the given uri and return a new [VmService] instance. +// +// Copied from vm_service_io so that we can pass a custom [HttpClient] for +// testing. Currently, the WebSocket API reuses an HttpClient that +// is created before the test can change the HttpOverrides. +Future _vmServiceConnectUri( + String wsUri, { + HttpClient? httpClient, +}) async { + final WebSocket socket = await WebSocket.connect(wsUri, customClient: httpClient); + final StreamController controller = StreamController(); + final Completer streamClosedCompleter = Completer(); + + socket.listen( + (dynamic data) => controller.add(data), + onDone: () => streamClosedCompleter.complete(), + ); + + return vm.VmService( + controller.stream, + (String message) => socket.add(message), + disposeHandler: () => socket.close(), + streamClosed: streamClosedCompleter.future, + ); +} diff --git a/flutter/packages/integration_test/lib/integration_test_driver.dart b/flutter/packages/integration_test/lib/integration_test_driver.dart new file mode 100644 index 0000000000000000000000000000000000000000..38df03dbf7015d4f1d3e39642835abbd9e0ab5a6 --- /dev/null +++ b/flutter/packages/integration_test/lib/integration_test_driver.dart @@ -0,0 +1,104 @@ +// Copyright 2014 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +// This is a CLI library; we use prints as part of the interface. +// ignore_for_file: avoid_print + +import 'dart:async'; +import 'dart:convert'; +import 'dart:io'; + +import 'package:flutter_driver/flutter_driver.dart'; +import 'package:path/path.dart' as path; + +import 'common.dart'; + +/// Flutter Driver test output directory. +/// +/// Tests should write any output files to this directory. Defaults to the path +/// set in the FLUTTER_TEST_OUTPUTS_DIR environment variable, or `build` if +/// unset. +String testOutputsDirectory = + Platform.environment['FLUTTER_TEST_OUTPUTS_DIR'] ?? 'build'; + +/// The callback type to handle [Response.data] after the test +/// succeeds. +typedef ResponseDataCallback = FutureOr Function(Map?); + +/// Writes a json-serializable data to +/// [testOutputsDirectory]/`testOutputFilename.json`. +/// +/// This is the default `responseDataCallback` in [integrationDriver]. +Future writeResponseData( + Map? data, { + String testOutputFilename = 'integration_response_data', + String? destinationDirectory, +}) async { + destinationDirectory ??= testOutputsDirectory; + await fs.directory(destinationDirectory).create(recursive: true); + final File file = fs.file(path.join( + destinationDirectory, + '$testOutputFilename.json', + )); + final String resultString = _encodeJson(data, true); + await file.writeAsString(resultString); +} + +/// Adaptor to run an integration test using `flutter drive`. +/// +/// To run an integration test `.dart` using `flutter drive`, put a file named +/// `_test.dart` in the app's `test_driver` directory: +/// +/// ```dart +/// import 'dart:async'; +/// +/// import 'package:integration_test/integration_test_driver.dart'; +/// +/// Future main() async => integrationDriver(); +/// +/// ``` +/// +/// ## Parameters: +/// +/// `timeout` controls the longest time waited before the test ends. +/// It is not necessarily the execution time for the test app: the test may +/// finish sooner than the `timeout`. +/// +/// `responseDataCallback` is the handler for processing [Response.data]. +/// The default value is `writeResponseData`. +/// +/// `writeResponseOnFailure` determines whether the `responseDataCallback` +/// function will be called to process the [Response.data] when a test fails. +/// The default value is `false`. +Future integrationDriver({ + Duration timeout = const Duration(minutes: 20), + ResponseDataCallback? responseDataCallback = writeResponseData, + bool writeResponseOnFailure = false, +}) async { + final FlutterDriver driver = await FlutterDriver.connect(); + final String jsonResult = await driver.requestData(null, timeout: timeout); + final Response response = Response.fromJson(jsonResult); + + await driver.close(); + + if (response.allTestsPassed) { + print('All tests passed.'); + if (responseDataCallback != null) { + await responseDataCallback(response.data); + } + exit(0); + } else { + print('Failure Details:\n${response.formattedFailureDetails}'); + if (responseDataCallback != null && writeResponseOnFailure) { + await responseDataCallback(response.data); + } + exit(1); + } +} + +const JsonEncoder _prettyEncoder = JsonEncoder.withIndent(' '); + +String _encodeJson(Map? jsonObject, bool pretty) { + return pretty ? _prettyEncoder.convert(jsonObject) : json.encode(jsonObject); +} diff --git a/flutter/packages/integration_test/lib/integration_test_driver_extended.dart b/flutter/packages/integration_test/lib/integration_test_driver_extended.dart new file mode 100644 index 0000000000000000000000000000000000000000..f4a7824abddc535da731872c7f1fb821b07494ab --- /dev/null +++ b/flutter/packages/integration_test/lib/integration_test_driver_extended.dart @@ -0,0 +1,194 @@ +// Copyright 2014 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +// This is a CLI library; we use prints as part of the interface. +// ignore_for_file: avoid_print + +import 'dart:async'; +import 'dart:convert'; +import 'dart:io'; + +import 'package:flutter_driver/flutter_driver.dart'; +import 'package:path/path.dart' as path; + +import 'common.dart'; + +/// Flutter Driver test output directory. +/// +/// Tests should write any output files to this directory. Defaults to the path +/// set in the FLUTTER_TEST_OUTPUTS_DIR environment variable, or `build` if +/// unset. +String testOutputsDirectory = + Platform.environment['FLUTTER_TEST_OUTPUTS_DIR'] ?? 'build'; + +/// The callback type to handle [Response.data] after the test +/// succeeds. +typedef ResponseDataCallback = FutureOr Function(Map?); + +/// Writes a json-serializable data to +/// [testOutputsDirectory]/`testOutputFilename.json`. +/// +/// This is the default `responseDataCallback` in [integrationDriver]. +Future writeResponseData( + Map? data, { + String testOutputFilename = 'integration_response_data', + String? destinationDirectory, +}) async { + destinationDirectory ??= testOutputsDirectory; + await fs.directory(destinationDirectory).create(recursive: true); + final File file = fs.file(path.join( + destinationDirectory, + '$testOutputFilename.json', + )); + final String resultString = _encodeJson(data, true); + await file.writeAsString(resultString); +} + +/// Adaptor to run an integration test using `flutter drive`. +/// +/// To an integration test `.dart` using `flutter drive`, put a file named +/// `_test.dart` in the app's `test_driver` directory: +/// +/// ```dart +/// import 'dart:async'; +/// +/// import 'package:flutter_driver/flutter_driver.dart'; +/// import 'package:integration_test/integration_test_driver_extended.dart'; +/// +/// Future main() async { +/// final FlutterDriver driver = await FlutterDriver.connect(); +/// await integrationDriver( +/// driver: driver, +/// onScreenshot: (String name, List image, [Map? args]) async { +/// return true; +/// }, +/// ); +/// } +/// ``` +/// +/// ## Parameters: +/// +/// `driver` A custom driver. Defaults to `FlutterDriver.connect()`. +/// +/// `onScreenshot` can be used to process the screenshots taken during the test. +/// An example could be that this callback compares the byte array against a baseline image, +/// and it returns `true` if both images are equal. +/// +/// As a result, returning `false` from `onScreenshot` will make the test fail. +/// +/// `responseDataCallback` is the handler for processing [Response.data]. +/// The default value is `writeResponseData`. +/// +/// `writeResponseOnFailure` determines whether the `responseDataCallback` +/// function will be called to process the [Response.data] when a test fails. +/// The default value is `false`. +Future integrationDriver({ + FlutterDriver? driver, + ScreenshotCallback? onScreenshot, + ResponseDataCallback? responseDataCallback = writeResponseData, + bool writeResponseOnFailure = false, +}) async { + driver ??= await FlutterDriver.connect(); + // Test states that it's waiting on web driver commands. + // [DriverTestMessage] is converted to string since json format causes an + // error if it's used as a message for requestData. + String jsonResponse = await driver.requestData(DriverTestMessage.pending().toString()); + + final Map onScreenshotResults = {}; + + Response response = Response.fromJson(jsonResponse); + + // Until `integration_test` returns a [WebDriverCommandType.noop], keep + // executing WebDriver commands. + while (response.data != null && + response.data!['web_driver_command'] != null && + response.data!['web_driver_command'] != '${WebDriverCommandType.noop}') { + final String? webDriverCommand = response.data!['web_driver_command'] as String?; + if (webDriverCommand == '${WebDriverCommandType.screenshot}') { + assert(onScreenshot != null, 'screenshot command requires an onScreenshot callback'); + // Use `driver.screenshot()` method to get a screenshot of the web page. + final List screenshotImage = await driver.screenshot(); + final String screenshotName = response.data!['screenshot_name']! as String; + final Map? args = (response.data!['args'] as Map?)?.cast(); + + final bool screenshotSuccess = await onScreenshot!(screenshotName, screenshotImage, args); + onScreenshotResults[screenshotName] = screenshotSuccess; + if (screenshotSuccess) { + jsonResponse = await driver.requestData(DriverTestMessage.complete().toString()); + } else { + jsonResponse = + await driver.requestData(DriverTestMessage.error().toString()); + } + + response = Response.fromJson(jsonResponse); + } else if (webDriverCommand == '${WebDriverCommandType.ack}') { + // Previous command completed ask for a new one. + jsonResponse = + await driver.requestData(DriverTestMessage.pending().toString()); + + response = Response.fromJson(jsonResponse); + } else { + break; + } + } + + // If No-op command is sent, ask for the result of all tests. + if (response.data != null && + response.data!['web_driver_command'] != null && + response.data!['web_driver_command'] == '${WebDriverCommandType.noop}') { + jsonResponse = await driver.requestData(null); + + response = Response.fromJson(jsonResponse); + print('result $jsonResponse'); + } + + if (response.data != null && response.data!['screenshots'] != null && onScreenshot != null) { + final List screenshots = response.data!['screenshots'] as List; + final List failures = []; + for (final dynamic screenshot in screenshots) { + final Map data = screenshot as Map; + final List screenshotBytes = data['bytes'] as List; + final String screenshotName = data['screenshotName'] as String; + + bool ok = false; + try { + ok = onScreenshotResults[screenshotName] ?? + await onScreenshot(screenshotName, screenshotBytes.cast()); + } catch (exception) { + throw StateError( + 'Screenshot failure:\n' + 'onScreenshot("$screenshotName", ) threw an exception: $exception', + ); + } + if (!ok) { + failures.add(screenshotName); + } + } + if (failures.isNotEmpty) { + throw StateError('The following screenshot tests failed: ${failures.join(', ')}'); + } + } + + await driver.close(); + + if (response.allTestsPassed) { + print('All tests passed.'); + if (responseDataCallback != null) { + await responseDataCallback(response.data); + } + exit(0); + } else { + print('Failure Details:\n${response.formattedFailureDetails}'); + if (responseDataCallback != null && writeResponseOnFailure) { + await responseDataCallback(response.data); + } + exit(1); + } +} + +const JsonEncoder _prettyEncoder = JsonEncoder.withIndent(' '); + +String _encodeJson(Map? jsonObject, bool pretty) { + return pretty ? _prettyEncoder.convert(jsonObject) : json.encode(jsonObject); +} diff --git a/flutter/packages/integration_test/lib/src/_callback_io.dart b/flutter/packages/integration_test/lib/src/_callback_io.dart new file mode 100644 index 0000000000000000000000000000000000000000..e2181cee60a1b4bb8063562e7dd3ed56a17f71fe --- /dev/null +++ b/flutter/packages/integration_test/lib/src/_callback_io.dart @@ -0,0 +1,113 @@ +// 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:io' show Platform; +import 'dart:ui'; + +import 'package:flutter/services.dart'; +import 'package:flutter_test/flutter_test.dart'; + +import '../common.dart'; +import 'channel.dart'; + +/// The dart:io implementation of [CallbackManager]. +/// +/// See also: +/// +/// * `_callback_web.dart`, which has the dart:html implementation +CallbackManager get callbackManager => _singletonCallbackManager; + +/// IOCallbackManager singleton. +final _IOCallbackManager _singletonCallbackManager = _IOCallbackManager(); + +/// Manages communication between `integration_tests` and the `driver_tests`. +/// +/// This is the dart:io implementation. +class _IOCallbackManager implements CallbackManager { + @override + Future> callback( + Map params, IntegrationTestResults testRunner) async { + final String command = params['command']!; + Map response; + switch (command) { + case 'request_data': + final bool allTestsPassed = await testRunner.allTestsPassed.future; + response = { + 'message': allTestsPassed + ? Response.allTestsPassed(data: testRunner.reportData).toJson() + : Response.someTestsFailed( + testRunner.failureMethodsDetails, + data: testRunner.reportData, + ).toJson(), + }; + case 'get_health': + response = {'status': 'ok'}; + default: + throw UnimplementedError('$command is not implemented'); + } + return { + 'isError': false, + 'response': response, + }; + } + + @override + void cleanup() { + // no-op. + // Add any IO platform specific Completer/Future cleanups to here if any + // comes up in the future. For example: `WebCallbackManager.cleanup`. + } + + // [convertFlutterSurfaceToImage] has been called and [takeScreenshot] is ready to capture the surface (Android only). + bool _isSurfaceRendered = false; + + @override + Future convertFlutterSurfaceToImage() async { + if (!Platform.isAndroid) { + // No-op on other platforms. + return; + } + assert(!_isSurfaceRendered, 'Surface already converted to an image'); + await integrationTestChannel.invokeMethod( + 'convertFlutterSurfaceToImage', + ); + _isSurfaceRendered = true; + + addTearDown(() async { + assert(_isSurfaceRendered, 'Surface is not an image'); + await integrationTestChannel.invokeMethod( + 'revertFlutterImage', + ); + _isSurfaceRendered = false; + }); + } + + @override + Future> takeScreenshot(String screenshot, [Map? args]) async { + assert(args == null, '[args] handling has not been implemented for this platform'); + if (Platform.isAndroid && !_isSurfaceRendered) { + throw StateError('Call convertFlutterSurfaceToImage() before taking a screenshot'); + } + integrationTestChannel.setMethodCallHandler(_onMethodChannelCall); + final List? rawBytes = await integrationTestChannel.invokeMethod>( + 'captureScreenshot', + {'name': screenshot}, + ); + if (rawBytes == null) { + throw StateError('Expected a list of bytes, but instead captureScreenshot returned null'); + } + return { + 'screenshotName': screenshot, + 'bytes': rawBytes, + }; + } + + Future _onMethodChannelCall(MethodCall call) async { + switch (call.method) { + case 'scheduleFrame': + PlatformDispatcher.instance.scheduleFrame(); + } + return null; + } +} diff --git a/flutter/packages/integration_test/lib/src/_callback_web.dart b/flutter/packages/integration_test/lib/src/_callback_web.dart new file mode 100644 index 0000000000000000000000000000000000000000..88d01c6d265bc35c287586b9c09a3c37433dc386 --- /dev/null +++ b/flutter/packages/integration_test/lib/src/_callback_web.dart @@ -0,0 +1,172 @@ +// 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 '../common.dart'; + +/// The dart:html implementation of [CallbackManager]. +/// +/// See also: +/// +/// * `_callback_io.dart`, which has the dart:io implementation +CallbackManager get callbackManager => _singletonWebDriverCommandManager; + +/// WebDriverCommandManager singleton. +final _WebCallbackManager _singletonWebDriverCommandManager = + _WebCallbackManager(); + +/// Manages communication between `integration_tests` and the `driver_tests`. +/// +/// Along with responding to callbacks from the driver side this calls enables +/// usage of Web Driver commands by sending [WebDriverCommand]s to driver side. +/// +/// Tests can execute an Web Driver commands such as `screenshot` using browsers' +/// WebDriver APIs. +/// +/// See: https://www.w3.org/TR/webdriver/ +class _WebCallbackManager implements CallbackManager { + /// App side tests will put the command requests from WebDriver to this pipe. + Completer _webDriverCommandPipe = + Completer(); + + /// Updated when WebDriver completes the request by the test method. + /// + /// For example, a test method will ask for a screenshot by calling + /// `takeScreenshot`. When this screenshot is taken [_driverCommandComplete] + /// will complete. + Completer _driverCommandComplete = Completer(); + + /// Takes screenshot using WebDriver screenshot command. + /// + /// Only works on Web when tests are run via `flutter driver` command. + /// + /// See: https://www.w3.org/TR/webdriver/#screen-capture. + @override + Future> takeScreenshot(String screenshotName, [Map? args]) async { + await _sendWebDriverCommand(WebDriverCommand.screenshot(screenshotName, args)); + return { + 'screenshotName': screenshotName, + // Flutter Web doesn't provide the bytes. + 'bytes': [] + }; + } + + @override + Future convertFlutterSurfaceToImage() async { + // Noop on Web. + } + + Future _sendWebDriverCommand(WebDriverCommand command) async { + try { + _webDriverCommandPipe.complete(command); + final bool awaitCommand = await _driverCommandComplete.future; + if (!awaitCommand) { + throw Exception( + 'Web Driver Command ${command.type} failed while waiting for ' + 'driver side'); + } + } catch (exception) { + throw Exception('Web Driver Command failed: ${command.type} with exception $exception'); + } finally { + // Reset the completer. + _driverCommandComplete = Completer(); + } + } + + /// The callback function to response the driver side input. + /// + /// Provides a handshake mechanism for executing [WebDriverCommand]s on the + /// driver side. + @override + Future> callback( + Map params, IntegrationTestResults testRunner) async { + final String command = params['command']!; + Map response; + switch (command) { + case 'request_data': + return params['message'] == null + ? _requestData(testRunner) + : _requestDataWithMessage(params['message']!, testRunner); + case 'get_health': + response = {'status': 'ok'}; + default: + throw UnimplementedError('$command is not implemented'); + } + return { + 'isError': false, + 'response': response, + }; + } + + Future> _requestDataWithMessage( + String extraMessage, IntegrationTestResults testRunner) async { + Map response; + // Driver side tests' status is added as an extra message. + final DriverTestMessage message = + DriverTestMessage.fromString(extraMessage); + // If driver side tests are pending send the first command in the + // `commandPipe` to the tests. + if (message.isPending) { + final WebDriverCommand command = await _webDriverCommandPipe.future; + switch (command.type) { + case WebDriverCommandType.screenshot: + final Map data = Map.from(command.values); + data.addAll( + WebDriverCommand.typeToMap(WebDriverCommandType.screenshot)); + response = { + 'message': Response.webDriverCommand(data: data).toJson(), + }; + case WebDriverCommandType.noop: + final Map data = {}; + data.addAll(WebDriverCommand.typeToMap(WebDriverCommandType.noop)); + response = { + 'message': Response.webDriverCommand(data: data).toJson(), + }; + case WebDriverCommandType.ack: + throw UnimplementedError('${command.type} is not implemented'); + } + } else { + final Map data = {}; + data.addAll(WebDriverCommand.typeToMap(WebDriverCommandType.ack)); + response = { + 'message': Response.webDriverCommand(data: data).toJson(), + }; + _driverCommandComplete.complete(message.isSuccess); + _webDriverCommandPipe = Completer(); + } + return { + 'isError': false, + 'response': response, + }; + } + + Future> _requestData(IntegrationTestResults testRunner) async { + final bool allTestsPassed = await testRunner.allTestsPassed.future; + final Map response = { + 'message': allTestsPassed + ? Response.allTestsPassed(data: testRunner.reportData).toJson() + : Response.someTestsFailed( + testRunner.failureMethodsDetails, + data: testRunner.reportData, + ).toJson(), + }; + return { + 'isError': false, + 'response': response, + }; + } + + @override + void cleanup() { + if (!_webDriverCommandPipe.isCompleted) { + _webDriverCommandPipe + .complete(Future.value(WebDriverCommand.noop())); + } + + if (!_driverCommandComplete.isCompleted) { + _driverCommandComplete.complete(Future.value(false)); + } + } +} diff --git a/flutter/packages/integration_test/lib/src/_extension_io.dart b/flutter/packages/integration_test/lib/src/_extension_io.dart new file mode 100644 index 0000000000000000000000000000000000000000..cf0c91cfc95f499075429c0ea1be4a57a807ef81 --- /dev/null +++ b/flutter/packages/integration_test/lib/src/_extension_io.dart @@ -0,0 +1,13 @@ +// 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. + +/// The dart:io implementation of [registerWebServiceExtension]. +/// +/// See also: +/// +/// * `_extension_web.dart`, which has the dart:html implementation +void registerWebServiceExtension( + Future> Function(Map) call) { + throw UnsupportedError('Use registerServiceExtension instead'); +} diff --git a/flutter/packages/integration_test/lib/src/_extension_web.dart b/flutter/packages/integration_test/lib/src/_extension_web.dart new file mode 100644 index 0000000000000000000000000000000000000000..e422cc5aa19be2f0ac0fded697f1802cd9e110d9 --- /dev/null +++ b/flutter/packages/integration_test/lib/src/_extension_web.dart @@ -0,0 +1,40 @@ +// Copyright 2014 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +import 'dart:async'; +import 'dart:convert'; +import 'dart:html' as html; +import 'dart:js'; +import 'dart:js_util' as js_util; + +/// The web implementation of [registerWebServiceExtension]. +/// +/// Adds a hidden `window.$flutterDriver` JavaScript function that's called by +/// `FlutterWebDriver` to fulfill FlutterDriver commands. +/// +/// See also: +/// +/// * `_extension_io.dart`, which has the dart:io implementation +void registerWebServiceExtension(Future> Function(Map) callback) { + // Define the result variable because packages/flutter_driver/lib/src/driver/web_driver.dart + // checks for this value to become non-null when waiting for the result. If this value is + // undefined at the time of the check, WebDriver throws an exception. + context[r'$flutterDriverResult'] = null; + + js_util.setProperty(html.window, r'$flutterDriver', allowInterop((dynamic message) async { + try { + final Map messageJson = jsonDecode(message as String) as Map; + final Map params = messageJson.cast(); + final Map result = await callback(params); + context[r'$flutterDriverResult'] = json.encode(result); + } catch (error, stackTrace) { + // Encode the error in the same format the FlutterDriver extension uses. + // See //packages/flutter_driver/lib/src/extension/extension.dart + context[r'$flutterDriverResult'] = json.encode({ + 'isError': true, + 'response': '$error\n$stackTrace', + }); + } + })); +} diff --git a/flutter/packages/integration_test/lib/src/callback.dart b/flutter/packages/integration_test/lib/src/callback.dart new file mode 100644 index 0000000000000000000000000000000000000000..c10e2d27c600b1c17175fdb54a04cbd047c1dade --- /dev/null +++ b/flutter/packages/integration_test/lib/src/callback.dart @@ -0,0 +1,5 @@ +// 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. + +export '_callback_io.dart' if (dart.library.html) '_callback_web.dart'; diff --git a/flutter/packages/integration_test/lib/src/channel.dart b/flutter/packages/integration_test/lib/src/channel.dart new file mode 100644 index 0000000000000000000000000000000000000000..7c25f0c06c4902ac20387002798492653e7875c4 --- /dev/null +++ b/flutter/packages/integration_test/lib/src/channel.dart @@ -0,0 +1,9 @@ +// 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/services.dart'; + +/// The method channel used to report the result of the tests to the platform. +/// On Android, this is relevant when running instrumented tests. +const MethodChannel integrationTestChannel = MethodChannel('plugins.flutter.io/integration_test'); diff --git a/flutter/packages/integration_test/lib/src/extension.dart b/flutter/packages/integration_test/lib/src/extension.dart new file mode 100644 index 0000000000000000000000000000000000000000..a2cb861fbf210246e46eae7ba3749f13055d3b14 --- /dev/null +++ b/flutter/packages/integration_test/lib/src/extension.dart @@ -0,0 +1,5 @@ +// 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. + +export '_extension_io.dart' if (dart.library.html) '_extension_web.dart'; diff --git a/flutter/packages/integration_test/pubspec.lock b/flutter/packages/integration_test/pubspec.lock new file mode 100644 index 0000000000000000000000000000000000000000..f92dcfe8ecf6f1da1d92419b418429b0168a7f7f --- /dev/null +++ b/flutter/packages/integration_test/pubspec.lock @@ -0,0 +1,238 @@ +# Generated by pub +# See https://dart.dev/tools/pub/glossary#lockfile +packages: + 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 main" + 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" + flutter_driver: + dependency: "direct main" + description: flutter + source: sdk + version: "0.0.0" + flutter_test: + dependency: "direct main" + description: flutter + source: sdk + version: "0.0.0" + fuchsia_remote_debug_protocol: + dependency: transitive + 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" + platform: + dependency: transitive + description: + name: platform + sha256: "12220bb4b65720483f8fa9450b4332347737cf8213dd2840d8b2c823e47243ec" + url: "https://pub.dev" + source: hosted + version: "3.1.4" + process: + dependency: transitive + description: + name: process + sha256: "21e54fd2faf1b5bdd5102afd25012184a6793927648ea81eea80552ac9405b32" + url: "https://pub.dev" + source: hosted + version: "5.0.2" + 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" + 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_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" + webdriver: + dependency: "direct main" + description: + name: webdriver + sha256: "003d7da9519e1e5f329422b36c4dcdf18d7d2978d1ba099ea4e45ba490ed845e" + url: "https://pub.dev" + source: hosted + version: "3.0.3" +sdks: + dart: ">=3.2.0-0 <4.0.0" diff --git a/flutter/packages/integration_test/pubspec.yaml b/flutter/packages/integration_test/pubspec.yaml new file mode 100644 index 0000000000000000000000000000000000000000..834732719e1369ae1c8987a4086860edf7210e4c --- /dev/null +++ b/flutter/packages/integration_test/pubspec.yaml @@ -0,0 +1,50 @@ +name: integration_test +description: Runs tests that use the flutter_test API as integration tests. +publish_to: none + +environment: + sdk: '>=3.2.0-0 <4.0.0' + +dependencies: + flutter: + sdk: flutter + flutter_driver: + sdk: flutter + flutter_test: + sdk: flutter + path: 1.9.0 + vm_service: 13.0.0 + + 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" + clock: 1.1.1 # 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" + fake_async: 1.3.1 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" + file: 7.0.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_flutter_testing: 2.0.1 # 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" + matcher: 0.12.16+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" + stack_trace: 1.11.1 # 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" + 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" + test_api: 0.6.1 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" + vector_math: 2.1.4 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" + webdriver: 3.0.3 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" + +flutter: + plugin: + platforms: + android: + package: dev.flutter.plugins.integration_test + pluginClass: IntegrationTestPlugin + ios: + pluginClass: IntegrationTestPlugin + +# PUBSPEC CHECKSUM: 4059 diff --git a/flutter/packages/integration_test/test/binding_fail_test.dart b/flutter/packages/integration_test/test/binding_fail_test.dart new file mode 100644 index 0000000000000000000000000000000000000000..f28d1f9dd98b4d597301cd2f35dbfa3c9b8b669b --- /dev/null +++ b/flutter/packages/integration_test/test/binding_fail_test.dart @@ -0,0 +1,92 @@ +// 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 'dart:io'; + +import 'package:flutter_test/flutter_test.dart'; +import 'package:path/path.dart' as path; + +final String bat = Platform.isWindows ? '.bat' : ''; +final String _flutterBin = path.join(Directory.current.parent.parent.path, 'bin', 'flutter$bat'); +const String _integrationResultsPrefix = 'IntegrationTestWidgetsFlutterBinding test results:'; +const String _failureExcerpt = r'Expected: \n Actual: '; + +Future main() async { + group('Integration binding result', () { + test('when multiple tests pass', () async { + final Map? results = await _runTest(path.join('test', 'data', 'pass_test_script.dart')); + + expect( + results, + equals({ + 'passing test 1': 'success', + 'passing test 2': 'success', + })); + }); + + test('when multiple tests fail', () async { + final Map? results = await _runTest(path.join('test', 'data', 'fail_test_script.dart')); + + expect(results, hasLength(2)); + expect(results, containsPair('failing test 1', contains(_failureExcerpt))); + expect(results, containsPair('failing test 2', contains(_failureExcerpt))); + }); + + test('when one test passes, then another fails', () async { + final Map? results = await _runTest(path.join('test', 'data', 'pass_then_fail_test_script.dart')); + + expect(results, hasLength(2)); + expect(results, containsPair('passing test', equals('success'))); + expect(results, containsPair('failing test', contains(_failureExcerpt))); + }); + + test('when one test fails, then another passes', () async { + final Map? results = await _runTest(path.join('test', 'data', 'fail_then_pass_test_script.dart')); + + expect(results, hasLength(2)); + expect(results, containsPair('failing test', contains(_failureExcerpt))); + expect(results, containsPair('passing test', equals('success'))); + }); + }); +} + +/// Runs a test script and returns the [IntegrationTestWidgetsFlutterBinding.result]. +/// +/// [scriptPath] is relative to the package root. +Future?> _runTest(String scriptPath) async { + final Process process = + await Process.start(_flutterBin, ['test', '--machine', scriptPath]); + + /// In the test [tearDownAll] block, the test results are encoded into JSON and + /// are printed with the [_integrationResultsPrefix] prefix. + /// + /// See the following for the test event spec which we parse the printed lines + /// out of: https://github.com/dart-lang/test/blob/master/pkgs/test/doc/json_reporter.md + final String testResults = (await process.stdout + .transform(utf8.decoder) + .expand((String text) => text.split('\n')) + .map((String line) { + try { + return jsonDecode(line); + } on FormatException { + // Only interested in test events which are JSON. + } + }) + .expand>((dynamic json) { + if (json is List) { + return json.cast(); + } + return >[ + if (json != null) + json as Map, + ]; + }) + .where((Map testEvent) => testEvent['type'] == 'print') + .map((Map printEvent) => printEvent['message'] as String) + .firstWhere((String message) => message.startsWith(_integrationResultsPrefix))) + .replaceAll(_integrationResultsPrefix, ''); + + return jsonDecode(testResults) as Map?; +} diff --git a/flutter/packages/integration_test/test/binding_test.dart b/flutter/packages/integration_test/test/binding_test.dart new file mode 100644 index 0000000000000000000000000000000000000000..bc02524475fb8486d43133c6103730da01ae4c48 --- /dev/null +++ b/flutter/packages/integration_test/test/binding_test.dart @@ -0,0 +1,173 @@ +// 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:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:integration_test/common.dart'; +import 'package:integration_test/integration_test.dart'; +import 'package:vm_service/vm_service.dart' as vm; + +vm.Timeline _kTimelines = vm.Timeline( + traceEvents: [], + timeOriginMicros: 100, + timeExtentMicros: 200, +); + +Future main() async { + Future>? request; + + group('Test Integration binding', () { + final IntegrationTestWidgetsFlutterBinding binding = IntegrationTestWidgetsFlutterBinding.ensureInitialized(); + + FakeVM? fakeVM; + + setUp(() { + request = binding.callback({ + 'command': 'request_data', + }); + fakeVM = FakeVM( + timeline: _kTimelines, + ); + }); + + testWidgets('Run Integration app', (WidgetTester tester) async { + runApp(const MaterialApp( + home: Text('Test'), + )); + expect(tester.binding, binding); + binding.reportData = {'answer': 42}; + await tester.pump(); + }); + + testWidgets('hitTesting works when using setSurfaceSize', (WidgetTester tester) async { + int invocations = 0; + await tester.pumpWidget( + MaterialApp( + home: Center( + child: GestureDetector( + onTap: () { + invocations++; + }, + child: const Text('Test'), + ), + ), + ), + ); + + await tester.tap(find.byType(Text)); + await tester.pump(); + expect(invocations, 1); + + await tester.binding.setSurfaceSize(const Size(200, 300)); + await tester.pump(); + await tester.tap(find.byType(Text)); + await tester.pump(); + expect(invocations, 2); + + await tester.binding.setSurfaceSize(null); + await tester.pump(); + await tester.tap(find.byType(Text)); + await tester.pump(); + expect(invocations, 3); + }); + + testWidgets('setSurfaceSize works', (WidgetTester tester) async { + await tester.pumpWidget(const MaterialApp(home: Center(child: Text('Test')))); + + final Size viewCenter = tester.view.physicalSize / + tester.view.devicePixelRatio / + 2; + final double viewCenterX = viewCenter.width; + final double viewCenterY = viewCenter.height; + + Offset widgetCenter = tester.getRect(find.byType(Text)).center; + expect(widgetCenter.dx, viewCenterX); + expect(widgetCenter.dy, viewCenterY); + + await tester.binding.setSurfaceSize(const Size(200, 300)); + await tester.pump(); + widgetCenter = tester.getRect(find.byType(Text)).center; + expect(widgetCenter.dx, 100); + expect(widgetCenter.dy, 150); + + await tester.binding.setSurfaceSize(null); + await tester.pump(); + widgetCenter = tester.getRect(find.byType(Text)).center; + expect(widgetCenter.dx, viewCenterX); + expect(widgetCenter.dy, viewCenterY); + }); + + testWidgets('Test traceAction', (WidgetTester tester) async { + await binding.enableTimeline(vmService: fakeVM); + await binding.traceAction(() async {}); + expect(binding.reportData, isNotNull); + expect(binding.reportData!.containsKey('timeline'), true); + expect( + json.encode(binding.reportData!['timeline']), + json.encode(_kTimelines), + ); + }); + + group('defaultTestTimeout', () { + final Timeout originalTimeout = binding.defaultTestTimeout; + tearDown(() { + binding.defaultTestTimeout = originalTimeout; + }); + + test('can be configured', () { + const Timeout newTimeout = Timeout(Duration(seconds: 17)); + binding.defaultTestTimeout = newTimeout; + expect(binding.defaultTestTimeout, newTimeout); + }); + }); + + // TODO(jiahaog): Remove when https://github.com/flutter/flutter/issues/66006 is fixed. + testWidgets('root widgets are wrapped with a RepaintBoundary', (WidgetTester tester) async { + await tester.pumpWidget(const Placeholder()); + + expect(find.byType(RepaintBoundary), findsOneWidget); + }); + }); + + tearDownAll(() async { + // This part is outside the group so that `request` has been completed as + // part of the `tearDownAll` registered in the group during + // `IntegrationTestWidgetsFlutterBinding` initialization. + final Map response = + (await request)!['response'] as Map; + final String message = response['message'] as String; + final Response result = Response.fromJson(message); + assert(result.data!['answer'] == 42); + }); +} + +class FakeVM extends Fake implements vm.VmService { + FakeVM({required this.timeline}); + + vm.Timeline timeline; + + @override + Future getVMTimeline({int? timeOriginMicros, int? timeExtentMicros}) async { + return timeline; + } + + int lastTimeStamp = 0; + @override + Future getVMTimelineMicros() async { + lastTimeStamp += 100; + return vm.Timestamp(timestamp: lastTimeStamp); + } + + @override + Future setVMTimelineFlags(List recordedStreams) async { + return vm.Success(); + } + + @override + Future clearVMTimeline() async { + return vm.Success(); + } +} diff --git a/flutter/packages/integration_test/test/data/README.md b/flutter/packages/integration_test/test/data/README.md new file mode 100644 index 0000000000000000000000000000000000000000..e52aca112ce4b8d7d02cc3b64f99398a9dfeceaf --- /dev/null +++ b/flutter/packages/integration_test/test/data/README.md @@ -0,0 +1,4 @@ +Files in this directory are not invoked directly by the test command. + +They are used as inputs for the other test files outside of this directory, so +that failures can be tested. \ No newline at end of file diff --git a/flutter/packages/integration_test/test/data/fail_test_script.dart b/flutter/packages/integration_test/test/data/fail_test_script.dart new file mode 100644 index 0000000000000000000000000000000000000000..d78d5e6f0a094db4f7f9e13e7b3dc279669600ab --- /dev/null +++ b/flutter/packages/integration_test/test/data/fail_test_script.dart @@ -0,0 +1,25 @@ +// 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:flutter_test/flutter_test.dart'; +import 'package:integration_test/integration_test.dart'; + +Future main() async { + final IntegrationTestWidgetsFlutterBinding binding = IntegrationTestWidgetsFlutterBinding.ensureInitialized(); + binding.allTestsPassed.future.then((_) { + // We use this print to communicate with ../binding_fail_test.dart + // ignore: avoid_print + print('IntegrationTestWidgetsFlutterBinding test results: ${jsonEncode(binding.results)}'); + }); + + testWidgets('failing test 1', (WidgetTester tester) async { + expect(true, false); + }); + + testWidgets('failing test 2', (WidgetTester tester) async { + expect(true, false); + }); +} diff --git a/flutter/packages/integration_test/test/data/fail_then_pass_test_script.dart b/flutter/packages/integration_test/test/data/fail_then_pass_test_script.dart new file mode 100644 index 0000000000000000000000000000000000000000..2de1659c0bf34d95e554ff81ade92e8cc0b4fad3 --- /dev/null +++ b/flutter/packages/integration_test/test/data/fail_then_pass_test_script.dart @@ -0,0 +1,25 @@ +// 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:flutter_test/flutter_test.dart'; +import 'package:integration_test/integration_test.dart'; + +Future main() async { + final IntegrationTestWidgetsFlutterBinding binding = IntegrationTestWidgetsFlutterBinding.ensureInitialized(); + binding.allTestsPassed.future.then((_) { + // We use this print to communicate with ../binding_fail_test.dart + // ignore: avoid_print + print('IntegrationTestWidgetsFlutterBinding test results: ${jsonEncode(binding.results)}'); + }); + + testWidgets('failing test', (WidgetTester tester) async { + expect(true, false); + }); + + testWidgets('passing test', (WidgetTester tester) async { + expect(true, true); + }); +} diff --git a/flutter/packages/integration_test/test/data/pass_test_script.dart b/flutter/packages/integration_test/test/data/pass_test_script.dart new file mode 100644 index 0000000000000000000000000000000000000000..478641f577f5efef5d64f203b2950c98e8759b0d --- /dev/null +++ b/flutter/packages/integration_test/test/data/pass_test_script.dart @@ -0,0 +1,25 @@ +// 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:flutter_test/flutter_test.dart'; +import 'package:integration_test/integration_test.dart'; + +Future main() async { + final IntegrationTestWidgetsFlutterBinding binding = IntegrationTestWidgetsFlutterBinding.ensureInitialized(); + binding.allTestsPassed.future.then((_) { + // We use this print to communicate with ../binding_fail_test.dart + // ignore: avoid_print + print('IntegrationTestWidgetsFlutterBinding test results: ${jsonEncode(binding.results)}'); + }); + + testWidgets('passing test 1', (WidgetTester tester) async { + expect(true, true); + }); + + testWidgets('passing test 2', (WidgetTester tester) async { + expect(true, true); + }); +} diff --git a/flutter/packages/integration_test/test/data/pass_then_fail_test_script.dart b/flutter/packages/integration_test/test/data/pass_then_fail_test_script.dart new file mode 100644 index 0000000000000000000000000000000000000000..d79d7a089d141b6c8ee677a03922dc56718f7497 --- /dev/null +++ b/flutter/packages/integration_test/test/data/pass_then_fail_test_script.dart @@ -0,0 +1,25 @@ +// 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:flutter_test/flutter_test.dart'; +import 'package:integration_test/integration_test.dart'; + +Future main() async { + final IntegrationTestWidgetsFlutterBinding binding = IntegrationTestWidgetsFlutterBinding.ensureInitialized(); + binding.allTestsPassed.future.then((_) { + // We use this print to communicate with ../binding_fail_test.dart + // ignore: avoid_print + print('IntegrationTestWidgetsFlutterBinding test results: ${jsonEncode(binding.results)}'); + }); + + testWidgets('passing test', (WidgetTester tester) async { + expect(true, true); + }); + + testWidgets('failing test', (WidgetTester tester) async { + expect(true, false); + }); +} diff --git a/flutter/packages/integration_test/test/response_serialization_test.dart b/flutter/packages/integration_test/test/response_serialization_test.dart new file mode 100644 index 0000000000000000000000000000000000000000..5e38c79ba81f1613c3d4160fc13f1bf95a9c5703 --- /dev/null +++ b/flutter/packages/integration_test/test/response_serialization_test.dart @@ -0,0 +1,51 @@ +// 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_test/flutter_test.dart'; + +import 'package:integration_test/common.dart'; + +void main() { + test('Serialize and deserialize Failure', () { + final Failure fail = Failure('what a name', 'no detail'); + final Failure restored = Failure.fromJsonString(fail.toString()); + expect(restored.methodName, fail.methodName); + expect(restored.details, fail.details); + }); + + test('Serialize and deserialize Response', () { + Response response, restored; + String jsonString; + + response = Response.allTestsPassed(); + jsonString = response.toJson(); + expect(jsonString, '{"result":"true","failureDetails":[]}'); + restored = Response.fromJson(jsonString); + expect(restored.allTestsPassed, response.allTestsPassed); + expect(restored.data, null); + expect(restored.formattedFailureDetails, ''); + + final Failure fail = Failure('what a name', 'no detail'); + final Failure fail2 = Failure('what a name2', 'no detail2'); + response = Response.someTestsFailed([fail, fail2]); + jsonString = response.toJson(); + restored = Response.fromJson(jsonString); + expect(restored.allTestsPassed, response.allTestsPassed); + expect(restored.data, null); + expect(restored.formattedFailureDetails, response.formattedFailureDetails); + + final Map data = {'aaa': 'bbb'}; + response = Response.allTestsPassed(data: data); + jsonString = response.toJson(); + restored = Response.fromJson(jsonString); + expect(restored.data!.keys, ['aaa']); + expect(restored.data!.values, ['bbb']); + + response = Response.someTestsFailed([fail, fail2], data: data); + jsonString = response.toJson(); + restored = Response.fromJson(jsonString); + expect(restored.data!.keys, ['aaa']); + expect(restored.data!.values, ['bbb']); + }); +} diff --git a/flutter/packages/integration_test/test/socket_fail_test.dart b/flutter/packages/integration_test/test/socket_fail_test.dart new file mode 100644 index 0000000000000000000000000000000000000000..4b02ed1cd26306c6546f05be311d3b3751c76363 --- /dev/null +++ b/flutter/packages/integration_test/test/socket_fail_test.dart @@ -0,0 +1,32 @@ +// 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:io'; + +import 'package:flutter_test/flutter_test.dart'; +import 'package:integration_test/integration_test.dart'; + +class SocketExceptionHttpClient extends Fake implements HttpClient { + @override + Future openUrl(String method, Uri url) { + throw const SocketException('always throw'); + } +} + +Future main() async { + final IntegrationTestWidgetsFlutterBinding binding = IntegrationTestWidgetsFlutterBinding.ensureInitialized(); + + test('Prints an appropriate message on socket exception', () async { + bool gotStateError = false; + try { + await binding.enableTimeline(httpClient: SocketExceptionHttpClient()); + } on StateError catch (e) { + gotStateError = true; + expect(e.toString(), contains('This may happen if DDS is enabled')); + } on SocketException catch (_) { + fail('Did not expect a socket exception.'); + } + expect(gotStateError, true); + }); +} diff --git a/flutter/packages/integration_test/test/web_extension_test.dart b/flutter/packages/integration_test/test/web_extension_test.dart new file mode 100644 index 0000000000000000000000000000000000000000..8097729366fdbe865a0b2b9965cfc040d8967d87 --- /dev/null +++ b/flutter/packages/integration_test/test/web_extension_test.dart @@ -0,0 +1,23 @@ +// 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. + +@Tags(['web']) +library; + +import 'dart:js' as js; + +import 'package:flutter_test/flutter_test.dart'; +import 'package:integration_test/integration_test.dart'; + +void main() { + IntegrationTestWidgetsFlutterBinding(); + + test('IntegrationTestWidgetsFlutterBinding on the web should register certain global properties', () { + expect(js.context.hasProperty(r'$flutterDriver'), true); + expect(js.context[r'$flutterDriver'], isNotNull); + + expect(js.context.hasProperty(r'$flutterDriverResult'), true); + expect(js.context[r'$flutterDriverResult'], isNull); + }); +} diff --git a/flutter/packages/integration_test/test_fixes/analysis_options.yaml b/flutter/packages/integration_test/test_fixes/analysis_options.yaml new file mode 100644 index 0000000000000000000000000000000000000000..7cca7b1d5ce214264462f093fd8e21425d44a25c --- /dev/null +++ b/flutter/packages/integration_test/test_fixes/analysis_options.yaml @@ -0,0 +1 @@ +# This ensures that parent analysis options do not accidentally break the fix tests. diff --git a/flutter/packages/integration_test/test_fixes/integration_test/binding/integration_test_widgets_flutter_binding.dart b/flutter/packages/integration_test/test_fixes/integration_test/binding/integration_test_widgets_flutter_binding.dart new file mode 100644 index 0000000000000000000000000000000000000000..2360ceccd7e75cfff56c4be0175d1b2abc3cb217 --- /dev/null +++ b/flutter/packages/integration_test/test_fixes/integration_test/binding/integration_test_widgets_flutter_binding.dart @@ -0,0 +1,15 @@ +// 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:integration_test/integration_test.dart'; + +void main() { + final binding = IntegrationTestWidgetsFlutterBinding.ensureInitialized(); + binding.runTest( + () async { }, + () { }, + // Changes made in https://github.com/flutter/flutter/pull/89952 + timeout: Duration(minutes: 30), + ); +} diff --git a/flutter/packages/integration_test/test_fixes/integration_test/binding/integration_test_widgets_flutter_binding.dart.expect b/flutter/packages/integration_test/test_fixes/integration_test/binding/integration_test_widgets_flutter_binding.dart.expect new file mode 100644 index 0000000000000000000000000000000000000000..8abee159a5b132e153879b08ebea32d401a693ab --- /dev/null +++ b/flutter/packages/integration_test/test_fixes/integration_test/binding/integration_test_widgets_flutter_binding.dart.expect @@ -0,0 +1,13 @@ +// 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:integration_test/integration_test.dart'; + +void main() { + final binding = IntegrationTestWidgetsFlutterBinding.ensureInitialized(); + binding.runTest( + () async { }, + () { }, + ); +}