dart_plugin_test.dart 37.4 KB
Newer Older
1 2 3 4 5 6 7 8 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:file/file.dart';
import 'package:file/memory.dart';
import 'package:flutter_tools/src/dart/package_map.dart';
import 'package:flutter_tools/src/flutter_manifest.dart';
import 'package:flutter_tools/src/flutter_plugins.dart';
10
import 'package:flutter_tools/src/globals.dart' as globals;
11 12 13
import 'package:flutter_tools/src/plugins.dart';
import 'package:flutter_tools/src/project.dart';
import 'package:package_config/package_config.dart';
14
import 'package:pub_semver/pub_semver.dart';
15
import 'package:test/fake.dart';
16 17 18 19 20 21 22
import 'package:yaml/yaml.dart';

import '../src/common.dart';
import '../src/context.dart';

void main() {
  group('Dart plugin registrant', () {
23 24 25
    late FileSystem fs;
    late FakeFlutterProject flutterProject;
    late FakeFlutterManifest flutterManifest;
26 27 28

    setUp(() async {
      fs = MemoryFileSystem.test();
29 30 31 32 33 34
      final Directory directory = fs.currentDirectory.childDirectory('app');
      flutterManifest = FakeFlutterManifest();
      flutterProject = FakeFlutterProject()
        ..manifest = flutterManifest
        ..directory = directory
        ..flutterPluginsFile = directory.childFile('.flutter-plugins')
35
        ..flutterPluginsDependenciesFile = directory.childFile('.flutter-plugins-dependencies')
36
        ..dartPluginRegistrant = directory.childFile('dart_plugin_registrant.dart');
37 38 39 40
      flutterProject.directory.childFile('.packages').createSync(recursive: true);
    });

    group('resolvePlatformImplementation', () {
41
      testWithoutContext('selects uncontested implementation from direct dependency', () async {
42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57
        final Set<String> directDependencies = <String>{
          'url_launcher_linux',
          'url_launcher_macos',
        };
        final List<PluginInterfaceResolution> resolutions = resolvePlatformImplementation(<Plugin>[
          Plugin.fromYaml(
            'url_launcher_linux',
            '',
            YamlMap.wrap(<String, dynamic>{
              'implements': 'url_launcher',
              'platforms': <String, dynamic>{
                'linux': <String, dynamic>{
                  'dartPluginClass': 'UrlLauncherPluginLinux',
                },
              },
            }),
58
            null,
59 60 61 62 63 64 65 66 67 68 69 70 71 72 73
            <String>[],
            fileSystem: fs,
            appDependencies: directDependencies,
          ),
          Plugin.fromYaml(
            'url_launcher_macos',
            '',
            YamlMap.wrap(<String, dynamic>{
              'implements': 'url_launcher',
              'platforms': <String, dynamic>{
                'macos': <String, dynamic>{
                  'dartPluginClass': 'UrlLauncherPluginMacOS',
                },
              },
            }),
74
            null,
75 76 77 78
            <String>[],
            fileSystem: fs,
            appDependencies: directDependencies,
          ),
79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102
        ]);

        expect(resolutions.length, equals(2));
        expect(resolutions[0].toMap(), equals(
          <String, String>{
            'pluginName': 'url_launcher_linux',
            'dartClass': 'UrlLauncherPluginLinux',
            'platform': 'linux',
          })
        );
        expect(resolutions[1].toMap(), equals(
          <String, String>{
            'pluginName': 'url_launcher_macos',
            'dartClass': 'UrlLauncherPluginMacOS',
            'platform': 'macos',
          })
        );
      });

      testWithoutContext('selects uncontested implementation from transitive dependency', () async {
        final Set<String> directDependencies = <String>{
          'url_launcher_macos',
        };
        final List<PluginInterfaceResolution> resolutions = resolvePlatformImplementation(<Plugin>[
103
          Plugin.fromYaml(
104
            'url_launcher_macos',
105 106 107 108
            '',
            YamlMap.wrap(<String, dynamic>{
              'implements': 'url_launcher',
              'platforms': <String, dynamic>{
109 110
                'macos': <String, dynamic>{
                  'dartPluginClass': 'UrlLauncherPluginMacOS',
111 112 113
                },
              },
            }),
114
            null,
115 116 117 118 119
            <String>[],
            fileSystem: fs,
            appDependencies: directDependencies,
          ),
          Plugin.fromYaml(
120
            'transitive_dependency_plugin',
121 122 123 124
            '',
            YamlMap.wrap(<String, dynamic>{
              'implements': 'url_launcher',
              'platforms': <String, dynamic>{
125 126
                'windows': <String, dynamic>{
                  'dartPluginClass': 'UrlLauncherPluginWindows',
127 128 129
                },
              },
            }),
130
            null,
131 132 133 134 135 136 137 138 139
            <String>[],
            fileSystem: fs,
            appDependencies: directDependencies,
          ),
        ]);

        expect(resolutions.length, equals(2));
        expect(resolutions[0].toMap(), equals(
          <String, String>{
140 141 142
            'pluginName': 'url_launcher_macos',
            'dartClass': 'UrlLauncherPluginMacOS',
            'platform': 'macos',
143 144 145 146
          })
        );
        expect(resolutions[1].toMap(), equals(
          <String, String>{
147 148 149
            'pluginName': 'transitive_dependency_plugin',
            'dartClass': 'UrlLauncherPluginWindows',
            'platform': 'windows',
150 151 152 153
          })
        );
      });

154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170
      testWithoutContext('selects inline implementation on mobile', () async {
        final Set<String> directDependencies = <String>{};

        final List<PluginInterfaceResolution> resolutions = resolvePlatformImplementation(<Plugin>[
          Plugin.fromYaml(
            'url_launcher',
            '',
            YamlMap.wrap(<String, dynamic>{
              'platforms': <String, dynamic>{
                'android': <String, dynamic>{
                  'dartPluginClass': 'UrlLauncherAndroid',
                },
                'ios': <String, dynamic>{
                  'dartPluginClass': 'UrlLauncherIos',
                },
              },
            }),
171
            null,
172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193
            <String>[],
            fileSystem: fs,
            appDependencies: directDependencies,
          ),
        ]);
        expect(resolutions.length, equals(2));
        expect(resolutions[0].toMap(), equals(
          <String, String>{
            'pluginName': 'url_launcher',
            'dartClass': 'UrlLauncherAndroid',
            'platform': 'android',
          })
        );
        expect(resolutions[1].toMap(), equals(
          <String, String>{
            'pluginName': 'url_launcher',
            'dartClass': 'UrlLauncherIos',
            'platform': 'ios',
          })
        );
      });

194 195 196
      // See https://github.com/flutter/flutter/issues/87862 for details.
      testWithoutContext('does not select inline implementation on desktop for '
      'missing min Flutter SDK constraint', () async {
197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215
        final Set<String> directDependencies = <String>{};

        final List<PluginInterfaceResolution> resolutions = resolvePlatformImplementation(<Plugin>[
          Plugin.fromYaml(
            'url_launcher',
            '',
            YamlMap.wrap(<String, dynamic>{
              'platforms': <String, dynamic>{
                'linux': <String, dynamic>{
                  'dartPluginClass': 'UrlLauncherLinux',
                },
                'macos': <String, dynamic>{
                  'dartPluginClass': 'UrlLauncherMacOS',
                },
                'windows': <String, dynamic>{
                  'dartPluginClass': 'UrlLauncherWindows',
                },
              },
            }),
216
            null,
217 218 219 220 221 222 223 224
            <String>[],
            fileSystem: fs,
            appDependencies: directDependencies,
          ),
        ]);
        expect(resolutions.length, equals(0));
      });

225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305
      // See https://github.com/flutter/flutter/issues/87862 for details.
      testWithoutContext('does not select inline implementation on desktop for '
      'min Flutter SDK constraint < 2.11', () async {
        final Set<String> directDependencies = <String>{};

        final List<PluginInterfaceResolution> resolutions = resolvePlatformImplementation(<Plugin>[
          Plugin.fromYaml(
            'url_launcher',
            '',
            YamlMap.wrap(<String, dynamic>{
              'platforms': <String, dynamic>{
                'linux': <String, dynamic>{
                  'dartPluginClass': 'UrlLauncherLinux',
                },
                'macos': <String, dynamic>{
                  'dartPluginClass': 'UrlLauncherMacOS',
                },
                'windows': <String, dynamic>{
                  'dartPluginClass': 'UrlLauncherWindows',
                },
              },
            }),
            VersionConstraint.parse('>=2.10.0'),
            <String>[],
            fileSystem: fs,
            appDependencies: directDependencies,
          ),
        ]);
        expect(resolutions.length, equals(0));
      });

      testWithoutContext('selects inline implementation on desktop for '
      'min Flutter SDK requirement of at least 2.11', () async {
        final Set<String> directDependencies = <String>{};

        final List<PluginInterfaceResolution> resolutions = resolvePlatformImplementation(<Plugin>[
          Plugin.fromYaml(
            'url_launcher',
            '',
            YamlMap.wrap(<String, dynamic>{
              'platforms': <String, dynamic>{
                'linux': <String, dynamic>{
                  'dartPluginClass': 'UrlLauncherLinux',
                },
                'macos': <String, dynamic>{
                  'dartPluginClass': 'UrlLauncherMacOS',
                },
                'windows': <String, dynamic>{
                  'dartPluginClass': 'UrlLauncherWindows',
                },
              },
            }),
            VersionConstraint.parse('>=2.11.0'),
            <String>[],
            fileSystem: fs,
            appDependencies: directDependencies,
          ),
        ]);
        expect(resolutions.length, equals(3));
        expect(
          resolutions.map((PluginInterfaceResolution resolution) => resolution.toMap()),
          containsAll(<Map<String, String>>[
            <String, String>{
              'pluginName': 'url_launcher',
              'dartClass': 'UrlLauncherLinux',
              'platform': 'linux',
            },
            <String, String>{
              'pluginName': 'url_launcher',
              'dartClass': 'UrlLauncherMacOS',
              'platform': 'macos',
            },
            <String, String>{
              'pluginName': 'url_launcher',
              'dartClass': 'UrlLauncherWindows',
              'platform': 'windows',
            },
          ])
        );
      });

306 307 308 309 310 311 312 313 314 315 316 317 318 319
      testWithoutContext('selects default implementation', () async {
        final Set<String> directDependencies = <String>{};

        final List<PluginInterfaceResolution> resolutions = resolvePlatformImplementation(<Plugin>[
          Plugin.fromYaml(
            'url_launcher',
            '',
            YamlMap.wrap(<String, dynamic>{
              'platforms': <String, dynamic>{
                'linux': <String, dynamic>{
                  'default_package': 'url_launcher_linux',
                },
              },
            }),
320
            null,
321 322 323 324
            <String>[],
            fileSystem: fs,
            appDependencies: directDependencies,
          ),
325 326 327
          // Include three possible implementations, one before and one after
          // to ensure that the selection is working as intended, not just by
          // coincidence of order.
328
          Plugin.fromYaml(
329
            'another_url_launcher_linux',
330 331 332 333 334
            '',
            YamlMap.wrap(<String, dynamic>{
              'implements': 'url_launcher',
              'platforms': <String, dynamic>{
                'linux': <String, dynamic>{
335
                  'dartPluginClass': 'UnofficialUrlLauncherPluginLinux',
336 337 338
                },
              },
            }),
339
            null,
340 341 342 343 344
            <String>[],
            fileSystem: fs,
            appDependencies: directDependencies,
          ),
          Plugin.fromYaml(
345
            'url_launcher_linux',
346 347
            '',
            YamlMap.wrap(<String, dynamic>{
348
              'implements': 'url_launcher',
349 350
              'platforms': <String, dynamic>{
                'linux': <String, dynamic>{
351
                  'dartPluginClass': 'UrlLauncherPluginLinux',
352 353 354
                },
              },
            }),
355
            null,
356 357 358 359 360
            <String>[],
            fileSystem: fs,
            appDependencies: directDependencies,
          ),
          Plugin.fromYaml(
361
            'yet_another_url_launcher_linux',
362 363 364 365 366
            '',
            YamlMap.wrap(<String, dynamic>{
              'implements': 'url_launcher',
              'platforms': <String, dynamic>{
                'linux': <String, dynamic>{
367
                  'dartPluginClass': 'UnofficialUrlLauncherPluginLinux2',
368 369 370
                },
              },
            }),
371
            null,
372 373 374 375 376 377 378 379 380 381 382 383 384 385 386
            <String>[],
            fileSystem: fs,
            appDependencies: directDependencies,
          ),
        ]);
        expect(resolutions.length, equals(1));
        expect(resolutions[0].toMap(), equals(
          <String, String>{
            'pluginName': 'url_launcher_linux',
            'dartClass': 'UrlLauncherPluginLinux',
            'platform': 'linux',
          })
        );
      });

387 388
      testWithoutContext('selects default implementation if interface is direct dependency', () async {
        final Set<String> directDependencies = <String>{'url_launcher'};
389 390 391 392 393 394 395 396 397 398 399 400

        final List<PluginInterfaceResolution> resolutions = resolvePlatformImplementation(<Plugin>[
          Plugin.fromYaml(
            'url_launcher',
            '',
            YamlMap.wrap(<String, dynamic>{
              'platforms': <String, dynamic>{
                'linux': <String, dynamic>{
                  'default_package': 'url_launcher_linux',
                },
              },
            }),
401
            null,
402 403 404 405 406 407 408 409 410 411 412 413 414 415 416
            <String>[],
            fileSystem: fs,
            appDependencies: directDependencies,
          ),
          Plugin.fromYaml(
            'url_launcher_linux',
            '',
            YamlMap.wrap(<String, dynamic>{
              'implements': 'url_launcher',
              'platforms': <String, dynamic>{
                'linux': <String, dynamic>{
                  'dartPluginClass': 'UrlLauncherPluginLinux',
                },
              },
            }),
417
            null,
418 419 420 421 422 423 424 425
            <String>[],
            fileSystem: fs,
            appDependencies: directDependencies,
          ),
        ]);
        expect(resolutions.length, equals(1));
        expect(resolutions[0].toMap(), equals(
          <String, String>{
426
            'pluginName': 'url_launcher_linux',
427 428 429 430 431 432
            'dartClass': 'UrlLauncherPluginLinux',
            'platform': 'linux',
          })
        );
      });

433
      testWithoutContext('selects user selected implementation despite default implementation', () async {
434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449
        final Set<String> directDependencies = <String>{
          'user_selected_url_launcher_implementation',
          'url_launcher',
        };

        final List<PluginInterfaceResolution> resolutions = resolvePlatformImplementation(<Plugin>[
          Plugin.fromYaml(
            'url_launcher',
            '',
            YamlMap.wrap(<String, dynamic>{
              'platforms': <String, dynamic>{
                'linux': <String, dynamic>{
                  'default_package': 'url_launcher_linux',
                },
              },
            }),
450
            null,
451 452 453 454 455 456 457 458 459 460 461 462 463 464 465
            <String>[],
            fileSystem: fs,
            appDependencies: directDependencies,
          ),
          Plugin.fromYaml(
            'url_launcher_linux',
            '',
            YamlMap.wrap(<String, dynamic>{
              'implements': 'url_launcher',
              'platforms': <String, dynamic>{
                'linux': <String, dynamic>{
                  'dartPluginClass': 'UrlLauncherPluginLinux',
                },
              },
            }),
466
            null,
467 468 469 470 471 472 473 474 475 476 477 478 479 480 481
            <String>[],
            fileSystem: fs,
            appDependencies: directDependencies,
          ),
          Plugin.fromYaml(
            'user_selected_url_launcher_implementation',
            '',
            YamlMap.wrap(<String, dynamic>{
              'implements': 'url_launcher',
              'platforms': <String, dynamic>{
                'linux': <String, dynamic>{
                  'dartPluginClass': 'UrlLauncherPluginLinux',
                },
              },
            }),
482
            null,
483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515
            <String>[],
            fileSystem: fs,
            appDependencies: directDependencies,
          ),
        ]);
        expect(resolutions.length, equals(1));
        expect(resolutions[0].toMap(), equals(
          <String, String>{
            'pluginName': 'user_selected_url_launcher_implementation',
            'dartClass': 'UrlLauncherPluginLinux',
            'platform': 'linux',
          })
        );
      });

      testUsingContext('provides error when user selected multiple implementations', () async {
        final Set<String> directDependencies = <String>{
          'url_launcher_linux_1',
          'url_launcher_linux_2',
        };
        expect(() {
          resolvePlatformImplementation(<Plugin>[
            Plugin.fromYaml(
              'url_launcher_linux_1',
              '',
              YamlMap.wrap(<String, dynamic>{
                'implements': 'url_launcher',
                'platforms': <String, dynamic>{
                  'linux': <String, dynamic>{
                    'dartPluginClass': 'UrlLauncherPluginLinux',
                  },
                },
              }),
516
              null,
517 518 519 520 521 522 523 524 525 526 527 528 529 530 531
              <String>[],
              fileSystem: fs,
              appDependencies: directDependencies,
            ),
            Plugin.fromYaml(
              'url_launcher_linux_2',
              '',
              YamlMap.wrap(<String, dynamic>{
                'implements': 'url_launcher',
                'platforms': <String, dynamic>{
                  'linux': <String, dynamic>{
                    'dartPluginClass': 'UrlLauncherPluginLinux',
                  },
                },
              }),
532
              null,
533 534 535 536 537 538 539 540 541 542
              <String>[],
              fileSystem: fs,
              appDependencies: directDependencies,
            ),
          ]);

        },
        throwsToolExit(
          message: 'Please resolve the errors',
        ));
543 544 545 546 547 548 549 550 551

        expect(
          testLogger.errorText,
          'Plugin url_launcher:linux has conflicting direct dependency implementations:\n'
          '  url_launcher_linux_1\n'
          '  url_launcher_linux_2\n'
          'To fix this issue, remove all but one of these dependencies from pubspec.yaml.'
          '\n\n'
        );
552 553 554 555 556 557
      });

      testUsingContext('provides all errors when user selected multiple implementations', () async {
        final Set<String> directDependencies = <String>{
          'url_launcher_linux_1',
          'url_launcher_linux_2',
558 559
          'url_launcher_windows_1',
          'url_launcher_windows_2',
560 561 562 563 564 565 566 567 568 569 570 571 572 573
        };
        expect(() {
          resolvePlatformImplementation(<Plugin>[
            Plugin.fromYaml(
              'url_launcher_linux_1',
              '',
              YamlMap.wrap(<String, dynamic>{
                'implements': 'url_launcher',
                'platforms': <String, dynamic>{
                  'linux': <String, dynamic>{
                    'dartPluginClass': 'UrlLauncherPluginLinux',
                  },
                },
              }),
574
              null,
575 576 577 578 579 580 581 582 583 584 585 586 587 588 589
              <String>[],
              fileSystem: fs,
              appDependencies: directDependencies,
            ),
            Plugin.fromYaml(
              'url_launcher_linux_2',
              '',
              YamlMap.wrap(<String, dynamic>{
                'implements': 'url_launcher',
                'platforms': <String, dynamic>{
                  'linux': <String, dynamic>{
                    'dartPluginClass': 'UrlLauncherPluginLinux',
                  },
                },
              }),
590
              null,
591 592 593 594
              <String>[],
              fileSystem: fs,
              appDependencies: directDependencies,
            ),
595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626
            Plugin.fromYaml(
              'url_launcher_windows_1',
              '',
              YamlMap.wrap(<String, dynamic>{
                'implements': 'url_launcher',
                'platforms': <String, dynamic>{
                  'windows': <String, dynamic>{
                    'dartPluginClass': 'UrlLauncherPluginWindows1',
                  },
                },
              }),
              null,
              <String>[],
              fileSystem: fs,
              appDependencies: directDependencies,
            ),
            Plugin.fromYaml(
              'url_launcher_windows_2',
              '',
              YamlMap.wrap(<String, dynamic>{
                'implements': 'url_launcher',
                'platforms': <String, dynamic>{
                  'windows': <String, dynamic>{
                    'dartPluginClass': 'UrlLauncherPluginWindows2',
                  },
                },
              }),
              null,
              <String>[],
              fileSystem: fs,
              appDependencies: directDependencies,
            ),
627
          ]);
628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646
        },
        throwsToolExit(
          message: 'Please resolve the errors',
        ));

        expect(
          testLogger.errorText,
          'Plugin url_launcher:linux has conflicting direct dependency implementations:\n'
          '  url_launcher_linux_1\n'
          '  url_launcher_linux_2\n'
          'To fix this issue, remove all but one of these dependencies from pubspec.yaml.'
          '\n\n'
          'Plugin url_launcher:windows has conflicting direct dependency implementations:\n'
          '  url_launcher_windows_1\n'
          '  url_launcher_windows_2\n'
          'To fix this issue, remove all but one of these dependencies from pubspec.yaml.'
          '\n\n'
        );
      });
647

648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684
      testUsingContext('provides error when user needs to select among multiple implementations', () async {
        final Set<String> directDependencies = <String>{};
        expect(() {
          resolvePlatformImplementation(<Plugin>[
            Plugin.fromYaml(
              'url_launcher_linux_1',
              '',
              YamlMap.wrap(<String, dynamic>{
                'implements': 'url_launcher',
                'platforms': <String, dynamic>{
                  'linux': <String, dynamic>{
                    'dartPluginClass': 'UrlLauncherPluginLinux1',
                  },
                },
              }),
              null,
              <String>[],
              fileSystem: fs,
              appDependencies: directDependencies,
            ),
            Plugin.fromYaml(
              'url_launcher_linux_2',
              '',
              YamlMap.wrap(<String, dynamic>{
                'implements': 'url_launcher',
                'platforms': <String, dynamic>{
                  'linux': <String, dynamic>{
                    'dartPluginClass': 'UrlLauncherPluginLinux2',
                  },
                },
              }),
              null,
              <String>[],
              fileSystem: fs,
              appDependencies: directDependencies,
            ),
          ]);
685 686 687 688
        },
        throwsToolExit(
          message: 'Please resolve the errors',
        ));
689 690 691 692 693 694 695 696 697

        expect(
          testLogger.errorText,
          'Plugin url_launcher:linux has multiple possible implementations:\n'
          '  url_launcher_linux_1\n'
          '  url_launcher_linux_2\n'
          'To fix this issue, add one of these dependencies to pubspec.yaml.'
          '\n\n'
        );
698 699 700 701 702
      });
    });

    group('generateMainDartWithPluginRegistrant', () {
      testUsingContext('Generates new entrypoint', () async {
703
        flutterProject.isModule = true;
704 705 706 707 708 709

        createFakeDartPlugins(
          flutterProject,
          flutterManifest,
          fs,
          <String, String>{
710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725
            'url_launcher_android': '''
  flutter:
    plugin:
      implements: url_launcher
      platforms:
        android:
          dartPluginClass: AndroidPlugin
''',
          'url_launcher_ios': '''
  flutter:
    plugin:
      implements: url_launcher
      platforms:
        ios:
          dartPluginClass: IosPlugin
''',
726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756
          'url_launcher_macos': '''
  flutter:
    plugin:
      implements: url_launcher
      platforms:
        macos:
          dartPluginClass: MacOSPlugin
''',
         'url_launcher_linux': '''
  flutter:
    plugin:
      implements: url_launcher
      platforms:
        linux:
          dartPluginClass: LinuxPlugin
''',
         'url_launcher_windows': '''
  flutter:
    plugin:
      implements: url_launcher
      platforms:
        windows:
          dartPluginClass: WindowsPlugin
''',
         'awesome_macos': '''
  flutter:
    plugin:
      implements: awesome
      platforms:
        macos:
          dartPluginClass: AwesomeMacOS
757
''',
758
          });
759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780

        final Directory libDir = flutterProject.directory.childDirectory('lib');
        libDir.createSync(recursive: true);

        final File mainFile = libDir.childFile('main.dart');
        mainFile.writeAsStringSync('''
// @dart = 2.8
void main() {
}
''');
        final PackageConfig packageConfig = await loadPackageConfigWithLogging(
          flutterProject.directory.childDirectory('.dart_tool').childFile('package_config.json'),
          logger: globals.logger,
          throwOnError: false,
        );
        await generateMainDartWithPluginRegistrant(
          flutterProject,
          packageConfig,
          'package:app/main.dart',
          mainFile,
          throwOnPluginPubspecError: true,
        );
781
        expect(flutterProject.dartPluginRegistrant.readAsStringSync(),
782 783 784 785 786 787 788
          '//\n'
          '// Generated file. Do not edit.\n'
          '// This file is generated from template in file `flutter_tools/lib/src/flutter_plugins.dart`.\n'
          '//\n'
          '\n'
          '// @dart = 2.8\n'
          '\n'
789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869
          "import 'dart:io'; // flutter_ignore: dart_io_import.\n"
          "import 'package:url_launcher_android/url_launcher_android.dart';\n"
          "import 'package:url_launcher_ios/url_launcher_ios.dart';\n"
          "import 'package:url_launcher_linux/url_launcher_linux.dart';\n"
          "import 'package:awesome_macos/awesome_macos.dart';\n"
          "import 'package:url_launcher_macos/url_launcher_macos.dart';\n"
          "import 'package:url_launcher_windows/url_launcher_windows.dart';\n"
          '\n'
          "@pragma('vm:entry-point')\n"
          'class _PluginRegistrant {\n'
          '\n'
          "  @pragma('vm:entry-point')\n"
          '  static void register() {\n'
          '    if (Platform.isAndroid) {\n'
          '      try {\n'
          '        AndroidPlugin.registerWith();\n'
          '      } catch (err) {\n'
          '        print(\n'
          "          '`url_launcher_android` threw an error: \$err. '\n"
          "          'The app may not function as expected until you remove this plugin from pubspec.yaml'\n"
          '        );\n'
          '      }\n'
          '\n'
          '    } else if (Platform.isIOS) {\n'
          '      try {\n'
          '        IosPlugin.registerWith();\n'
          '      } catch (err) {\n'
          '        print(\n'
          "          '`url_launcher_ios` threw an error: \$err. '\n"
          "          'The app may not function as expected until you remove this plugin from pubspec.yaml'\n"
          '        );\n'
          '      }\n'
          '\n'
          '    } else if (Platform.isLinux) {\n'
          '      try {\n'
          '        LinuxPlugin.registerWith();\n'
          '      } catch (err) {\n'
          '        print(\n'
          "          '`url_launcher_linux` threw an error: \$err. '\n"
          "          'The app may not function as expected until you remove this plugin from pubspec.yaml'\n"
          '        );\n'
          '      }\n'
          '\n'
          '    } else if (Platform.isMacOS) {\n'
          '      try {\n'
          '        AwesomeMacOS.registerWith();\n'
          '      } catch (err) {\n'
          '        print(\n'
          "          '`awesome_macos` threw an error: \$err. '\n"
          "          'The app may not function as expected until you remove this plugin from pubspec.yaml'\n"
          '        );\n'
          '      }\n'
          '\n'
          '      try {\n'
          '        MacOSPlugin.registerWith();\n'
          '      } catch (err) {\n'
          '        print(\n'
          "          '`url_launcher_macos` threw an error: \$err. '\n"
          "          'The app may not function as expected until you remove this plugin from pubspec.yaml'\n"
          '        );\n'
          '      }\n'
          '\n'
          '    } else if (Platform.isWindows) {\n'
          '      try {\n'
          '        WindowsPlugin.registerWith();\n'
          '      } catch (err) {\n'
          '        print(\n'
          "          '`url_launcher_windows` threw an error: \$err. '\n"
          "          'The app may not function as expected until you remove this plugin from pubspec.yaml'\n"
          '        );\n'
          '      }\n'
          '\n'
          '    }\n'
          '  }\n'
          '}\n'
        );
      }, overrides: <Type, Generator>{
        FileSystem: () => fs,
        ProcessManager: () => FakeProcessManager.any(),
      });

870
      testUsingContext('Plugin without platform support throws tool exit', () async {
871
        flutterProject.isModule = false;
872 873 874 875 876 877

        createFakeDartPlugins(
          flutterProject,
          flutterManifest,
          fs,
          <String, String>{
878
            'url_launcher_macos': '''
879 880 881 882 883 884
  flutter:
    plugin:
      implements: url_launcher
      platforms:
        macos:
          invalid:
885
''',
886
          });
887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914

        final Directory libDir = flutterProject.directory.childDirectory('lib');
        libDir.createSync(recursive: true);

        final File mainFile = libDir.childFile('main.dart')..writeAsStringSync('');
        final PackageConfig packageConfig = await loadPackageConfigWithLogging(
          flutterProject.directory.childDirectory('.dart_tool').childFile('package_config.json'),
          logger: globals.logger,
          throwOnError: false,
        );
        await expectLater(
          generateMainDartWithPluginRegistrant(
            flutterProject,
            packageConfig,
            'package:app/main.dart',
            mainFile,
            throwOnPluginPubspecError: true,
          ), throwsToolExit(message:
            'Invalid plugin specification url_launcher_macos.\n'
            'Invalid "macos" plugin specification.'
          ),
        );
      }, overrides: <Type, Generator>{
        FileSystem: () => fs,
        ProcessManager: () => FakeProcessManager.any(),
      });

      testUsingContext('Plugin with platform support without dart plugin class throws tool exit', () async {
915
        flutterProject.isModule = false;
916 917 918 919 920 921

        createFakeDartPlugins(
          flutterProject,
          flutterManifest,
          fs,
          <String, String>{
922
            'url_launcher_macos': '''
923 924 925
  flutter:
    plugin:
      implements: url_launcher
926
''',
927
          });
928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971

        final Directory libDir = flutterProject.directory.childDirectory('lib');
        libDir.createSync(recursive: true);

        final File mainFile = libDir.childFile('main.dart')..writeAsStringSync('');
        final PackageConfig packageConfig = await loadPackageConfigWithLogging(
          flutterProject.directory.childDirectory('.dart_tool').childFile('package_config.json'),
          logger: globals.logger,
          throwOnError: false,
        );
        await expectLater(
          generateMainDartWithPluginRegistrant(
            flutterProject,
            packageConfig,
            'package:app/main.dart',
            mainFile,
            throwOnPluginPubspecError: true,
          ), throwsToolExit(message:
            'Invalid plugin specification url_launcher_macos.\n'
            'Cannot find the `flutter.plugin.platforms` key in the `pubspec.yaml` file. '
            'An instruction to format the `pubspec.yaml` can be found here: '
            'https://flutter.dev/docs/development/packages-and-plugins/developing-packages#plugin-platforms'
          ),
        );
      }, overrides: <Type, Generator>{
        FileSystem: () => fs,
        ProcessManager: () => FakeProcessManager.any(),
      });

      testUsingContext('Does not show error messages if throwOnPluginPubspecError is false', () async {
        final Set<String> directDependencies = <String>{
          'url_launcher_windows',
        };
        resolvePlatformImplementation(<Plugin>[
          Plugin.fromYaml(
            'url_launcher_windows',
            '',
            YamlMap.wrap(<String, dynamic>{
              'platforms': <String, dynamic>{
                'windows': <String, dynamic>{
                  'dartPluginClass': 'UrlLauncherPluginWindows',
                },
              },
            }),
972
            null,
973 974 975 976 977 978 979 980 981 982 983 984 985 986
            <String>[],
            fileSystem: fs,
            appDependencies: directDependencies,
          ),
        ],
          throwOnPluginPubspecError: false,
        );
        expect(testLogger.errorText, '');
      }, overrides: <Type, Generator>{
        FileSystem: () => fs,
        ProcessManager: () => FakeProcessManager.any(),
      });

      testUsingContext('Does not create new entrypoint if there are no platform resolutions', () async {
987
        flutterProject.isModule = false;
988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004

        final Directory libDir = flutterProject.directory.childDirectory('lib');
        libDir.createSync(recursive: true);

        final File mainFile = libDir.childFile('main.dart')..writeAsStringSync('');
        final PackageConfig packageConfig = await loadPackageConfigWithLogging(
          flutterProject.directory.childDirectory('.dart_tool').childFile('package_config.json'),
          logger: globals.logger,
          throwOnError: false,
        );
        await generateMainDartWithPluginRegistrant(
          flutterProject,
          packageConfig,
          'package:app/main.dart',
          mainFile,
          throwOnPluginPubspecError: true,
        );
1005
        expect(flutterProject.dartPluginRegistrant.existsSync(), isFalse);
1006 1007 1008 1009 1010 1011
      }, overrides: <Type, Generator>{
        FileSystem: () => fs,
        ProcessManager: () => FakeProcessManager.any(),
      });

      testUsingContext('Deletes new entrypoint if there are no platform resolutions', () async {
1012
        flutterProject.isModule = false;
1013 1014 1015 1016 1017 1018

        createFakeDartPlugins(
          flutterProject,
          flutterManifest,
          fs,
          <String, String>{
1019
            'url_launcher_macos': '''
1020 1021 1022 1023 1024 1025
  flutter:
    plugin:
      implements: url_launcher
      platforms:
        macos:
          dartPluginClass: MacOSPlugin
1026
''',
1027
          });
1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044

        final Directory libDir = flutterProject.directory.childDirectory('lib');
        libDir.createSync(recursive: true);

        final File mainFile = libDir.childFile('main.dart')..writeAsStringSync('');
        final PackageConfig packageConfig = await loadPackageConfigWithLogging(
          flutterProject.directory.childDirectory('.dart_tool').childFile('package_config.json'),
          logger: globals.logger,
          throwOnError: false,
        );
        await generateMainDartWithPluginRegistrant(
          flutterProject,
          packageConfig,
          'package:app/main.dart',
          mainFile,
          throwOnPluginPubspecError: true,
        );
1045
        expect(flutterProject.dartPluginRegistrant.existsSync(), isTrue);
1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060

        // No plugins.
        createFakeDartPlugins(
          flutterProject,
          flutterManifest,
          fs,
          <String, String>{});

        await generateMainDartWithPluginRegistrant(
          flutterProject,
          packageConfig,
          'package:app/main.dart',
          mainFile,
          throwOnPluginPubspecError: true,
        );
1061
        expect(flutterProject.dartPluginRegistrant.existsSync(), isFalse);
1062 1063 1064 1065 1066 1067 1068 1069
      }, overrides: <Type, Generator>{
        FileSystem: () => fs,
        ProcessManager: () => FakeProcessManager.any(),
      });
    });
  });
}

1070 1071 1072 1073 1074 1075 1076 1077
void createFakeDartPlugins(
  FakeFlutterProject flutterProject,
  FakeFlutterManifest flutterManifest,
  FileSystem fs,
  Map<String, String> plugins,
) {
  final Directory fakePubCache = fs.systemTempDirectory.childDirectory('cache');
  final File packagesFile = flutterProject.directory
1078 1079 1080 1081 1082
    .childFile('.packages');
  if (packagesFile.existsSync()) {
    packagesFile.deleteSync();
  }
  packagesFile.createSync(recursive: true);
1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107

  for (final MapEntry<String, String> entry in plugins.entries) {
    final String name = fs.path.basename(entry.key);
    final Directory pluginDirectory = fakePubCache.childDirectory(name);
    packagesFile.writeAsStringSync(
      '$name:file://${pluginDirectory.childFile('lib').uri}\n',
      mode: FileMode.writeOnlyAppend,
    );
    pluginDirectory.childFile('pubspec.yaml')
      ..createSync(recursive: true)
      ..writeAsStringSync(entry.value);
  }
  flutterManifest.dependencies = plugins.keys.toSet();
}

class FakeFlutterManifest extends Fake implements FlutterManifest {
  @override
  Set<String> dependencies = <String>{};
}

class FakeFlutterProject extends Fake implements FlutterProject {
  @override
  bool isModule = false;

  @override
1108
  late FlutterManifest manifest;
1109 1110

  @override
1111
  late Directory directory;
1112 1113

  @override
1114
  late File flutterPluginsFile;
1115 1116

  @override
1117
  late File flutterPluginsDependenciesFile;
1118

1119
  @override
1120
  late File dartPluginRegistrant;
1121

1122
  @override
1123
  late IosProject ios;
1124 1125

  @override
1126
  late AndroidProject android;
1127 1128

  @override
1129
  late WebProject web;
1130 1131

  @override
1132
  late MacOSProject macos;
1133 1134

  @override
1135
  late LinuxProject linux;
1136 1137

  @override
1138
  late WindowsProject windows;
1139
}