devfs_test.dart 9.59 KB
Newer Older
1 2 3 4
// Copyright 2016 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 6 7
import 'dart:async';
import 'dart:convert';

8 9
import 'package:file/file.dart';
import 'package:file/memory.dart';
10
import 'package:flutter_tools/src/base/io.dart';
11
import 'package:flutter_tools/src/base/file_system.dart';
12
import 'package:flutter_tools/src/devfs.dart';
13
import 'package:flutter_tools/src/vmservice.dart';
14
import 'package:json_rpc_2/json_rpc_2.dart' as rpc;
15

16
import 'src/common.dart';
17 18 19 20
import 'src/context.dart';
import 'src/mocks.dart';

void main() {
21 22
  FileSystem fs;
  String filePath;
23 24 25
  Directory tempDir;
  String basePath;
  DevFS devFS;
26

27
  setUpAll(() {
28
    fs = MemoryFileSystem();
29 30 31
    filePath = fs.path.join('lib', 'foo.txt');
  });

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

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

69
      final DateTime fiveSecondsAgo = DateTime.now().subtract(const Duration(seconds:5));
70 71 72 73
      expect(content.isModifiedAfter(fiveSecondsAgo), isTrue);
      expect(content.isModifiedAfter(fiveSecondsAgo), isTrue);
      expect(content.isModifiedAfter(null), isTrue);

74
      file.writeAsBytesSync(<int>[2, 3, 4], flush: true);
75 76 77 78 79 80 81 82 83 84 85 86 87 88 89
      expect(content.fileDependencies, <String>[filePath]);
      expect(content.isModified, isTrue);
      expect(content.isModified, isFalse);
      expect(await content.contentsAsBytes(), <int>[2, 3, 4]);
      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,
    });
90 91 92 93
  });

  group('devfs remote', () {
    MockVMService vmService;
94
    final MockResidentCompiler residentCompiler = MockResidentCompiler();
95 96

    setUpAll(() async {
97
      tempDir = _newTempDir(fs);
98
      basePath = tempDir.path;
99
      vmService = MockVMService();
100 101 102 103 104
      await vmService.setUp();
    });
    tearDownAll(() async {
      await vmService.tearDown();
      _cleanupTempDirs();
105
    });
106 107 108

    testUsingContext('create dev file system', () async {
      // simulate workspace
109
      final File file = fs.file(fs.path.join(basePath, filePath));
110 111 112 113
      await file.parent.create(recursive: true);
      file.writeAsBytesSync(<int>[1, 2, 3]);

      // simulate package
114
      await _createPackage(fs, 'somepkg', 'somefile.txt');
115

116
      devFS = DevFS(vmService, 'test', tempDir);
117 118 119 120
      await devFS.create();
      vmService.expectMessages(<String>['create test']);
      expect(devFS.assetPathsToEvict, isEmpty);

121
      final UpdateFSReport report = await devFS.update(
122 123 124
        mainPath: 'lib/foo.txt',
        generator: residentCompiler,
        pathToReload: 'lib/foo.txt.dill',
125
        trackWidgetCreation: false,
126
        invalidatedFiles: <Uri>[],
127
      );
128
      vmService.expectMessages(<String>[
129
        'writeFile test lib/foo.txt.dill',
130 131
      ]);
      expect(devFS.assetPathsToEvict, isEmpty);
132 133
      expect(report.syncedBytes, 22);
      expect(report.success, true);
134 135
    }, overrides: <Type, Generator>{
      FileSystem: () => fs,
Dan Rubel's avatar
Dan Rubel committed
136
    });
137 138

    testUsingContext('delete dev file system', () async {
Dan Rubel's avatar
Dan Rubel committed
139
      expect(vmService.messages, isEmpty, reason: 'prior test timeout');
140
      await devFS.destroy();
141 142 143 144 145 146 147 148 149 150 151 152 153 154 155
      vmService.expectMessages(<String>['destroy test']);
      expect(devFS.assetPathsToEvict, isEmpty);
    }, overrides: <Type, Generator>{
      FileSystem: () => fs,
    });

    testUsingContext('cleanup preexisting file system', () async {
      // simulate workspace
      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');

156
      devFS = DevFS(vmService, 'test', tempDir);
157 158 159 160 161 162 163 164 165 166 167 168
      await devFS.create();
      vmService.expectMessages(<String>['create test']);
      expect(devFS.assetPathsToEvict, isEmpty);

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

      // Really destroy.
      await devFS.destroy();
      vmService.expectMessages(<String>['destroy test']);
169
      expect(devFS.assetPathsToEvict, isEmpty);
170 171
    }, overrides: <Type, Generator>{
      FileSystem: () => fs,
172
    });
173
  });
174 175 176 177
}

class MockVMService extends BasicMock implements VMService {
  MockVMService() {
178
    _vm = MockVM(this);
179 180
  }

181 182 183 184
  Uri _httpAddress;
  HttpServer _server;
  MockVM _vm;

185 186 187 188 189 190
  @override
  Uri get httpAddress => _httpAddress;

  @override
  VM get vm => _vm;

191
  Future<void> setUp() async {
192
    try {
193
      _server = await HttpServer.bind(InternetAddress.loopbackIPv6, 0);
194 195 196
      _httpAddress = Uri.parse('http://[::1]:${_server.port}');
    } on SocketException {
      // Fall back to IPv4 if the host doesn't support binding to IPv6 localhost
197
      _server = await HttpServer.bind(InternetAddress.loopbackIPv4, 0);
198 199
      _httpAddress = Uri.parse('http://127.0.0.1:${_server.port}');
    }
200
    _server.listen((HttpRequest request) {
201
      final String fsName = request.headers.value('dev_fs_name');
202
      final String devicePath = utf8.decode(base64.decode(request.headers.value('dev_fs_uri_b64')));
203
      messages.add('writeFile $fsName $devicePath');
204
      request.drain<List<int>>().then<void>((List<int> value) {
205 206 207 208 209 210 211
        request.response
          ..write('Got it')
          ..close();
      });
    });
  }

212
  Future<void> tearDown() async {
213
    await _server?.close();
214 215 216 217 218 219 220
  }

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

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

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

  static const int kFileSystemAlreadyExists = 1001;
228 229 230 231

  @override
  Future<Map<String, dynamic>> createDevFS(String fsName) async {
    _service.messages.add('create $fsName');
232
    if (_devFSExists) {
233
      throw rpc.RpcException(kFileSystemAlreadyExists, 'File system already exists');
234 235
    }
    _devFSExists = true;
236 237 238
    return <String, dynamic>{'uri': '$_baseUri'};
  }

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

246
  @override
247 248
  Future<Map<String, dynamic>> invokeRpcRaw(
    String method, {
249
    Map<String, dynamic> params = const <String, dynamic>{},
250
    Duration timeout,
251
    bool timeoutFatal = true,
252
  }) async {
253 254 255 256 257 258 259 260 261 262
    _service.messages.add('$method $params');
    return <String, dynamic>{'success': true};
  }

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


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

265
Directory _newTempDir(FileSystem fs) {
266
  final Directory tempDir = fs.systemTempDirectory.createTempSync('flutter_devfs${_tempDirs.length}_test.');
267 268 269 270 271
  _tempDirs.add(tempDir);
  return tempDir;
}

void _cleanupTempDirs() {
272 273
  while (_tempDirs.isNotEmpty)
    tryToDelete(_tempDirs.removeLast());
274 275
}

276
Future<void> _createPackage(FileSystem fs, String pkgName, String pkgFileName, { bool doubleSlash = false }) async {
277
  final Directory pkgTempDir = _newTempDir(fs);
278 279 280
  String pkgFilePath = fs.path.join(pkgTempDir.path, pkgName, 'lib', pkgFileName);
  if (doubleSlash) {
    // Force two separators into the path.
281
    final String doubleSlash = fs.path.separator + fs.path.separator;
282
    pkgFilePath = pkgTempDir.path + doubleSlash + fs.path.join(pkgName, 'lib', pkgFileName);
283 284
  }
  final File pkgFile = fs.file(pkgFilePath);
285 286
  await pkgFile.parent.create(recursive: true);
  pkgFile.writeAsBytesSync(<int>[11, 12, 13]);
287
  _packages[pkgName] = fs.path.toUri(pkgFile.parent.path);
288
  final StringBuffer sb = StringBuffer();
289 290
  _packages.forEach((String pkgName, Uri pkgUri) {
    sb.writeln('$pkgName:$pkgUri');
291
  });
292
  fs.file(fs.path.join(_tempDirs[0].path, '.packages')).writeAsStringSync(sb.toString());
293
}
294