Enable and fix `dartfmt --fix` lints
diff --git a/analysis_options.yaml b/analysis_options.yaml
index bfdbb7c..bd5c120 100644
--- a/analysis_options.yaml
+++ b/analysis_options.yaml
@@ -24,7 +24,9 @@
- package_api_docs
- package_names
- package_prefixed_library_names
+ - prefer_equal_for_default_values
- prefer_final_fields
+ - prefer_generic_function_type_aliases
- prefer_is_not_empty
- slash_for_doc_comments
- super_goes_last
@@ -32,5 +34,7 @@
- throw_in_finally
- type_init_formals
- unnecessary_brace_in_string_interps
+ - unnecessary_const
+ - unnecessary_new
- unrelated_type_equality_checks
- valid_regexps
diff --git a/example/example.dart b/example/example.dart
index 195e48e..e940925 100644
--- a/example/example.dart
+++ b/example/example.dart
@@ -19,5 +19,5 @@
}
shelf.Response _echoRequest(shelf.Request request) {
- return new shelf.Response.ok('Request for "${request.url}"');
+ return shelf.Response.ok('Request for "${request.url}"');
}
diff --git a/lib/shelf_io.dart b/lib/shelf_io.dart
index 7cb1230..30ed0d1 100644
--- a/lib/shelf_io.dart
+++ b/lib/shelf_io.dart
@@ -107,12 +107,12 @@
return;
}
- var message = new StringBuffer()
+ var message = StringBuffer()
..writeln("Got a response for hijacked request "
"${shelfRequest.method} ${shelfRequest.requestedUri}:")
..writeln(response.statusCode);
response.headers.forEach((key, value) => message.writeln("$key: $value"));
- throw new Exception(message.toString().trim());
+ throw Exception(message.toString().trim());
}
/// Creates a new [Request] from the provided [HttpRequest].
@@ -130,10 +130,10 @@
void onHijack(void callback(StreamChannel<List<int>> channel)) {
request.response
.detachSocket(writeHeaders: false)
- .then((socket) => callback(new StreamChannel(socket, socket)));
+ .then((socket) => callback(StreamChannel(socket, socket)));
}
- return new Request(request.method, request.requestedUri,
+ return Request(request.method, request.requestedUri,
protocolVersion: request.protocolVersion,
headers: headers,
body: request,
@@ -183,7 +183,7 @@
}
if (!response.headers.containsKey(HttpHeaders.dateHeader)) {
- httpResponse.headers.date = new DateTime.now().toUtc();
+ httpResponse.headers.date = DateTime.now().toUtc();
}
return httpResponse
@@ -195,7 +195,7 @@
// TODO(kevmoo) Make error output plugable. stderr, logging, etc
Response _logError(Request request, String message, [StackTrace stackTrace]) {
// Add information about the request itself.
- var buffer = new StringBuffer();
+ var buffer = StringBuffer();
buffer.write("${request.method} ${request.requestedUri.path}");
if (request.requestedUri.query.isNotEmpty) {
buffer.write("?${request.requestedUri.query}");
@@ -207,16 +207,16 @@
}
Response _logTopLevelError(String message, [StackTrace stackTrace]) {
- var chain = new Chain.current();
+ var chain = Chain.current();
if (stackTrace != null) {
- chain = new Chain.forTrace(stackTrace);
+ chain = Chain.forTrace(stackTrace);
}
chain = chain
.foldFrames((frame) => frame.isCore || frame.package == 'shelf')
.terse;
- stderr.writeln('ERROR - ${new DateTime.now()}');
+ stderr.writeln('ERROR - ${DateTime.now()}');
stderr.writeln(message);
stderr.writeln(chain);
- return new Response.internalServerError();
+ return Response.internalServerError();
}
diff --git a/lib/src/body.dart b/lib/src/body.dart
index b52733b..1ad6f3f 100644
--- a/lib/src/body.dart
+++ b/lib/src/body.dart
@@ -38,7 +38,7 @@
int contentLength;
if (body == null) {
contentLength = 0;
- stream = new Stream.fromIterable([]);
+ stream = Stream.fromIterable([]);
} else if (body is String) {
if (encoding == null) {
var encoded = utf8.encode(body);
@@ -46,23 +46,23 @@
// that an encoding of "text/plain" will stay put.
if (!_isPlainAscii(encoded, body.length)) encoding = utf8;
contentLength = encoded.length;
- stream = new Stream.fromIterable([encoded]);
+ stream = Stream.fromIterable([encoded]);
} else {
var encoded = encoding.encode(body);
contentLength = encoded.length;
- stream = new Stream.fromIterable([encoded]);
+ stream = Stream.fromIterable([encoded]);
}
} else if (body is List) {
contentLength = body.length;
- stream = new Stream.fromIterable([body.cast()]);
+ stream = Stream.fromIterable([body.cast()]);
} else if (body is Stream) {
stream = body.cast();
} else {
- throw new ArgumentError('Response body "$body" must be a String or a '
+ throw ArgumentError('Response body "$body" must be a String or a '
'Stream.');
}
- return new Body._(stream, encoding, contentLength);
+ return Body._(stream, encoding, contentLength);
}
/// Returns whether [bytes] is plain ASCII.
@@ -83,7 +83,7 @@
/// Can only be called once.
Stream<List<int>> read() {
if (_stream == null) {
- throw new StateError("The 'read' method can only be called once on a "
+ throw StateError("The 'read' method can only be called once on a "
"shelf.Request/shelf.Response object.");
}
var stream = _stream;
diff --git a/lib/src/cascade.dart b/lib/src/cascade.dart
index dee3665..459e780 100644
--- a/lib/src/cascade.dart
+++ b/lib/src/cascade.dart
@@ -8,7 +8,7 @@
import 'response.dart';
/// A typedef for [Cascade._shouldCascade].
-typedef bool _ShouldCascade(Response response);
+typedef _ShouldCascade = bool Function(Response response);
/// A helper that calls several handlers in sequence and returns the first
/// acceptable response.
@@ -44,7 +44,7 @@
_parent = null,
_handler = null {
if (statusCodes != null && shouldCascade != null) {
- throw new ArgumentError("statusCodes and shouldCascade may not both be "
+ throw ArgumentError("statusCodes and shouldCascade may not both be "
"passed.");
}
}
@@ -55,7 +55,7 @@
///
/// [handler] will only be called if all previous handlers in the cascade
/// return unacceptable responses.
- Cascade add(Handler handler) => new Cascade._(this, handler, _shouldCascade);
+ Cascade add(Handler handler) => Cascade._(this, handler, _shouldCascade);
/// Exposes this cascade as a single handler.
///
@@ -64,13 +64,13 @@
/// acceptable response, this will return the final response.
Handler get handler {
if (_handler == null) {
- throw new StateError("Can't get a handler for a cascade with no inner "
+ throw StateError("Can't get a handler for a cascade with no inner "
"handlers.");
}
return (request) {
if (_parent._handler == null) return _handler(request);
- return new Future.sync(() => _parent.handler(request)).then((response) {
+ return Future.sync(() => _parent.handler(request)).then((response) {
if (_shouldCascade(response)) return _handler(request);
return response;
});
diff --git a/lib/src/handler.dart b/lib/src/handler.dart
index 811f805..7a5b07a 100644
--- a/lib/src/handler.dart
+++ b/lib/src/handler.dart
@@ -18,4 +18,4 @@
/// may have been touched by other middleware. Similarly the response may be
/// directly returned by an HTTP server or have further processing done by other
/// middleware.
-typedef FutureOr<Response> Handler(Request request);
+typedef Handler = FutureOr<Response> Function(Request request);
diff --git a/lib/src/io_server.dart b/lib/src/io_server.dart
index f2d97f0..447f307 100644
--- a/lib/src/io_server.dart
+++ b/lib/src/io_server.dart
@@ -20,34 +20,33 @@
Uri get url {
if (server.address.isLoopback) {
- return new Uri(scheme: "http", host: "localhost", port: server.port);
+ return Uri(scheme: "http", host: "localhost", port: server.port);
}
// IPv6 addresses in URLs need to be enclosed in square brackets to avoid
// URL ambiguity with the ":" in the address.
if (server.address.type == InternetAddressType.IPv6) {
- return new Uri(
+ return Uri(
scheme: "http",
host: "[${server.address.address}]",
port: server.port);
}
- return new Uri(
- scheme: "http", host: server.address.address, port: server.port);
+ return Uri(scheme: "http", host: server.address.address, port: server.port);
}
/// Calls [HttpServer.bind] and wraps the result in an [IOServer].
static Future<IOServer> bind(address, int port, {int backlog}) async {
backlog ??= 0;
var server = await HttpServer.bind(address, port, backlog: backlog);
- return new IOServer(server);
+ return IOServer(server);
}
IOServer(this.server);
void mount(Handler handler) {
if (_mounted) {
- throw new StateError("Can't mount two handlers for the same server.");
+ throw StateError("Can't mount two handlers for the same server.");
}
_mounted = true;
diff --git a/lib/src/message.dart b/lib/src/message.dart
index 7a55ef5..cd19f03 100644
--- a/lib/src/message.dart
+++ b/lib/src/message.dart
@@ -16,9 +16,8 @@
/// The default set of headers for a message created with no body and no
/// explicit headers.
-final _defaultHeaders = new ShelfUnmodifiableMap<String>(
- {"content-length": "0"},
- ignoreKeyCase: true);
+final _defaultHeaders =
+ ShelfUnmodifiableMap<String>({"content-length": "0"}, ignoreKeyCase: true);
/// Represents logic shared between [Request] and [Response].
abstract class Message {
@@ -66,15 +65,13 @@
{Encoding encoding,
Map<String, String> headers,
Map<String, Object> context})
- : this._(new Body(body, encoding), headers, context);
+ : this._(Body(body, encoding), headers, context);
Message._(Body body, Map<String, String> headers, Map<String, Object> context)
: _body = body,
- headers = new ShelfUnmodifiableMap<String>(
- _adjustHeaders(headers, body),
+ headers = ShelfUnmodifiableMap<String>(_adjustHeaders(headers, body),
ignoreKeyCase: true),
- context =
- new ShelfUnmodifiableMap<Object>(context, ignoreKeyCase: false);
+ context = ShelfUnmodifiableMap<Object>(context, ignoreKeyCase: false);
/// The contents of the content-length field in [headers].
///
@@ -120,7 +117,7 @@
MediaType get _contentType {
if (_contentTypeCache != null) return _contentTypeCache;
if (!headers.containsKey('content-type')) return null;
- _contentTypeCache = new MediaType.parse(headers['content-type']);
+ _contentTypeCache = MediaType.parse(headers['content-type']);
return _contentTypeCache;
}
@@ -166,15 +163,15 @@
}
var newHeaders = headers == null
- ? new CaseInsensitiveMap<String>()
- : new CaseInsensitiveMap<String>.from(headers);
+ ? CaseInsensitiveMap<String>()
+ : CaseInsensitiveMap<String>.from(headers);
if (!sameEncoding) {
if (newHeaders['content-type'] == null) {
newHeaders['content-type'] =
'application/octet-stream; charset=${body.encoding.name}';
} else {
- var contentType = new MediaType.parse(newHeaders['content-type'])
+ var contentType = MediaType.parse(newHeaders['content-type'])
.change(parameters: {'charset': body.encoding.name});
newHeaders['content-type'] = contentType.toString();
}
@@ -197,6 +194,6 @@
var contentType = getHeader(headers, 'content-type');
if (contentType == null) return false;
- var charset = new MediaType.parse(contentType).parameters['charset'];
+ var charset = MediaType.parse(contentType).parameters['charset'];
return Encoding.getByName(charset) == body.encoding;
}
diff --git a/lib/src/middleware.dart b/lib/src/middleware.dart
index f470893..445efdd 100644
--- a/lib/src/middleware.dart
+++ b/lib/src/middleware.dart
@@ -25,7 +25,7 @@
/// [HijackException]s on without modification.
///
/// A simple [Middleware] can be created using [createMiddleware].
-typedef Handler Middleware(Handler innerHandler);
+typedef Middleware = Handler Function(Handler innerHandler);
/// Creates a [Middleware] using the provided functions.
///
@@ -64,10 +64,10 @@
return (Handler innerHandler) {
return (request) {
- return new Future.sync(() => requestHandler(request)).then((response) {
+ return Future.sync(() => requestHandler(request)).then((response) {
if (response != null) return response;
- return new Future.sync(() => innerHandler(request))
+ return Future.sync(() => innerHandler(request))
.then((response) => responseHandler(response), onError: onError);
});
};
diff --git a/lib/src/middleware/logger.dart b/lib/src/middleware/logger.dart
index cf10f54..412ce11 100644
--- a/lib/src/middleware/logger.dart
+++ b/lib/src/middleware/logger.dart
@@ -24,10 +24,10 @@
if (logger == null) logger = _defaultLogger;
return (request) {
- var startTime = new DateTime.now();
- var watch = new Stopwatch()..start();
+ var startTime = DateTime.now();
+ var watch = Stopwatch()..start();
- return new Future.sync(() => innerHandler(request)).then((response) {
+ return Future.sync(() => innerHandler(request)).then((response) {
var msg = _getMessage(startTime, response.statusCode,
request.requestedUri, request.method, watch.elapsed);
@@ -61,9 +61,9 @@
String _getErrorMessage(DateTime requestTime, Uri requestedUri, String method,
Duration elapsedTime, Object error, StackTrace stack) {
- var chain = new Chain.current();
+ var chain = Chain.current();
if (stack != null) {
- chain = new Chain.forTrace(stack)
+ chain = Chain.forTrace(stack)
.foldFrames((frame) => frame.isCore || frame.package == 'shelf')
.terse;
}
diff --git a/lib/src/pipeline.dart b/lib/src/pipeline.dart
index ff5b14f..a4d5c4a 100644
--- a/lib/src/pipeline.dart
+++ b/lib/src/pipeline.dart
@@ -27,8 +27,7 @@
///
/// [middleware] will be the last [Middleware] to process a request and
/// the first to process a response.
- Pipeline addMiddleware(Middleware middleware) =>
- new Pipeline._(middleware, this);
+ Pipeline addMiddleware(Middleware middleware) => Pipeline._(middleware, this);
/// Returns a new [Handler] with [handler] as the final processor of a
/// [Request] if all of the middleware in the pipeline have passed the request
diff --git a/lib/src/request.dart b/lib/src/request.dart
index cbb2602..4351737 100644
--- a/lib/src/request.dart
+++ b/lib/src/request.dart
@@ -13,7 +13,8 @@
/// A callback provided by a Shelf adapter that's used by [Request.hijack] to
/// provide a [HijackCallback] with a socket.
-typedef void _OnHijackCallback(void callback(StreamChannel<List<int>> channel));
+typedef _OnHijackCallback = void Function(
+ void Function(StreamChannel<List<int>> channel) callback);
/// Represents an HTTP request to be processed by a Shelf application.
class Request extends Message {
@@ -142,7 +143,7 @@
body: body,
encoding: encoding,
context: context,
- onHijack: onHijack == null ? null : new _OnHijack(onHijack));
+ onHijack: onHijack == null ? null : _OnHijack(onHijack));
/// This constructor has the same signature as [new Request] except that
/// accepts [onHijack] as [_OnHijack].
@@ -166,20 +167,20 @@
this.handlerPath = _computeHandlerPath(requestedUri, handlerPath, url),
this._onHijack = onHijack,
super(body, encoding: encoding, headers: headers, context: context) {
- if (method.isEmpty) throw new ArgumentError('method cannot be empty.');
+ if (method.isEmpty) throw ArgumentError('method cannot be empty.');
if (!requestedUri.isAbsolute) {
- throw new ArgumentError(
+ throw ArgumentError(
'requestedUri "$requestedUri" must be an absolute URL.');
}
if (requestedUri.fragment.isNotEmpty) {
- throw new ArgumentError(
+ throw ArgumentError(
'requestedUri "$requestedUri" may not have a fragment.');
}
if (this.handlerPath + this.url.path != this.requestedUri.path) {
- throw new ArgumentError('handlerPath "$handlerPath" and url "$url" must '
+ throw ArgumentError('handlerPath "$handlerPath" and url "$url" must '
'combine to equal requestedUri path "${requestedUri.path}".');
}
}
@@ -221,7 +222,7 @@
var handlerPath = this.handlerPath;
if (path != null) handlerPath += path;
- return new Request._(this.method, this.requestedUri,
+ return Request._(this.method, this.requestedUri,
protocolVersion: this.protocolVersion,
headers: headers,
handlerPath: handlerPath,
@@ -243,7 +244,7 @@
/// request can be hijacked.
void hijack(void callback(StreamChannel<List<int>> channel)) {
if (_onHijack == null) {
- throw new StateError("This request can't be hijacked.");
+ throw StateError("This request can't be hijacked.");
}
_onHijack.run(callback);
@@ -267,7 +268,7 @@
///
/// Throws a [StateError] if [this] has already been called.
void run(void callback(StreamChannel<List<int>> channel)) {
- if (called) throw new StateError("This request has already been hijacked.");
+ if (called) throw StateError("This request has already been hijacked.");
called = true;
newFuture(() => _callback(callback));
}
@@ -286,40 +287,40 @@
if (url != null) {
if (url.scheme.isNotEmpty || url.hasAuthority || url.fragment.isNotEmpty) {
- throw new ArgumentError('url "$url" may contain only a path and query '
+ throw ArgumentError('url "$url" may contain only a path and query '
'parameters.');
}
if (!requestedUri.path.endsWith(url.path)) {
- throw new ArgumentError('url "$url" must be a suffix of requestedUri '
+ throw ArgumentError('url "$url" must be a suffix of requestedUri '
'"$requestedUri".');
}
if (requestedUri.query != url.query) {
- throw new ArgumentError('url "$url" must have the same query parameters '
+ throw ArgumentError('url "$url" must have the same query parameters '
'as requestedUri "$requestedUri".');
}
if (url.path.startsWith('/')) {
- throw new ArgumentError('url "$url" must be relative.');
+ throw ArgumentError('url "$url" must be relative.');
}
var startOfUrl = requestedUri.path.length - url.path.length;
if (url.path.isNotEmpty &&
requestedUri.path.substring(startOfUrl - 1, startOfUrl) != '/') {
- throw new ArgumentError('url "$url" must be on a path boundary in '
+ throw ArgumentError('url "$url" must be on a path boundary in '
'requestedUri "$requestedUri".');
}
return url;
} else if (handlerPath != null) {
- return new Uri(
+ return Uri(
path: requestedUri.path.substring(handlerPath.length),
query: requestedUri.query);
} else {
// Skip the initial "/".
var path = requestedUri.path.substring(1);
- return new Uri(path: path, query: requestedUri.query);
+ return Uri(path: path, query: requestedUri.query);
}
}
@@ -336,13 +337,12 @@
if (handlerPath != null) {
if (!requestedUri.path.startsWith(handlerPath)) {
- throw new ArgumentError('handlerPath "$handlerPath" must be a prefix of '
+ throw ArgumentError('handlerPath "$handlerPath" must be a prefix of '
'requestedUri path "${requestedUri.path}"');
}
if (!handlerPath.startsWith('/')) {
- throw new ArgumentError(
- 'handlerPath "$handlerPath" must be root-relative.');
+ throw ArgumentError('handlerPath "$handlerPath" must be root-relative.');
}
return handlerPath;
diff --git a/lib/src/response.dart b/lib/src/response.dart
index 67e028e..b6cb0f0 100644
--- a/lib/src/response.dart
+++ b/lib/src/response.dart
@@ -171,8 +171,7 @@
Response.notModified(
{Map<String, String> headers, Map<String, Object> context})
: this(304,
- headers:
- addHeader(headers, 'date', formatHttpDate(new DateTime.now())),
+ headers: addHeader(headers, 'date', formatHttpDate(DateTime.now())),
context: context);
/// Constructs a 403 Forbidden response.
@@ -284,7 +283,7 @@
Map<String, Object> context})
: super(body, encoding: encoding, headers: headers, context: context) {
if (statusCode < 100) {
- throw new ArgumentError("Invalid status code: $statusCode.");
+ throw ArgumentError("Invalid status code: $statusCode.");
}
}
@@ -310,7 +309,7 @@
if (body == null) body = getBody(this);
- return new Response(this.statusCode,
+ return Response(this.statusCode,
body: body, headers: headers, context: context);
}
}
@@ -324,8 +323,8 @@
return addHeader(headers, 'content-type', 'text/plain');
}
- var contentType = new MediaType.parse(headers['content-type'])
- .change(mimeType: 'text/plain');
+ var contentType =
+ MediaType.parse(headers['content-type']).change(mimeType: 'text/plain');
return addHeader(headers, 'content-type', contentType.toString());
}
@@ -336,6 +335,6 @@
if (location is String) return location;
if (location is Uri) return location.toString();
- throw new ArgumentError('Response location must be a String or Uri, was '
+ throw ArgumentError('Response location must be a String or Uri, was '
'"$location".');
}
diff --git a/lib/src/server_handler.dart b/lib/src/server_handler.dart
index db9efc7..c6b6afd 100644
--- a/lib/src/server_handler.dart
+++ b/lib/src/server_handler.dart
@@ -38,13 +38,12 @@
///
/// If [onClose] is passed, it's called when [server] is closed. It may return
/// a [Future] or `null`; its return value is returned by [Server.close].
- ServerHandler(Uri url, {onClose()})
- : _server = new _HandlerServer(url, onClose);
+ ServerHandler(Uri url, {onClose()}) : _server = _HandlerServer(url, onClose);
/// Pipes requests to [server]'s handler.
FutureOr<Response> _onRequest(Request request) {
if (_server._closeMemo.hasRun) {
- throw new StateError("Request received after the server was closed.");
+ throw StateError("Request received after the server was closed.");
}
if (_server._handler != null) return _server._handler(request);
@@ -69,13 +68,13 @@
/// A future that fires once [mount] has been called.
Future get _onMounted => _onMountedCompleter.future;
- final _onMountedCompleter = new Completer();
+ final _onMountedCompleter = Completer();
_HandlerServer(this.url, this._onClose);
void mount(Handler handler) {
if (_handler != null) {
- throw new StateError("Can't mount two handlers for the same server.");
+ throw StateError("Can't mount two handlers for the same server.");
}
_handler = handler;
@@ -85,5 +84,5 @@
Future close() => _closeMemo.runOnce(() {
return _onClose == null ? null : _onClose();
});
- final _closeMemo = new AsyncMemoizer();
+ final _closeMemo = AsyncMemoizer();
}
diff --git a/lib/src/shelf_unmodifiable_map.dart b/lib/src/shelf_unmodifiable_map.dart
index 7d4de9b..e23df7b 100644
--- a/lib/src/shelf_unmodifiable_map.dart
+++ b/lib/src/shelf_unmodifiable_map.dart
@@ -35,12 +35,12 @@
}
if (ignoreKeyCase) {
- source = new CaseInsensitiveMap<V>.from(source);
+ source = CaseInsensitiveMap<V>.from(source);
} else {
- source = new Map<String, V>.from(source);
+ source = Map<String, V>.from(source);
}
- return new ShelfUnmodifiableMap<V>._(source, ignoreKeyCase);
+ return ShelfUnmodifiableMap<V>._(source, ignoreKeyCase);
}
/// Returns an empty [ShelfUnmodifiableMap].
diff --git a/lib/src/util.dart b/lib/src/util.dart
index 167969e..b2fc769 100644
--- a/lib/src/util.dart
+++ b/lib/src/util.dart
@@ -10,7 +10,7 @@
/// Like [new Future], but avoids around issue 11911 by using [new Future.value]
/// under the covers.
-Future newFuture(callback()) => new Future.value().then((_) => callback());
+Future newFuture(callback()) => Future.value().then((_) => callback());
/// Run [callback] and capture any errors that would otherwise be top-leveled.
///
@@ -35,7 +35,7 @@
Map<K, V> updateMap<K, V>(Map<K, V> original, Map<K, V> updates) {
if (updates == null || updates.isEmpty) return original;
- return new Map.from(original)..addAll(updates);
+ return Map.from(original)..addAll(updates);
}
/// Adds a header with [name] and [value] to [headers], which may be null.
@@ -43,7 +43,7 @@
/// Returns a new map without modifying [headers].
Map<String, String> addHeader(
Map<String, String> headers, String name, String value) {
- headers = headers == null ? {} : new Map.from(headers);
+ headers = headers == null ? {} : Map.from(headers);
headers[name] = value;
return headers;
}
diff --git a/test/add_chunked_encoding_test.dart b/test/add_chunked_encoding_test.dart
index ad12d73..2b06ad0 100644
--- a/test/add_chunked_encoding_test.dart
+++ b/test/add_chunked_encoding_test.dart
@@ -10,56 +10,51 @@
void main() {
test('adds chunked encoding with no transfer-encoding header', () async {
var response = await _chunkResponse(
- new Response.ok(new Stream.fromIterable(["hi".codeUnits])));
+ Response.ok(Stream.fromIterable(["hi".codeUnits])));
expect(response.headers, containsPair('transfer-encoding', 'chunked'));
expect(response.readAsString(), completion(equals("2\r\nhi\r\n0\r\n\r\n")));
});
test('adds chunked encoding with transfer-encoding: identity', () async {
- var response = await _chunkResponse(new Response.ok(
- new Stream.fromIterable(["hi".codeUnits]),
+ var response = await _chunkResponse(Response.ok(
+ Stream.fromIterable(["hi".codeUnits]),
headers: {'transfer-encoding': 'identity'}));
expect(response.headers, containsPair('transfer-encoding', 'chunked'));
expect(response.readAsString(), completion(equals("2\r\nhi\r\n0\r\n\r\n")));
});
test("doesn't add chunked encoding with content length", () async {
- var response = await _chunkResponse(new Response.ok("hi"));
+ var response = await _chunkResponse(Response.ok("hi"));
expect(response.headers, isNot(contains('transfer-encoding')));
expect(response.readAsString(), completion(equals("hi")));
});
test("doesn't add chunked encoding with status 1xx", () async {
- var response =
- await _chunkResponse(new Response(123, body: new Stream.empty()));
+ var response = await _chunkResponse(Response(123, body: Stream.empty()));
expect(response.headers, isNot(contains('transfer-encoding')));
expect(response.read().toList(), completion(isEmpty));
});
test("doesn't add chunked encoding with status 204", () async {
- var response =
- await _chunkResponse(new Response(204, body: new Stream.empty()));
+ var response = await _chunkResponse(Response(204, body: Stream.empty()));
expect(response.headers, isNot(contains('transfer-encoding')));
expect(response.read().toList(), completion(isEmpty));
});
test("doesn't add chunked encoding with status 304", () async {
- var response =
- await _chunkResponse(new Response(204, body: new Stream.empty()));
+ var response = await _chunkResponse(Response(204, body: Stream.empty()));
expect(response.headers, isNot(contains('transfer-encoding')));
expect(response.read().toList(), completion(isEmpty));
});
test("doesn't add chunked encoding with status 204", () async {
- var response =
- await _chunkResponse(new Response(204, body: new Stream.empty()));
+ var response = await _chunkResponse(Response(204, body: Stream.empty()));
expect(response.headers, isNot(contains('transfer-encoding')));
expect(response.read().toList(), completion(isEmpty));
});
test("doesn't add chunked encoding with status 204", () async {
- var response =
- await _chunkResponse(new Response(204, body: new Stream.empty()));
+ var response = await _chunkResponse(Response(204, body: Stream.empty()));
expect(response.headers, isNot(contains('transfer-encoding')));
expect(response.read().toList(), completion(isEmpty));
});
diff --git a/test/cascade_test.dart b/test/cascade_test.dart
index 714f632..afa33b4 100644
--- a/test/cascade_test.dart
+++ b/test/cascade_test.dart
@@ -13,23 +13,23 @@
group('a cascade with several handlers', () {
Handler handler;
setUp(() {
- handler = new Cascade().add((request) {
+ handler = Cascade().add((request) {
if (request.headers['one'] == 'false') {
- return new Response.notFound('handler 1');
+ return Response.notFound('handler 1');
} else {
- return new Response.ok('handler 1');
+ return Response.ok('handler 1');
}
}).add((request) {
if (request.headers['two'] == 'false') {
- return new Response.notFound('handler 2');
+ return Response.notFound('handler 2');
} else {
- return new Response.ok('handler 2');
+ return Response.ok('handler 2');
}
}).add((request) {
if (request.headers['three'] == 'false') {
- return new Response.notFound('handler 3');
+ return Response.notFound('handler 3');
} else {
- return new Response.ok('handler 3');
+ return Response.ok('handler 3');
}
}).handler;
});
@@ -43,9 +43,8 @@
test(
"the second response should be returned if it matches and the first "
"doesn't", () {
- return new Future.sync(() {
- return handler(
- new Request('GET', localhostUri, headers: {'one': 'false'}));
+ return Future.sync(() {
+ return handler(Request('GET', localhostUri, headers: {'one': 'false'}));
}).then((response) {
expect(response.statusCode, equals(200));
expect(response.readAsString(), completion(equals('handler 2')));
@@ -55,8 +54,8 @@
test(
"the third response should be returned if it matches and the first "
"two don't", () {
- return new Future.sync(() {
- return handler(new Request('GET', localhostUri,
+ return Future.sync(() {
+ return handler(Request('GET', localhostUri,
headers: {'one': 'false', 'two': 'false'}));
}).then((response) {
expect(response.statusCode, equals(200));
@@ -65,8 +64,8 @@
});
test("the third response should be returned if no response matches", () {
- return new Future.sync(() {
- return handler(new Request('GET', localhostUri,
+ return Future.sync(() {
+ return handler(Request('GET', localhostUri,
headers: {'one': 'false', 'two': 'false', 'three': 'false'}));
}).then((response) {
expect(response.statusCode, equals(404));
@@ -76,9 +75,9 @@
});
test('a 404 response triggers a cascade by default', () {
- var handler = new Cascade()
- .add((_) => new Response.notFound('handler 1'))
- .add((_) => new Response.ok('handler 2'))
+ var handler = Cascade()
+ .add((_) => Response.notFound('handler 1'))
+ .add((_) => Response.ok('handler 2'))
.handler;
return makeSimpleRequest(handler).then((response) {
@@ -88,9 +87,9 @@
});
test('a 405 response triggers a cascade by default', () {
- var handler = new Cascade()
- .add((_) => new Response(405))
- .add((_) => new Response.ok('handler 2'))
+ var handler = Cascade()
+ .add((_) => Response(405))
+ .add((_) => Response.ok('handler 2'))
.handler;
return makeSimpleRequest(handler).then((response) {
@@ -100,11 +99,11 @@
});
test('[statusCodes] controls which statuses cause cascading', () {
- var handler = new Cascade(statusCodes: [302, 403])
- .add((_) => new Response.found('/'))
- .add((_) => new Response.forbidden('handler 2'))
- .add((_) => new Response.notFound('handler 3'))
- .add((_) => new Response.ok('handler 4'))
+ var handler = Cascade(statusCodes: [302, 403])
+ .add((_) => Response.found('/'))
+ .add((_) => Response.forbidden('handler 2'))
+ .add((_) => Response.notFound('handler 3'))
+ .add((_) => Response.ok('handler 4'))
.handler;
return makeSimpleRequest(handler).then((response) {
@@ -115,11 +114,11 @@
test('[shouldCascade] controls which responses cause cascading', () {
var handler =
- new Cascade(shouldCascade: (response) => response.statusCode % 2 == 1)
- .add((_) => new Response.movedPermanently('/'))
- .add((_) => new Response.forbidden('handler 2'))
- .add((_) => new Response.notFound('handler 3'))
- .add((_) => new Response.ok('handler 4'))
+ Cascade(shouldCascade: (response) => response.statusCode % 2 == 1)
+ .add((_) => Response.movedPermanently('/'))
+ .add((_) => Response.forbidden('handler 2'))
+ .add((_) => Response.notFound('handler 3'))
+ .add((_) => Response.ok('handler 4'))
.handler;
return makeSimpleRequest(handler).then((response) {
@@ -130,14 +129,13 @@
group('errors', () {
test('getting the handler for an empty cascade fails', () {
- expect(() => new Cascade().handler, throwsStateError);
+ expect(() => Cascade().handler, throwsStateError);
});
test('passing [statusCodes] and [shouldCascade] at the same time fails',
() {
expect(
- () =>
- new Cascade(statusCodes: [404, 405], shouldCascade: (_) => false),
+ () => Cascade(statusCodes: [404, 405], shouldCascade: (_) => false),
throwsArgumentError);
});
});
diff --git a/test/create_middleware_test.dart b/test/create_middleware_test.dart
index 868ea34..db515f7 100644
--- a/test/create_middleware_test.dart
+++ b/test/create_middleware_test.dart
@@ -40,8 +40,8 @@
test('async null response forwards to inner handler', () {
var handler = const Pipeline()
- .addMiddleware(createMiddleware(
- requestHandler: (request) => new Future.value(null)))
+ .addMiddleware(
+ createMiddleware(requestHandler: (request) => Future.value(null)))
.addHandler(syncHandler);
return makeSimpleRequest(handler).then((response) {
@@ -63,8 +63,7 @@
test('async response is returned', () {
var handler = const Pipeline()
.addMiddleware(createMiddleware(
- requestHandler: (request) =>
- new Future.value(_middlewareResponse)))
+ requestHandler: (request) => Future.value(_middlewareResponse)))
.addHandler(_failHandler);
return makeSimpleRequest(handler).then((response) {
@@ -88,7 +87,7 @@
test('with async result, responseHandler is not called', () {
var middleware = createMiddleware(
- requestHandler: (request) => new Future.value(_middlewareResponse),
+ requestHandler: (request) => Future.value(_middlewareResponse),
responseHandler: (response) => _fail('should not be called'));
var handler =
const Pipeline().addMiddleware(middleware).addHandler(syncHandler);
@@ -119,10 +118,9 @@
var handler = const Pipeline()
.addMiddleware(createMiddleware(responseHandler: (response) {
expect(response.headers['from'], 'handler');
- return new Future.value(_middlewareResponse);
+ return Future.value(_middlewareResponse);
})).addHandler((request) {
- return new Future(
- () => syncHandler(request, headers: {'from': 'handler'}));
+ return Future(() => syncHandler(request, headers: {'from': 'handler'}));
});
return makeSimpleRequest(handler).then((response) {
@@ -144,8 +142,7 @@
test('async error thrown by requestHandler bubbles down', () {
var handler = const Pipeline()
.addMiddleware(createMiddleware(
- requestHandler: (request) =>
- new Future.error('middleware error')))
+ requestHandler: (request) => Future.error('middleware error')))
.addHandler(_failHandler);
expect(makeSimpleRequest(handler), throwsA('middleware error'));
@@ -237,4 +234,4 @@
Response _failHandler(Request request) => _fail('should never get here');
final Response _middlewareResponse =
- new Response.ok('middleware content', headers: {'from': 'middleware'});
+ Response.ok('middleware content', headers: {'from': 'middleware'});
diff --git a/test/hijack_test.dart b/test/hijack_test.dart
index 852fcee..426f7c2 100644
--- a/test/hijack_test.dart
+++ b/test/hijack_test.dart
@@ -12,7 +12,7 @@
void main() {
test('hijacking a non-hijackable request throws a StateError', () {
- expect(() => new Request('GET', localhostUri).hijack((_) => null),
+ expect(() => Request('GET', localhostUri).hijack((_) => null),
throwsStateError);
});
@@ -20,15 +20,15 @@
'hijacking a hijackable request throws a HijackException and calls '
'onHijack', () {
var request =
- new Request('GET', localhostUri, onHijack: expectAsync1((callback) {
- var streamController = new StreamController<List<int>>();
+ Request('GET', localhostUri, onHijack: expectAsync1((callback) {
+ var streamController = StreamController<List<int>>();
streamController.add([1, 2, 3]);
streamController.close();
- var sinkController = new StreamController<List<int>>();
+ var sinkController = StreamController<List<int>>();
expect(sinkController.stream.first, completion(equals([4, 5, 6])));
- callback(new StreamChannel(streamController.stream, sinkController));
+ callback(StreamChannel(streamController.stream, sinkController));
}));
expect(
@@ -42,7 +42,7 @@
test('hijacking a hijackable request twice throws a StateError', () {
// Assert that the [onHijack] callback is only called once.
- var request = new Request('GET', localhostUri,
+ var request = Request('GET', localhostUri,
onHijack: expectAsync1((_) => null, count: 1));
expect(() => request.hijack((_) => null), throwsHijackException);
@@ -52,7 +52,7 @@
group('calling change', () {
test('hijacking a non-hijackable request throws a StateError', () {
- var request = new Request('GET', localhostUri);
+ var request = Request('GET', localhostUri);
var newRequest = request.change();
expect(() => newRequest.hijack((_) => null), throwsStateError);
});
@@ -61,15 +61,15 @@
'hijacking a hijackable request throws a HijackException and calls '
'onHijack', () {
var request =
- new Request('GET', localhostUri, onHijack: expectAsync1((callback) {
- var streamController = new StreamController<List<int>>();
+ Request('GET', localhostUri, onHijack: expectAsync1((callback) {
+ var streamController = StreamController<List<int>>();
streamController.add([1, 2, 3]);
streamController.close();
- var sinkController = new StreamController<List<int>>();
+ var sinkController = StreamController<List<int>>();
expect(sinkController.stream.first, completion(equals([4, 5, 6])));
- callback(new StreamChannel(streamController.stream, sinkController));
+ callback(StreamChannel(streamController.stream, sinkController));
}));
var newRequest = request.change();
@@ -87,7 +87,7 @@
'hijacking the original request after calling change throws a '
'StateError', () {
// Assert that the [onHijack] callback is only called once.
- var request = new Request('GET', localhostUri,
+ var request = Request('GET', localhostUri,
onHijack: expectAsync1((_) => null, count: 1));
var newRequest = request.change();
diff --git a/test/io_server_test.dart b/test/io_server_test.dart
index 4d5e3fc..54bb0b9 100644
--- a/test/io_server_test.dart
+++ b/test/io_server_test.dart
@@ -33,7 +33,7 @@
test("delays HTTP requests until a handler is mounted", () async {
expect(http.read(server.url), completion(equals('Hello from /')));
- await new Future.delayed(Duration.zero);
+ await Future.delayed(Duration.zero);
server.mount(asyncHandler);
});
diff --git a/test/message_change_test.dart b/test/message_change_test.dart
index cea323e..17c9d4d 100644
--- a/test/message_change_test.dart
+++ b/test/message_change_test.dart
@@ -15,14 +15,14 @@
void main() {
group('Request', () {
_testChange(({body, headers, context}) {
- return new Request('GET', localhostUri,
+ return Request('GET', localhostUri,
body: body, headers: headers, context: context);
});
});
group('Response', () {
_testChange(({body, headers, context}) {
- return new Response.ok(body, headers: headers, context: context);
+ return Response.ok(body, headers: headers, context: context);
});
});
}
@@ -45,8 +45,8 @@
test('with Stream', () async {
var request = factory(body: 'Hello, world');
var copy = request.change(
- body: new Stream.fromIterable(['Goodbye, world'])
- .transform(utf8.encoder));
+ body:
+ Stream.fromIterable(['Goodbye, world']).transform(utf8.encoder));
var newBody = await copy.readAsString();
diff --git a/test/message_test.dart b/test/message_test.dart
index 62cff27..6ee475c 100644
--- a/test/message_test.dart
+++ b/test/message_test.dart
@@ -17,7 +17,7 @@
Message change(
{Map<String, String> headers, Map<String, Object> context, body}) {
- throw new UnimplementedError();
+ throw UnimplementedError();
}
}
@@ -26,7 +26,7 @@
Map<String, Object> context,
body,
Encoding encoding}) {
- return new _TestMessage(headers, context, body, encoding);
+ return _TestMessage(headers, context, body, encoding);
}
void main() {
@@ -81,12 +81,12 @@
});
test("supports a Stream<List<int>> body", () {
- var controller = new StreamController();
+ var controller = StreamController();
var request = _createMessage(body: controller.stream);
expect(request.readAsString(), completion(equals("hello, world")));
controller.add(helloBytes);
- return new Future(() {
+ return Future(() {
controller
..add(worldBytes)
..close();
@@ -95,7 +95,7 @@
test("defaults to UTF-8", () {
var request = _createMessage(
- body: new Stream.fromIterable([
+ body: Stream.fromIterable([
[195, 168]
]));
expect(request.readAsString(), completion(equals("è")));
@@ -104,7 +104,7 @@
test("the content-type header overrides the default", () {
var request = _createMessage(
headers: {'content-type': 'text/plain; charset=iso-8859-1'},
- body: new Stream.fromIterable([
+ body: Stream.fromIterable([
[195, 168]
]));
expect(request.readAsString(), completion(equals("è")));
@@ -113,7 +113,7 @@
test("an explicit encoding overrides the content-type header", () {
var request = _createMessage(
headers: {'content-type': 'text/plain; charset=iso-8859-1'},
- body: new Stream.fromIterable([
+ body: Stream.fromIterable([
[195, 168]
]));
expect(request.readAsString(latin1), completion(equals("è")));
@@ -127,13 +127,13 @@
});
test("supports a Stream<List<int>> body", () {
- var controller = new StreamController();
+ var controller = StreamController();
var request = _createMessage(body: controller.stream);
expect(request.read().toList(),
completion(equals([helloBytes, worldBytes])));
controller.add(helloBytes);
- return new Future(() {
+ return Future(() {
controller
..add(worldBytes)
..close();
@@ -191,13 +191,13 @@
});
test("is null for a stream body", () {
- var request = _createMessage(body: new Stream.empty());
+ var request = _createMessage(body: Stream.empty());
expect(request.contentLength, isNull);
});
test("uses the content-length header for a stream body", () {
var request = _createMessage(
- body: new Stream.empty(), headers: {'content-length': '42'});
+ body: Stream.empty(), headers: {'content-length': '42'});
expect(request.contentLength, 42);
});
diff --git a/test/request_test.dart b/test/request_test.dart
index bcd3701..6febec0 100644
--- a/test/request_test.dart
+++ b/test/request_test.dart
@@ -11,45 +11,42 @@
import 'test_util.dart';
Request _request({Map<String, String> headers, body, Encoding encoding}) {
- return new Request("GET", localhostUri,
+ return Request("GET", localhostUri,
headers: headers, body: body, encoding: encoding);
}
void main() {
group('constructor', () {
test('protocolVersion defaults to "1.1"', () {
- var request = new Request('GET', localhostUri);
+ var request = Request('GET', localhostUri);
expect(request.protocolVersion, '1.1');
});
test('provide non-default protocolVersion', () {
- var request = new Request('GET', localhostUri, protocolVersion: '1.0');
+ var request = Request('GET', localhostUri, protocolVersion: '1.0');
expect(request.protocolVersion, '1.0');
});
group("url", () {
test("defaults to the requestedUri's relativized path and query", () {
- var request =
- new Request('GET', Uri.parse("http://localhost/foo/bar?q=1"));
+ var request = Request('GET', Uri.parse("http://localhost/foo/bar?q=1"));
expect(request.url, equals(Uri.parse("foo/bar?q=1")));
});
test("is inferred from handlerPath if possible", () {
- var request = new Request(
- 'GET', Uri.parse("http://localhost/foo/bar?q=1"),
+ var request = Request('GET', Uri.parse("http://localhost/foo/bar?q=1"),
handlerPath: '/foo/');
expect(request.url, equals(Uri.parse("bar?q=1")));
});
test("uses the given value if passed", () {
- var request = new Request(
- 'GET', Uri.parse("http://localhost/foo/bar?q=1"),
+ var request = Request('GET', Uri.parse("http://localhost/foo/bar?q=1"),
url: Uri.parse("bar?q=1"));
expect(request.url, equals(Uri.parse("bar?q=1")));
});
test("may be empty", () {
- var request = new Request('GET', Uri.parse("http://localhost/foo/bar"),
+ var request = Request('GET', Uri.parse("http://localhost/foo/bar"),
url: Uri.parse(""));
expect(request.url, equals(Uri.parse("")));
});
@@ -57,35 +54,31 @@
group("handlerPath", () {
test("defaults to '/'", () {
- var request = new Request('GET', Uri.parse("http://localhost/foo/bar"));
+ var request = Request('GET', Uri.parse("http://localhost/foo/bar"));
expect(request.handlerPath, equals('/'));
});
test("is inferred from url if possible", () {
- var request = new Request(
- 'GET', Uri.parse("http://localhost/foo/bar?q=1"),
+ var request = Request('GET', Uri.parse("http://localhost/foo/bar?q=1"),
url: Uri.parse("bar?q=1"));
expect(request.handlerPath, equals("/foo/"));
});
test("uses the given value if passed", () {
- var request = new Request(
- 'GET', Uri.parse("http://localhost/foo/bar?q=1"),
+ var request = Request('GET', Uri.parse("http://localhost/foo/bar?q=1"),
handlerPath: '/foo/');
expect(request.handlerPath, equals("/foo/"));
});
test("adds a trailing slash to the given value if necessary", () {
- var request = new Request(
- 'GET', Uri.parse("http://localhost/foo/bar?q=1"),
+ var request = Request('GET', Uri.parse("http://localhost/foo/bar?q=1"),
handlerPath: '/foo');
expect(request.handlerPath, equals("/foo/"));
expect(request.url, equals(Uri.parse("bar?q=1")));
});
test("may be a single slash", () {
- var request = new Request(
- 'GET', Uri.parse("http://localhost/foo/bar?q=1"),
+ var request = Request('GET', Uri.parse("http://localhost/foo/bar?q=1"),
handlerPath: '/');
expect(request.handlerPath, equals("/"));
expect(request.url, equals(Uri.parse("foo/bar?q=1")));
@@ -95,13 +88,12 @@
group("errors", () {
group('requestedUri', () {
test('must be absolute', () {
- expect(() => new Request('GET', Uri.parse('/path')),
- throwsArgumentError);
+ expect(() => Request('GET', Uri.parse('/path')), throwsArgumentError);
});
test('may not have a fragment', () {
expect(() {
- new Request('GET', Uri.parse('http://localhost/#fragment'));
+ Request('GET', Uri.parse('http://localhost/#fragment'));
}, throwsArgumentError);
});
});
@@ -109,41 +101,41 @@
group('url', () {
test('must be relative', () {
expect(() {
- new Request('GET', Uri.parse('http://localhost/test'),
+ Request('GET', Uri.parse('http://localhost/test'),
url: Uri.parse('http://localhost/test'));
}, throwsArgumentError);
});
test('may not be root-relative', () {
expect(() {
- new Request('GET', Uri.parse('http://localhost/test'),
+ Request('GET', Uri.parse('http://localhost/test'),
url: Uri.parse('/test'));
}, throwsArgumentError);
});
test('may not have a fragment', () {
expect(() {
- new Request('GET', Uri.parse('http://localhost/test'),
+ Request('GET', Uri.parse('http://localhost/test'),
url: Uri.parse('test#fragment'));
}, throwsArgumentError);
});
test('must be a suffix of requestedUri', () {
expect(() {
- new Request('GET', Uri.parse('http://localhost/dir/test'),
+ Request('GET', Uri.parse('http://localhost/dir/test'),
url: Uri.parse('dir'));
}, throwsArgumentError);
});
test('must have the same query parameters as requestedUri', () {
expect(() {
- new Request('GET', Uri.parse('http://localhost/test?q=1&r=2'),
+ Request('GET', Uri.parse('http://localhost/test?q=1&r=2'),
url: Uri.parse('test?q=2&r=1'));
}, throwsArgumentError);
// Order matters for query parameters.
expect(() {
- new Request('GET', Uri.parse('http://localhost/test?q=1&r=2'),
+ Request('GET', Uri.parse('http://localhost/test?q=1&r=2'),
url: Uri.parse('test?r=2&q=1'));
}, throwsArgumentError);
});
@@ -152,21 +144,21 @@
group('handlerPath', () {
test('must be a prefix of requestedUri', () {
expect(() {
- new Request('GET', Uri.parse('http://localhost/dir/test'),
+ Request('GET', Uri.parse('http://localhost/dir/test'),
handlerPath: '/test');
}, throwsArgumentError);
});
test('must start with "/"', () {
expect(() {
- new Request('GET', Uri.parse('http://localhost/test'),
+ Request('GET', Uri.parse('http://localhost/test'),
handlerPath: 'test');
}, throwsArgumentError);
});
test('must be the requestedUri path if url is empty', () {
expect(() {
- new Request('GET', Uri.parse('http://localhost/test'),
+ Request('GET', Uri.parse('http://localhost/test'),
handlerPath: '/', url: Uri.parse(''));
}, throwsArgumentError);
});
@@ -175,14 +167,14 @@
group('handlerPath + url must', () {
test('be requestedUrl path', () {
expect(() {
- new Request('GET', Uri.parse('http://localhost/foo/bar/baz'),
+ Request('GET', Uri.parse('http://localhost/foo/bar/baz'),
handlerPath: '/foo/', url: Uri.parse('baz'));
}, throwsArgumentError);
});
test('be on a path boundary', () {
expect(() {
- new Request('GET', Uri.parse('http://localhost/foo/bar/baz'),
+ Request('GET', Uri.parse('http://localhost/foo/bar/baz'),
handlerPath: '/foo/ba', url: Uri.parse('r/baz'));
}, throwsArgumentError);
});
@@ -206,11 +198,11 @@
group('change', () {
test('with no arguments returns instance with equal values', () {
- var controller = new StreamController();
+ var controller = StreamController();
var uri = Uri.parse('https://test.example.com/static/file.html');
- var request = new Request('GET', uri,
+ var request = Request('GET', uri,
protocolVersion: '2.0',
headers: {'header1': 'header value 1'},
url: Uri.parse('file.html'),
@@ -230,7 +222,7 @@
expect(copy.readAsString(), completion('hello, world'));
controller.add(helloBytes);
- return new Future(() {
+ return Future(() {
controller
..add(worldBytes)
..close();
@@ -240,7 +232,7 @@
group('with path', () {
test('updates handlerPath and url', () {
var uri = Uri.parse('https://test.example.com/static/dir/file.html');
- var request = new Request('GET', uri,
+ var request = Request('GET', uri,
handlerPath: '/static/', url: Uri.parse('dir/file.html'));
var copy = request.change(path: 'dir');
@@ -250,7 +242,7 @@
test('allows a trailing slash', () {
var uri = Uri.parse('https://test.example.com/static/dir/file.html');
- var request = new Request('GET', uri,
+ var request = Request('GET', uri,
handlerPath: '/static/', url: Uri.parse('dir/file.html'));
var copy = request.change(path: 'dir/');
@@ -260,7 +252,7 @@
test('throws if path does not match existing uri', () {
var uri = Uri.parse('https://test.example.com/static/dir/file.html');
- var request = new Request('GET', uri,
+ var request = Request('GET', uri,
handlerPath: '/static/', url: Uri.parse('dir/file.html'));
expect(() => request.change(path: 'wrong'), throwsArgumentError);
@@ -268,7 +260,7 @@
test("throws if path isn't a path boundary", () {
var uri = Uri.parse('https://test.example.com/static/dir/file.html');
- var request = new Request('GET', uri,
+ var request = Request('GET', uri,
handlerPath: '/static/', url: Uri.parse('dir/file.html'));
expect(() => request.change(path: 'di'), throwsArgumentError);
diff --git a/test/response_test.dart b/test/response_test.dart
index c5e2de5..d316a4d 100644
--- a/test/response_test.dart
+++ b/test/response_test.dart
@@ -13,32 +13,32 @@
void main() {
group("supports a String body", () {
test("readAsString", () {
- var response = new Response.ok("hello, world");
+ var response = Response.ok("hello, world");
expect(response.readAsString(), completion(equals("hello, world")));
});
test("read", () {
- var helloWorldBytes = new List.from(helloBytes)..addAll(worldBytes);
+ var helloWorldBytes = List.from(helloBytes)..addAll(worldBytes);
- var response = new Response.ok("hello, world");
+ var response = Response.ok("hello, world");
expect(response.read().toList(), completion(equals([helloWorldBytes])));
});
});
group("new Response.internalServerError without a body", () {
test('sets the body to "Internal Server Error"', () {
- var response = new Response.internalServerError();
+ var response = Response.internalServerError();
expect(
response.readAsString(), completion(equals("Internal Server Error")));
});
test('sets the content-type header to text/plain', () {
- var response = new Response.internalServerError();
+ var response = Response.internalServerError();
expect(response.headers, containsPair('content-type', 'text/plain'));
});
test('preserves content-type parameters', () {
- var response = new Response.internalServerError(headers: {
+ var response = Response.internalServerError(headers: {
'content-type': 'application/octet-stream; param=whatever'
});
expect(response.headers,
@@ -48,24 +48,24 @@
group("Response redirect", () {
test("sets the location header for a String", () {
- var response = new Response.found('/foo');
+ var response = Response.found('/foo');
expect(response.headers, containsPair('location', '/foo'));
});
test("sets the location header for a Uri", () {
- var response = new Response.found(new Uri(path: '/foo'));
+ var response = Response.found(Uri(path: '/foo'));
expect(response.headers, containsPair('location', '/foo'));
});
});
group("expires", () {
test("is null without an Expires header", () {
- expect(new Response.ok("okay!").expires, isNull);
+ expect(Response.ok("okay!").expires, isNull);
});
test("comes from the Expires header", () {
expect(
- new Response.ok("okay!",
+ Response.ok("okay!",
headers: {'expires': 'Sun, 06 Nov 1994 08:49:37 GMT'}).expires,
equals(DateTime.parse("1994-11-06 08:49:37z")));
});
@@ -73,12 +73,12 @@
group("lastModified", () {
test("is null without a Last-Modified header", () {
- expect(new Response.ok("okay!").lastModified, isNull);
+ expect(Response.ok("okay!").lastModified, isNull);
});
test("comes from the Last-Modified header", () {
expect(
- new Response.ok("okay!",
+ Response.ok("okay!",
headers: {'last-modified': 'Sun, 06 Nov 1994 08:49:37 GMT'})
.lastModified,
equals(DateTime.parse("1994-11-06 08:49:37z")));
@@ -87,9 +87,9 @@
group('change', () {
test('with no arguments returns instance with equal values', () {
- var controller = new StreamController();
+ var controller = StreamController();
- var request = new Response(345,
+ var request = Response(345,
body: 'hèllo, world',
encoding: latin1,
headers: {'header1': 'header value 1'},
@@ -104,7 +104,7 @@
expect(copy.context, same(request.context));
controller.add(helloBytes);
- return new Future(() {
+ return Future(() {
controller
..add(worldBytes)
..close();
@@ -112,7 +112,7 @@
});
test("allows the original response to be read", () {
- var response = new Response.ok(null);
+ var response = Response.ok(null);
var changed = response.change();
expect(response.read().toList(), completion(isEmpty));
@@ -120,7 +120,7 @@
});
test("allows the changed response to be read", () {
- var response = new Response.ok(null);
+ var response = Response.ok(null);
var changed = response.change();
expect(changed.read().toList(), completion(isEmpty));
@@ -128,7 +128,7 @@
});
test("allows another changed response to be read", () {
- var response = new Response.ok(null);
+ var response = Response.ok(null);
var changed1 = response.change();
var changed2 = response.change();
diff --git a/test/server_handler_test.dart b/test/server_handler_test.dart
index 8edae23..9b44349 100644
--- a/test/server_handler_test.dart
+++ b/test/server_handler_test.dart
@@ -12,13 +12,13 @@
void main() {
test("passes the URL to the server", () {
- var serverHandler = new ServerHandler(localhostUri);
+ var serverHandler = ServerHandler(localhostUri);
expect(serverHandler.server.url, equals(localhostUri));
});
test("pipes a request from ServerHandler.handler to a mounted handler",
() async {
- var serverHandler = new ServerHandler(localhostUri);
+ var serverHandler = ServerHandler(localhostUri);
serverHandler.server.mount(asyncHandler);
var response = await makeSimpleRequest(serverHandler.handler);
@@ -28,9 +28,9 @@
test("waits until the server's handler is mounted to service a request",
() async {
- var serverHandler = new ServerHandler(localhostUri);
+ var serverHandler = ServerHandler(localhostUri);
var future = makeSimpleRequest(serverHandler.handler);
- await new Future.delayed(Duration.zero);
+ await Future.delayed(Duration.zero);
serverHandler.server.mount(syncHandler);
var response = await future;
@@ -39,7 +39,7 @@
});
test("stops servicing requests after Server.close is called", () {
- var serverHandler = new ServerHandler(localhostUri);
+ var serverHandler = ServerHandler(localhostUri);
serverHandler.server.mount(expectAsync1((_) {}, count: 0));
serverHandler.server.close();
@@ -48,8 +48,8 @@
test("calls onClose when Server.close is called", () async {
var onCloseCalled = false;
- var completer = new Completer();
- var serverHandler = new ServerHandler(localhostUri, onClose: () {
+ var completer = Completer();
+ var serverHandler = ServerHandler(localhostUri, onClose: () {
onCloseCalled = true;
return completer.future;
});
@@ -59,17 +59,17 @@
closeDone = true;
}));
expect(onCloseCalled, isTrue);
- await new Future.delayed(Duration.zero);
+ await Future.delayed(Duration.zero);
expect(closeDone, isFalse);
completer.complete();
- await new Future.delayed(Duration.zero);
+ await Future.delayed(Duration.zero);
expect(closeDone, isTrue);
});
test("doesn't allow Server.mount to be called multiple times", () {
- var serverHandler = new ServerHandler(localhostUri);
+ var serverHandler = ServerHandler(localhostUri);
serverHandler.server.mount((_) {});
expect(() => serverHandler.server.mount((_) {}), throwsStateError);
expect(() => serverHandler.server.mount((_) {}), throwsStateError);
diff --git a/test/shelf_io_test.dart b/test/shelf_io_test.dart
index fb8faa7..3e94561 100644
--- a/test/shelf_io_test.dart
+++ b/test/shelf_io_test.dart
@@ -51,7 +51,7 @@
});
test('async null response leads to a 500', () async {
- await _scheduleServer((request) => new Future.value(null));
+ await _scheduleServer((request) => Future.value(null));
var response = await _get();
expect(response.statusCode, HttpStatus.internalServerError);
@@ -60,7 +60,7 @@
test('thrown error leads to a 500', () async {
await _scheduleServer((request) {
- throw new UnsupportedError('test');
+ throw UnsupportedError('test');
});
var response = await _get();
@@ -70,7 +70,7 @@
test('async error leads to a 500', () async {
await _scheduleServer((request) {
- return new Future.error('test');
+ return Future.error('test');
});
var response = await _get();
@@ -113,10 +113,10 @@
completion(equals([
[1, 2, 3, 4]
])));
- return new Response.ok(null);
+ return Response.ok(null);
}));
- var request = new http.StreamedRequest(
+ var request = http.StreamedRequest(
'POST', Uri.parse('http://localhost:$_serverPort'));
request.sink.add([1, 2, 3, 4]);
request.sink.close();
@@ -127,7 +127,7 @@
test('custom response headers are received by the client', () async {
await _scheduleServer((request) {
- return new Response.ok('Hello from /',
+ return Response.ok('Hello from /',
headers: {'test-header': 'test-value', 'test-list': 'a, b, c'});
});
@@ -139,7 +139,7 @@
test('custom status code is received by the client', () async {
await _scheduleServer((request) {
- return new Response(299, body: 'Hello from /');
+ return Response(299, body: 'Hello from /');
});
var response = await _get();
@@ -236,7 +236,7 @@
test('passes asynchronous exceptions to the parent error zone', () async {
await runZoned(() async {
var server = await shelf_io.serve((request) {
- new Future(() => throw 'oh no');
+ Future(() => throw 'oh no');
return syncHandler(request);
}, 'localhost', 0);
@@ -252,7 +252,7 @@
test("doesn't pass asynchronous exceptions to the root error zone", () async {
var response = await Zone.root.run(() async {
var server = await shelf_io.serve((request) {
- new Future(() => throw 'oh no');
+ Future(() => throw 'oh no');
return syncHandler(request);
}, 'localhost', 0);
@@ -291,20 +291,20 @@
// Update beforeRequest to be one second earlier. HTTP dates only have
// second-level granularity and the request will likely take less than a
// second.
- var beforeRequest = new DateTime.now().subtract(new Duration(seconds: 1));
+ var beforeRequest = DateTime.now().subtract(Duration(seconds: 1));
var response = await _get();
expect(response.headers, contains('date'));
var responseDate = parser.parseHttpDate(response.headers['date']);
expect(responseDate.isAfter(beforeRequest), isTrue);
- expect(responseDate.isBefore(new DateTime.now()), isTrue);
+ expect(responseDate.isBefore(DateTime.now()), isTrue);
});
test('defers to header in response', () async {
- var date = new DateTime.utc(1981, 6, 5);
+ var date = DateTime.utc(1981, 6, 5);
await _scheduleServer((request) {
- return new Response.ok('test',
+ return Response.ok('test',
headers: {HttpHeaders.dateHeader: parser.formatHttpDate(date)});
});
@@ -326,7 +326,7 @@
test('defers to header in response', () async {
await _scheduleServer((request) {
- return new Response.ok('test',
+ return Response.ok('test',
headers: {HttpHeaders.serverHeader: 'myServer'});
});
@@ -340,7 +340,7 @@
group('is added when the transfer-encoding header is', () {
test('unset', () async {
await _scheduleServer((request) {
- return new Response.ok(new Stream.fromIterable([
+ return Response.ok(Stream.fromIterable([
[1, 2, 3, 4]
]));
});
@@ -353,8 +353,8 @@
test('"identity"', () async {
await _scheduleServer((request) {
- return new Response.ok(
- new Stream.fromIterable([
+ return Response.ok(
+ Stream.fromIterable([
[1, 2, 3, 4]
]),
headers: {HttpHeaders.transferEncodingHeader: 'identity'});
@@ -370,8 +370,8 @@
test('is preserved when the transfer-encoding header is "chunked"',
() async {
await _scheduleServer((request) {
- return new Response.ok(
- new Stream.fromIterable(["2\r\nhi\r\n0\r\n\r\n".codeUnits]),
+ return Response.ok(
+ Stream.fromIterable(["2\r\nhi\r\n0\r\n\r\n".codeUnits]),
headers: {HttpHeaders.transferEncodingHeader: 'chunked'});
});
@@ -384,8 +384,8 @@
group('is not added when', () {
test('content-length is set', () async {
await _scheduleServer((request) {
- return new Response.ok(
- new Stream.fromIterable([
+ return Response.ok(
+ Stream.fromIterable([
[1, 2, 3, 4]
]),
headers: {HttpHeaders.contentLengthHeader: '4'});
@@ -399,7 +399,7 @@
test('status code is 1xx', () async {
await _scheduleServer((request) {
- return new Response(123, body: new Stream.empty());
+ return Response(123, body: Stream.empty());
});
var response = await _get();
@@ -410,7 +410,7 @@
test('status code is 204', () async {
await _scheduleServer((request) {
- return new Response(204, body: new Stream.empty());
+ return Response(204, body: Stream.empty());
});
var response = await _get();
@@ -421,7 +421,7 @@
test('status code is 304', () async {
await _scheduleServer((request) {
- return new Response(304, body: new Stream.empty());
+ return Response(304, body: Stream.empty());
});
var response = await _get();
@@ -433,19 +433,19 @@
});
test('respects the "shelf.io.buffer_output" context parameter', () async {
- var controller = new StreamController<String>();
+ var controller = StreamController<String>();
await _scheduleServer((request) {
controller.add("Hello, ");
- return new Response.ok(utf8.encoder.bind(controller.stream),
+ return Response.ok(utf8.encoder.bind(controller.stream),
context: {"shelf.io.buffer_output": false});
});
var request =
- new http.Request("GET", Uri.parse('http://localhost:$_serverPort/'));
+ http.Request("GET", Uri.parse('http://localhost:$_serverPort/'));
var response = await request.send();
- var stream = new StreamQueue(utf8.decoder.bind(response.stream));
+ var stream = StreamQueue(utf8.decoder.bind(response.stream));
var data = await stream.next;
expect(data, equals("Hello, "));
@@ -461,8 +461,8 @@
await _scheduleServer((request) {
expect(
request.context,
- containsPair('shelf.io.connection_info',
- new TypeMatcher<HttpConnectionInfo>()));
+ containsPair(
+ 'shelf.io.connection_info', TypeMatcher<HttpConnectionInfo>()));
var connectionInfo =
request.context['shelf.io.connection_info'] as HttpConnectionInfo;
@@ -477,12 +477,12 @@
});
group('ssl tests', () {
- var securityContext = new SecurityContext()
+ var securityContext = SecurityContext()
..setTrustedCertificatesBytes(certChainBytes)
..useCertificateChainBytes(certChainBytes)
..usePrivateKeyBytes(certKeyBytes, password: 'dartdart');
- var sslClient = new HttpClient(context: securityContext);
+ var sslClient = HttpClient(context: securityContext);
Future<HttpClientRequest> _scheduleSecureGet() =>
sslClient.getUrl(Uri.parse('https://localhost:${_server.port}/'));
@@ -525,7 +525,7 @@
Future<http.StreamedResponse> _post(
{Map<String, String> headers, String body}) {
var request =
- new http.Request('POST', Uri.parse('http://localhost:$_serverPort/'));
+ http.Request('POST', Uri.parse('http://localhost:$_serverPort/'));
if (headers != null) request.headers.addAll(headers);
if (body != null) request.body = body;
diff --git a/test/test_util.dart b/test/test_util.dart
index 4238468..8af96fa 100644
--- a/test/test_util.dart
+++ b/test/test_util.dart
@@ -8,13 +8,12 @@
import 'package:shelf/shelf.dart';
// "hello,"
-const helloBytes = const [104, 101, 108, 108, 111, 44];
+const helloBytes = [104, 101, 108, 108, 111, 44];
// " world"
-const worldBytes = const [32, 119, 111, 114, 108, 100];
+const worldBytes = [32, 119, 111, 114, 108, 100];
-final Matcher throwsHijackException =
- throwsA(new TypeMatcher<HijackException>());
+final Matcher throwsHijackException = throwsA(TypeMatcher<HijackException>());
/// A simple, synchronous handler for [Request].
///
@@ -23,18 +22,18 @@
Response syncHandler(Request request,
{int statusCode, Map<String, String> headers}) {
if (statusCode == null) statusCode = 200;
- return new Response(statusCode,
+ return Response(statusCode,
headers: headers, body: 'Hello from ${request.requestedUri.path}');
}
/// Calls [syncHandler] and wraps the response in a [Future].
Future<Response> asyncHandler(Request request) =>
- new Future(() => syncHandler(request));
+ Future(() => syncHandler(request));
/// Makes a simple GET request to [handler] and returns the result.
Future<Response> makeSimpleRequest(Handler handler) =>
- new Future.sync(() => handler(_request));
+ Future.sync(() => handler(_request));
-final _request = new Request('GET', localhostUri);
+final _request = Request('GET', localhostUri);
final localhostUri = Uri.parse('http://localhost/');