devfs_test.dart 16.4 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 6
import 'dart:async';
import 'dart:convert';
7
import 'dart:io'; // ignore: dart_io_import
8

9 10
import 'package:file/file.dart';
import 'package:file/memory.dart';
11
import 'package:flutter_tools/src/base/file_system.dart';
12
import 'package:flutter_tools/src/base/io.dart';
13
import 'package:flutter_tools/src/base/net.dart';
14
import 'package:flutter_tools/src/base/os.dart';
15
import 'package:flutter_tools/src/compile.dart';
16
import 'package:flutter_tools/src/devfs.dart';
17
import 'package:flutter_tools/src/vmservice.dart';
18
import 'package:mockito/mockito.dart';
19
import 'package:vm_service/vm_service.dart' as vm_service;
20

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

void main() {
26
  FileSystem fs;
27 28 29 30 31
  String filePath;
  Directory tempDir;
  String basePath;

  setUpAll(() {
Dan Field's avatar
Dan Field committed
32
    fs = MemoryFileSystem.test();
33
    filePath = fs.path.join('lib', 'foo.txt');
34 35
  });

36 37
  group('DevFSContent', () {
    test('bytes', () {
38
      final DevFSByteContent content = DevFSByteContent(<int>[4, 5, 6]);
39 40 41 42 43 44 45 46 47
      expect(content.bytes, orderedEquals(<int>[4, 5, 6]));
      expect(content.isModified, isTrue);
      expect(content.isModified, isFalse);
      content.bytes = <int>[7, 8, 9, 2];
      expect(content.bytes, orderedEquals(<int>[7, 8, 9, 2]));
      expect(content.isModified, isTrue);
      expect(content.isModified, isFalse);
    });
    test('string', () {
48
      final DevFSStringContent content = DevFSStringContent('some string');
49
      expect(content.string, 'some string');
50
      expect(content.bytes, orderedEquals(utf8.encode('some string')));
51 52 53 54
      expect(content.isModified, isTrue);
      expect(content.isModified, isFalse);
      content.string = 'another string';
      expect(content.string, 'another string');
55
      expect(content.bytes, orderedEquals(utf8.encode('another string')));
56 57
      expect(content.isModified, isTrue);
      expect(content.isModified, isFalse);
58
      content.bytes = utf8.encode('foo bar');
59
      expect(content.string, 'foo bar');
60
      expect(content.bytes, orderedEquals(utf8.encode('foo bar')));
61 62 63
      expect(content.isModified, isTrue);
      expect(content.isModified, isFalse);
    });
64
    testUsingContext('file', () async {
65
      final File file = fs.file(filePath);
66 67 68 69 70
      final DevFSFileContent content = DevFSFileContent(file);
      expect(content.isModified, isFalse);
      expect(content.isModified, isFalse);

      file.parent.createSync(recursive: true);
71
      file.writeAsBytesSync(<int>[1, 2, 3], flush: true);
72

Dan Field's avatar
Dan Field committed
73
      final DateTime fiveSecondsAgo = file.statSync().modified.subtract(const Duration(seconds: 5));
74 75 76 77
      expect(content.isModifiedAfter(fiveSecondsAgo), isTrue);
      expect(content.isModifiedAfter(fiveSecondsAgo), isTrue);
      expect(content.isModifiedAfter(null), isTrue);

78
      file.writeAsBytesSync(<int>[2, 3, 4], flush: true);
79
      expect(content.fileDependencies, <String>[filePath]);
80 81
      expect(content.isModified, isTrue);
      expect(content.isModified, isFalse);
82
      expect(await content.contentsAsBytes(), <int>[2, 3, 4]);
83 84 85 86 87 88 89 90 91 92
      updateFileModificationTime(file.path, fiveSecondsAgo, 0);
      expect(content.isModified, isFalse);
      expect(content.isModified, isFalse);

      file.deleteSync();
      expect(content.isModified, isTrue);
      expect(content.isModified, isFalse);
      expect(content.isModified, isFalse);
    }, overrides: <Type, Generator>{
      FileSystem: () => fs,
93
      ProcessManager: () => FakeProcessManager.any(),
94
    }, skip: Platform.isWindows); // TODO(jonahwilliams): fix or disable this functionality.
95 96
  });

97 98 99
  group('mocked http client', () {
    HttpOverrides savedHttpOverrides;
    HttpClient httpClient;
100
    OperatingSystemUtils osUtils;
101 102 103 104 105 106 107

    setUpAll(() {
      tempDir = _newTempDir(fs);
      basePath = tempDir.path;
      savedHttpOverrides = HttpOverrides.current;
      httpClient = MockOddlyFailingHttpClient();
      HttpOverrides.global = MyHttpOverrides(httpClient);
108
      osUtils = MockOperatingSystemUtils();
109 110 111 112 113 114
    });

    tearDownAll(() async {
      HttpOverrides.global = savedHttpOverrides;
    });

115 116 117 118 119 120 121 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
    final List<dynamic> exceptions = <dynamic>[
      Exception('Connection resert by peer'),
      const OSError('Connection reset by peer'),
    ];

    for (final dynamic exception in exceptions) {
      testUsingContext('retry uploads when failure: $exception', () async {
        final File file = fs.file(fs.path.join(basePath, filePath));
        await file.parent.create(recursive: true);
        file.writeAsBytesSync(<int>[1, 2, 3]);
        // simulate package
        await _createPackage(fs, 'somepkg', 'somefile.txt');

        final RealMockVMService vmService = RealMockVMService();
        final RealMockVM vm = RealMockVM();
        final Map<String, dynamic> response =  <String, dynamic>{ 'uri': 'file://abc' };
        when(vm.createDevFS(any)).thenAnswer((Invocation invocation) {
          return Future<Map<String, dynamic>>.value(response);
        });
        when(vmService.vm).thenReturn(vm);

        reset(httpClient);

        final MockHttpClientRequest httpRequest = MockHttpClientRequest();
        when(httpRequest.headers).thenReturn(MockHttpHeaders());
        when(httpClient.putUrl(any)).thenAnswer((Invocation invocation) {
          return Future<HttpClientRequest>.value(httpRequest);
        });
        final MockHttpClientResponse httpClientResponse = MockHttpClientResponse();
        int nRequest = 0;
        const int kFailedAttempts = 5;
        when(httpRequest.close()).thenAnswer((Invocation invocation) {
          if (nRequest++ < kFailedAttempts) {
            throw exception;
          }
          return Future<HttpClientResponse>.value(httpClientResponse);
        });

153 154 155 156 157 158
        final DevFS devFS = DevFS(
          vmService,
          'test',
          tempDir,
          osUtils: osUtils,
        );
159 160 161 162 163 164 165 166 167 168 169 170 171 172 173
        await devFS.create();

        final MockResidentCompiler residentCompiler = MockResidentCompiler();
        final UpdateFSReport report = await devFS.update(
          mainPath: 'lib/foo.txt',
          generator: residentCompiler,
          pathToReload: 'lib/foo.txt.dill',
          trackWidgetCreation: false,
          invalidatedFiles: <Uri>[],
        );

        expect(report.syncedBytes, 22);
        expect(report.success, isTrue);
        verify(httpClient.putUrl(any)).called(kFailedAttempts + 1);
        verify(httpRequest.close()).called(kFailedAttempts + 1);
174
        verify(osUtils.gzipLevel1Stream(any)).called(kFailedAttempts + 1);
175 176 177 178
      }, overrides: <Type, Generator>{
        FileSystem: () => fs,
        HttpClientFactory: () => () => httpClient,
        ProcessManager: () => FakeProcessManager.any(),
179
      });
180
    }
181 182
  });

183
  group('devfs remote', () {
184 185
    MockVMService vmService;
    final MockResidentCompiler residentCompiler = MockResidentCompiler();
186
    DevFS devFS;
187 188 189 190 191 192 193

    setUpAll(() async {
      tempDir = _newTempDir(fs);
      basePath = tempDir.path;
      vmService = MockVMService();
      await vmService.setUp();
    });
194

195 196
    setUp(() {
      vmService.resetState();
197 198 199 200 201 202
      devFS = DevFS(
        vmService,
        'test',
        tempDir,
        osUtils: FakeOperatingSystemUtils(),
      );
203 204
    });

205 206 207
    tearDownAll(() async {
      await vmService.tearDown();
      _cleanupTempDirs();
208
    });
209 210 211

    testUsingContext('create dev file system', () async {
      // simulate workspace
212
      final File file = fs.file(fs.path.join(basePath, filePath));
213 214 215 216
      await file.parent.create(recursive: true);
      file.writeAsBytesSync(<int>[1, 2, 3]);

      // simulate package
217
      await _createPackage(fs, 'somepkg', 'somefile.txt');
218

219 220
      await devFS.create();
      vmService.expectMessages(<String>['create test']);
221 222
      expect(devFS.assetPathsToEvict, isEmpty);

223
      final UpdateFSReport report = await devFS.update(
224 225 226
        mainPath: 'lib/foo.txt',
        generator: residentCompiler,
        pathToReload: 'lib/foo.txt.dill',
227
        trackWidgetCreation: false,
228
        invalidatedFiles: <Uri>[],
229
      );
230 231 232
      vmService.expectMessages(<String>[
        'writeFile test lib/foo.txt.dill',
      ]);
233
      expect(devFS.assetPathsToEvict, isEmpty);
234 235
      expect(report.syncedBytes, 22);
      expect(report.success, true);
236 237
    }, overrides: <Type, Generator>{
      FileSystem: () => fs,
238
      HttpClient: () => () => HttpClient(),
239
      ProcessManager: () => FakeProcessManager.any(),
Dan Rubel's avatar
Dan Rubel committed
240
    });
241 242

    testUsingContext('delete dev file system', () async {
243
      expect(vmService.messages, isEmpty, reason: 'prior test timeout');
244
      await devFS.destroy();
245
      vmService.expectMessages(<String>['destroy test']);
246 247 248
      expect(devFS.assetPathsToEvict, isEmpty);
    }, overrides: <Type, Generator>{
      FileSystem: () => fs,
249
      ProcessManager: () => FakeProcessManager.any(),
250 251 252 253
    });

    testUsingContext('cleanup preexisting file system', () async {
      // simulate workspace
254
      final File file = fs.file(fs.path.join(basePath, filePath));
255 256 257 258 259 260
      await file.parent.create(recursive: true);
      file.writeAsBytesSync(<int>[1, 2, 3]);

      // simulate package
      await _createPackage(fs, 'somepkg', 'somefile.txt');
      await devFS.create();
261
      vmService.expectMessages(<String>['create test']);
262 263 264 265
      expect(devFS.assetPathsToEvict, isEmpty);

      // Try to create again.
      await devFS.create();
266
      vmService.expectMessages(<String>['create test', 'destroy test', 'create test']);
267 268 269 270
      expect(devFS.assetPathsToEvict, isEmpty);

      // Really destroy.
      await devFS.destroy();
271
      vmService.expectMessages(<String>['destroy test']);
272
      expect(devFS.assetPathsToEvict, isEmpty);
273 274
    }, overrides: <Type, Generator>{
      FileSystem: () => fs,
275
      ProcessManager: () => FakeProcessManager.any(),
276
    });
277 278 279

    testUsingContext('reports unsuccessful compile when errors are returned', () async {
      await devFS.create();
280
      final DateTime previousCompile = devFS.lastCompiled;
281 282 283 284 285 286

      final RealMockResidentCompiler residentCompiler = RealMockResidentCompiler();
      when(residentCompiler.recompile(
        any,
        any,
        outputPath: anyNamed('outputPath'),
287
        packagesFilePath: anyNamed('packagesFilePath'),
288 289 290 291 292 293 294 295 296 297 298 299 300
      )).thenAnswer((Invocation invocation) {
        return Future<CompilerOutput>.value(const CompilerOutput('example', 2, <Uri>[]));
      });

      final UpdateFSReport report = await devFS.update(
        mainPath: 'lib/foo.txt',
        generator: residentCompiler,
        pathToReload: 'lib/foo.txt.dill',
        trackWidgetCreation: false,
        invalidatedFiles: <Uri>[],
      );

      expect(report.success, false);
301 302 303
      expect(devFS.lastCompiled, previousCompile);
    }, overrides: <Type, Generator>{
      FileSystem: () => fs,
304
      ProcessManager: () => FakeProcessManager.any(),
305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320
    });

    testUsingContext('correctly updates last compiled time when compilation does not fail', () async {
      // simulate package
      final File sourceFile = await _createPackage(fs, 'somepkg', 'main.dart');

      await devFS.create();
      final DateTime previousCompile = devFS.lastCompiled;

      final RealMockResidentCompiler residentCompiler = RealMockResidentCompiler();
      when(residentCompiler.recompile(
        any,
        any,
        outputPath: anyNamed('outputPath'),
        packagesFilePath: anyNamed('packagesFilePath'),
      )).thenAnswer((Invocation invocation) {
321
        fs.file('example').createSync();
322 323 324 325 326 327 328 329 330 331 332 333 334
        return Future<CompilerOutput>.value(CompilerOutput('example', 0, <Uri>[sourceFile.uri]));
      });

      final UpdateFSReport report = await devFS.update(
        mainPath: 'lib/main.dart',
        generator: residentCompiler,
        pathToReload: 'lib/foo.txt.dill',
        trackWidgetCreation: false,
        invalidatedFiles: <Uri>[],
      );

      expect(report.success, true);
      expect(devFS.lastCompiled, isNot(previousCompile));
335 336
    }, overrides: <Type, Generator>{
      FileSystem: () => fs,
337
      HttpClient: () => () => HttpClient(),
338
      ProcessManager: () => FakeProcessManager.any(),
339
    });
340
  });
341 342
}

343 344 345 346
class MockVMService extends BasicMock implements VMService {
  MockVMService() {
    _vm = MockVM(this);
  }
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
  Uri _httpAddress;
  HttpServer _server;
  MockVM _vm;

  @override
  Uri get httpAddress => _httpAddress;

  @override
  VM get vm => _vm;

  Future<void> setUp() async {
    try {
      _server = await HttpServer.bind(InternetAddress.loopbackIPv6, 0);
      _httpAddress = Uri.parse('http://[::1]:${_server.port}');
    } on SocketException {
      // Fall back to IPv4 if the host doesn't support binding to IPv6 localhost
      _server = await HttpServer.bind(InternetAddress.loopbackIPv4, 0);
      _httpAddress = Uri.parse('http://127.0.0.1:${_server.port}');
    }
    _server.listen((HttpRequest request) {
      final String fsName = request.headers.value('dev_fs_name');
      final String devicePath = utf8.decode(base64.decode(request.headers.value('dev_fs_uri_b64')));
      messages.add('writeFile $fsName $devicePath');
      request.drain<List<int>>().then<void>((List<int> value) {
        request.response
          ..write('Got it')
          ..close();
      });
    });
  }
378

379 380 381
  Future<void> tearDown() async {
    await _server?.close();
  }
382

383 384 385 386 387
  void resetState() {
    _vm = MockVM(this);
    messages.clear();
  }

388 389
  @override
  dynamic noSuchMethod(Invocation invocation) => super.noSuchMethod(invocation);
390

391 392 393 394 395 396 397 398 399 400 401 402 403 404 405
}

class MockVM implements VM {
  MockVM(this._service);

  final MockVMService _service;
  final Uri _baseUri = Uri.parse('file:///tmp/devfs/test');
  bool _devFSExists = false;

  static const int kFileSystemAlreadyExists = 1001;

  @override
  Future<Map<String, dynamic>> createDevFS(String fsName) async {
    _service.messages.add('create $fsName');
    if (_devFSExists) {
406
      throw vm_service.RPCError('File system already exists', kFileSystemAlreadyExists, '');
407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424
    }
    _devFSExists = true;
    return <String, dynamic>{'uri': '$_baseUri'};
  }

  @override
  Future<Map<String, dynamic>> deleteDevFS(String fsName) async {
    _service.messages.add('destroy $fsName');
    _devFSExists = false;
    return <String, dynamic>{'type': 'Success'};
  }

  @override
  Future<Map<String, dynamic>> invokeRpcRaw(
    String method, {
    Map<String, dynamic> params = const <String, dynamic>{},
    Duration timeout,
    bool timeoutFatal = true,
425
    bool truncateLogs = true,
426 427 428 429 430 431 432 433 434
  }) async {
    _service.messages.add('$method $params');
    return <String, dynamic>{'success': true};
  }

  @override
  dynamic noSuchMethod(Invocation invocation) => super.noSuchMethod(invocation);
}

435
class RealMockResidentCompiler extends Mock implements ResidentCompiler {}
436 437

final List<Directory> _tempDirs = <Directory>[];
438
final Map <String, Uri> _packages = <String, Uri>{};
439

440
Directory _newTempDir(FileSystem fs) {
441
  final Directory tempDir = fs.systemTempDirectory.createTempSync('flutter_devfs${_tempDirs.length}_test.');
442 443 444 445 446
  _tempDirs.add(tempDir);
  return tempDir;
}

void _cleanupTempDirs() {
447
  while (_tempDirs.isNotEmpty) {
448
    tryToDelete(_tempDirs.removeLast());
449
  }
450
}
451

452
Future<File> _createPackage(FileSystem fs, String pkgName, String pkgFileName, { bool doubleSlash = false }) async {
453
  final Directory pkgTempDir = _newTempDir(fs);
454
  String pkgFilePath = fs.path.join(pkgTempDir.path, pkgName, 'lib', pkgFileName);
455 456
  if (doubleSlash) {
    // Force two separators into the path.
457 458
    final String doubleSlash = fs.path.separator + fs.path.separator;
    pkgFilePath = pkgTempDir.path + doubleSlash + fs.path.join(pkgName, 'lib', pkgFileName);
459
  }
460
  final File pkgFile = fs.file(pkgFilePath);
461 462
  await pkgFile.parent.create(recursive: true);
  pkgFile.writeAsBytesSync(<int>[11, 12, 13]);
463
  _packages[pkgName] = fs.path.toUri(pkgFile.parent.path);
464
  final StringBuffer sb = StringBuffer();
465 466
  _packages.forEach((String pkgName, Uri pkgUri) {
    sb.writeln('$pkgName:$pkgUri');
467
  });
468
  return fs.file(fs.path.join(_tempDirs[0].path, '.packages'))
469
    ..writeAsStringSync(sb.toString());
470
}
471

472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492
class RealMockVM extends Mock implements VM {

}

class RealMockVMService extends Mock implements VMService {

}

class MyHttpOverrides extends HttpOverrides {
  MyHttpOverrides(this._httpClient);
  @override
  HttpClient createHttpClient(SecurityContext context) {
    return _httpClient;
  }

  final HttpClient _httpClient;
}

class MockOddlyFailingHttpClient extends Mock implements HttpClient {}
class MockHttpClientRequest extends Mock implements HttpClientRequest {}
class MockHttpHeaders extends Mock implements HttpHeaders {}
493
class MockHttpClientResponse extends Mock implements HttpClientResponse {}
494
class MockOperatingSystemUtils extends Mock implements OperatingSystemUtils {}