create_test.dart 41.3 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/base/net.dart';
12
import 'package:flutter_tools/src/base/platform.dart';
13
import 'package:flutter_tools/src/cache.dart';
14
import 'package:flutter_tools/src/commands/create.dart';
15
import 'package:flutter_tools/src/dart/sdk.dart';
16
import 'package:flutter_tools/src/project.dart';
17 18
import 'package:flutter_tools/src/version.dart';
import 'package:mockito/mockito.dart';
19
import 'package:process/process.dart';
20

21 22
import '../src/common.dart';
import '../src/context.dart';
23

24 25
const String frameworkRevision = '12345678';
const String frameworkChannel = 'omega';
26
final Generator _kNoColorTerminalPlatform = () => FakePlatform.fromPlatform(const LocalPlatform())..stdoutSupportsAnsi = false;
27
final Map<Type, Generator> noColorTerminalOverride = <Type, Generator>{
28 29
  Platform: _kNoColorTerminalPlatform,
};
30 31 32 33
const String samplesIndexJson = '''[
  { "id": "sample1" },
  { "id": "sample2" }
]''';
34

35
void main() {
36 37 38 39
  Directory tempDir;
  Directory projectDir;
  FlutterVersion mockFlutterVersion;
  LoggingProcessManager loggingProcessManager;
40

41 42 43 44 45 46 47 48 49 50
  setUpAll(() {
    Cache.disableLocking();
  });

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

52 53 54 55
  tearDown(() {
    tryToDelete(tempDir);
  });

56
  // Verify that we create a default project ('app') that is
57 58
  // well-formed.
  testUsingContext('can create a default project', () async {
59 60 61 62
    await _createAndAnalyzeProject(
      projectDir,
      <String>[],
      <String>[
63
        'android/app/src/main/java/com/example/flutter_project/MainActivity.java',
64 65 66 67 68
        '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',
69
        'lib/main.dart',
70 71
      ],
    );
72 73 74
    return _runFlutterTest(projectDir);
  }, timeout: allowForRemotePubInvocation);

75 76 77 78
  testUsingContext('can create a default project if empty directory exists', () async {
    await projectDir.create(recursive: true);
    await _createAndAnalyzeProject(
      projectDir,
79
      <String>[],
80
      <String>[
81
        'android/app/src/main/java/com/example/flutter_project/MainActivity.java',
82 83 84 85 86 87 88 89 90
        '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);

91 92
  testUsingContext('creates a module project correctly', () async {
    await _createAndAnalyzeProject(projectDir, <String>[
93
      '--template=module',
94
    ], <String>[
95 96 97 98 99 100 101 102 103 104 105 106
      '.android/app/',
      '.gitignore',
      '.ios/Flutter',
      '.metadata',
      'lib/main.dart',
      'pubspec.yaml',
      'README.md',
      'test/widget_test.dart',
    ], unexpectedPaths: <String>[
      'android/',
      'ios/',
    ]);
107 108 109 110 111 112 113 114 115 116 117 118 119 120
    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'));
121
  }, timeout: allowForRemotePubInvocation, overrides: noColorTerminalOverride);
122

123 124 125 126
  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>[
127
      'android/app/src/main/java/com/example/flutter_project/MainActivity.java',
128 129 130 131 132 133 134 135 136 137 138 139
      '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 {
140
    await projectDir.absolute.childDirectory('lib').create(recursive: true);
141 142
    await projectDir.absolute.childDirectory('ios').create(recursive: true);
    await _createAndAnalyzeProject(projectDir, <String>[], <String>[
143
      'android/app/src/main/java/com/example/flutter_project/MainActivity.java',
144 145 146 147 148
      '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',
149
    ], unexpectedPaths: <String>[
150 151
      '.android/',
      '.ios/',
152 153 154 155 156 157 158 159 160 161
    ]);
  }, 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>[
162 163
        'android/src/main/java/com/example/flutter_project/FlutterProjectPlugin.java',
        'example/android/app/src/main/java/com/example/flutter_project_example/MainActivity.java',
164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186
        '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>[
187 188 189
        'android/app/src/main/java/com/example/flutter_project/MainActivity.java',
        'android/src/main/java/com/example/flutter_project/FlutterProjectPlugin.java',
        'example/android/app/src/main/java/com/example/flutter_project_example/MainActivity.java',
190 191 192 193 194 195 196 197 198 199 200 201 202 203 204
        '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);

205 206 207 208 209
  testUsingContext('kotlin/swift legacy app project', () async {
    return _createProject(
      projectDir,
      <String>['--no-pub', '--template=app', '--android-language=kotlin', '--ios-language=swift'],
      <String>[
210
        'android/app/src/main/kotlin/com/example/flutter_project/MainActivity.kt',
211 212 213
        'ios/Runner/AppDelegate.swift',
        'ios/Runner/Runner-Bridging-Header.h',
        'lib/main.dart',
214
        '.idea/libraries/KotlinJavaRuntime.xml',
215 216
      ],
      unexpectedPaths: <String>[
217
        'android/app/src/main/java/com/example/flutter_project/MainActivity.java',
218 219 220 221 222 223 224
        'ios/Runner/AppDelegate.h',
        'ios/Runner/AppDelegate.m',
        'ios/Runner/main.m',
      ],
    );
  }, timeout: allowForCreateFlutterProject);

225
  testUsingContext('can create a package project', () async {
226 227 228 229 230 231 232 233
    await _createAndAnalyzeProject(
      projectDir,
      <String>['--template=package'],
      <String>[
        'lib/flutter_project.dart',
        'test/flutter_project_test.dart',
      ],
      unexpectedPaths: <String>[
234 235 236
        'android/app/src/main/java/com/example/flutter_project/MainActivity.java',
        'android/src/main/java/com/example/flutter_project/FlutterProjectPlugin.java',
        'example/android/app/src/main/java/com/example/flutter_project_example/MainActivity.java',
237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252
        '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);

253
  testUsingContext('can create a plugin project', () async {
254 255 256 257
    await _createAndAnalyzeProject(
      projectDir,
      <String>['--template=plugin'],
      <String>[
258 259
        'android/src/main/java/com/example/flutter_project/FlutterProjectPlugin.java',
        'example/android/app/src/main/java/com/example/flutter_project_example/MainActivity.java',
260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277
        '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>[
278 279
        'android/src/main/kotlin/com/example/flutter_project/FlutterProjectPlugin.kt',
        'example/android/app/src/main/kotlin/com/example/flutter_project_example/MainActivity.kt',
280 281 282 283 284 285 286 287 288
        '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>[
289 290
        'android/src/main/java/com/example/flutter_project/FlutterProjectPlugin.java',
        'example/android/app/src/main/java/com/example/flutter_project_example/MainActivity.java',
291 292 293 294 295 296 297 298 299 300 301 302
        '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>[
303 304
        'android/src/main/java/com/bar/foo/flutter_project/FlutterProjectPlugin.java',
        'example/android/app/src/main/java/com/bar/foo/flutter_project_example/MainActivity.java',
305 306
      ],
      unexpectedPaths: <String>[
307 308
        'android/src/main/java/com/example/flutter_project/FlutterProjectPlugin.java',
        'example/android/app/src/main/java/com/example/flutter_project_example/MainActivity.java',
309 310 311
      ],
    );
  }, timeout: allowForCreateFlutterProject);
312

313 314 315 316 317 318
  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',
319
        'example/android/app/src/main/java/com/example/xyz_example/MainActivity.java',
320 321
      ],
      unexpectedPaths: <String>[
322 323
        'android/src/main/java/com/example/flutter_project/FlutterProjectPlugin.java',
        'example/android/app/src/main/java/com/example/flutter_project_example/MainActivity.java',
324 325 326 327 328 329 330 331 332 333 334 335 336 337
      ],
    );
  }, 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);

338 339 340 341 342 343 344 345
  testUsingContext('legacy app project with-driver-test', () async {
    return _createAndAnalyzeProject(
      projectDir,
      <String>['--with-driver-test', '--template=app'],
      <String>['lib/main.dart'],
    );
  }, timeout: allowForRemotePubInvocation);

346
  testUsingContext('module project with pub', () async {
347
    return _createProject(projectDir, <String>[
348
      '--template=module',
349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377
    ], <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);

378
  testUsingContext('has correct content and formatting with module template', () async {
379 380 381 382 383
    Cache.flutterRoot = '../..';
    when(mockFlutterVersion.frameworkRevision).thenReturn(frameworkRevision);
    when(mockFlutterVersion.channel).thenReturn(frameworkChannel);

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

386
    await runner.run(<String>['create', '--template=module', '--no-pub', '--org', 'com.foo.bar', projectDir.path]);
387 388 389 390 391 392 393 394

    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
395 396 397 398
    final String actualContents = await fs.file(projectDir.path + '/test/widget_test.dart').readAsString();

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

399 400 401 402 403 404 405 406 407 408 409 410
    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);
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 441 442 443 444 445 446 447 448 449 450
    }

    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,
451
    Platform: _kNoColorTerminalPlatform,
452 453
  }, timeout: allowForCreateFlutterProject);

454
  testUsingContext('has correct content and formatting with app template', () async {
455 456 457 458 459
    Cache.flutterRoot = '../..';
    when(mockFlutterVersion.frameworkRevision).thenReturn(frameworkRevision);
    when(mockFlutterVersion.channel).thenReturn(frameworkChannel);

    final CreateCommand command = CreateCommand();
460
    final CommandRunner<void> runner = createTestCommandRunner(command);
461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484

    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);
      }
    }
485

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

488 489 490 491 492 493 494 495 496 497 498 499 500
    // 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='));
    // 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'));
501

502 503 504 505 506 507
    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'));
508

509 510 511 512 513 514 515 516 517 518 519 520 521
    // 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,
522
    Platform: _kNoColorTerminalPlatform,
523
  }, timeout: allowForCreateFlutterProject);
524

525 526 527 528 529 530 531 532 533 534 535 536 537
  testUsingContext('has correct application id for android and bundle id for ios', () async {
    Cache.flutterRoot = '../..';
    when(mockFlutterVersion.frameworkRevision).thenReturn(frameworkRevision);
    when(mockFlutterVersion.channel).thenReturn(frameworkChannel);

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

    String tmpProjectDir = fs.path.join(tempDir.path, 'hello_flutter');
    await runner.run(<String>['create', '--template=app', '--no-pub', '--org', 'com.example', tmpProjectDir]);
    FlutterProject project = await FlutterProject.fromDirectory(fs.directory(tmpProjectDir));
    expect(
        project.ios.productBundleIdentifier,
538
        'com.example.helloFlutter',
539 540 541
    );
    expect(
        project.android.applicationId,
542
        'com.example.hello_flutter',
543 544 545 546 547 548 549
    );

    tmpProjectDir = fs.path.join(tempDir.path, 'test_abc');
    await runner.run(<String>['create', '--template=app', '--no-pub', '--org', 'abc^*.1#@', tmpProjectDir]);
    project = await FlutterProject.fromDirectory(fs.directory(tmpProjectDir));
    expect(
        project.ios.productBundleIdentifier,
550
        'abc.1.testAbc',
551 552 553
    );
    expect(
        project.android.applicationId,
554
        'abc.u1.test_abc',
555 556 557 558 559 560 561
    );

    tmpProjectDir = fs.path.join(tempDir.path, 'flutter_project');
    await runner.run(<String>['create', '--template=app', '--no-pub', '--org', '#+^%', tmpProjectDir]);
    project = await FlutterProject.fromDirectory(fs.directory(tmpProjectDir));
    expect(
        project.ios.productBundleIdentifier,
562
        'flutterProject.untitled',
563 564 565
    );
    expect(
        project.android.applicationId,
566
        'flutter_project.untitled',
567 568 569 570 571 572
    );
  }, overrides: <Type, Generator>{
    FlutterVersion: () => mockFlutterVersion,
    Platform: _kNoColorTerminalPlatform,
  }, timeout: allowForCreateFlutterProject);

573 574
  testUsingContext('can re-gen default template over existing project', () async {
    Cache.flutterRoot = '../..';
575

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

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

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

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

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

590
    final CreateCommand command = CreateCommand();
591
    final CommandRunner<void> runner = createTestCommandRunner(command);
592 593 594 595 596 597 598 599 600 601 602 603

    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);

604
  testUsingContext('can re-gen app template over existing app project and detect the type', () async {
605 606 607
    Cache.flutterRoot = '../..';

    final CreateCommand command = CreateCommand();
608
    final CommandRunner<void> runner = createTestCommandRunner(command);
609 610 611 612 613 614 615 616 617

    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);

618 619 620 621 622 623 624 625 626 627 628 629 630 631
  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);

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

    final CreateCommand command = CreateCommand();
636
    final CommandRunner<void> runner = createTestCommandRunner(command);
637 638 639 640 641 642 643 644 645 646 647 648 649

    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();
650
    final CommandRunner<void> runner = createTestCommandRunner(command);
651

652 653 654 655 656 657 658 659
    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);

660
  testUsingContext('can re-gen module .android/ folder, reusing custom org', () async {
661 662
    await _createProject(
      projectDir,
663
      <String>['--template=module', '--org', 'com.bar.foo'],
664 665 666 667 668 669 670
      <String>[],
    );
    projectDir.childDirectory('.android').deleteSync(recursive: true);
    return _createProject(
      projectDir,
      <String>[],
      <String>[
671
        '.android/app/src/main/java/com/bar/foo/flutter_project/host/MainActivity.java',
672 673 674 675
      ],
    );
  }, timeout: allowForRemotePubInvocation);

676
  testUsingContext('can re-gen module .ios/ folder, reusing custom org', () async {
677 678
    await _createProject(
      projectDir,
679
      <String>['--template=module', '--org', 'com.bar.foo'],
680 681 682 683 684 685 686 687 688 689 690
      <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);

691
  testUsingContext('can re-gen app android/ folder, reusing custom org', () async {
692 693 694 695 696 697 698 699 700 701
    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>[
702
        'android/app/src/main/java/com/bar/foo/flutter_project/MainActivity.java',
703 704
      ],
      unexpectedPaths: <String>[
705
        'android/app/src/main/java/com/example/flutter_project/MainActivity.java',
706 707 708 709
      ],
    );
  }, timeout: allowForCreateFlutterProject);

710
  testUsingContext('can re-gen app ios/ folder, reusing custom org', () async {
711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736
    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>[
737
        'example/android/app/src/main/java/com/bar/foo/flutter_project_example/MainActivity.java',
738 739 740
        'ios/Classes/FlutterProjectPlugin.h',
      ],
      unexpectedPaths: <String>[
741 742
        'example/android/app/src/main/java/com/example/flutter_project_example/MainActivity.java',
        'android/src/main/java/com/example/flutter_project/FlutterProjectPlugin.java',
743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774
      ],
    );
    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();
775
    final CommandRunner<void> runner = createTestCommandRunner(command);
776 777 778 779 780 781 782

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

783
  testUsingContext('fails when file exists where output directory should be', () async {
784 785
    Cache.flutterRoot = '../..';
    final CreateCommand command = CreateCommand();
786
    final CommandRunner<void> runner = createTestCommandRunner(command);
787
    final File existingFile = fs.file(fs.path.join(projectDir.path, 'bad'));
788 789 790 791 792
    if (!existingFile.existsSync()) {
      existingFile.createSync(recursive: true);
    }
    expect(
      runner.run(<String>['create', existingFile.path]),
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
      throwsToolExit(message: 'existing file'),
    );
  });

  testUsingContext('fails overwrite when file exists where output directory should be', () async {
    Cache.flutterRoot = '../..';
    final CreateCommand command = CreateCommand();
    final CommandRunner<void> runner = createTestCommandRunner(command);
    final File existingFile = fs.file(fs.path.join(projectDir.path, 'bad'));
    if (!existingFile.existsSync()) {
      existingFile.createSync(recursive: true);
    }
    expect(
      runner.run(<String>['create', '--overwrite', existingFile.path]),
      throwsToolExit(message: 'existing file'),
    );
  });

  testUsingContext('overwrites existing directory when requested', () async {
    Cache.flutterRoot = '../..';
    final Directory existingDirectory = fs.directory(fs.path.join(projectDir.path, 'bad'));
    if (!existingDirectory.existsSync()) {
      existingDirectory.createSync(recursive: true);
    }
    final File existingFile = fs.file(fs.path.join(existingDirectory.path, 'lib', 'main.dart'));
    existingFile.createSync(recursive: true);
    await _createProject(
      fs.directory(existingDirectory.path),
      <String>['--overwrite'],
      <String>[
        'android/app/src/main/java/io/flutter/plugins/GeneratedPluginRegistrant.java',
        'lib/main.dart',
        'ios/Flutter/AppFrameworkInfo.plist',
        'ios/Runner/AppDelegate.m',
        'ios/Runner/GeneratedPluginRegistrant.h',
      ],
829 830 831 832 833 834
    );
  });

  testUsingContext('fails when invalid package name', () async {
    Cache.flutterRoot = '../..';
    final CreateCommand command = CreateCommand();
835
    final CommandRunner<void> runner = createTestCommandRunner(command);
836 837 838 839 840 841 842 843 844
    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 {
845 846
      Cache.flutterRoot = '../..';

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

850
      await runner.run(<String>['create', '--pub', '--offline', projectDir.path]);
851 852
      expect(loggingProcessManager.commands.first, contains(matches(r'dart-sdk[\\/]bin[\\/]pub')));
      expect(loggingProcessManager.commands.first, contains('--offline'));
853
    },
854 855 856 857 858
    timeout: allowForCreateFlutterProject,
    overrides: <Type, Generator>{
      ProcessManager: () => loggingProcessManager,
    },
  );
859

860 861 862
  testUsingContext(
    'invokes pub online when offline not requested',
    () async {
863 864
      Cache.flutterRoot = '../..';

865
      final CreateCommand command = CreateCommand();
866
      final CommandRunner<void> runner = createTestCommandRunner(command);
867 868

      await runner.run(<String>['create', '--pub', projectDir.path]);
869 870
      expect(loggingProcessManager.commands.first, contains(matches(r'dart-sdk[\\/]bin[\\/]pub')));
      expect(loggingProcessManager.commands.first, isNot(contains('--offline')));
871
    },
872 873 874 875 876
    timeout: allowForCreateFlutterProject,
    overrides: <Type, Generator>{
      ProcessManager: () => loggingProcessManager,
    },
  );
877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894

  testUsingContext('can create a sample-based project', () async {
    await _createAndAnalyzeProject(
      projectDir,
      <String>['--no-pub', '--sample=foo.bar.Baz'],
      <String>[
        'lib/main.dart',
        'flutter_project.iml',
        'android/app/src/main/AndroidManifest.xml',
        'ios/Flutter/AppFrameworkInfo.plist',
      ],
      unexpectedPaths: <String>['test'],
    );
    expect(projectDir.childDirectory('lib').childFile('main.dart').readAsStringSync(),
      contains('void main() {}'));
  }, timeout: allowForRemotePubInvocation, overrides: <Type, Generator>{
    HttpClientFactory: () => () => MockHttpClient(200, result: 'void main() {}'),
  });
895 896 897 898 899 900 901 902

  testUsingContext('can write samples index to disk', () async {
    final String outputFile = fs.path.join(tempDir.path, 'flutter_samples.json');
    final CreateCommand command = CreateCommand();
    final CommandRunner<void> runner = createTestCommandRunner(command);
    final List<String> args = <String>[
      'create',
      '--list-samples',
903
      outputFile,
904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920
    ];

    await runner.run(args);
    final File expectedFile = fs.file(outputFile);
    expect(expectedFile.existsSync(), isTrue);
    expect(expectedFile.readAsStringSync(), equals(samplesIndexJson));
  }, overrides: <Type, Generator>{
    HttpClientFactory: () =>
        () => MockHttpClient(200, result: samplesIndexJson),
  });
  testUsingContext('provides an error to the user if samples json download fails', () async {
    final String outputFile = fs.path.join(tempDir.path, 'flutter_samples.json');
    final CreateCommand command = CreateCommand();
    final CommandRunner<void> runner = createTestCommandRunner(command);
    final List<String> args = <String>[
      'create',
      '--list-samples',
921
      outputFile,
922 923 924 925 926 927 928 929
    ];

    await expectLater(runner.run(args), throwsToolExit(exitCode: 2, message: 'Failed to write samples'));
    expect(fs.file(outputFile).existsSync(), isFalse);
  }, overrides: <Type, Generator>{
    HttpClientFactory: () =>
        () => MockHttpClient(404, result: 'not found'),
  });
930
}
931

932
Future<void> _createProject(
933 934 935 936 937
  Directory dir,
  List<String> createArgs,
  List<String> expectedPaths, {
  List<String> unexpectedPaths = const <String>[],
}) async {
938
  Cache.flutterRoot = '../..';
939
  final CreateCommand command = CreateCommand();
940
  final CommandRunner<void> runner = createTestCommandRunner(command);
941
  final List<String> args = <String>['create'];
942 943
  args.addAll(createArgs);
  args.add(dir.path);
944
  await runner.run(args);
945

946 947 948 949 950
  bool pathExists(String path) {
    final String fullPath = fs.path.join(dir.path, path);
    return fs.typeSync(fullPath) != FileSystemEntityType.notFound;
  }

951
  final List<String> failures = <String>[];
952
  for (String path in expectedPaths) {
953 954 955
    if (!pathExists(path)) {
      failures.add('Path "$path" does not exist.');
    }
956 957
  }
  for (String path in unexpectedPaths) {
958 959 960
    if (pathExists(path)) {
      failures.add('Path "$path" exists when it shouldn\'t.');
    }
961
  }
962
  expect(failures, isEmpty, reason: failures.join('\n'));
963
}
964

965
Future<void> _createAndAnalyzeProject(
966 967 968 969 970 971 972
  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);
973 974
}

975
Future<void> _analyzeProject(String workingDir) async {
976 977 978 979
  final String flutterToolsPath = fs.path.absolute(fs.path.join(
    'bin',
    'flutter_tools.dart',
  ));
980

981 982 983 984
  final List<String> args = <String>[]
    ..addAll(dartVmFlags)
    ..add(flutterToolsPath)
    ..add('analyze');
985

986
  final ProcessResult exec = await Process.run(
987
    '$dartSdkPath/bin/dart',
988 989
    args,
    workingDirectory: workingDir,
990 991 992 993 994 995 996
  );
  if (exec.exitCode != 0) {
    print(exec.stdout);
    print(exec.stderr);
  }
  expect(exec.exitCode, 0);
}
997

998
Future<void> _runFlutterTest(Directory workingDir, { String target }) async {
999 1000 1001 1002 1003
  final String flutterToolsPath = fs.path.absolute(fs.path.join(
    'bin',
    'flutter_tools.dart',
  ));

1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014
  // While flutter test does get packages, it doesn't write version
  // files anymore.
  await Process.run(
    '$dartSdkPath/bin/dart',
    <String>[]
    ..addAll(dartVmFlags)
    ..add(flutterToolsPath)
    ..addAll(<String>['packages', 'get']),
    workingDirectory: workingDir.path,
  );

1015 1016 1017 1018 1019
  final List<String> args = <String>[]
    ..addAll(dartVmFlags)
    ..add(flutterToolsPath)
    ..add('test')
    ..add('--no-color');
1020
  if (target != null) {
1021
    args.add(target);
1022
  }
1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035

  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);
}

1036
class MockFlutterVersion extends Mock implements FlutterVersion {}
1037 1038

/// A ProcessManager that invokes a real process manager, but keeps
1039
/// track of all commands sent to it.
1040
class LoggingProcessManager extends LocalProcessManager {
1041
  List<List<String>> commands = <List<String>>[];
1042 1043 1044 1045

  @override
  Future<Process> start(
    List<dynamic> command, {
1046 1047 1048 1049 1050 1051
    String workingDirectory,
    Map<String, String> environment,
    bool includeParentEnvironment = true,
    bool runInShell = false,
    ProcessStartMode mode = ProcessStartMode.normal,
  }) {
1052
    commands.add(command);
1053 1054 1055 1056 1057 1058 1059 1060 1061
    return super.start(
      command,
      workingDirectory: workingDirectory,
      environment: environment,
      includeParentEnvironment: includeParentEnvironment,
      runInShell: runInShell,
      mode: mode,
    );
  }
1062
}
1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 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 1108 1109

class MockHttpClient implements HttpClient {
  MockHttpClient(this.statusCode, {this.result});

  final int statusCode;
  final String result;

  @override
  Future<HttpClientRequest> getUrl(Uri url) async {
    return MockHttpClientRequest(statusCode, result: result);
  }

  @override
  dynamic noSuchMethod(Invocation invocation) {
    throw 'io.HttpClient - $invocation';
  }
}

class MockHttpClientRequest implements HttpClientRequest {
  MockHttpClientRequest(this.statusCode, {this.result});

  final int statusCode;
  final String result;

  @override
  Future<HttpClientResponse> close() async {
    return MockHttpClientResponse(statusCode, result: result);
  }

  @override
  dynamic noSuchMethod(Invocation invocation) {
    throw 'io.HttpClientRequest - $invocation';
  }
}

class MockHttpClientResponse extends Stream<List<int>> implements HttpClientResponse {
  MockHttpClientResponse(this.statusCode, {this.result});

  @override
  final int statusCode;

  final String result;

  @override
  String get reasonPhrase => '<reason phrase>';

  @override
1110 1111 1112 1113
  StreamSubscription<List<int>> listen(
    void onData(List<int> event), {
    Function onError,
    void onDone(),
1114
    bool cancelOnError,
1115 1116 1117 1118 1119 1120 1121 1122 1123 1124
  }) {
    return Stream<List<int>>.fromIterable(<List<int>>[result.codeUnits])
      .listen(onData, onError: onError, onDone: onDone, cancelOnError: cancelOnError);
  }

  @override
  dynamic noSuchMethod(Invocation invocation) {
    throw 'io.HttpClientResponse - $invocation';
  }
}