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

5 6 7
import 'dart:typed_data';

import 'package:args/args.dart';
8
import 'package:file/memory.dart';
9 10 11
import 'package:file_testing/file_testing.dart';
import 'package:flutter_tools/src/artifacts.dart';
import 'package:flutter_tools/src/asset.dart';
12
import 'package:flutter_tools/src/base/config.dart';
13
import 'package:flutter_tools/src/base/file_system.dart';
14
import 'package:flutter_tools/src/base/logger.dart';
15 16
import 'package:flutter_tools/src/build_info.dart';
import 'package:flutter_tools/src/build_system/build_system.dart';
17
import 'package:flutter_tools/src/bundle.dart' hide defaultManifestPath;
18
import 'package:flutter_tools/src/bundle_builder.dart';
19 20 21
import 'package:flutter_tools/src/devfs.dart';
import 'package:flutter_tools/src/device.dart';
import 'package:flutter_tools/src/flutter_manifest.dart';
22
import 'package:flutter_tools/src/globals.dart' as globals;
23
import 'package:flutter_tools/src/project.dart';
24
import 'package:test/fake.dart';
25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44

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

// Tests for BundleBuilder.
void main() {
  testUsingContext('Copies assets to expected directory after building', () async {
    final BuildSystem buildSystem = TestBuildSystem.all(
      BuildResult(success: true),
      (Target target, Environment environment) {
        environment.outputDir.childFile('kernel_blob.bin').createSync(recursive: true);
        environment.outputDir.childFile('isolate_snapshot_data').createSync();
        environment.outputDir.childFile('vm_snapshot_data').createSync();
        environment.outputDir.childFile('LICENSE').createSync(recursive: true);
      }
    );

    await BundleBuilder().build(
      platform: TargetPlatform.ios,
45
      buildInfo: BuildInfo.debug,
46 47 48 49 50 51 52 53 54 55 56 57 58 59
      project: FlutterProject.fromDirectoryTest(globals.fs.currentDirectory),
      mainPath: globals.fs.path.join('lib', 'main.dart'),
      assetDirPath: 'example',
      depfilePath: 'example.d',
      buildSystem: buildSystem
    );
    expect(globals.fs.file(globals.fs.path.join('example', 'kernel_blob.bin')).existsSync(), true);
    expect(globals.fs.file(globals.fs.path.join('example', 'LICENSE')).existsSync(), true);
    expect(globals.fs.file(globals.fs.path.join('example.d')).existsSync(), false);
  }, overrides: <Type, Generator>{
    FileSystem: () => MemoryFileSystem.test(),
    ProcessManager: () => FakeProcessManager.any(),
  });

60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128
  testWithoutContext('writeBundle applies transformations to any assets that have them defined', () async {
    final MemoryFileSystem fileSystem = MemoryFileSystem.test();
    final File asset = fileSystem.file('my-asset.txt')
      ..createSync()
      ..writeAsBytesSync(<int>[1, 2, 3]);
    final Artifacts artifacts = Artifacts.test();

    final FakeProcessManager processManager = FakeProcessManager.list(
        <FakeCommand>[
          FakeCommand(
            command: <Pattern>[
              artifacts.getArtifactPath(Artifact.engineDartBinary),
              'run',
              'increment',
              '--input=/.tmp_rand0/my-asset.txt-transformOutput0.txt',
              '--output=/.tmp_rand0/my-asset.txt-transformOutput1.txt'
            ],
            onRun: (List<String> command) {
              final ArgResults argParseResults = (ArgParser()
                  ..addOption('input', mandatory: true)
                  ..addOption('output', mandatory: true))
                .parse(command);

              final File inputFile = fileSystem.file(argParseResults['input']);
              final File outputFile = fileSystem.file(argParseResults['output']);

              expect(inputFile, exists);
              outputFile
                ..createSync()
                ..writeAsBytesSync(
                  Uint8List.fromList(
                    inputFile.readAsBytesSync().map((int b) => b + 1).toList(),
                  ),
                );
            },
          ),
        ],
      );

    final FakeAssetBundle bundle = FakeAssetBundle()
      ..entries['my-asset.txt'] = AssetBundleEntry(
        DevFSFileContent(asset),
        kind: AssetKind.regular,
        transformers: const <AssetTransformerEntry>[
          AssetTransformerEntry(package: 'increment', args: <String>[]),
        ],
      );

    final Directory bundleDir = fileSystem.directory(
      getAssetBuildDirectory(Config.test(), fileSystem),
    );

    await writeBundle(
      bundleDir,
      bundle.entries,
      targetPlatform: TargetPlatform.tester,
      impellerStatus: ImpellerStatus.platformDefault,
      processManager: processManager,
      fileSystem: fileSystem,
      artifacts: artifacts,
      logger: BufferLogger.test(),
      projectDir: fileSystem.currentDirectory,
    );

    final File outputAssetFile = fileSystem.file('build/flutter_assets/my-asset.txt');
    expect(outputAssetFile, exists);
    expect(outputAssetFile.readAsBytesSync(), orderedEquals(<int>[2, 3, 4]));
  });

129 130 131 132
  testUsingContext('Handles build system failure', () {
    expect(
      () => BundleBuilder().build(
        platform: TargetPlatform.ios,
133
        buildInfo: BuildInfo.debug,
134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151
        project: FlutterProject.fromDirectoryTest(globals.fs.currentDirectory),
        mainPath: 'lib/main.dart',
        assetDirPath: 'example',
        depfilePath: 'example.d',
        buildSystem: TestBuildSystem.all(BuildResult(success: false))
      ),
      throwsToolExit()
    );
  }, overrides: <Type, Generator>{
    FileSystem: () => MemoryFileSystem.test(),
    ProcessManager: () => FakeProcessManager.any(),
  });

  testUsingContext('Passes correct defines to build system', () async {
    final FlutterProject project = FlutterProject.fromDirectoryTest(globals.fs.currentDirectory);
    final String mainPath = globals.fs.path.join('lib', 'main.dart');
    const String assetDirPath = 'example';
    const String depfilePath = 'example.d';
152
    Environment? env;
153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169
    final BuildSystem buildSystem = TestBuildSystem.all(
      BuildResult(success: true),
      (Target target, Environment environment) {
        env = environment;
        environment.outputDir.childFile('kernel_blob.bin').createSync(recursive: true);
        environment.outputDir.childFile('isolate_snapshot_data').createSync();
        environment.outputDir.childFile('vm_snapshot_data').createSync();
        environment.outputDir.childFile('LICENSE').createSync(recursive: true);
      }
    );

    await BundleBuilder().build(
      platform: TargetPlatform.ios,
      buildInfo: const BuildInfo(
        BuildMode.debug,
        null,
        trackWidgetCreation: true,
170
        frontendServerStarterPath: 'path/to/frontend_server_starter.dart',
171 172 173 174 175 176 177 178 179 180 181 182 183 184 185
        extraFrontEndOptions: <String>['test1', 'test2'],
        extraGenSnapshotOptions: <String>['test3', 'test4'],
        fileSystemRoots: <String>['test5', 'test6'],
        fileSystemScheme: 'test7',
        dartDefines: <String>['test8', 'test9'],
        treeShakeIcons: true,
      ),
      project: project,
      mainPath: mainPath,
      assetDirPath: assetDirPath,
      depfilePath: depfilePath,
      buildSystem: buildSystem
    );

    expect(env, isNotNull);
186 187 188 189
    expect(env!.defines[kBuildMode], 'debug');
    expect(env!.defines[kTargetPlatform], 'ios');
    expect(env!.defines[kTargetFile], mainPath);
    expect(env!.defines[kTrackWidgetCreation], 'true');
190
    expect(env!.defines[kFrontendServerStarterPath], 'path/to/frontend_server_starter.dart');
191 192 193 194 195 196 197
    expect(env!.defines[kExtraFrontEndOptions], 'test1,test2');
    expect(env!.defines[kExtraGenSnapshotOptions], 'test3,test4');
    expect(env!.defines[kFileSystemRoots], 'test5,test6');
    expect(env!.defines[kFileSystemScheme], 'test7');
    expect(env!.defines[kDartDefines], encodeDartDefines(<String>['test8', 'test9']));
    expect(env!.defines[kIconTreeShakerFlag], 'true');
    expect(env!.defines[kDeferredComponents], 'false');
198 199 200 201
  }, overrides: <Type, Generator>{
    FileSystem: () => MemoryFileSystem.test(),
    ProcessManager: () => FakeProcessManager.any(),
  });
202

203
  testWithoutContext('--enable-experiment is removed from getDefaultCachedKernelPath hash', () {
204 205 206 207 208 209
    final FileSystem fileSystem = MemoryFileSystem.test();
    final Config config = Config.test();

    expect(getDefaultCachedKernelPath(
      trackWidgetCreation: true,
      dartDefines: <String>[],
210
      extraFrontEndOptions: <String>['--enable-experiment=foo'],
211 212 213 214 215 216 217
      fileSystem: fileSystem,
      config: config,
    ), 'build/cache.dill.track.dill');

    expect(getDefaultCachedKernelPath(
      trackWidgetCreation: true,
      dartDefines: <String>['foo=bar'],
218
      extraFrontEndOptions: <String>['--enable-experiment=foo'],
219 220 221 222 223 224 225
      fileSystem: fileSystem,
      config: config,
    ), 'build/06ad47d8e64bd28de537b62ff85357c4.cache.dill.track.dill');

    expect(getDefaultCachedKernelPath(
      trackWidgetCreation: false,
      dartDefines: <String>[],
226
      extraFrontEndOptions: <String>['--enable-experiment=foo'],
227 228 229 230 231 232 233
      fileSystem: fileSystem,
      config: config,
    ), 'build/cache.dill');

    expect(getDefaultCachedKernelPath(
      trackWidgetCreation: true,
      dartDefines: <String>[],
234
      extraFrontEndOptions: <String>['--enable-experiment=foo', '--foo=bar'],
235 236 237 238
      fileSystem: fileSystem,
      config: config,
    ), 'build/95b595cca01caa5f0ca0a690339dd7f6.cache.dill.track.dill');
  });
239
}
240 241 242 243 244

class FakeAssetBundle extends Fake implements AssetBundle {
  @override
  final Map<String, AssetBundleEntry> entries = <String, AssetBundleEntry>{};
}