Chromium Code Reviews
chromiumcodereview-hr@appspot.gserviceaccount.com (chromiumcodereview-hr) | Please choose your nickname with Settings | Help | Chromium Project | Gerrit Changes | Sign out
(148)

Side by Side Diff: tools/testing/dart/http_server.dart

Issue 11810004: Make browser tests all run from a server instead of the local filesystem. (Closed) Base URL: https://dart.googlecode.com/svn/branches/bleeding_edge/dart
Patch Set: Created 7 years, 11 months ago
Use n/p to move between diff chunks; N/P to move between comments. Draft comments are only viewable by you.
Jump to:
View unified diff | Download patch | Annotate | Revision Log
OLDNEW
1 // Copyright (c) 2012, the Dart project authors. Please see the AUTHORS file 1 // Copyright (c) 2012, the Dart project authors. Please see the AUTHORS file
2 // for details. All rights reserved. Use of this source code is governed by a 2 // for details. All rights reserved. Use of this source code is governed by a
3 // BSD-style license that can be found in the LICENSE file. 3 // BSD-style license that can be found in the LICENSE file.
4 4
5 library http_server; 5 library http_server;
6 6
7 import 'dart:io'; 7 import 'dart:io';
8 import 'dart:isolate'; 8 import 'dart:isolate';
9 import 'test_suite.dart'; // For TestUtils. 9 import 'test_suite.dart'; // For TestUtils.
10 import '../../../pkg/args/lib/args.dart';
11 import '../../../pkg/path/lib/path.dart' as pathLib;
10 12
11 HttpServer _httpServer; 13 main() {
14 /** Convenience method for local testing. */
15 var parser = new ArgParser();
16 parser.addOption('port', abbr: 'p',
17 help: 'The main server port we wish to respond to requests.',
18 defaultsTo: '0');
19 parser.addOption('crossOriginPort', abbr: 'c',
20 help: 'A different port that accepts request from the main server port.',
21 defaultsTo: '0');
22 parser.addFlag('help', abbr: 'h', negatable: false,
23 help: 'Print this usage information.');
24 var args = parser.parse(new Options().arguments);
25 if (args['help']) {
26 print(parser.getUsage());
27 } else {
28 // Pretend we're running test.dart so that TestUtils doesn't get confused
29 // about the "current directory." This is only used if we're trying to run
30 // this file independently for local testing.
31 TestUtils.testScriptPath = 'tools/test.dart';
32 TestingServerRunner.setPackageRootDir({'mode': 'release'});
12 33
13 void startHttpServer(String host, int port) { 34 TestingServerRunner.startHttpServer('127.0.0.1',
14 var basePath = TestUtils.dartDir(); 35 port: int.parse(args['port']));
15 _httpServer = new HttpServer(); 36 print(
16 _httpServer.onError = (e) { 37 'Server listening on port ${TestingServerRunner.serverList[0].port}.');
Mads Ager (google) 2013/01/11 10:11:03 Nit: consider splitting the string in the middle i
17 // Consider errors in the builtin http server fatal. 38 TestingServerRunner.startHttpServer('127.0.0.1',
18 // Intead of just throwing the exception we print 39 allowedPort: TestingServerRunner.serverList[0].port, port:
19 // a message that makes it clearer what happened. 40 int.parse(args['crossOriginPort']));
20 print('Test http server error: $e'); 41 print(
21 exit(1); 42 'Server listening on port ${TestingServerRunner.serverList[1].port}.');
22 }; 43 }
23 _httpServer.defaultRequestHandler = (request, resp) { 44 }
24 var requestPath = new Path(request.path).canonicalize(); 45 /**
25 if (!requestPath.isAbsolute) { 46 * Runs a set of servers that are initialized specifically the needs for our
Mads Ager (google) 2013/01/11 10:11:03 Reformulate: specifically the needs for
26 resp.statusCode = HttpStatus.NOT_FOUND; 47 * test framework, such as dealing with package-root.
27 resp.outputStream.close(); 48 */
28 } else { 49 class TestingServerRunner {
29 var path = basePath; 50 static List serverList = [];
30 requestPath.segments().forEach((s) => path = path.append(s)); 51 static String _packageRootDir = null;
31 var file = new File(path.toNativePath()); 52
53 // Added as a getter so that the function will be called again each time the
54 // default request handler closure is executed.
55 static String get packageRootDir => _packageRootDir;
56
57 static setPackageRootDir(Map configuration) {
58 _packageRootDir = pathLib.join(TestUtils.currentWorkingDirectory.toString(),
59 TestUtils.buildDir(configuration));
60 }
61
62 static startHttpServer(String host, {int allowedPort:-1, int port: 0}) {
63 var basePath = TestUtils.dartDir().toNativePath();
64 var httpServer = new HttpServer();
65 var packagesDirName = 'packages';
66 httpServer.onError = (e) {
67 // Consider errors in the builtin http server fatal.
68 // Intead of just throwing the exception we print
69 // a message that makes it clearer what happened.
70 print('Test http server error: $e');
71 exit(1);
72 };
73 httpServer.defaultRequestHandler = (request, resp) {
74 var builder = new pathLib.Builder(style: pathLib.Style.posix);
75 // URLs will have a starting slash, but in this case we don't want to
76 // interpret it as the root directory.
77 var requestPath = builder.normalize(request.path).substring(1);
78 var path = pathLib.join(basePath, requestPath);
79 var file = new File(path);
80
81 if (pathLib.split(requestPath).contains(packagesDirName)) {
82 // Essentially implement the packages path rewriting, so we don't have
83 // to pass environment variables to the browsers.
84 requestPath = requestPath.substring(
85 requestPath.indexOf(packagesDirName));
86 path = pathLib.join(packageRootDir, requestPath);
87 file = new File(path);
88 }
32 file.exists().then((exists) { 89 file.exists().then((exists) {
33 if (exists) { 90 if (exists) {
34 // Allow loading from localhost in browsers. 91 if (allowedPort != -1) {
35 resp.headers.set("Access-Control-Allow-Origin", "*"); 92 // Allow loading from localhost:$allowedPort in browsers.
93 resp.headers.set("Access-Control-Allow-Origin",
94 "http://127.0.0.1:$allowedPort");
95 resp.headers.set('Access-Control-Allow-Credentials', 'true');
96 } else {
97 // No allowedPort specified. Allow from anywhere (but cross-origin
98 // requests *with credentials* will fail because you can't use "*").
99 resp.headers.set("Access-Control-Allow-Origin", "*");
100 }
101 if (path.endsWith('.html')) {
102 resp.headers.set('Content-Type', 'text/html');
103 } else if (path.endsWith('.js')) {
104 resp.headers.set('Content-Type', 'application/javascript');
105 } else if (path.endsWith('.dart')) {
106 resp.headers.set('Content-Type', 'application/dart');
107 }
36 file.openInputStream().pipe(resp.outputStream); 108 file.openInputStream().pipe(resp.outputStream);
37 } else { 109 } else {
38 resp.statusCode = HttpStatus.NOT_FOUND; 110 resp.statusCode = HttpStatus.NOT_FOUND;
39 resp.outputStream.close(); 111 try {
112 resp.outputStream.close();
113 } catch (e) {
114 if (e is StreamException) {
115 print('Test http_server error closing the response stream: $e');
116 } else {
117 throw e;
118 }
119 }
40 } 120 }
41 }); 121 });
42 }
43 };
44 122
45 // Echos back the contents of the request as the response data. 123 };
46 _httpServer.addRequestHandler((req) => req.path == "/echo", (request, resp) {
47 resp.headers.set("Access-Control-Allow-Origin", "*");
48 124
49 request.inputStream.pipe(resp.outputStream); 125 // Echos back the contents of the request as the response data.
50 }); 126 httpServer.addRequestHandler((req) => req.path == "/echo", (request, resp) {
127 resp.headers.set("Access-Control-Allow-Origin", "*");
51 128
52 _httpServer.listen(host, port); 129 request.inputStream.pipe(resp.outputStream);
130 });
131
132 httpServer.listen(host, port);
133 serverList.add(httpServer);
134 }
135
136 static terminateHttpServers() {
137 for (var server in serverList) server.close();
138 }
53 } 139 }
54
55 terminateHttpServer() {
56 if (_httpServer != null) _httpServer.close();
57 }
OLDNEW

Powered by Google App Engine
This is Rietveld 408576698