devfs_web_test.dart 41.3 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
// @dart = 2.8

7
import 'dart:io' hide Directory, File;
8

9
import 'package:flutter_tools/src/artifacts.dart';
10
import 'package:flutter_tools/src/base/file_system.dart';
11
import 'package:flutter_tools/src/base/platform.dart';
12
import 'package:flutter_tools/src/build_info.dart';
13
import 'package:flutter_tools/src/build_system/targets/web.dart';
14
import 'package:flutter_tools/src/compile.dart';
15
import 'package:flutter_tools/src/convert.dart';
16
import 'package:flutter_tools/src/globals.dart' as globals;
17
import 'package:flutter_tools/src/isolated/devfs_web.dart';
18
import 'package:flutter_tools/src/web/compile.dart';
19
import 'package:package_config/package_config.dart';
20
import 'package:shelf/shelf.dart';
21
import 'package:test/fake.dart';
22 23 24 25 26 27 28 29 30 31 32 33 34 35 36

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

const List<int> kTransparentImage = <int>[
  0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A, 0x00, 0x00, 0x00, 0x0D, 0x49,
  0x48, 0x44, 0x52, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0x08, 0x06,
  0x00, 0x00, 0x00, 0x1F, 0x15, 0xC4, 0x89, 0x00, 0x00, 0x00, 0x0A, 0x49, 0x44,
  0x41, 0x54, 0x78, 0x9C, 0x63, 0x00, 0x01, 0x00, 0x00, 0x05, 0x00, 0x01, 0x0D,
  0x0A, 0x2D, 0xB4, 0x00, 0x00, 0x00, 0x00, 0x49, 0x45, 0x4E, 0x44, 0xAE,
];

void main() {
  Testbed testbed;
  WebAssetServer webAssetServer;
37
  ReleaseAssetServer releaseAssetServer;
38
  Platform linux;
39
  PackageConfig packages;
40
  Platform windows;
41
  FakeHttpServer httpServer;
42 43

  setUpAll(() async {
44 45 46
    packages = PackageConfig(<Package>[
      Package('flutter_tools', Uri.file('/flutter_tools/lib/').normalizePath())
    ]);
47
  });
48 49

  setUp(() {
50
    httpServer = FakeHttpServer();
51
    linux = FakePlatform(environment: <String, String>{});
52
    windows = FakePlatform(operatingSystem: 'windows', environment: <String, String>{});
53
    testbed = Testbed(setup: () {
54
      webAssetServer = WebAssetServer(
55
        httpServer,
56 57 58 59
        packages,
        InternetAddress.loopbackIPv4,
        null,
        null,
60
        null,
61
      );
62 63 64 65 66 67 68 69
      releaseAssetServer = ReleaseAssetServer(
        globals.fs.file('main.dart').uri,
        fileSystem: null,
        flutterRoot: null,
        platform: null,
        webBuildDirectory: null,
        basePath: null,
      );
70 71 72 73
    });
  });

  test('Handles against malformed manifest', () => testbed.run(() async {
74
    final File source = globals.fs.file('source')
75
      ..writeAsStringSync('main() {}');
76
    final File sourcemap = globals.fs.file('sourcemap')
77
      ..writeAsStringSync('{}');
78 79
    final File metadata = globals.fs.file('metadata')
      ..writeAsStringSync('{}');
80 81

    // Missing ending offset.
82
    final File manifestMissingOffset = globals.fs.file('manifestA')
83 84 85
      ..writeAsStringSync(json.encode(<String, Object>{'/foo.js': <String, Object>{
        'code': <int>[0],
        'sourcemap': <int>[0],
86
        'metadata': <int>[0],
87
      }}));
88
    final File manifestOutOfBounds = globals.fs.file('manifest')
89 90 91
      ..writeAsStringSync(json.encode(<String, Object>{'/foo.js': <String, Object>{
        'code': <int>[0, 100],
        'sourcemap': <int>[0],
92
        'metadata': <int>[0],
93
      }}));
94

95 96
    expect(webAssetServer.write(source, manifestMissingOffset, sourcemap, metadata), isEmpty);
    expect(webAssetServer.write(source, manifestOutOfBounds, sourcemap, metadata), isEmpty);
97 98 99
  }));

  test('serves JavaScript files from in memory cache', () => testbed.run(() async {
100
    final File source = globals.fs.file('source')
101
      ..writeAsStringSync('main() {}');
102
    final File sourcemap = globals.fs.file('sourcemap')
103
      ..writeAsStringSync('{}');
104 105
    final File metadata = globals.fs.file('metadata')
      ..writeAsStringSync('{}');
106
    final File manifest = globals.fs.file('manifest')
107 108 109
      ..writeAsStringSync(json.encode(<String, Object>{'/foo.js': <String, Object>{
        'code': <int>[0, source.lengthSync()],
        'sourcemap': <int>[0, 2],
110
        'metadata':  <int>[0, 2],
111
      }}));
112
    webAssetServer.write(source, manifest, sourcemap, metadata);
113

114 115
    final Response response = await webAssetServer
      .handleRequest(Request('GET', Uri.parse('http://foobar/foo.js')));
116

117
    expect(response.headers, allOf(<Matcher>[
118 119 120
      containsPair(HttpHeaders.contentLengthHeader, source.lengthSync().toString()),
      containsPair(HttpHeaders.contentTypeHeader, 'application/javascript'),
      containsPair(HttpHeaders.etagHeader, isNotNull)
121 122
    ]));
    expect((await response.read().toList()).first, source.readAsBytesSync());
123 124 125 126
  }, overrides: <Type, Generator>{
    Platform: () => linux,
  }));

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
  test('serves metadata files from in memory cache', () => testbed.run(() async {
    const String metadataContents = '{"name":"foo"}';
    final File source = globals.fs.file('source')
      ..writeAsStringSync('main() {}');
    final File sourcemap = globals.fs.file('sourcemap')
      ..writeAsStringSync('{}');
    final File metadata = globals.fs.file('metadata')
      ..writeAsStringSync(metadataContents);
    final File manifest = globals.fs.file('manifest')
      ..writeAsStringSync(json.encode(<String, Object>{'/foo.js': <String, Object>{
        'code': <int>[0, source.lengthSync()],
        'sourcemap': <int>[0, sourcemap.lengthSync()],
        'metadata':  <int>[0, metadata.lengthSync()],
      }}));
    webAssetServer.write(source, manifest, sourcemap, metadata);

    final String merged = await webAssetServer.metadataContents('main_module.ddc_merged_metadata');
    expect(merged, equals(metadataContents));

    final String single = await webAssetServer.metadataContents('foo.js.metadata');
    expect(single, equals(metadataContents));
  }, overrides: <Type, Generator>{
    Platform: () => linux,
  }));

152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172
  test('Removes leading slashes for valid requests to avoid requesting outside'
    ' of served directory', () => testbed.run(() async {
    globals.fs.file('foo.png').createSync();
    globals.fs.currentDirectory = globals.fs.directory('project_directory')
      ..createSync();

    final File source = globals.fs.file(globals.fs.path.join('web', 'foo.png'))
      ..createSync(recursive: true)
      ..writeAsBytesSync(kTransparentImage);
    final Response response = await webAssetServer
      .handleRequest(Request('GET', Uri.parse('http://foobar////foo.png')));

    expect(response.headers, allOf(<Matcher>[
      containsPair(HttpHeaders.contentLengthHeader, source.lengthSync().toString()),
      containsPair(HttpHeaders.contentTypeHeader, 'image/png'),
      containsPair(HttpHeaders.etagHeader, isNotNull),
      containsPair(HttpHeaders.cacheControlHeader, 'max-age=0, must-revalidate')
    ]));
    expect((await response.read().toList()).first, source.readAsBytesSync());
  }));

173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212
  test('takes base path into account when serving', () => testbed.run(() async {
    webAssetServer.basePath = 'base/path';

    globals.fs.file('foo.png').createSync();
    globals.fs.currentDirectory = globals.fs.directory('project_directory')
      ..createSync();

    final File source = globals.fs.file(globals.fs.path.join('web', 'foo.png'))
      ..createSync(recursive: true)
      ..writeAsBytesSync(kTransparentImage);
    final Response response =
      await webAssetServer.handleRequest(
        Request('GET', Uri.parse('http://foobar/base/path/foo.png')),
      );

    expect(response.headers, allOf(<Matcher>[
      containsPair(HttpHeaders.contentLengthHeader, source.lengthSync().toString()),
      containsPair(HttpHeaders.contentTypeHeader, 'image/png'),
      containsPair(HttpHeaders.etagHeader, isNotNull),
      containsPair(HttpHeaders.cacheControlHeader, 'max-age=0, must-revalidate')
    ]));
    expect((await response.read().toList()).first, source.readAsBytesSync());
  }));

  test('serves index.html at the base path', () => testbed.run(() async {
    webAssetServer.basePath = 'base/path';

    const String htmlContent = '<html><head></head><body id="test"></body></html>';
    final Directory webDir = globals.fs.currentDirectory
      .childDirectory('web')
      ..createSync();
    webDir.childFile('index.html').writeAsStringSync(htmlContent);

    final Response response = await webAssetServer
      .handleRequest(Request('GET', Uri.parse('http://foobar/base/path/')));

    expect(response.statusCode, HttpStatus.ok);
    expect(await response.readAsString(), htmlContent);
  }));

213 214 215 216 217 218 219 220 221 222 223 224 225
  test('serves index.html at / if href attribute is $kBaseHrefPlaceholder', () => testbed.run(() async {
    const String htmlContent = '<html><head><base href ="$kBaseHrefPlaceholder"></head><body id="test"></body></html>';
    final Directory webDir = globals.fs.currentDirectory.childDirectory('web')
      ..createSync();
    webDir.childFile('index.html').writeAsStringSync(htmlContent);

    final Response response = await webAssetServer
      .handleRequest(Request('GET', Uri.parse('http://foobar/')));

    expect(response.statusCode, HttpStatus.ok);
    expect(await response.readAsString(), htmlContent.replaceAll(kBaseHrefPlaceholder, '/'));
  }));

226 227 228 229 230 231 232 233 234 235 236 237 238 239 240
  test('does not serve outside the base path', () => testbed.run(() async {
    webAssetServer.basePath = 'base/path';

    const String htmlContent = '<html><head></head><body id="test"></body></html>';
    final Directory webDir = globals.fs.currentDirectory
      .childDirectory('web')
      ..createSync();
    webDir.childFile('index.html').writeAsStringSync(htmlContent);

    final Response response = await webAssetServer
      .handleRequest(Request('GET', Uri.parse('http://foobar/')));

    expect(response.statusCode, HttpStatus.notFound);
  }));

241 242 243 244 245 246 247 248
  test('parses base path from index.html', () => testbed.run(() async {
    const String htmlContent = '<html><head><base href="/foo/bar/"></head><body id="test"></body></html>';
    final Directory webDir = globals.fs.currentDirectory
      .childDirectory('web')
      ..createSync();
    webDir.childFile('index.html').writeAsStringSync(htmlContent);

    final WebAssetServer webAssetServer = WebAssetServer(
249
      httpServer,
250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267
      packages,
      InternetAddress.loopbackIPv4,
      null,
      null,
      null,
    );

    expect(webAssetServer.basePath, 'foo/bar');
  }));

  test('handles lack of base path in index.html', () => testbed.run(() async {
    const String htmlContent = '<html><head></head><body id="test"></body></html>';
    final Directory webDir = globals.fs.currentDirectory
      .childDirectory('web')
      ..createSync();
    webDir.childFile('index.html').writeAsStringSync(htmlContent);

    final WebAssetServer webAssetServer = WebAssetServer(
268
      httpServer,
269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288
      packages,
      InternetAddress.loopbackIPv4,
      null,
      null,
      null,
    );

    // Defaults to "/" when there's no base element.
    expect(webAssetServer.basePath, '');
  }));

  test('throws if base path is relative', () => testbed.run(() async {
    const String htmlContent = '<html><head><base href="foo/bar/"></head><body id="test"></body></html>';
    final Directory webDir = globals.fs.currentDirectory
      .childDirectory('web')
      ..createSync();
    webDir.childFile('index.html').writeAsStringSync(htmlContent);

    expect(
      () => WebAssetServer(
289
        httpServer,
290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308
        packages,
        InternetAddress.loopbackIPv4,
        null,
        null,
        null,
      ),
      throwsToolExit(),
    );
  }));

  test('throws if base path does not end with slash', () => testbed.run(() async {
    const String htmlContent = '<html><head><base href="/foo/bar"></head><body id="test"></body></html>';
    final Directory webDir = globals.fs.currentDirectory
      .childDirectory('web')
      ..createSync();
    webDir.childFile('index.html').writeAsStringSync(htmlContent);

    expect(
      () => WebAssetServer(
309
        httpServer,
310 311 312 313 314 315 316 317 318 319
        packages,
        InternetAddress.loopbackIPv4,
        null,
        null,
        null,
      ),
      throwsToolExit(),
    );
  }));

320
  test('serves JavaScript files from in memory cache not from manifest', () => testbed.run(() async {
321
    webAssetServer.writeFile('foo.js', 'main() {}');
322

323 324
    final Response response = await webAssetServer
      .handleRequest(Request('GET', Uri.parse('http://foobar/foo.js')));
325

326
    expect(response.headers, allOf(<Matcher>[
327 328 329 330
      containsPair(HttpHeaders.contentLengthHeader, '9'),
      containsPair(HttpHeaders.contentTypeHeader, 'application/javascript'),
      containsPair(HttpHeaders.etagHeader, isNotNull),
      containsPair(HttpHeaders.cacheControlHeader, 'max-age=0, must-revalidate')
331 332
    ]));
    expect((await response.read().toList()).first, utf8.encode('main() {}'));
333 334
  }));

335
  test('Returns notModified when the ifNoneMatch header matches the etag', () => testbed.run(() async {
336
    webAssetServer.writeFile('foo.js', 'main() {}');
337 338 339 340 341 342 343 344 345 346 347 348 349 350

    final Response response = await webAssetServer
      .handleRequest(Request('GET', Uri.parse('http://foobar/foo.js')));
    final String etag = response.headers[HttpHeaders.etagHeader];

    final Response cachedResponse = await webAssetServer
      .handleRequest(Request('GET', Uri.parse('http://foobar/foo.js'), headers: <String, String>{
        HttpHeaders.ifNoneMatchHeader: etag
      }));

    expect(cachedResponse.statusCode, HttpStatus.notModified);
    expect(await cachedResponse.read().toList(), isEmpty);
  }));

351 352 353 354 355 356
  test('serves index.html when path is unknown', () => testbed.run(() async {
    const String htmlContent = '<html><head></head><body id="test"></body></html>';
    final Directory webDir = globals.fs.currentDirectory
      .childDirectory('web')
      ..createSync();
    webDir.childFile('index.html').writeAsStringSync(htmlContent);
357

358
    final Response response = await webAssetServer
359
      .handleRequest(Request('GET', Uri.parse('http://foobar/bar/baz')));
360

361 362
    expect(response.statusCode, HttpStatus.ok);
    expect(await response.readAsString(), htmlContent);
363 364
  }));

365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405
  test('does not serve outside the base path', () => testbed.run(() async {
    webAssetServer.basePath = 'base/path';

    const String htmlContent = '<html><head></head><body id="test"></body></html>';
    final Directory webDir = globals.fs.currentDirectory
      .childDirectory('web')
      ..createSync();
    webDir.childFile('index.html').writeAsStringSync(htmlContent);

    final Response response = await webAssetServer
      .handleRequest(Request('GET', Uri.parse('http://foobar/')));

    expect(response.statusCode, HttpStatus.notFound);
  }));

  test('does not serve index.html when path is inside assets or packages', () => testbed.run(() async {
    const String htmlContent = '<html><head></head><body id="test"></body></html>';
    final Directory webDir = globals.fs.currentDirectory
      .childDirectory('web')
      ..createSync();
    webDir.childFile('index.html').writeAsStringSync(htmlContent);

    Response response = await webAssetServer
      .handleRequest(Request('GET', Uri.parse('http://foobar/assets/foo/bar.png')));
    expect(response.statusCode, HttpStatus.notFound);

    response = await webAssetServer
      .handleRequest(Request('GET', Uri.parse('http://foobar/packages/foo/bar.dart.js')));
    expect(response.statusCode, HttpStatus.notFound);

    webAssetServer.basePath = 'base/path';

    response = await webAssetServer
      .handleRequest(Request('GET', Uri.parse('http://foobar/base/path/assets/foo/bar.png')));
    expect(response.statusCode, HttpStatus.notFound);

    response = await webAssetServer
      .handleRequest(Request('GET', Uri.parse('http://foobar/base/path/packages/foo/bar.dart.js')));
    expect(response.statusCode, HttpStatus.notFound);
  }));

406 407 408 409 410 411 412 413 414
  test('serves default index.html', () => testbed.run(() async {
    final Response response = await webAssetServer
      .handleRequest(Request('GET', Uri.parse('http://foobar/')));

    expect(response.statusCode, HttpStatus.ok);
    expect((await response.read().toList()).first,
      containsAllInOrder(utf8.encode('<html>')));
  }));

415 416 417 418 419
  test('handles web server paths without .lib extension', () => testbed.run(() async {
    final File source = globals.fs.file('source')
      ..writeAsStringSync('main() {}');
    final File sourcemap = globals.fs.file('sourcemap')
      ..writeAsStringSync('{}');
420 421
    final File metadata = globals.fs.file('metadata')
      ..writeAsStringSync('{}');
422 423 424 425
    final File manifest = globals.fs.file('manifest')
      ..writeAsStringSync(json.encode(<String, Object>{'/foo.dart.lib.js': <String, Object>{
        'code': <int>[0, source.lengthSync()],
        'sourcemap': <int>[0, 2],
426
        'metadata': <int>[0, 2],
427
      }}));
428
    webAssetServer.write(source, manifest, sourcemap, metadata);
429 430 431 432 433 434 435

    final Response response = await webAssetServer
      .handleRequest(Request('GET', Uri.parse('http://foobar/foo.dart.js')));

    expect(response.statusCode, HttpStatus.ok);
  }));

436 437 438 439 440
  test('serves JavaScript files from in memory cache on Windows', () => testbed.run(() async {
    final File source = globals.fs.file('source')
      ..writeAsStringSync('main() {}');
    final File sourcemap = globals.fs.file('sourcemap')
      ..writeAsStringSync('{}');
441 442
    final File metadata = globals.fs.file('metadata')
      ..writeAsStringSync('{}');
443
    final File manifest = globals.fs.file('manifest')
444
      ..writeAsStringSync(json.encode(<String, Object>{'/foo.js': <String, Object>{
445 446
        'code': <int>[0, source.lengthSync()],
        'sourcemap': <int>[0, 2],
447
        'metadata': <int>[0, 2],
448
      }}));
449
    webAssetServer.write(source, manifest, sourcemap, metadata);
450 451 452 453
    final Response response = await webAssetServer
      .handleRequest(Request('GET', Uri.parse('http://localhost/foo.js')));

    expect(response.headers, allOf(<Matcher>[
454 455 456 457
      containsPair(HttpHeaders.contentLengthHeader, source.lengthSync().toString()),
      containsPair(HttpHeaders.contentTypeHeader, 'application/javascript'),
      containsPair(HttpHeaders.etagHeader, isNotNull),
      containsPair(HttpHeaders.cacheControlHeader, 'max-age=0, must-revalidate')
458 459
    ]));
    expect((await response.read().toList()).first, source.readAsBytesSync());
460 461 462 463
  }, overrides: <Type, Generator>{
    Platform: () => windows,
  }));

464 465 466 467 468 469 470 471
   test('serves asset files from in filesystem with url-encoded paths', () => testbed.run(() async {
    final File source = globals.fs.file(globals.fs.path.join('build', 'flutter_assets', Uri.encodeFull('abcd象形字.png')))
      ..createSync(recursive: true)
      ..writeAsBytesSync(kTransparentImage);
    final Response response = await webAssetServer
      .handleRequest(Request('GET', Uri.parse('http://foobar/assets/abcd%25E8%25B1%25A1%25E5%25BD%25A2%25E5%25AD%2597.png')));

    expect(response.headers, allOf(<Matcher>[
472 473 474 475
      containsPair(HttpHeaders.contentLengthHeader, source.lengthSync().toString()),
      containsPair(HttpHeaders.contentTypeHeader, 'image/png'),
      containsPair(HttpHeaders.etagHeader, isNotNull),
      containsPair(HttpHeaders.cacheControlHeader, 'max-age=0, must-revalidate')
476 477 478
    ]));
    expect((await response.read().toList()).first, source.readAsBytesSync());
  }));
479 480 481 482 483 484 485 486 487 488 489 490 491 492 493
  test('serves files from web directory', () => testbed.run(() async {
    final File source = globals.fs.file(globals.fs.path.join('web', 'foo.png'))
      ..createSync(recursive: true)
      ..writeAsBytesSync(kTransparentImage);
    final Response response = await webAssetServer
      .handleRequest(Request('GET', Uri.parse('http://foobar/foo.png')));

    expect(response.headers, allOf(<Matcher>[
      containsPair(HttpHeaders.contentLengthHeader, source.lengthSync().toString()),
      containsPair(HttpHeaders.contentTypeHeader, 'image/png'),
      containsPair(HttpHeaders.etagHeader, isNotNull),
      containsPair(HttpHeaders.cacheControlHeader, 'max-age=0, must-revalidate')
    ]));
    expect((await response.read().toList()).first, source.readAsBytesSync());
  }));
494

495 496 497 498
   test('serves asset files from in filesystem with known mime type on Windows', () => testbed.run(() async {
    final File source = globals.fs.file(globals.fs.path.join('build', 'flutter_assets', 'foo.png'))
      ..createSync(recursive: true)
      ..writeAsBytesSync(kTransparentImage);
499 500 501 502
    final Response response = await webAssetServer
      .handleRequest(Request('GET', Uri.parse('http://foobar/assets/foo.png')));

    expect(response.headers, allOf(<Matcher>[
503 504 505 506
      containsPair(HttpHeaders.contentLengthHeader, source.lengthSync().toString()),
      containsPair(HttpHeaders.contentTypeHeader, 'image/png'),
      containsPair(HttpHeaders.etagHeader, isNotNull),
      containsPair(HttpHeaders.cacheControlHeader, 'max-age=0, must-revalidate')
507 508
    ]));
    expect((await response.read().toList()).first, source.readAsBytesSync());
509 510 511 512
  }, overrides: <Type,  Generator>{
    Platform: () => windows,
  }));

513
  test('serves Dart files from in filesystem on Linux/macOS', () => testbed.run(() async {
514
    final File source = globals.fs.file('foo.dart').absolute
515 516 517
      ..createSync(recursive: true)
      ..writeAsStringSync('void main() {}');

518 519
    final Response response = await webAssetServer
      .handleRequest(Request('GET', Uri.parse('http://foobar/foo.dart')));
520

521
    expect(response.headers, containsPair(HttpHeaders.contentLengthHeader, source.lengthSync().toString()));
522
    expect((await response.read().toList()).first, source.readAsBytesSync());
523 524 525 526 527
  }, overrides: <Type,  Generator>{
    Platform: () => linux,
  }));

  test('serves asset files from in filesystem with known mime type', () => testbed.run(() async {
528
    final File source = globals.fs.file(globals.fs.path.join('build', 'flutter_assets', 'foo.png'))
529 530 531
      ..createSync(recursive: true)
      ..writeAsBytesSync(kTransparentImage);

532 533
    final Response response = await webAssetServer
      .handleRequest(Request('GET', Uri.parse('http://foobar/assets/foo.png')));
534

535
    expect(response.headers, allOf(<Matcher>[
536 537
      containsPair(HttpHeaders.contentLengthHeader, source.lengthSync().toString()),
      containsPair(HttpHeaders.contentTypeHeader, 'image/png'),
538 539
    ]));
    expect((await response.read().toList()).first, source.readAsBytesSync());
540 541
  }));

542 543 544
  test('serves asset files from in filesystem with known mime type and empty content', () => testbed.run(() async {
    final File source = globals.fs.file(globals.fs.path.join('web', 'foo.js'))
      ..createSync(recursive: true);
545

546
    final Response response = await webAssetServer
547
        .handleRequest(Request('GET', Uri.parse('http://foobar/foo.js')));
548

549
    expect(response.headers, allOf(<Matcher>[
550 551
      containsPair(HttpHeaders.contentLengthHeader, '0'),
      containsPair(HttpHeaders.contentTypeHeader, 'application/javascript'),
552 553
    ]));
    expect((await response.read().toList()).first, source.readAsBytesSync());
554 555
  }));

556
  test('serves asset files files from in filesystem with unknown mime type', () => testbed.run(() async {
557
    final File source = globals.fs.file(globals.fs.path.join('build', 'flutter_assets', 'foo'))
558
      ..createSync(recursive: true)
559
      ..writeAsBytesSync(List<int>.filled(100, 0));
560

561 562
    final Response response = await webAssetServer
      .handleRequest(Request('GET', Uri.parse('http://foobar/assets/foo')));
563

564
    expect(response.headers, allOf(<Matcher>[
565
      containsPair(HttpHeaders.contentLengthHeader, '100'),
566
      containsPair(HttpHeaders.contentTypeHeader, 'application/octet-stream'),
567 568
    ]));
    expect((await response.read().toList()).first, source.readAsBytesSync());
569 570
  }));

571
  test('serves valid etag header for asset files with non-ascii characters', () => testbed.run(() async {
572 573 574 575 576 577 578 579 580 581 582
    globals.fs.file(globals.fs.path.join('build', 'flutter_assets', 'fooπ'))
      ..createSync(recursive: true)
      ..writeAsBytesSync(<int>[1, 2, 3]);

    final Response response = await webAssetServer
      .handleRequest(Request('GET', Uri.parse('http://foobar/assets/fooπ')));
    final String etag = response.headers[HttpHeaders.etagHeader];

    expect(etag.runes, everyElement(predicate((int char) => char < 255)));
  }));

583 584 585 586 587 588 589
  test('serves /packages/<package>/<path> files as if they were '
       'package:<package>/<path> uris', () => testbed.run(() async {
    final Uri expectedUri = packages.resolve(
        Uri.parse('package:flutter_tools/foo.dart'));
    final File source = globals.fs.file(globals.fs.path.fromUri(expectedUri))
      ..createSync(recursive: true)
      ..writeAsBytesSync(<int>[1, 2, 3]);
590 591 592 593 594

    final Response response = await webAssetServer
      .handleRequest(Request('GET', Uri.parse('http:///packages/flutter_tools/foo.dart')));

    expect(response.headers, allOf(<Matcher>[
595
      containsPair(HttpHeaders.contentLengthHeader, '3'),
596
      containsPair(HttpHeaders.contentTypeHeader, 'text/x-dart'),
597 598
    ]));
    expect((await response.read().toList()).first, source.readAsBytesSync());
599 600
  }));

601 602 603
  test('calling dispose closes the http server', () => testbed.run(() async {
    await webAssetServer.dispose();

604
    expect(httpServer.closed, true);
605
  }));
606 607

  test('Can start web server with specified assets', () => testbed.run(() async {
608 609 610 611 612
    final File outputFile = globals.fs.file(globals.fs.path.join('lib', 'main.dart'))
      ..createSync(recursive: true);
    outputFile.parent.childFile('a.sources').writeAsStringSync('');
    outputFile.parent.childFile('a.json').writeAsStringSync('{}');
    outputFile.parent.childFile('a.map').writeAsStringSync('{}');
613
    outputFile.parent.childFile('a.metadata').writeAsStringSync('{}');
614

615 616
    final ResidentCompiler residentCompiler = FakeResidentCompiler()
      ..output = const CompilerOutput('a', 0, <Uri>[]);
617 618 619 620 621 622

    final WebDevFS webDevFS = WebDevFS(
      hostname: 'localhost',
      port: 0,
      packagesFilePath: '.packages',
      urlTunneller: null,
623
      useSseForDebugProxy: true,
624
      useSseForDebugBackend: true,
625
      useSseForInjectedClient: true,
626
      nullAssertions: true,
627
      nativeNullAssertions: true,
628 629 630 631 632 633 634
      buildInfo: const BuildInfo(
        BuildMode.debug,
        '',
        treeShakeIcons: false,
        nullSafetyMode: NullSafetyMode.unsound,
      ),
      enableDwds: false,
635
      enableDds: false,
636 637 638 639
      entrypoint: Uri.base,
      testMode: true,
      expressionCompiler: null,
      chromiumLauncher: null,
640
      nullSafetyMode: NullSafetyMode.unsound,
641 642 643 644 645 646 647
    );
    webDevFS.requireJS.createSync(recursive: true);
    webDevFS.stackTraceMapper.createSync(recursive: true);

    final Uri uri = await webDevFS.create();
    webDevFS.webAssetServer.entrypointCacheDirectory = globals.fs.currentDirectory;
    final String webPrecompiledSdk = globals.artifacts
648
      .getHostArtifact(HostArtifact.webPrecompiledSdk).path;
649
    final String webPrecompiledSdkSourcemaps = globals.artifacts
650
      .getHostArtifact(HostArtifact.webPrecompiledSdkSourcemaps).path;
651
    final String webPrecompiledCanvaskitSdk = globals.artifacts
652
      .getHostArtifact(HostArtifact.webPrecompiledCanvaskitSdk).path;
653
    final String webPrecompiledCanvaskitSdkSourcemaps = globals.artifacts
654
      .getHostArtifact(HostArtifact.webPrecompiledCanvaskitSdkSourcemaps).path;
655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679
    globals.fs.currentDirectory
      .childDirectory('lib')
      .childFile('web_entrypoint.dart')
      ..createSync(recursive: true)
      ..writeAsStringSync('GENERATED');
    globals.fs.file(webPrecompiledSdk)
      ..createSync(recursive: true)
      ..writeAsStringSync('HELLO');
    globals.fs.file(webPrecompiledSdkSourcemaps)
      ..createSync(recursive: true)
      ..writeAsStringSync('THERE');
    globals.fs.file(webPrecompiledCanvaskitSdk)
      ..createSync(recursive: true)
      ..writeAsStringSync('OL');
    globals.fs.file(webPrecompiledCanvaskitSdkSourcemaps)
      ..createSync(recursive: true)
      ..writeAsStringSync('CHUM');

    await webDevFS.update(
      mainUri: globals.fs.file(globals.fs.path.join('lib', 'main.dart')).uri,
      generator: residentCompiler,
      trackWidgetCreation: true,
      bundleFirstUpload: true,
      invalidatedFiles: <Uri>[],
      packageConfig: PackageConfig.empty,
680
      pathToReload: '',
681
      dillOutputPath: 'out.dill',
682 683 684 685 686 687 688
    );

    expect(webDevFS.webAssetServer.getFile('require.js'), isNotNull);
    expect(webDevFS.webAssetServer.getFile('stack_trace_mapper.js'), isNotNull);
    expect(webDevFS.webAssetServer.getFile('main.dart'), isNotNull);
    expect(webDevFS.webAssetServer.getFile('manifest.json'), isNotNull);
    expect(webDevFS.webAssetServer.getFile('flutter_service_worker.js'), isNotNull);
689
    expect(webDevFS.webAssetServer.getFile('version.json'),isNotNull);
690 691 692 693 694 695 696 697 698 699
    expect(await webDevFS.webAssetServer.dartSourceContents('dart_sdk.js'), 'HELLO');
    expect(await webDevFS.webAssetServer.dartSourceContents('dart_sdk.js.map'), 'THERE');

    // Update to the SDK.
   globals.fs.file(webPrecompiledSdk).writeAsStringSync('BELLOW');

    // New SDK should be visible..
    expect(await webDevFS.webAssetServer.dartSourceContents('dart_sdk.js'), 'BELLOW');

    // Toggle CanvasKit
700 701
    expect(webDevFS.webAssetServer.webRenderer, WebRendererMode.html);
    webDevFS.webAssetServer.webRenderer = WebRendererMode.canvaskit;
702

703 704 705 706 707 708 709 710
    expect(await webDevFS.webAssetServer.dartSourceContents('dart_sdk.js'), 'OL');
    expect(await webDevFS.webAssetServer.dartSourceContents('dart_sdk.js.map'), 'CHUM');

    // Generated entrypoint.
    expect(await webDevFS.webAssetServer.dartSourceContents('web_entrypoint.dart'),
      contains('GENERATED'));

    // served on localhost
711
    expect(uri.host, 'localhost');
712 713 714 715 716 717 718 719 720 721 722 723

    await webDevFS.destroy();
  }, overrides: <Type, Generator>{
    Artifacts: () => Artifacts.test(),
  }));

  test('Can start web server with specified assets in sound null safety mode', () => testbed.run(() async {
    final File outputFile = globals.fs.file(globals.fs.path.join('lib', 'main.dart'))
      ..createSync(recursive: true);
    outputFile.parent.childFile('a.sources').writeAsStringSync('');
    outputFile.parent.childFile('a.json').writeAsStringSync('{}');
    outputFile.parent.childFile('a.map').writeAsStringSync('{}');
724
    outputFile.parent.childFile('a.metadata').writeAsStringSync('{}');
725

726 727
    final ResidentCompiler residentCompiler = FakeResidentCompiler()
      ..output = const CompilerOutput('a', 0, <Uri>[]);
728 729 730 731 732 733 734

    final WebDevFS webDevFS = WebDevFS(
      hostname: 'localhost',
      port: 0,
      packagesFilePath: '.packages',
      urlTunneller: null,
      useSseForDebugProxy: true,
735
      useSseForDebugBackend: true,
736
      useSseForInjectedClient: true,
737
      nullAssertions: true,
738
      nativeNullAssertions: true,
739 740 741 742 743
      buildInfo: const BuildInfo(
        BuildMode.debug,
        '',
        treeShakeIcons: false,
      ),
744
      enableDwds: false,
745
      enableDds: false,
746 747
      entrypoint: Uri.base,
      testMode: true,
748
      expressionCompiler: null,
749
      chromiumLauncher: null,
750
      nullSafetyMode: NullSafetyMode.sound,
751 752 753 754
    );
    webDevFS.requireJS.createSync(recursive: true);
    webDevFS.stackTraceMapper.createSync(recursive: true);

755
    final Uri uri = await webDevFS.create();
756 757 758 759 760 761
    webDevFS.webAssetServer.entrypointCacheDirectory = globals.fs.currentDirectory;
    globals.fs.currentDirectory
      .childDirectory('lib')
      .childFile('web_entrypoint.dart')
      ..createSync(recursive: true)
      ..writeAsStringSync('GENERATED');
762
    final String webPrecompiledSdk = globals.artifacts
763
      .getHostArtifact(HostArtifact.webPrecompiledSoundSdk).path;
764
    final String webPrecompiledSdkSourcemaps = globals.artifacts
765
      .getHostArtifact(HostArtifact.webPrecompiledSoundSdkSourcemaps).path;
766
    final String webPrecompiledCanvaskitSdk = globals.artifacts
767
      .getHostArtifact(HostArtifact.webPrecompiledCanvaskitSoundSdk).path;
768
    final String webPrecompiledCanvaskitSdkSourcemaps = globals.artifacts
769
      .getHostArtifact(HostArtifact.webPrecompiledCanvaskitSoundSdkSourcemaps).path;
770
    globals.fs.file(webPrecompiledSdk)
771 772
      ..createSync(recursive: true)
      ..writeAsStringSync('HELLO');
773
    globals.fs.file(webPrecompiledSdkSourcemaps)
774 775
      ..createSync(recursive: true)
      ..writeAsStringSync('THERE');
776
    globals.fs.file(webPrecompiledCanvaskitSdk)
777 778
      ..createSync(recursive: true)
      ..writeAsStringSync('OL');
779
    globals.fs.file(webPrecompiledCanvaskitSdkSourcemaps)
780 781
      ..createSync(recursive: true)
      ..writeAsStringSync('CHUM');
782 783

    await webDevFS.update(
784
      mainUri: globals.fs.file(globals.fs.path.join('lib', 'main.dart')).uri,
785 786 787 788
      generator: residentCompiler,
      trackWidgetCreation: true,
      bundleFirstUpload: true,
      invalidatedFiles: <Uri>[],
789
      packageConfig: PackageConfig.empty,
790
      pathToReload: '',
791
      dillOutputPath: '',
792 793
    );

794 795 796 797 798
    expect(webDevFS.webAssetServer.getFile('require.js'), isNotNull);
    expect(webDevFS.webAssetServer.getFile('stack_trace_mapper.js'), isNotNull);
    expect(webDevFS.webAssetServer.getFile('main.dart'), isNotNull);
    expect(webDevFS.webAssetServer.getFile('manifest.json'), isNotNull);
    expect(webDevFS.webAssetServer.getFile('flutter_service_worker.js'), isNotNull);
799
    expect(webDevFS.webAssetServer.getFile('version.json'), isNotNull);
800 801
    expect(await webDevFS.webAssetServer.dartSourceContents('dart_sdk.js'), 'HELLO');
    expect(await webDevFS.webAssetServer.dartSourceContents('dart_sdk.js.map'), 'THERE');
802 803

    // Update to the SDK.
804
    globals.fs.file(webPrecompiledSdk).writeAsStringSync('BELLOW');
805 806

    // New SDK should be visible..
807
    expect(await webDevFS.webAssetServer.dartSourceContents('dart_sdk.js'), 'BELLOW');
808

809
    // Toggle CanvasKit
810
    webDevFS.webAssetServer.webRenderer = WebRendererMode.canvaskit;
811 812 813 814
    expect(await webDevFS.webAssetServer.dartSourceContents('dart_sdk.js'), 'OL');
    expect(await webDevFS.webAssetServer.dartSourceContents('dart_sdk.js.map'), 'CHUM');

    // Generated entrypoint.
815 816
    expect(await webDevFS.webAssetServer.dartSourceContents('web_entrypoint.dart'),
      contains('GENERATED'));
817

818
    // served on localhost
819
    expect(uri.host, 'localhost');
820 821

    await webDevFS.destroy();
822 823
  }, overrides: <Type, Generator>{
    Artifacts: () => Artifacts.test(),
824 825 826 827 828 829 830 831 832 833 834 835 836 837 838
  }));

  test('Can start web server with hostname any', () => testbed.run(() async {
    final File outputFile = globals.fs.file(globals.fs.path.join('lib', 'main.dart'))
      ..createSync(recursive: true);
    outputFile.parent.childFile('a.sources').writeAsStringSync('');
    outputFile.parent.childFile('a.json').writeAsStringSync('{}');
    outputFile.parent.childFile('a.map').writeAsStringSync('{}');

    final WebDevFS webDevFS = WebDevFS(
      hostname: 'any',
      port: 0,
      packagesFilePath: '.packages',
      urlTunneller: null,
      useSseForDebugProxy: true,
839
      useSseForDebugBackend: true,
840
      useSseForInjectedClient: true,
841
      buildInfo: BuildInfo.debug,
842
      enableDwds: false,
843
      enableDds: false,
844 845 846
      entrypoint: Uri.base,
      testMode: true,
      expressionCompiler: null,
847
      chromiumLauncher: null,
848
      nullAssertions: true,
849
      nativeNullAssertions: true,
850
      nullSafetyMode: NullSafetyMode.sound,
851 852 853 854 855 856
    );
    webDevFS.requireJS.createSync(recursive: true);
    webDevFS.stackTraceMapper.createSync(recursive: true);

    final Uri uri = await webDevFS.create();

857
    expect(uri.host, 'localhost');
858 859
    await webDevFS.destroy();
  }));
860 861 862 863 864 865 866 867 868 869 870 871 872 873

  test('Can start web server with canvaskit enabled', () => testbed.run(() async {
    final File outputFile = globals.fs.file(globals.fs.path.join('lib', 'main.dart'))
      ..createSync(recursive: true);
    outputFile.parent.childFile('a.sources').writeAsStringSync('');
    outputFile.parent.childFile('a.json').writeAsStringSync('{}');
    outputFile.parent.childFile('a.map').writeAsStringSync('{}');

    final WebDevFS webDevFS = WebDevFS(
      hostname: 'localhost',
      port: 0,
      packagesFilePath: '.packages',
      urlTunneller: null,
      useSseForDebugProxy: true,
874
      useSseForDebugBackend: true,
875
      useSseForInjectedClient: true,
876
      nullAssertions: true,
877
      nativeNullAssertions: true,
878 879 880 881 882 883 884 885 886
      buildInfo: const BuildInfo(
        BuildMode.debug,
        '',
        treeShakeIcons: false,
        dartDefines: <String>[
          'FLUTTER_WEB_USE_SKIA=true',
        ]
      ),
      enableDwds: false,
887
      enableDds: false,
888 889 890 891
      entrypoint: Uri.base,
      testMode: true,
      expressionCompiler: null,
      chromiumLauncher: null,
892
      nullSafetyMode: NullSafetyMode.sound,
893 894 895 896 897 898
    );
    webDevFS.requireJS.createSync(recursive: true);
    webDevFS.stackTraceMapper.createSync(recursive: true);

    await webDevFS.create();

899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917
    expect(webDevFS.webAssetServer.webRenderer, WebRendererMode.canvaskit);

    await webDevFS.destroy();
  }));

  test('Can start web server with auto detect enabled', () => testbed.run(() async {
    final File outputFile = globals.fs.file(globals.fs.path.join('lib', 'main.dart'))
      ..createSync(recursive: true);
    outputFile.parent.childFile('a.sources').writeAsStringSync('');
    outputFile.parent.childFile('a.json').writeAsStringSync('{}');
    outputFile.parent.childFile('a.map').writeAsStringSync('{}');

    final WebDevFS webDevFS = WebDevFS(
      hostname: 'localhost',
      port: 0,
      packagesFilePath: '.packages',
      urlTunneller: null,
      useSseForDebugProxy: true,
      useSseForDebugBackend: true,
918
      useSseForInjectedClient: true,
919
      nullAssertions: true,
920
      nativeNullAssertions: true,
921
      buildInfo: const BuildInfo(
922 923 924 925 926 927
        BuildMode.debug,
        '',
        treeShakeIcons: false,
        dartDefines: <String>[
          'FLUTTER_WEB_AUTO_DETECT=true',
        ]
928 929
      ),
      enableDwds: false,
930
      enableDds: false,
931 932 933 934
      entrypoint: Uri.base,
      testMode: true,
      expressionCompiler: null,
      chromiumLauncher: null,
935
      nullSafetyMode: NullSafetyMode.sound,
936 937 938 939 940 941 942
    );
    webDevFS.requireJS.createSync(recursive: true);
    webDevFS.stackTraceMapper.createSync(recursive: true);

    await webDevFS.create();

    expect(webDevFS.webAssetServer.webRenderer, WebRendererMode.autoDetect);
943 944 945

    await webDevFS.destroy();
  }));
946 947 948 949 950 951 952 953 954

  test('allows frame embedding', () async {
    final WebAssetServer webAssetServer = await WebAssetServer.start(
      null,
      'localhost',
      0,
      null,
      true,
      true,
955
      true,
956 957 958 959 960 961
      const BuildInfo(
        BuildMode.debug,
        '',
        treeShakeIcons: false,
      ),
      false,
962
      false,
963 964
      Uri.base,
      null,
965
      null,
966 967 968 969 970
      testMode: true);

    expect(webAssetServer.defaultResponseHeaders['x-frame-options'], null);
    await webAssetServer.dispose();
  });
971 972 973 974 975 976 977 978 979 980 981 982 983 984

  test('WebAssetServer responds to POST requests with 404 not found', () => testbed.run(() async {
    final Response response = await webAssetServer.handleRequest(
      Request('POST', Uri.parse('http://foobar/something')),
    );
    expect(response.statusCode, 404);
  }));

  test('ReleaseAssetServer responds to POST requests with 404 not found', () => testbed.run(() async {
    final Response response = await releaseAssetServer.handle(
      Request('POST', Uri.parse('http://foobar/something')),
    );
    expect(response.statusCode, 404);
  }));
985

nt4f04uNd's avatar
nt4f04uNd committed
986
  test('WebAssetServer strips leading base href off of asset requests', () => testbed.run(() async {
987 988 989 990 991 992 993
    const String htmlContent = '<html><head><base href="/foo/"></head><body id="test"></body></html>';
    globals.fs.currentDirectory
      .childDirectory('web')
      .childFile('index.html')
      ..createSync(recursive: true)
      ..writeAsStringSync(htmlContent);
    final WebAssetServer webAssetServer = WebAssetServer(
994
      FakeHttpServer(),
995 996 997 998 999 1000 1001 1002 1003
      PackageConfig.empty,
      InternetAddress.anyIPv4,
      <String, String>{},
      <String, String>{},
      NullSafetyMode.sound,
    );

    expect(await webAssetServer.metadataContents('foo/main_module.ddc_merged_metadata'), null);
    // Not base href.
1004
    expect(() async => webAssetServer.metadataContents('bar/main_module.ddc_merged_metadata'), throwsException);
1005 1006
  }));

1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027
  test('DevFS URI includes any specified base path.', () => testbed.run(() async {
    final File outputFile = globals.fs.file(globals.fs.path.join('lib', 'main.dart'))
      ..createSync(recursive: true);
    const String htmlContent = '<html><head><base href="/foo/"></head><body id="test"></body></html>';
    globals.fs.currentDirectory
      .childDirectory('web')
      .childFile('index.html')
      ..createSync(recursive: true)
      ..writeAsStringSync(htmlContent);
    outputFile.parent.childFile('a.sources').writeAsStringSync('');
    outputFile.parent.childFile('a.json').writeAsStringSync('{}');
    outputFile.parent.childFile('a.map').writeAsStringSync('{}');
    outputFile.parent.childFile('a.metadata').writeAsStringSync('{}');

    final WebDevFS webDevFS = WebDevFS(
      hostname: 'localhost',
      port: 0,
      packagesFilePath: '.packages',
      urlTunneller: null,
      useSseForDebugProxy: true,
      useSseForDebugBackend: true,
1028
      useSseForInjectedClient: true,
1029 1030 1031 1032
      nullAssertions: true,
      nativeNullAssertions: true,
      buildInfo: BuildInfo.debug,
      enableDwds: false,
1033
      enableDds: false,
1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053
      entrypoint: Uri.base,
      testMode: true,
      expressionCompiler: null,
      chromiumLauncher: null,
      nullSafetyMode: NullSafetyMode.unsound,
    );
    webDevFS.requireJS.createSync(recursive: true);
    webDevFS.stackTraceMapper.createSync(recursive: true);

    final Uri uri = await webDevFS.create();

    // served on localhost
    expect(uri.host, 'localhost');
    // Matches base URI specified in html.
    expect(uri.path, '/foo');

    await webDevFS.destroy();
  }, overrides: <Type, Generator>{
    Artifacts: () => Artifacts.test(),
  }));
1054 1055
}

1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077
class FakeHttpServer extends Fake implements HttpServer {
  bool closed = false;

  @override
  Future<void> close({bool force = false}) async {
    closed = true;
  }
}

class FakeResidentCompiler extends Fake implements ResidentCompiler {
  CompilerOutput output;

  @override
  void addFileSystemRoot(String root) { }

  @override
  Future<CompilerOutput> recompile(Uri mainUri, List<Uri> invalidatedFiles, {
    String outputPath,
    PackageConfig packageConfig,
    String projectRootPath,
    FileSystem fs,
    bool suppressErrors = false,
1078
    bool checkDartPluginRegistry = false,
1079 1080 1081 1082
  }) async {
    return output;
  }
}