cold_test.dart 8.94 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:file/memory.dart';
6
import 'package:flutter_tools/src/base/file_system.dart';
7
import 'package:flutter_tools/src/base/io.dart';
8
import 'package:flutter_tools/src/base/platform.dart';
9
import 'package:flutter_tools/src/build_info.dart';
10
import 'package:flutter_tools/src/build_system/targets/shader_compiler.dart';
11
import 'package:flutter_tools/src/compile.dart';
12
import 'package:flutter_tools/src/devfs.dart';
13
import 'package:flutter_tools/src/device.dart';
14
import 'package:flutter_tools/src/project.dart';
15 16
import 'package:flutter_tools/src/resident_runner.dart';
import 'package:flutter_tools/src/run_cold.dart';
17
import 'package:flutter_tools/src/tracing.dart';
18
import 'package:flutter_tools/src/vmservice.dart';
19
import 'package:test/fake.dart';
20
import 'package:vm_service/vm_service.dart';
21 22 23 24 25

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

void main() {
nt4f04uNd's avatar
nt4f04uNd committed
26
  testUsingContext('Exits with code 2 when HttpException is thrown '
27
    'during VM service connection', () async {
28
    final FakeResidentCompiler residentCompiler = FakeResidentCompiler();
29 30 31
    final FakeDevice device = FakeDevice()
      ..supportsHotReload = true
      ..supportsHotRestart = false;
32 33 34

    final List<FlutterDevice> devices = <FlutterDevice>[
      TestFlutterDevice(
35
        device: device,
36 37 38 39 40 41 42 43
        generator: residentCompiler,
        exception: const HttpException('Connection closed before full header was received, '
            'uri = http://127.0.0.1:63394/5ZmLv8A59xY=/ws'),
      ),
    ];

    final int exitCode = await ColdRunner(devices,
      debuggingOptions: DebuggingOptions.enabled(BuildInfo.debug),
44
      target: 'main.dart',
45
    ).attach();
46
    expect(exitCode, 2);
47
  });
48 49 50

  group('cleanupAtFinish()', () {
    testUsingContext('disposes each device', () async {
51 52 53 54
      final FakeDevice device1 = FakeDevice();
      final FakeDevice device2 = FakeDevice();
      final FakeFlutterDevice flutterDevice1 = FakeFlutterDevice(device1);
      final FakeFlutterDevice flutterDevice2 = FakeFlutterDevice(device2);
55

56
      final List<FlutterDevice> devices = <FlutterDevice>[flutterDevice1, flutterDevice2];
57 58 59

      await ColdRunner(devices,
        debuggingOptions: DebuggingOptions.enabled(BuildInfo.debug),
60
        target: 'main.dart',
61 62
      ).cleanupAtFinish();

63 64 65 66
      expect(flutterDevice1.stopEchoingDeviceLogCount, 1);
      expect(flutterDevice2.stopEchoingDeviceLogCount, 1);
      expect(device2.wasDisposed, true);
      expect(device1.wasDisposed, true);
67 68 69 70
    });
  });

  group('cold run', () {
71 72 73
    late MemoryFileSystem memoryFileSystem;
    late FakePlatform fakePlatform;

74 75 76 77 78
    setUp(() {
      memoryFileSystem = MemoryFileSystem();
      fakePlatform = FakePlatform(environment: <String, String>{});
    });

79
    testUsingContext('calls runCold on attached device', () async {
80 81 82 83
      final FakeDevice device = FakeDevice();
      final FakeFlutterDevice flutterDevice = FakeFlutterDevice(device)
        ..runColdCode = 1;
      final List<FlutterDevice> devices = <FlutterDevice>[flutterDevice];
84
      final File applicationBinary = MemoryFileSystem.test().file('binary');
85 86 87 88
      final int result = await ColdRunner(
        devices,
        applicationBinary: applicationBinary,
        debuggingOptions: DebuggingOptions.enabled(BuildInfo.debug),
89
        target: 'main.dart',
90
      ).run();
91

92 93
      expect(result, 1);
    });
94 95

    testUsingContext('with traceStartup, no env variable', () async {
96 97 98
      final FakeDevice device = FakeDevice();
      final FakeFlutterDevice flutterDevice = FakeFlutterDevice(device);
      final List<FlutterDevice> devices = <FlutterDevice>[flutterDevice];
99 100 101 102 103 104 105
      final File applicationBinary = MemoryFileSystem.test().file('binary');
      final int result = await ColdRunner(
        devices,
        applicationBinary: applicationBinary,
        debuggingOptions: DebuggingOptions.disabled(BuildInfo.debug),
        target: 'main.dart',
        traceStartup: true,
106
      ).run();
107 108 109 110 111 112 113 114 115 116 117 118

      expect(result, 0);
      expect(memoryFileSystem.directory(getBuildDirectory()).childFile('start_up_info.json').existsSync(), true);
    }, overrides: <Type, Generator>{
      FileSystem: () => memoryFileSystem,
      ProcessManager: () => FakeProcessManager.any(),
      Platform: () => fakePlatform,
    });

    testUsingContext('with traceStartup, env variable', () async {
      fakePlatform.environment[kFlutterTestOutputsDirEnvName] = 'test_output_dir';

119 120 121
      final FakeDevice device = FakeDevice();
      final FakeFlutterDevice flutterDevice = FakeFlutterDevice(device);
      final List<FlutterDevice> devices = <FlutterDevice>[flutterDevice];
122 123 124 125 126 127 128
      final File applicationBinary = MemoryFileSystem.test().file('binary');
      final int result = await ColdRunner(
        devices,
        applicationBinary: applicationBinary,
        debuggingOptions: DebuggingOptions.disabled(BuildInfo.debug),
        target: 'main.dart',
        traceStartup: true,
129
      ).run();
130 131 132 133 134 135 136 137

      expect(result, 0);
      expect(memoryFileSystem.directory('test_output_dir').childFile('start_up_info.json').existsSync(), true);
    }, overrides: <Type, Generator>{
      FileSystem: () => memoryFileSystem,
      ProcessManager: () => FakeProcessManager.any(),
      Platform: () => fakePlatform,
    });
138
  });
139 140
}

141 142 143 144
class FakeFlutterDevice extends Fake implements FlutterDevice {
  FakeFlutterDevice(this.device);

  @override
145
  Stream<Uri> get vmServiceUris => const Stream<Uri>.empty();
146 147 148 149

  @override
  final Device device;

150 151 152 153 154 155 156 157 158
  int stopEchoingDeviceLogCount = 0;

  @override
  Future<void> stopEchoingDeviceLog() async {
    stopEchoingDeviceLogCount += 1;
  }

  @override
  FlutterVmService get vmService => FakeFlutterVmService();
159 160 161 162

  int runColdCode = 0;

  @override
163
  Future<int> runCold({ColdRunner? coldRunner, String? route}) async {
164 165 166 167 168
    return runColdCode;
  }

  @override
  Future<void> initLogReader() async { }
169
}
170 171 172 173 174 175

class FakeDevice extends Fake implements Device {
  @override
  bool isSupported() => true;

  @override
176
  bool supportsHotReload = false;
177 178

  @override
179
  bool supportsHotRestart = false;
180 181 182 183 184 185 186 187 188 189 190 191 192 193 194

  @override
  Future<String> get sdkNameAndVersion async => 'Android 10';

  @override
  String get name => 'test';

  @override
  Future<TargetPlatform> get targetPlatform async => TargetPlatform.tester;

  bool wasDisposed = false;

  @override
  Future<void> dispose() async {
    wasDisposed = true;
195 196 197 198 199
  }
}

class TestFlutterDevice extends FlutterDevice {
  TestFlutterDevice({
200 201 202
    required Device device,
    required this.exception,
    required ResidentCompiler generator,
203
  })  : super(device, buildInfo: BuildInfo.debug, generator: generator, developmentShaderCompiler: const FakeShaderCompiler());
204 205 206 207 208 209

  /// The exception to throw when the connect method is called.
  final Exception exception;

  @override
  Future<void> connect({
210 211 212 213
    ReloadSources? reloadSources,
    Restart? restart,
    CompileExpression? compileExpression,
    GetSkSLMethod? getSkSLMethod,
214
    FlutterProject? flutterProject,
215
    PrintStructuredErrorLogMethod? printStructuredErrorLogMethod,
216
    bool enableDds = true,
217
    bool cacheStartupProfile = false,
218
    bool disableServiceAuthCodes = false,
219 220 221
    int? hostVmServicePort,
    int? ddsPort,
    bool? ipv6 = false,
222
    bool allowExistingDdsInstance = false,
223 224 225 226
  }) async {
    throw exception;
  }
}
227

228
class FakeResidentCompiler extends Fake implements ResidentCompiler { }
229 230 231 232 233 234 235 236 237 238 239

class FakeFlutterVmService extends Fake implements FlutterVmService {
  @override
  VmService get service => FakeVmService();

  @override
  Future<List<FlutterView>> getFlutterViews({bool returnEarly = false, Duration delay = const Duration(milliseconds: 50)}) async {
    return <FlutterView>[];
  }

  @override
240
  Future<bool> flutterAlreadyPaintedFirstUsefulFrame({String? isolateId}) async => true;
241 242

  @override
243
  Future<Response?> getTimeline() async {
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
    return Response.parse(<String, dynamic>{
      'traceEvents': <dynamic>[
        <String, dynamic>{
          'name': kFlutterEngineMainEnterEventName,
          'ts': 123,
        },
        <String, dynamic>{
          'name': kFirstFrameBuiltEventName,
          'ts': 124,
        },
        <String, dynamic>{
          'name': kFirstFrameRasterizedEventName,
          'ts': 124,
        },
      ],
    });
  }

  @override
  Future<void> setTimelineFlags(List<String> recordedStreams) async {}
}

class FakeVmService extends Fake implements VmService {
  @override
  Future<Success> streamListen(String streamId) async => Success();

  @override
  Stream<Event> get onExtensionEvent {
    return Stream<Event>.fromIterable(<Event>[
      Event(kind: 'Extension', extensionKind: 'Flutter.FirstFrame', timestamp: 1),
    ]);
  }
}
277 278 279 280 281

class FakeShaderCompiler implements DevelopmentShaderCompiler {
  const FakeShaderCompiler();

  @override
282 283 284 285
  void configureCompiler(
    TargetPlatform? platform, {
    required ImpellerStatus impellerStatus,
  }) { }
286 287 288 289 290 291

  @override
  Future<DevFSContent> recompileShader(DevFSContent inputShader) {
    throw UnimplementedError();
  }
}