build_web_test.dart 15.5 KB
Newer Older
Ian Hickson's avatar
Ian Hickson committed
1
// Copyright 2014 The Flutter Authors. All rights reserved.
2 3 4
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

5
import 'package:args/command_runner.dart';
6 7
import 'package:file/memory.dart';
import 'package:flutter_tools/src/base/file_system.dart';
8
import 'package:flutter_tools/src/base/logger.dart';
9
import 'package:flutter_tools/src/base/platform.dart';
10
import 'package:flutter_tools/src/build_info.dart';
11
import 'package:flutter_tools/src/build_system/build_system.dart';
12
import 'package:flutter_tools/src/cache.dart';
13
import 'package:flutter_tools/src/commands/build.dart';
14
import 'package:flutter_tools/src/commands/build_web.dart';
15
import 'package:flutter_tools/src/features.dart';
16
import 'package:flutter_tools/src/runner/flutter_command.dart';
17

18
import '../../src/common.dart';
19
import '../../src/context.dart';
20
import '../../src/fakes.dart';
21
import '../../src/test_build_system.dart';
22
import '../../src/test_flutter_command_runner.dart';
23 24

void main() {
25
  late FileSystem fileSystem;
26 27
  final Platform fakePlatform = FakePlatform(
    environment: <String, String>{
28 29
      'FLUTTER_ROOT': '/',
    },
30
  );
31 32

  setUpAll(() {
33
    Cache.flutterRoot = '';
34 35 36 37
    Cache.disableLocking();
  });

  setUp(() {
38 39 40 41 42 43 44
    fileSystem = MemoryFileSystem.test();
    fileSystem.file('pubspec.yaml')
      ..createSync()
      ..writeAsStringSync('name: foo\n');
    fileSystem.file('.packages').createSync();
    fileSystem.file(fileSystem.path.join('web', 'index.html')).createSync(recursive: true);
    fileSystem.file(fileSystem.path.join('lib', 'main.dart')).createSync(recursive: true);
45 46
  });

47 48
  testUsingContext('Refuses to build for web when missing index.html', () async {
    fileSystem.file(fileSystem.path.join('web', 'index.html')).deleteSync();
49 50 51 52
    final CommandRunner<void> runner = createTestCommandRunner(BuildCommand(
      androidSdk: FakeAndroidSdk(),
      buildSystem: TestBuildSystem.all(BuildResult(success: true)),
      fileSystem: MemoryFileSystem.test(),
53
      logger: BufferLogger.test(),
54 55
      osUtils: FakeOperatingSystemUtils(),
    ));
56

57 58 59 60
    expect(
      () => runner.run(<String>['build', 'web', '--no-pub']),
      throwsToolExit(message: 'Missing index.html.')
    );
61 62 63 64 65 66
  }, overrides: <Type, Generator>{
    Platform: () => fakePlatform,
    FileSystem: () => fileSystem,
    FeatureFlags: () => TestFeatureFlags(isWebEnabled: true),
    ProcessManager: () => FakeProcessManager.any(),
  });
67

68
  testUsingContext('Refuses to build a debug build for web', () async {
69 70 71 72
    final CommandRunner<void> runner = createTestCommandRunner(BuildCommand(
      androidSdk: FakeAndroidSdk(),
      buildSystem: TestBuildSystem.all(BuildResult(success: true)),
      fileSystem: fileSystem,
73
      logger: BufferLogger.test(),
74 75
      osUtils: FakeOperatingSystemUtils(),
    ));
76

77
    expect(() => runner.run(<String>['build', 'web', '--debug', '--no-pub']),
78
      throwsA(isA<UsageException>()));
79
  }, overrides: <Type, Generator>{
80
    Platform: () => fakePlatform,
81
    FeatureFlags: () => TestFeatureFlags(isWebEnabled: true),
82 83
    ProcessManager: () => FakeProcessManager.any(),
  });
84

85
  testUsingContext('Refuses to build for web when feature is disabled', () async {
86 87 88 89
    final CommandRunner<void> runner = createTestCommandRunner(BuildCommand(
      androidSdk: FakeAndroidSdk(),
      buildSystem: TestBuildSystem.all(BuildResult(success: true)),
      fileSystem: MemoryFileSystem.test(),
90
      logger: BufferLogger.test(),
91 92
      osUtils: FakeOperatingSystemUtils(),
    ));
93

94
    expect(
95
      () => runner.run(<String>['build', 'web', '--no-pub']),
96
      throwsToolExit(message: '"build web" is not currently supported. To enable, run "flutter config --enable-web".')
97
    );
98
  }, overrides: <Type, Generator>{
99 100
    Platform: () => fakePlatform,
    FileSystem: () => fileSystem,
101
    FeatureFlags: () => TestFeatureFlags(),
102 103
    ProcessManager: () => FakeProcessManager.any(),
  });
104

105
  testUsingContext('Setup for a web build with default output directory', () async {
106 107 108 109
    final BuildCommand buildCommand = BuildCommand(
      androidSdk: FakeAndroidSdk(),
      buildSystem: TestBuildSystem.all(BuildResult(success: true)),
      fileSystem: fileSystem,
110
      logger: BufferLogger.test(),
111 112
      osUtils: FakeOperatingSystemUtils(),
    );
113
    final CommandRunner<void> runner = createTestCommandRunner(buildCommand);
114
    setupFileSystemForEndToEndTest(fileSystem);
115
    await runner.run(<String>['build', 'web', '--no-pub', '--no-web-resources-cdn', '--dart-define=foo=a', '--dart2js-optimization=O3']);
116

117 118 119
    final Directory buildDir = fileSystem.directory(fileSystem.path.join('build', 'web'));

    expect(buildDir.existsSync(), true);
120
  }, overrides: <Type, Generator>{
121
    Platform: () => fakePlatform,
122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 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
    FileSystem: () => fileSystem,
    FeatureFlags: () => TestFeatureFlags(isWebEnabled: true),
    ProcessManager: () => FakeProcessManager.any(),
    BuildSystem: () => TestBuildSystem.all(BuildResult(success: true), (Target target, Environment environment) {
      expect(environment.defines, <String, String>{
        'TargetFile': 'lib/main.dart',
        'HasWebPlugins': 'true',
        'cspMode': 'false',
        'SourceMaps': 'false',
        'NativeNullAssertions': 'true',
        'ServiceWorkerStrategy': 'offline-first',
        'Dart2jsDumpInfo': 'false',
        'Dart2jsNoFrequencyBasedMinification': 'false',
        'Dart2jsOptimization': 'O3',
        'BuildMode': 'release',
        'DartDefines': 'Zm9vPWE=,RkxVVFRFUl9XRUJfQVVUT19ERVRFQ1Q9dHJ1ZQ==',
        'DartObfuscation': 'false',
        'TrackWidgetCreation': 'false',
        'TreeShakeIcons': 'true',
      });
    }),
  });

  testUsingContext('Does not allow -O0 optimization level', () async {
    final BuildCommand buildCommand = BuildCommand(
      androidSdk: FakeAndroidSdk(),
      buildSystem: TestBuildSystem.all(BuildResult(success: true)),
      fileSystem: fileSystem,
      logger: BufferLogger.test(),
      osUtils: FakeOperatingSystemUtils(),
    );
    final CommandRunner<void> runner = createTestCommandRunner(buildCommand);
    setupFileSystemForEndToEndTest(fileSystem);
    await expectLater(
      () => runner.run(<String>[
        'build',
        'web',
        '--no-pub', '--no-web-resources-cdn', '--dart-define=foo=a', '--dart2js-optimization=O0']),
      throwsUsageException(message: '"O0" is not an allowed value for option "dart2js-optimization"'),
    );

    final Directory buildDir = fileSystem.directory(fileSystem.path.join('build', 'web'));

    expect(buildDir.existsSync(), isFalse);
  }, overrides: <Type, Generator>{
    Platform: () => fakePlatform,
168
    FileSystem: () => fileSystem,
169
    FeatureFlags: () => TestFeatureFlags(isWebEnabled: true),
170
    ProcessManager: () => FakeProcessManager.any(),
171 172 173 174 175 176 177 178
    BuildSystem: () => TestBuildSystem.all(BuildResult(success: true), (Target target, Environment environment) {
      expect(environment.defines, <String, String>{
        'TargetFile': 'lib/main.dart',
        'HasWebPlugins': 'true',
        'cspMode': 'false',
        'SourceMaps': 'false',
        'NativeNullAssertions': 'true',
        'ServiceWorkerStrategy': 'offline-first',
179 180
        'Dart2jsDumpInfo': 'false',
        'Dart2jsNoFrequencyBasedMinification': 'false',
181
        'Dart2jsOptimization': 'O3',
182 183 184 185
        'BuildMode': 'release',
        'DartDefines': 'Zm9vPWE=,RkxVVFRFUl9XRUJfQVVUT19ERVRFQ1Q9dHJ1ZQ==',
        'DartObfuscation': 'false',
        'TrackWidgetCreation': 'false',
186
        'TreeShakeIcons': 'true',
187 188
      });
    }),
189
  });
190

191 192
  testUsingContext('Setup for a web build with a user specified output directory',
      () async {
193 194 195 196
    final BuildCommand buildCommand = BuildCommand(
      androidSdk: FakeAndroidSdk(),
      buildSystem: TestBuildSystem.all(BuildResult(success: true)),
      fileSystem: fileSystem,
197
      logger: BufferLogger.test(),
198 199
      osUtils: FakeOperatingSystemUtils(),
    );
200 201 202 203 204 205 206 207 208 209 210 211 212
    final CommandRunner<void> runner = createTestCommandRunner(buildCommand);

    setupFileSystemForEndToEndTest(fileSystem);

    const String newBuildDir = 'new_dir';
    final Directory buildDir = fileSystem.directory(fileSystem.path.join(newBuildDir));

    expect(buildDir.existsSync(), false);

    await runner.run(<String>[
      'build',
      'web',
      '--no-pub',
213
      '--no-web-resources-cdn',
214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230
      '--output=$newBuildDir'
    ]);

    expect(buildDir.existsSync(), true);
  }, overrides: <Type, Generator>{
    Platform: () => fakePlatform,
    FileSystem: () => fileSystem,
    FeatureFlags: () => TestFeatureFlags(isWebEnabled: true),
    ProcessManager: () => FakeProcessManager.any(),
    BuildSystem: () => TestBuildSystem.all(BuildResult(success: true), (Target target, Environment environment) {
      expect(environment.defines, <String, String>{
        'TargetFile': 'lib/main.dart',
        'HasWebPlugins': 'true',
        'cspMode': 'false',
        'SourceMaps': 'false',
        'NativeNullAssertions': 'true',
        'ServiceWorkerStrategy': 'offline-first',
231 232
        'Dart2jsDumpInfo': 'false',
        'Dart2jsNoFrequencyBasedMinification': 'false',
233
        'Dart2jsOptimization': 'O4',
234 235 236 237
        'BuildMode': 'release',
        'DartDefines': 'RkxVVFRFUl9XRUJfQVVUT19ERVRFQ1Q9dHJ1ZQ==',
        'DartObfuscation': 'false',
        'TrackWidgetCreation': 'false',
238
        'TreeShakeIcons': 'true',
239 240 241 242
      });
    }),
  });

243
  testUsingContext('hidden if feature flag is not enabled', () async {
244
    expect(BuildWebCommand(fileSystem: fileSystem, logger: BufferLogger.test(), verboseHelp: false).hidden, true);
245
  }, overrides: <Type, Generator>{
246 247
    Platform: () => fakePlatform,
    FileSystem: () => fileSystem,
248
    FeatureFlags: () => TestFeatureFlags(),
249 250
    ProcessManager: () => FakeProcessManager.any(),
  });
251

252
  testUsingContext('not hidden if feature flag is enabled', () async {
253
    expect(BuildWebCommand(fileSystem: fileSystem, logger: BufferLogger.test(), verboseHelp: false).hidden, false);
254
  }, overrides: <Type, Generator>{
255 256
    Platform: () => fakePlatform,
    FileSystem: () => fileSystem,
257
    FeatureFlags: () => TestFeatureFlags(isWebEnabled: true),
258 259
    ProcessManager: () => FakeProcessManager.any(),
  });
260 261

  testUsingContext('Defaults to web renderer auto mode when no option is specified', () async {
262
    final TestWebBuildCommand buildCommand = TestWebBuildCommand(fileSystem: fileSystem);
263 264
    final CommandRunner<void> runner = createTestCommandRunner(buildCommand);
    setupFileSystemForEndToEndTest(fileSystem);
265
    await runner.run(<String>['build', 'web', '--no-pub']);
266 267 268 269 270 271 272
    final BuildInfo buildInfo =
        await buildCommand.webCommand.getBuildInfo(forcedBuildMode: BuildMode.debug);
    expect(buildInfo.dartDefines, contains('FLUTTER_WEB_AUTO_DETECT=true'));
  }, overrides: <Type, Generator>{
    Platform: () => fakePlatform,
    FileSystem: () => fileSystem,
    FeatureFlags: () => TestFeatureFlags(isWebEnabled: true),
273 274 275 276 277
    ProcessManager: () => FakeProcessManager.any(),
    BuildSystem: () => TestBuildSystem.all(BuildResult(success: true)),
  });

  testUsingContext('Web build supports build-name and build-number', () async {
278
    final TestWebBuildCommand buildCommand = TestWebBuildCommand(fileSystem: fileSystem);
279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297
    final CommandRunner<void> runner = createTestCommandRunner(buildCommand);
    setupFileSystemForEndToEndTest(fileSystem);

    await runner.run(<String>[
      'build',
      'web',
      '--no-pub',
      '--build-name=1.2.3',
      '--build-number=42',
    ]);

    final BuildInfo buildInfo = await buildCommand.webCommand
        .getBuildInfo(forcedBuildMode: BuildMode.debug);
    expect(buildInfo.buildNumber, '42');
    expect(buildInfo.buildName, '1.2.3');
  }, overrides: <Type, Generator>{
    Platform: () => fakePlatform,
    FileSystem: () => fileSystem,
    FeatureFlags: () => TestFeatureFlags(isWebEnabled: true),
298
    ProcessManager: () => FakeProcessManager.any(),
299
    BuildSystem: () => TestBuildSystem.all(BuildResult(success: true)),
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 326 327 328 329 330 331
  });

  testUsingContext('Defaults to gstatic CanvasKit artifacts', () async {
    final TestWebBuildCommand buildCommand = TestWebBuildCommand(fileSystem: fileSystem);
    final CommandRunner<void> runner = createTestCommandRunner(buildCommand);
    setupFileSystemForEndToEndTest(fileSystem);
    await runner.run(<String>['build', 'web', '--no-pub', '--web-resources-cdn']);
    final BuildInfo buildInfo =
        await buildCommand.webCommand.getBuildInfo(forcedBuildMode: BuildMode.debug);
    expect(buildInfo.dartDefines, contains(startsWith('FLUTTER_WEB_CANVASKIT_URL=https://www.gstatic.com/flutter-canvaskit/')));
  }, overrides: <Type, Generator>{
    Platform: () => fakePlatform,
    FileSystem: () => fileSystem,
    FeatureFlags: () => TestFeatureFlags(isWebEnabled: true),
    ProcessManager: () => FakeProcessManager.any(),
    BuildSystem: () => TestBuildSystem.all(BuildResult(success: true)),
  });

  testUsingContext('Does not override custom CanvasKit URL', () async {
    final TestWebBuildCommand buildCommand = TestWebBuildCommand(fileSystem: fileSystem);
    final CommandRunner<void> runner = createTestCommandRunner(buildCommand);
    setupFileSystemForEndToEndTest(fileSystem);
    await runner.run(<String>['build', 'web', '--no-pub', '--web-resources-cdn', '--dart-define=FLUTTER_WEB_CANVASKIT_URL=abcdefg']);
    final BuildInfo buildInfo =
        await buildCommand.webCommand.getBuildInfo(forcedBuildMode: BuildMode.debug);
    expect(buildInfo.dartDefines, contains('FLUTTER_WEB_CANVASKIT_URL=abcdefg'));
  }, overrides: <Type, Generator>{
    Platform: () => fakePlatform,
    FileSystem: () => fileSystem,
    FeatureFlags: () => TestFeatureFlags(isWebEnabled: true),
    ProcessManager: () => FakeProcessManager.any(),
    BuildSystem: () => TestBuildSystem.all(BuildResult(success: true)),
332 333 334 335 336 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 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382
  });
}

void setupFileSystemForEndToEndTest(FileSystem fileSystem) {
  final List<String> dependencies = <String>[
    fileSystem.path.join('packages', 'flutter_tools', 'lib', 'src', 'build_system', 'targets', 'web.dart'),
    fileSystem.path.join('bin', 'cache', 'flutter_web_sdk'),
    fileSystem.path.join('bin', 'cache', 'dart-sdk', 'bin', 'snapshots', 'dart2js.dart.snapshot'),
    fileSystem.path.join('bin', 'cache', 'dart-sdk', 'bin', 'dart'),
    fileSystem.path.join('bin', 'cache', 'dart-sdk '),
  ];
  for (final String dependency in dependencies) {
    fileSystem.file(dependency).createSync(recursive: true);
  }

  // Project files.
  fileSystem.file('.packages')
      .writeAsStringSync('''
foo:lib/
fizz:bar/lib/
''');
  fileSystem.file('pubspec.yaml')
      .writeAsStringSync('''
name: foo

dependencies:
  flutter:
    sdk: flutter
  fizz:
    path:
      bar/
''');
  fileSystem.file(fileSystem.path.join('bar', 'pubspec.yaml'))
    ..createSync(recursive: true)
    ..writeAsStringSync('''
name: bar

flutter:
  plugin:
    platforms:
      web:
        pluginClass: UrlLauncherPlugin
        fileName: url_launcher_web.dart
''');
  fileSystem.file(fileSystem.path.join('bar', 'lib', 'url_launcher_web.dart'))
    ..createSync(recursive: true)
    ..writeAsStringSync('''
class UrlLauncherPlugin {}
''');
  fileSystem.file(fileSystem.path.join('lib', 'main.dart'))
      .writeAsStringSync('void main() { }');
383 384
}

385
class TestWebBuildCommand extends FlutterCommand {
386 387 388
  TestWebBuildCommand({ required FileSystem fileSystem, bool verboseHelp = false }) :
    webCommand = BuildWebCommand(
      fileSystem: fileSystem,
389
      logger: BufferLogger.test(),
390
      verboseHelp: verboseHelp) {
391 392 393 394 395 396 397 398 399 400 401 402
    addSubcommand(webCommand);
  }

  final BuildWebCommand webCommand;

  @override
  final String name = 'build';

  @override
  final String description = 'Build a test executable app.';

  @override
403
  Future<FlutterCommandResult> runCommand() async => FlutterCommandResult.fail();
404 405 406

  @override
  bool get shouldRunPub => false;
407
}