create_test.dart 33.8 KB
Newer Older
1 2 3 4
// Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

5
import 'dart:async';
6
import 'dart:convert';
7

8
import 'package:args/command_runner.dart';
9
import 'package:flutter_tools/src/base/file_system.dart';
10
import 'package:flutter_tools/src/base/io.dart';
11
import 'package:flutter_tools/src/cache.dart';
12
import 'package:flutter_tools/src/commands/create.dart';
13
import 'package:flutter_tools/src/dart/sdk.dart';
14
import 'package:flutter_tools/src/project.dart';
15 16
import 'package:flutter_tools/src/version.dart';
import 'package:mockito/mockito.dart';
17
import 'package:process/process.dart';
18

19 20
import '../src/common.dart';
import '../src/context.dart';
21

22 23 24
const String frameworkRevision = '12345678';
const String frameworkChannel = 'omega';

25
void main() {
26 27 28 29
  Directory tempDir;
  Directory projectDir;
  FlutterVersion mockFlutterVersion;
  LoggingProcessManager loggingProcessManager;
30

31 32 33 34 35 36 37 38 39 40
  setUpAll(() {
    Cache.disableLocking();
  });

  setUp(() {
    loggingProcessManager = LoggingProcessManager();
    tempDir = fs.systemTempDirectory.createTempSync('flutter_tools_create_test.');
    projectDir = tempDir.childDirectory('flutter_project');
    mockFlutterVersion = MockFlutterVersion();
  });
41

42 43 44 45
  tearDown(() {
    tryToDelete(tempDir);
  });

46
  // Verify that we create a default project ('app') that is
47 48
  // well-formed.
  testUsingContext('can create a default project', () async {
49 50 51 52 53 54 55 56 57 58 59 60
    await _createAndAnalyzeProject(
      projectDir,
      <String>[],
      <String>[
        'android/app/src/main/java/com/example/flutterproject/MainActivity.java',
        'android/app/src/main/java/io/flutter/plugins/GeneratedPluginRegistrant.java',
        'flutter_project.iml',
        'ios/Flutter/AppFrameworkInfo.plist',
        'ios/Runner/AppDelegate.m',
        'ios/Runner/GeneratedPluginRegistrant.h',
      ],
    );
61 62 63
    return _runFlutterTest(projectDir);
  }, timeout: allowForRemotePubInvocation);

64 65 66 67
  testUsingContext('can create a default project if empty directory exists', () async {
    await projectDir.create(recursive: true);
    await _createAndAnalyzeProject(
      projectDir,
68
      <String>[],
69 70 71 72 73 74 75 76 77 78 79
      <String>[
        'android/app/src/main/java/com/example/flutterproject/MainActivity.java',
        'android/app/src/main/java/io/flutter/plugins/GeneratedPluginRegistrant.java',
        'flutter_project.iml',
        'ios/Flutter/AppFrameworkInfo.plist',
        'ios/Runner/AppDelegate.m',
        'ios/Runner/GeneratedPluginRegistrant.h',
      ],
    );
  }, timeout: allowForRemotePubInvocation);

80 81 82 83
  testUsingContext('creates a module project correctly', () async {
    await _createAndAnalyzeProject(projectDir, <String>[
      '--template=module'
    ], <String>[
84 85 86 87 88 89 90 91 92 93 94 95
      '.android/app/',
      '.gitignore',
      '.ios/Flutter',
      '.metadata',
      'lib/main.dart',
      'pubspec.yaml',
      'README.md',
      'test/widget_test.dart',
    ], unexpectedPaths: <String>[
      'android/',
      'ios/',
    ]);
96 97 98 99 100 101 102 103 104 105 106 107 108 109
    return _runFlutterTest(projectDir);
  }, timeout: allowForRemotePubInvocation);

  testUsingContext('cannot create a project if non-empty non-project directory exists with .metadata', () async {
    await projectDir.absolute.childDirectory('blag').create(recursive: true);
    await projectDir.absolute.childFile('.metadata').writeAsString('project_type: blag\n');
    expect(
        () async => await _createAndAnalyzeProject(projectDir, <String>[], <String>[], unexpectedPaths: <String>[
              'android/',
              'ios/',
              '.android/',
              '.ios/',
            ]),
        throwsToolExit(message: 'Sorry, unable to detect the type of project to recreate'));
110 111
  }, timeout: allowForRemotePubInvocation);

112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128
  testUsingContext('Will create an app project if non-empty non-project directory exists without .metadata', () async {
    await projectDir.absolute.childDirectory('blag').create(recursive: true);
    await projectDir.absolute.childDirectory('.idea').create(recursive: true);
    await _createAndAnalyzeProject(projectDir, <String>[], <String>[
      'android/app/src/main/java/com/example/flutterproject/MainActivity.java',
      'android/app/src/main/java/io/flutter/plugins/GeneratedPluginRegistrant.java',
      'flutter_project.iml',
      'ios/Flutter/AppFrameworkInfo.plist',
      'ios/Runner/AppDelegate.m',
      'ios/Runner/GeneratedPluginRegistrant.h',
    ], unexpectedPaths: <String>[
      '.android/',
      '.ios/',
    ]);
  }, timeout: allowForRemotePubInvocation);

  testUsingContext('detects and recreates an app project correctly', () async {
129
    await projectDir.absolute.childDirectory('lib').create(recursive: true);
130 131 132 133 134 135 136 137
    await projectDir.absolute.childDirectory('ios').create(recursive: true);
    await _createAndAnalyzeProject(projectDir, <String>[], <String>[
      'android/app/src/main/java/com/example/flutterproject/MainActivity.java',
      'android/app/src/main/java/io/flutter/plugins/GeneratedPluginRegistrant.java',
      'flutter_project.iml',
      'ios/Flutter/AppFrameworkInfo.plist',
      'ios/Runner/AppDelegate.m',
      'ios/Runner/GeneratedPluginRegistrant.h',
138
    ], unexpectedPaths: <String>[
139 140
      '.android/',
      '.ios/',
141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193
    ]);
  }, timeout: allowForRemotePubInvocation);

  testUsingContext('detects and recreates a plugin project correctly', () async {
    await projectDir.create(recursive: true);
    await projectDir.absolute.childFile('.metadata').writeAsString('project_type: plugin\n');
    return _createAndAnalyzeProject(
      projectDir,
      <String>[],
      <String>[
        'android/src/main/java/com/example/flutterproject/FlutterProjectPlugin.java',
        'example/android/app/src/main/java/com/example/flutterprojectexample/MainActivity.java',
        'example/ios/Runner/AppDelegate.h',
        'example/ios/Runner/AppDelegate.m',
        'example/ios/Runner/main.m',
        'example/lib/main.dart',
        'flutter_project.iml',
        'ios/Classes/FlutterProjectPlugin.h',
        'ios/Classes/FlutterProjectPlugin.m',
        'lib/flutter_project.dart',
      ],
    );
  }, timeout: allowForRemotePubInvocation);

  testUsingContext('detects and recreates a package project correctly', () async {
    await projectDir.create(recursive: true);
    await projectDir.absolute.childFile('.metadata').writeAsString('project_type: package\n');
    return _createAndAnalyzeProject(
      projectDir,
      <String>[],
      <String>[
        'lib/flutter_project.dart',
        'test/flutter_project_test.dart',
      ],
      unexpectedPaths: <String>[
        'android/app/src/main/java/com/example/flutterproject/MainActivity.java',
        'android/src/main/java/com/example/flutterproject/FlutterProjectPlugin.java',
        'example/android/app/src/main/java/com/example/flutterprojectexample/MainActivity.java',
        'example/ios/Runner/AppDelegate.h',
        'example/ios/Runner/AppDelegate.m',
        'example/ios/Runner/main.m',
        'example/lib/main.dart',
        'ios/Classes/FlutterProjectPlugin.h',
        'ios/Classes/FlutterProjectPlugin.m',
        'ios/Runner/AppDelegate.h',
        'ios/Runner/AppDelegate.m',
        'ios/Runner/main.m',
        'lib/main.dart',
        'test/widget_test.dart',
      ],
    );
  }, timeout: allowForRemotePubInvocation);

194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212
  testUsingContext('kotlin/swift legacy app project', () async {
    return _createProject(
      projectDir,
      <String>['--no-pub', '--template=app', '--android-language=kotlin', '--ios-language=swift'],
      <String>[
        'android/app/src/main/kotlin/com/example/flutterproject/MainActivity.kt',
        'ios/Runner/AppDelegate.swift',
        'ios/Runner/Runner-Bridging-Header.h',
        'lib/main.dart',
      ],
      unexpectedPaths: <String>[
        'android/app/src/main/java/com/example/flutterproject/MainActivity.java',
        'ios/Runner/AppDelegate.h',
        'ios/Runner/AppDelegate.m',
        'ios/Runner/main.m',
      ],
    );
  }, timeout: allowForCreateFlutterProject);

213
  testUsingContext('can create a package project', () async {
214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240
    await _createAndAnalyzeProject(
      projectDir,
      <String>['--template=package'],
      <String>[
        'lib/flutter_project.dart',
        'test/flutter_project_test.dart',
      ],
      unexpectedPaths: <String>[
        'android/app/src/main/java/com/example/flutterproject/MainActivity.java',
        'android/src/main/java/com/example/flutterproject/FlutterProjectPlugin.java',
        'example/android/app/src/main/java/com/example/flutterprojectexample/MainActivity.java',
        'example/ios/Runner/AppDelegate.h',
        'example/ios/Runner/AppDelegate.m',
        'example/ios/Runner/main.m',
        'example/lib/main.dart',
        'ios/Classes/FlutterProjectPlugin.h',
        'ios/Classes/FlutterProjectPlugin.m',
        'ios/Runner/AppDelegate.h',
        'ios/Runner/AppDelegate.m',
        'ios/Runner/main.m',
        'lib/main.dart',
        'test/widget_test.dart',
      ],
    );
    return _runFlutterTest(projectDir);
  }, timeout: allowForRemotePubInvocation);

241
  testUsingContext('can create a plugin project', () async {
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
    await _createAndAnalyzeProject(
      projectDir,
      <String>['--template=plugin'],
      <String>[
        'android/src/main/java/com/example/flutterproject/FlutterProjectPlugin.java',
        'example/android/app/src/main/java/com/example/flutterprojectexample/MainActivity.java',
        'example/ios/Runner/AppDelegate.h',
        'example/ios/Runner/AppDelegate.m',
        'example/ios/Runner/main.m',
        'example/lib/main.dart',
        'flutter_project.iml',
        'ios/Classes/FlutterProjectPlugin.h',
        'ios/Classes/FlutterProjectPlugin.m',
        'lib/flutter_project.dart',
      ],
    );
    return _runFlutterTest(projectDir.childDirectory('example'));
  }, timeout: allowForRemotePubInvocation);

  testUsingContext('kotlin/swift plugin project', () async {
    return _createProject(
      projectDir,
      <String>['--no-pub', '--template=plugin', '-a', 'kotlin', '--ios-language', 'swift'],
      <String>[
        'android/src/main/kotlin/com/example/flutterproject/FlutterProjectPlugin.kt',
        'example/android/app/src/main/kotlin/com/example/flutterprojectexample/MainActivity.kt',
        'example/ios/Runner/AppDelegate.swift',
        'example/ios/Runner/Runner-Bridging-Header.h',
        'example/lib/main.dart',
        'ios/Classes/FlutterProjectPlugin.h',
        'ios/Classes/FlutterProjectPlugin.m',
        'ios/Classes/SwiftFlutterProjectPlugin.swift',
        'lib/flutter_project.dart',
      ],
      unexpectedPaths: <String>[
        'android/src/main/java/com/example/flutterproject/FlutterProjectPlugin.java',
        'example/android/app/src/main/java/com/example/flutterprojectexample/MainActivity.java',
        'example/ios/Runner/AppDelegate.h',
        'example/ios/Runner/AppDelegate.m',
        'example/ios/Runner/main.m',
      ],
    );
  }, timeout: allowForCreateFlutterProject);

  testUsingContext('plugin project with custom org', () async {
    return _createProject(
      projectDir,
      <String>['--no-pub', '--template=plugin', '--org', 'com.bar.foo'],
      <String>[
        'android/src/main/java/com/bar/foo/flutterproject/FlutterProjectPlugin.java',
        'example/android/app/src/main/java/com/bar/foo/flutterprojectexample/MainActivity.java',
      ],
      unexpectedPaths: <String>[
        'android/src/main/java/com/example/flutterproject/FlutterProjectPlugin.java',
        'example/android/app/src/main/java/com/example/flutterprojectexample/MainActivity.java',
      ],
    );
  }, timeout: allowForCreateFlutterProject);
300

301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325
  testUsingContext('plugin project with valid custom project name', () async {
    return _createProject(
      projectDir,
      <String>['--no-pub', '--template=plugin', '--project-name', 'xyz'],
      <String>[
        'android/src/main/java/com/example/xyz/XyzPlugin.java',
        'example/android/app/src/main/java/com/example/xyzexample/MainActivity.java',
      ],
      unexpectedPaths: <String>[
        'android/src/main/java/com/example/flutterproject/FlutterProjectPlugin.java',
        'example/android/app/src/main/java/com/example/flutterprojectexample/MainActivity.java',
      ],
    );
  }, timeout: allowForCreateFlutterProject);

  testUsingContext('plugin project with invalid custom project name', () async {
    expect(
      () => _createProject(projectDir,
        <String>['--no-pub', '--template=plugin', '--project-name', 'xyz.xyz'],
        <String>[],
      ),
      throwsToolExit(message: '"xyz.xyz" is not a valid Dart package name.'),
    );
  }, timeout: allowForCreateFlutterProject);

326 327 328 329 330 331 332 333
  testUsingContext('legacy app project with-driver-test', () async {
    return _createAndAnalyzeProject(
      projectDir,
      <String>['--with-driver-test', '--template=app'],
      <String>['lib/main.dart'],
    );
  }, timeout: allowForRemotePubInvocation);

334
  testUsingContext('module project with pub', () async {
335
    return _createProject(projectDir, <String>[
336
      '--template=module'
337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365
    ], <String>[
      '.android/build.gradle',
      '.android/Flutter/build.gradle',
      '.android/Flutter/src/main/AndroidManifest.xml',
      '.android/Flutter/src/main/java/io/flutter/facade/Flutter.java',
      '.android/Flutter/src/main/java/io/flutter/facade/FlutterFragment.java',
      '.android/Flutter/src/main/java/io/flutter/plugins/GeneratedPluginRegistrant.java',
      '.android/gradle.properties',
      '.android/gradle/wrapper/gradle-wrapper.jar',
      '.android/gradle/wrapper/gradle-wrapper.properties',
      '.android/gradlew',
      '.android/gradlew.bat',
      '.android/include_flutter.groovy',
      '.android/local.properties',
      '.android/settings.gradle',
      '.gitignore',
      '.metadata',
      '.packages',
      'lib/main.dart',
      'pubspec.lock',
      'pubspec.yaml',
      'README.md',
      'test/widget_test.dart',
    ], unexpectedPaths: <String>[
      'android/',
      'ios/',
    ]);
  }, timeout: allowForRemotePubInvocation);

366
  testUsingContext('has correct content and formatting with module template', () async {
367 368 369 370 371
    Cache.flutterRoot = '../..';
    when(mockFlutterVersion.frameworkRevision).thenReturn(frameworkRevision);
    when(mockFlutterVersion.channel).thenReturn(frameworkChannel);

    final CreateCommand command = CreateCommand();
372
    final CommandRunner<void> runner = createTestCommandRunner(command);
373

374
    await runner.run(<String>['create', '--template=module', '--no-pub', '--org', 'com.foo.bar', projectDir.path]);
375 376 377 378 379 380 381 382

    void expectExists(String relPath) {
      expect(fs.isFileSync('${projectDir.path}/$relPath'), true);
    }

    expectExists('lib/main.dart');
    expectExists('test/widget_test.dart');

jslavitz's avatar
jslavitz committed
383 384 385 386
    final String actualContents = await fs.file(projectDir.path + '/test/widget_test.dart').readAsString();

    expect(actualContents.contains('flutter_test.dart'), true);

387 388 389 390 391 392 393 394 395 396 397 398
    for (FileSystemEntity file in projectDir.listSync(recursive: true)) {
      if (file is File && file.path.endsWith('.dart')) {
        final String original = file.readAsStringSync();

        final Process process = await Process.start(
          sdkBinaryName('dartfmt'),
          <String>[file.path],
          workingDirectory: projectDir.path,
        );
        final String formatted = await process.stdout.transform(utf8.decoder).join();

        expect(original, formatted, reason: file.path);
399
      }
400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440
    }

    await _runFlutterTest(projectDir, target: fs.path.join(projectDir.path, 'test', 'widget_test.dart'));

    // Generated Xcode settings
    final String xcodeConfigPath = fs.path.join('.ios', 'Flutter', 'Generated.xcconfig');
    expectExists(xcodeConfigPath);
    final File xcodeConfigFile = fs.file(fs.path.join(projectDir.path, xcodeConfigPath));
    final String xcodeConfig = xcodeConfigFile.readAsStringSync();
    expect(xcodeConfig, contains('FLUTTER_ROOT='));
    expect(xcodeConfig, contains('FLUTTER_APPLICATION_PATH='));
    expect(xcodeConfig, contains('FLUTTER_TARGET='));
    // App identification
    final String xcodeProjectPath = fs.path.join('.ios', 'Runner.xcodeproj', 'project.pbxproj');
    expectExists(xcodeProjectPath);
    final File xcodeProjectFile = fs.file(fs.path.join(projectDir.path, xcodeProjectPath));
    final String xcodeProject = xcodeProjectFile.readAsStringSync();
    expect(xcodeProject, contains('PRODUCT_BUNDLE_IDENTIFIER = com.foo.bar.flutterProject'));

    final String versionPath = fs.path.join('.metadata');
    expectExists(versionPath);
    final String version = fs.file(fs.path.join(projectDir.path, versionPath)).readAsStringSync();
    expect(version, contains('version:'));
    expect(version, contains('revision: 12345678'));
    expect(version, contains('channel: omega'));

    // IntelliJ metadata
    final String intelliJSdkMetadataPath = fs.path.join('.idea', 'libraries', 'Dart_SDK.xml');
    expectExists(intelliJSdkMetadataPath);
    final String sdkMetaContents = fs
        .file(fs.path.join(
          projectDir.path,
          intelliJSdkMetadataPath,
        ))
        .readAsStringSync();
    expect(sdkMetaContents, contains('<root url="file:/'));
    expect(sdkMetaContents, contains('/bin/cache/dart-sdk/lib/core"'));
  }, overrides: <Type, Generator>{
    FlutterVersion: () => mockFlutterVersion,
  }, timeout: allowForCreateFlutterProject);

441
  testUsingContext('has correct content and formatting with app template', () async {
442 443 444 445 446
    Cache.flutterRoot = '../..';
    when(mockFlutterVersion.frameworkRevision).thenReturn(frameworkRevision);
    when(mockFlutterVersion.channel).thenReturn(frameworkChannel);

    final CreateCommand command = CreateCommand();
447
    final CommandRunner<void> runner = createTestCommandRunner(command);
448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471

    await runner.run(<String>['create', '--template=app', '--no-pub', '--org', 'com.foo.bar', projectDir.path]);

    void expectExists(String relPath) {
      expect(fs.isFileSync('${projectDir.path}/$relPath'), true);
    }

    expectExists('lib/main.dart');
    expectExists('test/widget_test.dart');

    for (FileSystemEntity file in projectDir.listSync(recursive: true)) {
      if (file is File && file.path.endsWith('.dart')) {
        final String original = file.readAsStringSync();

        final Process process = await Process.start(
          sdkBinaryName('dartfmt'),
          <String>[file.path],
          workingDirectory: projectDir.path,
        );
        final String formatted = await process.stdout.transform(utf8.decoder).join();

        expect(original, formatted, reason: file.path);
      }
    }
472

473
    await _runFlutterTest(projectDir, target: fs.path.join(projectDir.path, 'test', 'widget_test.dart'));
474

475 476 477 478 479 480 481
    // Generated Xcode settings
    final String xcodeConfigPath = fs.path.join('ios', 'Flutter', 'Generated.xcconfig');
    expectExists(xcodeConfigPath);
    final File xcodeConfigFile = fs.file(fs.path.join(projectDir.path, xcodeConfigPath));
    final String xcodeConfig = xcodeConfigFile.readAsStringSync();
    expect(xcodeConfig, contains('FLUTTER_ROOT='));
    expect(xcodeConfig, contains('FLUTTER_APPLICATION_PATH='));
482
    expect(xcodeConfig, contains('FLUTTER_FRAMEWORK_DIR='));
483 484 485 486 487 488
    // App identification
    final String xcodeProjectPath = fs.path.join('ios', 'Runner.xcodeproj', 'project.pbxproj');
    expectExists(xcodeProjectPath);
    final File xcodeProjectFile = fs.file(fs.path.join(projectDir.path, xcodeProjectPath));
    final String xcodeProject = xcodeProjectFile.readAsStringSync();
    expect(xcodeProject, contains('PRODUCT_BUNDLE_IDENTIFIER = com.foo.bar.flutterProject'));
489

490 491 492 493 494 495
    final String versionPath = fs.path.join('.metadata');
    expectExists(versionPath);
    final String version = fs.file(fs.path.join(projectDir.path, versionPath)).readAsStringSync();
    expect(version, contains('version:'));
    expect(version, contains('revision: 12345678'));
    expect(version, contains('channel: omega'));
496

497 498 499 500 501 502 503 504 505 506 507 508 509 510
    // IntelliJ metadata
    final String intelliJSdkMetadataPath = fs.path.join('.idea', 'libraries', 'Dart_SDK.xml');
    expectExists(intelliJSdkMetadataPath);
    final String sdkMetaContents = fs
        .file(fs.path.join(
          projectDir.path,
          intelliJSdkMetadataPath,
        ))
        .readAsStringSync();
    expect(sdkMetaContents, contains('<root url="file:/'));
    expect(sdkMetaContents, contains('/bin/cache/dart-sdk/lib/core"'));
  }, overrides: <Type, Generator>{
    FlutterVersion: () => mockFlutterVersion,
  }, timeout: allowForCreateFlutterProject);
511

512 513
  testUsingContext('can re-gen default template over existing project', () async {
    Cache.flutterRoot = '../..';
514

515
    final CreateCommand command = CreateCommand();
516
    final CommandRunner<void> runner = createTestCommandRunner(command);
517

518
    await runner.run(<String>['create', '--no-pub', projectDir.path]);
519

520
    await runner.run(<String>['create', '--no-pub', projectDir.path]);
521 522 523

    final String metadata = fs.file(fs.path.join(projectDir.path, '.metadata')).readAsStringSync();
    expect(metadata, contains('project_type: app\n'));
524
  }, timeout: allowForCreateFlutterProject);
525

526
  testUsingContext('can re-gen default template over existing app project with no metadta and detect the type', () async {
527
    Cache.flutterRoot = '../..';
528

529
    final CreateCommand command = CreateCommand();
530
    final CommandRunner<void> runner = createTestCommandRunner(command);
531 532 533 534 535 536 537 538 539 540 541 542

    await runner.run(<String>['create', '--no-pub', '--template=app', projectDir.path]);

    // Remove the .metadata to simulate an older instantiation that didn't generate those.
    fs.file(fs.path.join(projectDir.path, '.metadata')).deleteSync();

    await runner.run(<String>['create', '--no-pub', projectDir.path]);

    final String metadata = fs.file(fs.path.join(projectDir.path, '.metadata')).readAsStringSync();
    expect(metadata, contains('project_type: app\n'));
  }, timeout: allowForCreateFlutterProject);

543
  testUsingContext('can re-gen app template over existing app project and detect the type', () async {
544 545 546
    Cache.flutterRoot = '../..';

    final CreateCommand command = CreateCommand();
547
    final CommandRunner<void> runner = createTestCommandRunner(command);
548 549 550 551 552 553 554 555 556

    await runner.run(<String>['create', '--no-pub', '--template=app', projectDir.path]);

    await runner.run(<String>['create', '--no-pub', projectDir.path]);

    final String metadata = fs.file(fs.path.join(projectDir.path, '.metadata')).readAsStringSync();
    expect(metadata, contains('project_type: app\n'));
  }, timeout: allowForCreateFlutterProject);

557 558 559 560 561 562 563 564 565 566 567 568 569 570
  testUsingContext('can re-gen template over existing module project and detect the type', () async {
    Cache.flutterRoot = '../..';

    final CreateCommand command = CreateCommand();
    final CommandRunner<void> runner = createTestCommandRunner(command);

    await runner.run(<String>['create', '--no-pub', '--template=module', projectDir.path]);

    await runner.run(<String>['create', '--no-pub', projectDir.path]);

    final String metadata = fs.file(fs.path.join(projectDir.path, '.metadata')).readAsStringSync();
    expect(metadata, contains('project_type: module\n'));
  }, timeout: allowForCreateFlutterProject);

571 572 573 574
  testUsingContext('can re-gen default template over existing plugin project and detect the type', () async {
    Cache.flutterRoot = '../..';

    final CreateCommand command = CreateCommand();
575
    final CommandRunner<void> runner = createTestCommandRunner(command);
576 577 578 579 580 581 582 583 584 585 586 587 588

    await runner.run(<String>['create', '--no-pub', '--template=plugin', projectDir.path]);

    await runner.run(<String>['create', '--no-pub', projectDir.path]);

    final String metadata = fs.file(fs.path.join(projectDir.path, '.metadata')).readAsStringSync();
    expect(metadata, contains('project_type: plugin'));
  }, timeout: allowForCreateFlutterProject);

  testUsingContext('can re-gen default template over existing package project and detect the type', () async {
    Cache.flutterRoot = '../..';

    final CreateCommand command = CreateCommand();
589
    final CommandRunner<void> runner = createTestCommandRunner(command);
590

591 592 593 594 595 596 597 598
    await runner.run(<String>['create', '--no-pub', '--template=package', projectDir.path]);

    await runner.run(<String>['create', '--no-pub', projectDir.path]);

    final String metadata = fs.file(fs.path.join(projectDir.path, '.metadata')).readAsStringSync();
    expect(metadata, contains('project_type: package'));
  }, timeout: allowForCreateFlutterProject);

599
  testUsingContext('can re-gen module .android/ folder, reusing custom org', () async {
600 601
    await _createProject(
      projectDir,
602
      <String>['--template=module', '--org', 'com.bar.foo'],
603 604 605 606 607 608 609 610 611 612 613 614
      <String>[],
    );
    projectDir.childDirectory('.android').deleteSync(recursive: true);
    return _createProject(
      projectDir,
      <String>[],
      <String>[
        '.android/app/src/main/java/com/bar/foo/flutterproject/host/MainActivity.java',
      ],
    );
  }, timeout: allowForRemotePubInvocation);

615
  testUsingContext('can re-gen module .ios/ folder, reusing custom org', () async {
616 617
    await _createProject(
      projectDir,
618
      <String>['--template=module', '--org', 'com.bar.foo'],
619 620 621 622 623 624 625 626 627 628 629
      <String>[],
    );
    projectDir.childDirectory('.ios').deleteSync(recursive: true);
    await _createProject(projectDir, <String>[], <String>[]);
    final FlutterProject project = await FlutterProject.fromDirectory(projectDir);
    expect(
      project.ios.productBundleIdentifier,
      'com.bar.foo.flutterProject',
    );
  }, timeout: allowForRemotePubInvocation);

630
  testUsingContext('can re-gen app android/ folder, reusing custom org', () async {
631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648
    await _createProject(
      projectDir,
      <String>['--no-pub', '--template=app', '--org', 'com.bar.foo'],
      <String>[],
    );
    projectDir.childDirectory('android').deleteSync(recursive: true);
    return _createProject(
      projectDir,
      <String>['--no-pub'],
      <String>[
        'android/app/src/main/java/com/bar/foo/flutterproject/MainActivity.java',
      ],
      unexpectedPaths: <String>[
        'android/app/src/main/java/com/example/flutterproject/MainActivity.java',
      ],
    );
  }, timeout: allowForCreateFlutterProject);

649
  testUsingContext('can re-gen app ios/ folder, reusing custom org', () async {
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 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713
    await _createProject(
      projectDir,
      <String>['--no-pub', '--template=app', '--org', 'com.bar.foo'],
      <String>[],
    );
    projectDir.childDirectory('ios').deleteSync(recursive: true);
    await _createProject(projectDir, <String>['--no-pub'], <String>[]);
    final FlutterProject project = await FlutterProject.fromDirectory(projectDir);
    expect(
      project.ios.productBundleIdentifier,
      'com.bar.foo.flutterProject',
    );
  }, timeout: allowForCreateFlutterProject);

  testUsingContext('can re-gen plugin ios/ and example/ folders, reusing custom org', () async {
    await _createProject(
      projectDir,
      <String>['--no-pub', '--template=plugin', '--org', 'com.bar.foo'],
      <String>[],
    );
    projectDir.childDirectory('example').deleteSync(recursive: true);
    projectDir.childDirectory('ios').deleteSync(recursive: true);
    await _createProject(
      projectDir,
      <String>['--no-pub', '--template=plugin'],
      <String>[
        'example/android/app/src/main/java/com/bar/foo/flutterprojectexample/MainActivity.java',
        'ios/Classes/FlutterProjectPlugin.h',
      ],
      unexpectedPaths: <String>[
        'example/android/app/src/main/java/com/example/flutterprojectexample/MainActivity.java',
        'android/src/main/java/com/example/flutterproject/FlutterProjectPlugin.java',
      ],
    );
    final FlutterProject project = await FlutterProject.fromDirectory(projectDir);
    expect(
      project.example.ios.productBundleIdentifier,
      'com.bar.foo.flutterProjectExample',
    );
  }, timeout: allowForCreateFlutterProject);

  testUsingContext('fails to re-gen without specified org when org is ambiguous', () async {
    await _createProject(
      projectDir,
      <String>['--no-pub', '--template=app', '--org', 'com.bar.foo'],
      <String>[],
    );
    fs.directory(fs.path.join(projectDir.path, 'ios')).deleteSync(recursive: true);
    await _createProject(
      projectDir,
      <String>['--no-pub', '--template=app', '--org', 'com.bar.baz'],
      <String>[],
    );
    expect(
      () => _createProject(projectDir, <String>[], <String>[]),
      throwsToolExit(message: 'Ambiguous organization'),
    );
  }, timeout: allowForCreateFlutterProject);

  // Verify that we help the user correct an option ordering issue
  testUsingContext('produces sensible error message', () async {
    Cache.flutterRoot = '../..';

    final CreateCommand command = CreateCommand();
714
    final CommandRunner<void> runner = createTestCommandRunner(command);
715 716 717 718 719 720 721 722 723 724 725

    expect(
      runner.run(<String>['create', projectDir.path, '--pub']),
      throwsToolExit(exitCode: 2, message: 'Try moving --pub'),
    );
  });

  // Verify that we fail with an error code when the file exists.
  testUsingContext('fails when file exists', () async {
    Cache.flutterRoot = '../..';
    final CreateCommand command = CreateCommand();
726
    final CommandRunner<void> runner = createTestCommandRunner(command);
727 728 729 730 731 732 733 734 735 736 737 738 739
    final File existingFile = fs.file('${projectDir.path.toString()}/bad');
    if (!existingFile.existsSync()) {
      existingFile.createSync(recursive: true);
    }
    expect(
      runner.run(<String>['create', existingFile.path]),
      throwsToolExit(message: 'file exists'),
    );
  });

  testUsingContext('fails when invalid package name', () async {
    Cache.flutterRoot = '../..';
    final CreateCommand command = CreateCommand();
740
    final CommandRunner<void> runner = createTestCommandRunner(command);
741 742 743 744 745 746 747 748 749
    expect(
      runner.run(<String>['create', fs.path.join(projectDir.path, 'invalidName')]),
      throwsToolExit(message: '"invalidName" is not a valid Dart package name.'),
    );
  });

  testUsingContext(
    'invokes pub offline when requested',
    () async {
750 751
      Cache.flutterRoot = '../..';

752
      final CreateCommand command = CreateCommand();
753
      final CommandRunner<void> runner = createTestCommandRunner(command);
754

755
      await runner.run(<String>['create', '--pub', '--offline', projectDir.path]);
756 757
      expect(loggingProcessManager.commands.first, contains(matches(r'dart-sdk[\\/]bin[\\/]pub')));
      expect(loggingProcessManager.commands.first, contains('--offline'));
758
    },
759 760 761 762 763
    timeout: allowForCreateFlutterProject,
    overrides: <Type, Generator>{
      ProcessManager: () => loggingProcessManager,
    },
  );
764

765 766 767
  testUsingContext(
    'invokes pub online when offline not requested',
    () async {
768 769
      Cache.flutterRoot = '../..';

770
      final CreateCommand command = CreateCommand();
771
      final CommandRunner<void> runner = createTestCommandRunner(command);
772 773

      await runner.run(<String>['create', '--pub', projectDir.path]);
774 775
      expect(loggingProcessManager.commands.first, contains(matches(r'dart-sdk[\\/]bin[\\/]pub')));
      expect(loggingProcessManager.commands.first, isNot(contains('--offline')));
776
    },
777 778 779 780 781
    timeout: allowForCreateFlutterProject,
    overrides: <Type, Generator>{
      ProcessManager: () => loggingProcessManager,
    },
  );
782
}
783

784
Future<void> _createProject(
785 786 787 788 789
  Directory dir,
  List<String> createArgs,
  List<String> expectedPaths, {
  List<String> unexpectedPaths = const <String>[],
}) async {
790
  Cache.flutterRoot = '../..';
791
  final CreateCommand command = CreateCommand();
792
  final CommandRunner<void> runner = createTestCommandRunner(command);
793
  final List<String> args = <String>['create'];
794 795
  args.addAll(createArgs);
  args.add(dir.path);
796
  await runner.run(args);
797

798 799 800 801 802
  bool pathExists(String path) {
    final String fullPath = fs.path.join(dir.path, path);
    return fs.typeSync(fullPath) != FileSystemEntityType.notFound;
  }

803
  final List<String> failures = <String>[];
804
  for (String path in expectedPaths) {
805 806 807
    if (!pathExists(path)) {
      failures.add('Path "$path" does not exist.');
    }
808 809
  }
  for (String path in unexpectedPaths) {
810 811 812
    if (pathExists(path)) {
      failures.add('Path "$path" exists when it shouldn\'t.');
    }
813
  }
814
  expect(failures, isEmpty, reason: failures.join('\n'));
815
}
816

817
Future<void> _createAndAnalyzeProject(
818 819 820 821 822 823 824
  Directory dir,
  List<String> createArgs,
  List<String> expectedPaths, {
  List<String> unexpectedPaths = const <String>[],
}) async {
  await _createProject(dir, createArgs, expectedPaths, unexpectedPaths: unexpectedPaths);
  await _analyzeProject(dir.path);
825 826
}

827
Future<void> _analyzeProject(String workingDir) async {
828 829 830 831
  final String flutterToolsPath = fs.path.absolute(fs.path.join(
    'bin',
    'flutter_tools.dart',
  ));
832

833 834 835 836
  final List<String> args = <String>[]
    ..addAll(dartVmFlags)
    ..add(flutterToolsPath)
    ..add('analyze');
837

838
  final ProcessResult exec = await Process.run(
839
    '$dartSdkPath/bin/dart',
840 841
    args,
    workingDirectory: workingDir,
842 843 844 845 846 847 848
  );
  if (exec.exitCode != 0) {
    print(exec.stdout);
    print(exec.stderr);
  }
  expect(exec.exitCode, 0);
}
849

850
Future<void> _runFlutterTest(Directory workingDir, {String target}) async {
851 852 853 854 855 856 857 858 859 860
  final String flutterToolsPath = fs.path.absolute(fs.path.join(
    'bin',
    'flutter_tools.dart',
  ));

  final List<String> args = <String>[]
    ..addAll(dartVmFlags)
    ..add(flutterToolsPath)
    ..add('test')
    ..add('--no-color');
861
  if (target != null) {
862
    args.add(target);
863
  }
864 865 866 867 868 869 870 871 872 873 874 875 876

  final ProcessResult exec = await Process.run(
    '$dartSdkPath/bin/dart',
    args,
    workingDirectory: workingDir.path,
  );
  if (exec.exitCode != 0) {
    print(exec.stdout);
    print(exec.stderr);
  }
  expect(exec.exitCode, 0);
}

877
class MockFlutterVersion extends Mock implements FlutterVersion {}
878 879

/// A ProcessManager that invokes a real process manager, but keeps
880
/// track of all commands sent to it.
881
class LoggingProcessManager extends LocalProcessManager {
882
  List<List<String>> commands = <List<String>>[];
883 884 885 886

  @override
  Future<Process> start(
    List<dynamic> command, {
887 888 889 890 891 892
    String workingDirectory,
    Map<String, String> environment,
    bool includeParentEnvironment = true,
    bool runInShell = false,
    ProcessStartMode mode = ProcessStartMode.normal,
  }) {
893
    commands.add(command);
894 895 896 897 898 899 900 901 902
    return super.start(
      command,
      workingDirectory: workingDirectory,
      environment: environment,
      includeParentEnvironment: includeParentEnvironment,
      runInShell: runInShell,
      mode: mode,
    );
  }
903
}