Fix newly enforced package:pedantic lints (#123)
- always_declare_return_types
- annotate_overrides
- omit_local_variable_types
- prefer_conditional_assignment
- prefer_single_quotes
- unnecessary_this
- use_function_type_syntax_for_parameters
diff --git a/example/example.dart b/example/example.dart
index e940925..6d6beaf 100644
--- a/example/example.dart
+++ b/example/example.dart
@@ -5,7 +5,7 @@
import 'package:shelf/shelf.dart' as shelf;
import 'package:shelf/shelf_io.dart' as io;
-main() async {
+void main() async {
var handler = const shelf.Pipeline()
.addMiddleware(shelf.logRequests())
.addHandler(_echoRequest);
diff --git a/lib/shelf_io.dart b/lib/shelf_io.dart
index aa0c130..d41b8dc 100644
--- a/lib/shelf_io.dart
+++ b/lib/shelf_io.dart
@@ -41,7 +41,7 @@
Future<HttpServer> serve(Handler handler, address, int port,
{SecurityContext securityContext, int backlog, bool shared = false}) async {
backlog ??= 0;
- HttpServer server = await (securityContext == null
+ var server = await (securityContext == null
? HttpServer.bind(address, port, backlog: backlog, shared: shared)
: HttpServer.bindSecure(address, port, securityContext,
backlog: backlog, shared: shared));
@@ -121,10 +121,10 @@
}
var message = StringBuffer()
- ..writeln("Got a response for hijacked request "
- "${shelfRequest.method} ${shelfRequest.requestedUri}:")
+ ..writeln('Got a response for hijacked request '
+ '${shelfRequest.method} ${shelfRequest.requestedUri}:')
..writeln(response.statusCode);
- response.headers.forEach((key, value) => message.writeln("$key: $value"));
+ response.headers.forEach((key, value) => message.writeln('$key: $value'));
throw Exception(message.toString().trim());
}
@@ -140,7 +140,7 @@
// Remove the Transfer-Encoding header per the adapter requirements.
headers.remove(HttpHeaders.transferEncodingHeader);
- void onHijack(void callback(StreamChannel<List<int>> channel)) {
+ void onHijack(void Function(StreamChannel<List<int>>) callback) {
request.response
.detachSocket(writeHeaders: false)
.then((socket) => callback(StreamChannel(socket, socket)));
@@ -155,9 +155,9 @@
}
Future _writeResponse(Response response, HttpResponse httpResponse) {
- if (response.context.containsKey("shelf.io.buffer_output")) {
+ if (response.context.containsKey('shelf.io.buffer_output')) {
httpResponse.bufferOutput =
- response.context["shelf.io.buffer_output"] as bool;
+ response.context['shelf.io.buffer_output'] as bool;
}
httpResponse.statusCode = response.statusCode;
@@ -210,9 +210,9 @@
Response _logError(Request request, String message, [StackTrace stackTrace]) {
// Add information about the request itself.
var buffer = StringBuffer();
- buffer.write("${request.method} ${request.requestedUri.path}");
+ buffer.write('${request.method} ${request.requestedUri.path}');
if (request.requestedUri.query.isNotEmpty) {
- buffer.write("?${request.requestedUri.query}");
+ buffer.write('?${request.requestedUri.query}');
}
buffer.writeln();
buffer.write(message);
diff --git a/lib/src/body.dart b/lib/src/body.dart
index 1ad6f3f..a4660fb 100644
--- a/lib/src/body.dart
+++ b/lib/src/body.dart
@@ -84,7 +84,7 @@
Stream<List<int>> read() {
if (_stream == null) {
throw StateError("The 'read' method can only be called once on a "
- "shelf.Request/shelf.Response object.");
+ 'shelf.Request/shelf.Response object.');
}
var stream = _stream;
_stream = null;
diff --git a/lib/src/cascade.dart b/lib/src/cascade.dart
index 459e780..de991b3 100644
--- a/lib/src/cascade.dart
+++ b/lib/src/cascade.dart
@@ -39,13 +39,13 @@
/// considered unacceptable. If [shouldCascade] is passed, responses for which
/// it returns `true` are considered unacceptable. [statusCodes] and
/// [shouldCascade] may not both be passed.
- Cascade({Iterable<int> statusCodes, bool shouldCascade(Response response)})
+ Cascade({Iterable<int> statusCodes, bool Function(Response) shouldCascade})
: _shouldCascade = _computeShouldCascade(statusCodes, shouldCascade),
_parent = null,
_handler = null {
if (statusCodes != null && shouldCascade != null) {
- throw ArgumentError("statusCodes and shouldCascade may not both be "
- "passed.");
+ throw ArgumentError('statusCodes and shouldCascade may not both be '
+ 'passed.');
}
}
@@ -65,7 +65,7 @@
Handler get handler {
if (_handler == null) {
throw StateError("Can't get a handler for a cascade with no inner "
- "handlers.");
+ 'handlers.');
}
return (request) {
@@ -81,9 +81,9 @@
/// Computes the [Cascade._shouldCascade] function based on the user's
/// parameters.
_ShouldCascade _computeShouldCascade(
- Iterable<int> statusCodes, bool shouldCascade(Response response)) {
+ Iterable<int> statusCodes, bool Function(Response) shouldCascade) {
if (shouldCascade != null) return shouldCascade;
- if (statusCodes == null) statusCodes = [404, 405];
+ statusCodes ??= [404, 405];
statusCodes = statusCodes.toSet();
return (response) => statusCodes.contains(response.statusCode);
}
diff --git a/lib/src/hijack_exception.dart b/lib/src/hijack_exception.dart
index d7e4cd1..4a3d84e 100644
--- a/lib/src/hijack_exception.dart
+++ b/lib/src/hijack_exception.dart
@@ -12,8 +12,9 @@
class HijackException implements Exception {
const HijackException();
+ @override
String toString() =>
"A shelf request's underlying data stream was hijacked.\n"
- "This exception is used for control flow and should only be handled by a "
- "Shelf adapter.";
+ 'This exception is used for control flow and should only be handled by a '
+ 'Shelf adapter.';
}
diff --git a/lib/src/io_server.dart b/lib/src/io_server.dart
index 447f307..19c5e37 100644
--- a/lib/src/io_server.dart
+++ b/lib/src/io_server.dart
@@ -18,21 +18,22 @@
/// Whether [mount] has been called.
bool _mounted = false;
+ @override
Uri get url {
if (server.address.isLoopback) {
- return 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 Uri(
- scheme: "http",
- host: "[${server.address.address}]",
+ scheme: 'http',
+ host: '[${server.address.address}]',
port: server.port);
}
- return 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].
@@ -44,6 +45,7 @@
IOServer(this.server);
+ @override
void mount(Handler handler) {
if (_mounted) {
throw StateError("Can't mount two handlers for the same server.");
@@ -53,5 +55,6 @@
serveRequests(server, handler);
}
+ @override
Future close() => server.close();
}
diff --git a/lib/src/message.dart b/lib/src/message.dart
index cd19f03..1796fa8 100644
--- a/lib/src/message.dart
+++ b/lib/src/message.dart
@@ -17,7 +17,7 @@
/// The default set of headers for a message created with no body and no
/// explicit headers.
final _defaultHeaders =
- ShelfUnmodifiableMap<String>({"content-length": "0"}, ignoreKeyCase: true);
+ ShelfUnmodifiableMap<String>({'content-length': '0'}, ignoreKeyCase: true);
/// Represents logic shared between [Request] and [Response].
abstract class Message {
@@ -136,8 +136,7 @@
///
/// This calls [read] internally, which can only be called once.
Future<String> readAsString([Encoding encoding]) {
- if (encoding == null) encoding = this.encoding;
- if (encoding == null) encoding = utf8;
+ encoding ??= this.encoding ?? utf8;
return encoding.decodeStream(read());
}
diff --git a/lib/src/middleware.dart b/lib/src/middleware.dart
index 05b9b47..d972a67 100644
--- a/lib/src/middleware.dart
+++ b/lib/src/middleware.dart
@@ -47,12 +47,11 @@
/// does it receive [HijackException]s. It can either return a new response or
/// throw an error.
Middleware createMiddleware(
- {FutureOr<Response> requestHandler(Request request),
- FutureOr<Response> responseHandler(Response response),
- FutureOr<Response> errorHandler(error, StackTrace stackTrace)}) {
- if (requestHandler == null) requestHandler = (request) => null;
-
- if (responseHandler == null) responseHandler = (response) => response;
+ {FutureOr<Response> Function(Request) requestHandler,
+ FutureOr<Response> Function(Response) responseHandler,
+ FutureOr<Response> Function(dynamic error, StackTrace) errorHandler}) {
+ requestHandler ??= (request) => null;
+ responseHandler ??= (response) => response;
void Function(Object, StackTrace) onError;
if (errorHandler != null) {
diff --git a/lib/src/middleware/logger.dart b/lib/src/middleware/logger.dart
index 0d11ca1..444ef08 100644
--- a/lib/src/middleware/logger.dart
+++ b/lib/src/middleware/logger.dart
@@ -19,9 +19,9 @@
/// The `isError` parameter indicates whether the message is caused by an error.
///
/// If [logger] is not passed, the message is just passed to [print].
-Middleware logRequests({void logger(String msg, bool isError)}) =>
+Middleware logRequests({void Function(String message, bool isError) logger}) =>
(innerHandler) {
- if (logger == null) logger = _defaultLogger;
+ logger ??= _defaultLogger;
return (request) {
var startTime = DateTime.now();
diff --git a/lib/src/request.dart b/lib/src/request.dart
index c5ae87f..9c6d1cb 100644
--- a/lib/src/request.dart
+++ b/lib/src/request.dart
@@ -134,7 +134,7 @@
body,
Encoding encoding,
Map<String, Object> context,
- void onHijack(void hijack(StreamChannel<List<int>> channel))})
+ void Function(void Function(StreamChannel<List<int>>)) onHijack})
: this._(method, requestedUri,
protocolVersion: protocolVersion,
headers: headers,
@@ -160,12 +160,11 @@
Encoding encoding,
Map<String, Object> context,
_OnHijack onHijack})
- : this.requestedUri = requestedUri,
- this.protocolVersion =
- protocolVersion == null ? '1.1' : protocolVersion,
- this.url = _computeUrl(requestedUri, handlerPath, url),
- this.handlerPath = _computeHandlerPath(requestedUri, handlerPath, url),
- this._onHijack = onHijack,
+ : requestedUri = requestedUri,
+ protocolVersion = protocolVersion ?? '1.1',
+ url = _computeUrl(requestedUri, handlerPath, url),
+ handlerPath = _computeHandlerPath(requestedUri, handlerPath, url),
+ _onHijack = onHijack,
super(body, encoding: encoding, headers: headers, context: context) {
if (method.isEmpty) {
throw ArgumentError.value(method, 'method', 'cannot be empty.');
@@ -214,6 +213,7 @@
/// request = request.change(path: "dir");
/// print(request.handlerPath); // => /static/dir/
/// print(request.url); // => file.html
+ @override
Request change(
{Map<String, String> headers,
Map<String, Object> context,
@@ -222,13 +222,13 @@
headers = updateMap(this.headers, headers);
context = updateMap(this.context, context);
- if (body == null) body = getBody(this);
+ body ??= getBody(this);
var handlerPath = this.handlerPath;
if (path != null) handlerPath += path;
- return Request._(this.method, this.requestedUri,
- protocolVersion: this.protocolVersion,
+ return Request._(method, requestedUri,
+ protocolVersion: protocolVersion,
headers: headers,
handlerPath: handlerPath,
body: body,
@@ -247,7 +247,7 @@
/// hijacking, such as the `dart:io` adapter. In addition, a given request may
/// only be hijacked once. [canHijack] can be used to detect whether this
/// request can be hijacked.
- void hijack(void callback(StreamChannel<List<int>> channel)) {
+ void hijack(void Function(StreamChannel<List<int>>) callback) {
if (_onHijack == null) {
throw StateError("This request can't be hijacked.");
}
@@ -272,8 +272,8 @@
/// Calls [this].
///
/// Throws a [StateError] if [this] has already been called.
- void run(void callback(StreamChannel<List<int>> channel)) {
- if (called) throw StateError("This request has already been hijacked.");
+ void run(void Function(StreamChannel<List<int>>) callback) {
+ if (called) throw StateError('This request has already been hijacked.');
called = true;
newFuture(() => _callback(callback));
}
@@ -286,8 +286,8 @@
Uri _computeUrl(Uri requestedUri, String handlerPath, Uri url) {
if (handlerPath != null &&
handlerPath != requestedUri.path &&
- !handlerPath.endsWith("/")) {
- handlerPath += "/";
+ !handlerPath.endsWith('/')) {
+ handlerPath += '/';
}
if (url != null) {
@@ -336,8 +336,8 @@
String _computeHandlerPath(Uri requestedUri, String handlerPath, Uri url) {
if (handlerPath != null &&
handlerPath != requestedUri.path &&
- !handlerPath.endsWith("/")) {
- handlerPath += "/";
+ !handlerPath.endsWith('/')) {
+ handlerPath += '/';
}
if (handlerPath != null) {
diff --git a/lib/src/response.dart b/lib/src/response.dart
index b7275b0..ada9744 100644
--- a/lib/src/response.dart
+++ b/lib/src/response.dart
@@ -198,7 +198,7 @@
Map<String, Object> context})
: this(403,
headers: body == null ? _adjustErrorHeaders(headers) : headers,
- body: body == null ? 'Forbidden' : body,
+ body: body ?? 'Forbidden',
context: context,
encoding: encoding);
@@ -227,7 +227,7 @@
Map<String, Object> context})
: this(404,
headers: body == null ? _adjustErrorHeaders(headers) : headers,
- body: body == null ? 'Not Found' : body,
+ body: body ?? 'Not Found',
context: context,
encoding: encoding);
@@ -257,7 +257,7 @@
Map<String, Object> context})
: this(500,
headers: body == null ? _adjustErrorHeaders(headers) : headers,
- body: body == null ? 'Internal Server Error' : body,
+ body: body ?? 'Internal Server Error',
context: context,
encoding: encoding);
@@ -286,7 +286,7 @@
Map<String, Object> context})
: super(body, encoding: encoding, headers: headers, context: context) {
if (statusCode < 100) {
- throw ArgumentError("Invalid status code: $statusCode.");
+ throw ArgumentError('Invalid status code: $statusCode.');
}
}
@@ -305,15 +305,15 @@
///
/// [body] is the request body. It may be either a [String], a [List<int>], a
/// [Stream<List<int>>], or `null` to indicate no body.
+ @override
Response change(
{Map<String, String> headers, Map<String, Object> context, body}) {
headers = updateMap(this.headers, headers);
context = updateMap(this.context, context);
- if (body == null) body = getBody(this);
+ body ??= getBody(this);
- return Response(this.statusCode,
- body: body, headers: headers, context: context);
+ return Response(statusCode, body: body, headers: headers, context: context);
}
}
diff --git a/lib/src/server_handler.dart b/lib/src/server_handler.dart
index c6b6afd..6aa999d 100644
--- a/lib/src/server_handler.dart
+++ b/lib/src/server_handler.dart
@@ -38,12 +38,13 @@
///
/// 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 = _HandlerServer(url, onClose);
+ ServerHandler(Uri url, {void Function() onClose})
+ : _server = _HandlerServer(url, onClose);
/// Pipes requests to [server]'s handler.
FutureOr<Response> _onRequest(Request request) {
if (_server._closeMemo.hasRun) {
- throw 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);
@@ -56,6 +57,7 @@
/// The [Server] returned by [ServerHandler].
class _HandlerServer implements Server {
+ @override
final Uri url;
/// The callback to call when [close] is called, or `null`.
@@ -72,6 +74,7 @@
_HandlerServer(this.url, this._onClose);
+ @override
void mount(Handler handler) {
if (_handler != null) {
throw StateError("Can't mount two handlers for the same server.");
@@ -81,6 +84,7 @@
_onMountedCompleter.complete();
}
+ @override
Future close() => _closeMemo.runOnce(() {
return _onClose == null ? null : _onClose();
});
diff --git a/lib/src/shelf_unmodifiable_map.dart b/lib/src/shelf_unmodifiable_map.dart
index e23df7b..794cb00 100644
--- a/lib/src/shelf_unmodifiable_map.dart
+++ b/lib/src/shelf_unmodifiable_map.dart
@@ -53,13 +53,17 @@
/// A const implementation of an empty [ShelfUnmodifiableMap].
class _EmptyShelfUnmodifiableMap<V> extends MapView<String, V>
implements ShelfUnmodifiableMap<V> {
+ @override
bool get _ignoreKeyCase => true;
const _EmptyShelfUnmodifiableMap() : super(const <String, Null>{});
// Override modifier methods that care about the type of key they use so that
// when V is Null, they throw UnsupportedErrors instead of type errors.
+ @override
void operator []=(String key, Object value) => super[key] = null;
+ @override
void addAll(Map<String, Object> other) => super.addAll({});
- V putIfAbsent(String key, Object ifAbsent()) =>
+ @override
+ V putIfAbsent(String key, Object Function() ifAbsent) =>
super.putIfAbsent(key, () => null);
}
diff --git a/lib/src/util.dart b/lib/src/util.dart
index b2fc769..5cb0d2e 100644
--- a/lib/src/util.dart
+++ b/lib/src/util.dart
@@ -10,14 +10,16 @@
/// Like [new Future], but avoids around issue 11911 by using [new Future.value]
/// under the covers.
-Future newFuture(callback()) => Future.value().then((_) => callback());
+Future newFuture(void Function() callback) =>
+ Future.value().then((_) => callback());
/// Run [callback] and capture any errors that would otherwise be top-leveled.
///
/// If [this] is called in a non-root error zone, it will just run [callback]
/// and return the result. Otherwise, it will capture any errors using
/// [runZoned] and pass them to [onError].
-catchTopLevelErrors(callback(), void onError(error, StackTrace stackTrace)) {
+void catchTopLevelErrors(void Function() callback,
+ void Function(dynamic error, StackTrace) onError) {
if (Zone.current.inSameErrorZone(Zone.root)) {
return runZoned(callback, onError: onError);
} else {
diff --git a/pubspec.yaml b/pubspec.yaml
index b10625e..5c430c5 100644
--- a/pubspec.yaml
+++ b/pubspec.yaml
@@ -1,5 +1,5 @@
name: shelf
-version: 0.7.5
+version: 0.7.6-dev
description: >-
A model for web server middleware that encourages composition and easy reuse
author: Dart Team <misc@dartlang.org>
diff --git a/test/add_chunked_encoding_test.dart b/test/add_chunked_encoding_test.dart
index 2ae1dbf..071739e 100644
--- a/test/add_chunked_encoding_test.dart
+++ b/test/add_chunked_encoding_test.dart
@@ -10,23 +10,23 @@
void main() {
test('adds chunked encoding with no transfer-encoding header', () async {
var response = await _chunkResponse(
- Response.ok(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")));
+ 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(Response.ok(
- Stream.fromIterable(["hi".codeUnits]),
+ 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")));
+ 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(Response.ok("hi"));
+ var response = await _chunkResponse(Response.ok('hi'));
expect(response.headers, isNot(contains('transfer-encoding')));
- expect(response.readAsString(), completion(equals("hi")));
+ expect(response.readAsString(), completion(equals('hi')));
});
test("doesn't add chunked encoding with status 1xx", () async {
diff --git a/test/cascade_test.dart b/test/cascade_test.dart
index afa33b4..fa7701c 100644
--- a/test/cascade_test.dart
+++ b/test/cascade_test.dart
@@ -41,7 +41,7 @@
});
test(
- "the second response should be returned if it matches and the first "
+ 'the second response should be returned if it matches and the first '
"doesn't", () {
return Future.sync(() {
return handler(Request('GET', localhostUri, headers: {'one': 'false'}));
@@ -52,7 +52,7 @@
});
test(
- "the third response should be returned if it matches and the first "
+ 'the third response should be returned if it matches and the first '
"two don't", () {
return Future.sync(() {
return handler(Request('GET', localhostUri,
@@ -63,7 +63,7 @@
});
});
- test("the third response should be returned if no response matches", () {
+ test('the third response should be returned if no response matches', () {
return Future.sync(() {
return handler(Request('GET', localhostUri,
headers: {'one': 'false', 'two': 'false', 'three': 'false'}));
diff --git a/test/io_server_test.dart b/test/io_server_test.dart
index 0ed2a59..26226d4 100644
--- a/test/io_server_test.dart
+++ b/test/io_server_test.dart
@@ -26,19 +26,19 @@
tearDown(() => server.close());
- test("serves HTTP requests with the mounted handler", () async {
+ test('serves HTTP requests with the mounted handler', () async {
server.mount(syncHandler);
expect(await http.read(server.url), equals('Hello from /'));
});
- test("delays HTTP requests until a handler is mounted", () async {
+ test('delays HTTP requests until a handler is mounted', () async {
expect(http.read(server.url), completion(equals('Hello from /')));
await Future.delayed(Duration.zero);
server.mount(asyncHandler);
});
- test("disallows more than one handler from being mounted", () async {
+ test('disallows more than one handler from being mounted', () async {
server.mount((_) => null);
expect(() => server.mount((_) => null), throwsStateError);
expect(() => server.mount((_) => null), throwsStateError);
diff --git a/test/message_change_test.dart b/test/message_change_test.dart
index 17c9d4d..9f93d6d 100644
--- a/test/message_change_test.dart
+++ b/test/message_change_test.dart
@@ -30,8 +30,11 @@
/// Shared test method used by [Request] and [Response] tests to validate
/// the behavior of `change` with different `headers` and `context` values.
void _testChange(
- Message factory(
- {body, Map<String, String> headers, Map<String, Object> context})) {
+ Message Function(
+ {dynamic body,
+ Map<String, String> headers,
+ Map<String, Object> context})
+ factory) {
group('body', () {
test('with String', () async {
var request = factory(body: 'Hello, world');
diff --git a/test/message_test.dart b/test/message_test.dart
index 6ee475c..a5de23f 100644
--- a/test/message_test.dart
+++ b/test/message_test.dart
@@ -15,6 +15,7 @@
Encoding encoding)
: super(body, headers: headers, context: context, encoding: encoding);
+ @override
Message change(
{Map<String, String> headers, Map<String, Object> context, body}) {
throw UnimplementedError();
@@ -74,16 +75,16 @@
});
});
- group("readAsString", () {
- test("supports a null body", () {
+ group('readAsString', () {
+ test('supports a null body', () {
var request = _createMessage();
- expect(request.readAsString(), completion(equals("")));
+ expect(request.readAsString(), completion(equals('')));
});
- test("supports a Stream<List<int>> body", () {
+ test('supports a Stream<List<int>> body', () {
var controller = StreamController();
var request = _createMessage(body: controller.stream);
- expect(request.readAsString(), completion(equals("hello, world")));
+ expect(request.readAsString(), completion(equals('hello, world')));
controller.add(helloBytes);
return Future(() {
@@ -93,40 +94,40 @@
});
});
- test("defaults to UTF-8", () {
+ test('defaults to UTF-8', () {
var request = _createMessage(
body: Stream.fromIterable([
[195, 168]
]));
- expect(request.readAsString(), completion(equals("è")));
+ expect(request.readAsString(), completion(equals('è')));
});
- test("the content-type header overrides the default", () {
+ test('the content-type header overrides the default', () {
var request = _createMessage(
headers: {'content-type': 'text/plain; charset=iso-8859-1'},
body: Stream.fromIterable([
[195, 168]
]));
- expect(request.readAsString(), completion(equals("è")));
+ expect(request.readAsString(), completion(equals('è')));
});
- test("an explicit encoding overrides the content-type header", () {
+ test('an explicit encoding overrides the content-type header', () {
var request = _createMessage(
headers: {'content-type': 'text/plain; charset=iso-8859-1'},
body: Stream.fromIterable([
[195, 168]
]));
- expect(request.readAsString(latin1), completion(equals("è")));
+ expect(request.readAsString(latin1), completion(equals('è')));
});
});
- group("read", () {
- test("supports a null body", () {
+ group('read', () {
+ test('supports a null body', () {
var request = _createMessage();
expect(request.read().toList(), completion(isEmpty));
});
- test("supports a Stream<List<int>> body", () {
+ test('supports a Stream<List<int>> body', () {
var controller = StreamController();
var request = _createMessage(body: controller.stream);
expect(request.read().toList(),
@@ -140,12 +141,12 @@
});
});
- test("supports a List<int> body", () {
+ test('supports a List<int> body', () {
var request = _createMessage(body: helloBytes);
expect(request.read().toList(), completion(equals([helloBytes])));
});
- test("throws when calling read()/readAsString() multiple times", () {
+ test('throws when calling read()/readAsString() multiple times', () {
var request;
request = _createMessage();
@@ -166,23 +167,23 @@
});
});
- group("content-length", () {
- test("is 0 with a default body and without a content-length header", () {
+ group('content-length', () {
+ test('is 0 with a default body and without a content-length header', () {
var request = _createMessage();
expect(request.contentLength, 0);
});
- test("comes from a byte body", () {
+ test('comes from a byte body', () {
var request = _createMessage(body: [1, 2, 3]);
expect(request.contentLength, 3);
});
- test("comes from a string body", () {
+ test('comes from a string body', () {
var request = _createMessage(body: 'foobar');
expect(request.contentLength, 6);
});
- test("is set based on byte length for a string body", () {
+ test('is set based on byte length for a string body', () {
var request = _createMessage(body: 'fööbär');
expect(request.contentLength, 9);
@@ -190,48 +191,48 @@
expect(request.contentLength, 6);
});
- test("is null for a stream body", () {
+ test('is null for a stream body', () {
var request = _createMessage(body: Stream.empty());
expect(request.contentLength, isNull);
});
- test("uses the content-length header for a stream body", () {
+ test('uses the content-length header for a stream body', () {
var request = _createMessage(
body: Stream.empty(), headers: {'content-length': '42'});
expect(request.contentLength, 42);
});
- test("real body length takes precedence over content-length header", () {
+ test('real body length takes precedence over content-length header', () {
var request =
_createMessage(body: [1, 2, 3], headers: {'content-length': '42'});
expect(request.contentLength, 3);
});
- test("is null for a chunked transfer encoding", () {
+ test('is null for a chunked transfer encoding', () {
var request = _createMessage(
- body: "1\r\na0\r\n\r\n", headers: {'transfer-encoding': 'chunked'});
+ body: '1\r\na0\r\n\r\n', headers: {'transfer-encoding': 'chunked'});
expect(request.contentLength, isNull);
});
- test("is null for a non-identity transfer encoding", () {
+ test('is null for a non-identity transfer encoding', () {
var request = _createMessage(
- body: "1\r\na0\r\n\r\n", headers: {'transfer-encoding': 'custom'});
+ body: '1\r\na0\r\n\r\n', headers: {'transfer-encoding': 'custom'});
expect(request.contentLength, isNull);
});
- test("is set for identity transfer encoding", () {
+ test('is set for identity transfer encoding', () {
var request = _createMessage(
- body: "1\r\na0\r\n\r\n", headers: {'transfer-encoding': 'identity'});
+ body: '1\r\na0\r\n\r\n', headers: {'transfer-encoding': 'identity'});
expect(request.contentLength, equals(9));
});
});
- group("mimeType", () {
- test("is null without a content-type header", () {
+ group('mimeType', () {
+ test('is null without a content-type header', () {
expect(_createMessage().mimeType, isNull);
});
- test("comes from the content-type header", () {
+ test('comes from the content-type header', () {
expect(_createMessage(headers: {'content-type': 'text/plain'}).mimeType,
equals('text/plain'));
});
@@ -245,24 +246,24 @@
});
});
- group("encoding", () {
- test("is null without a content-type header", () {
+ group('encoding', () {
+ test('is null without a content-type header', () {
expect(_createMessage().encoding, isNull);
});
- test("is null without a charset parameter", () {
+ test('is null without a charset parameter', () {
expect(_createMessage(headers: {'content-type': 'text/plain'}).encoding,
isNull);
});
- test("is null with an unrecognized charset parameter", () {
+ test('is null with an unrecognized charset parameter', () {
expect(
_createMessage(
headers: {'content-type': 'text/plain; charset=fblthp'}).encoding,
isNull);
});
- test("comes from the content-type charset parameter", () {
+ test('comes from the content-type charset parameter', () {
expect(
_createMessage(
headers: {'content-type': 'text/plain; charset=iso-8859-1'})
@@ -270,7 +271,7 @@
equals(latin1));
});
- test("comes from the content-type charset parameter with a different case",
+ test('comes from the content-type charset parameter with a different case',
() {
expect(
_createMessage(
@@ -279,50 +280,50 @@
equals(latin1));
});
- test("defaults to encoding a String as UTF-8", () {
+ test('defaults to encoding a String as UTF-8', () {
expect(
- _createMessage(body: "è").read().toList(),
+ _createMessage(body: 'è').read().toList(),
completion(equals([
[195, 168]
])));
});
- test("uses the explicit encoding if available", () {
+ test('uses the explicit encoding if available', () {
expect(
- _createMessage(body: "è", encoding: latin1).read().toList(),
+ _createMessage(body: 'è', encoding: latin1).read().toList(),
completion(equals([
[232]
])));
});
- test("adds an explicit encoding to the content-type", () {
+ test('adds an explicit encoding to the content-type', () {
var request = _createMessage(
- body: "è", encoding: latin1, headers: {'content-type': 'text/plain'});
+ body: 'è', encoding: latin1, headers: {'content-type': 'text/plain'});
expect(request.headers,
containsPair('content-type', 'text/plain; charset=iso-8859-1'));
});
- test("adds an explicit encoding to the content-type with a different case",
+ test('adds an explicit encoding to the content-type with a different case',
() {
var request = _createMessage(
- body: "è", encoding: latin1, headers: {'Content-Type': 'text/plain'});
+ body: 'è', encoding: latin1, headers: {'Content-Type': 'text/plain'});
expect(request.headers,
containsPair('Content-Type', 'text/plain; charset=iso-8859-1'));
});
test(
- "sets an absent content-type to application/octet-stream in order to "
- "set the charset", () {
- var request = _createMessage(body: "è", encoding: latin1);
+ 'sets an absent content-type to application/octet-stream in order to '
+ 'set the charset', () {
+ var request = _createMessage(body: 'è', encoding: latin1);
expect(
request.headers,
containsPair(
'content-type', 'application/octet-stream; charset=iso-8859-1'));
});
- test("overwrites an existing charset if given an explicit encoding", () {
+ test('overwrites an existing charset if given an explicit encoding', () {
var request = _createMessage(
- body: "è",
+ body: 'è',
encoding: latin1,
headers: {'content-type': 'text/plain; charset=whatever'});
expect(request.headers,
diff --git a/test/pipeline_test.dart b/test/pipeline_test.dart
index 20b601a..c697e0c 100644
--- a/test/pipeline_test.dart
+++ b/test/pipeline_test.dart
@@ -9,7 +9,7 @@
void main() {
test('compose middleware with Pipeline', () {
- int accessLocation = 0;
+ var accessLocation = 0;
var middlewareA = createMiddleware(requestHandler: (request) {
expect(accessLocation, 0);
@@ -47,7 +47,7 @@
});
test('Pipeline can be used as middleware', () {
- int accessLocation = 0;
+ var accessLocation = 0;
var middlewareA = createMiddleware(requestHandler: (request) {
expect(accessLocation, 0);
diff --git a/test/request_test.dart b/test/request_test.dart
index 6febec0..96c14e7 100644
--- a/test/request_test.dart
+++ b/test/request_test.dart
@@ -11,7 +11,7 @@
import 'test_util.dart';
Request _request({Map<String, String> headers, body, Encoding encoding}) {
- return Request("GET", localhostUri,
+ return Request('GET', localhostUri,
headers: headers, body: body, encoding: encoding);
}
@@ -27,65 +27,65 @@
expect(request.protocolVersion, '1.0');
});
- group("url", () {
+ group('url', () {
test("defaults to the requestedUri's relativized path and query", () {
- var request = Request('GET', Uri.parse("http://localhost/foo/bar?q=1"));
- expect(request.url, equals(Uri.parse("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 = Request('GET', Uri.parse("http://localhost/foo/bar?q=1"),
+ test('is inferred from handlerPath if possible', () {
+ var request = Request('GET', Uri.parse('http://localhost/foo/bar?q=1'),
handlerPath: '/foo/');
- expect(request.url, equals(Uri.parse("bar?q=1")));
+ expect(request.url, equals(Uri.parse('bar?q=1')));
});
- test("uses the given value if passed", () {
- 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('uses the given value if passed', () {
+ 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 = Request('GET', Uri.parse("http://localhost/foo/bar"),
- url: Uri.parse(""));
- expect(request.url, equals(Uri.parse("")));
+ test('may be empty', () {
+ var request = Request('GET', Uri.parse('http://localhost/foo/bar'),
+ url: Uri.parse(''));
+ expect(request.url, equals(Uri.parse('')));
});
});
- group("handlerPath", () {
+ group('handlerPath', () {
test("defaults to '/'", () {
- var request = 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 = Request('GET', Uri.parse("http://localhost/foo/bar?q=1"),
- url: Uri.parse("bar?q=1"));
- expect(request.handlerPath, equals("/foo/"));
+ test('is inferred from url if possible', () {
+ 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 = Request('GET', Uri.parse("http://localhost/foo/bar?q=1"),
+ test('uses the given value if passed', () {
+ var request = Request('GET', Uri.parse('http://localhost/foo/bar?q=1'),
handlerPath: '/foo/');
- expect(request.handlerPath, equals("/foo/"));
+ expect(request.handlerPath, equals('/foo/'));
});
- test("adds a trailing slash to the given value if necessary", () {
- var request = Request('GET', Uri.parse("http://localhost/foo/bar?q=1"),
+ test('adds a trailing slash to the given value if necessary', () {
+ 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")));
+ expect(request.handlerPath, equals('/foo/'));
+ expect(request.url, equals(Uri.parse('bar?q=1')));
});
- test("may be a single slash", () {
- var request = Request('GET', Uri.parse("http://localhost/foo/bar?q=1"),
+ test('may be a single slash', () {
+ 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")));
+ expect(request.handlerPath, equals('/'));
+ expect(request.url, equals(Uri.parse('foo/bar?q=1')));
});
});
- group("errors", () {
+ group('errors', () {
group('requestedUri', () {
test('must be absolute', () {
expect(() => Request('GET', Uri.parse('/path')), throwsArgumentError);
@@ -182,17 +182,17 @@
});
});
- group("ifModifiedSince", () {
- test("is null without an If-Modified-Since header", () {
+ group('ifModifiedSince', () {
+ test('is null without an If-Modified-Since header', () {
var request = _request();
expect(request.ifModifiedSince, isNull);
});
- test("comes from the Last-Modified header", () {
+ test('comes from the Last-Modified header', () {
var request = _request(
headers: {'if-modified-since': 'Sun, 06 Nov 1994 08:49:37 GMT'});
expect(request.ifModifiedSince,
- equals(DateTime.parse("1994-11-06 08:49:37z")));
+ equals(DateTime.parse('1994-11-06 08:49:37z')));
});
});
@@ -267,7 +267,7 @@
});
});
- test("allows the original request to be read", () {
+ test('allows the original request to be read', () {
var request = _request();
var changed = request.change();
@@ -275,7 +275,7 @@
expect(changed.read, throwsStateError);
});
- test("allows the changed request to be read", () {
+ test('allows the changed request to be read', () {
var request = _request();
var changed = request.change();
@@ -283,7 +283,7 @@
expect(request.read, throwsStateError);
});
- test("allows another changed request to be read", () {
+ test('allows another changed request to be read', () {
var request = _request();
var changed1 = request.change();
var changed2 = request.change();
diff --git a/test/response_test.dart b/test/response_test.dart
index d316a4d..5d2149b 100644
--- a/test/response_test.dart
+++ b/test/response_test.dart
@@ -11,25 +11,25 @@
import 'test_util.dart';
void main() {
- group("supports a String body", () {
- test("readAsString", () {
- var response = Response.ok("hello, world");
- expect(response.readAsString(), completion(equals("hello, world")));
+ group('supports a String body', () {
+ test('readAsString', () {
+ var response = Response.ok('hello, world');
+ expect(response.readAsString(), completion(equals('hello, world')));
});
- test("read", () {
+ test('read', () {
var helloWorldBytes = List.from(helloBytes)..addAll(worldBytes);
- var response = Response.ok("hello, world");
+ var response = Response.ok('hello, world');
expect(response.read().toList(), completion(equals([helloWorldBytes])));
});
});
- group("new Response.internalServerError without a body", () {
+ group('new Response.internalServerError without a body', () {
test('sets the body to "Internal Server Error"', () {
var response = Response.internalServerError();
expect(
- response.readAsString(), completion(equals("Internal Server Error")));
+ response.readAsString(), completion(equals('Internal Server Error')));
});
test('sets the content-type header to text/plain', () {
@@ -46,42 +46,42 @@
});
});
- group("Response redirect", () {
- test("sets the location header for a String", () {
+ group('Response redirect', () {
+ test('sets the location header for a String', () {
var response = Response.found('/foo');
expect(response.headers, containsPair('location', '/foo'));
});
- test("sets the location header for a Uri", () {
+ test('sets the location header for a Uri', () {
var response = Response.found(Uri(path: '/foo'));
expect(response.headers, containsPair('location', '/foo'));
});
});
- group("expires", () {
- test("is null without an Expires header", () {
- expect(Response.ok("okay!").expires, isNull);
+ group('expires', () {
+ test('is null without an Expires header', () {
+ expect(Response.ok('okay!').expires, isNull);
});
- test("comes from the Expires header", () {
+ test('comes from the Expires header', () {
expect(
- 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")));
+ equals(DateTime.parse('1994-11-06 08:49:37z')));
});
});
- group("lastModified", () {
- test("is null without a Last-Modified header", () {
- expect(Response.ok("okay!").lastModified, isNull);
+ group('lastModified', () {
+ test('is null without a Last-Modified header', () {
+ expect(Response.ok('okay!').lastModified, isNull);
});
- test("comes from the Last-Modified header", () {
+ test('comes from the Last-Modified header', () {
expect(
- 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")));
+ equals(DateTime.parse('1994-11-06 08:49:37z')));
});
});
@@ -111,7 +111,7 @@
});
});
- test("allows the original response to be read", () {
+ test('allows the original response to be read', () {
var response = Response.ok(null);
var changed = response.change();
@@ -119,7 +119,7 @@
expect(changed.read, throwsStateError);
});
- test("allows the changed response to be read", () {
+ test('allows the changed response to be read', () {
var response = Response.ok(null);
var changed = response.change();
@@ -127,7 +127,7 @@
expect(response.read, throwsStateError);
});
- test("allows another changed response to be read", () {
+ test('allows another changed response to be read', () {
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 8a23b51..f42b361 100644
--- a/test/server_handler_test.dart
+++ b/test/server_handler_test.dart
@@ -11,12 +11,12 @@
import 'test_util.dart';
void main() {
- test("passes the URL to the server", () {
+ test('passes the URL to the server', () {
var serverHandler = ServerHandler(localhostUri);
expect(serverHandler.server.url, equals(localhostUri));
});
- test("pipes a request from ServerHandler.handler to a mounted handler",
+ test('pipes a request from ServerHandler.handler to a mounted handler',
() async {
var serverHandler = ServerHandler(localhostUri);
serverHandler.server.mount(asyncHandler);
@@ -38,7 +38,7 @@
expect(response.readAsString(), completion(equals('Hello from /')));
});
- test("stops servicing requests after Server.close is called", () {
+ test('stops servicing requests after Server.close is called', () {
var serverHandler = ServerHandler(localhostUri);
serverHandler.server.mount(expectAsync1((_) => null, count: 0));
serverHandler.server.close();
@@ -46,7 +46,7 @@
expect(makeSimpleRequest(serverHandler.handler), throwsStateError);
});
- test("calls onClose when Server.close is called", () async {
+ test('calls onClose when Server.close is called', () async {
var onCloseCalled = false;
var completer = Completer();
var serverHandler = ServerHandler(localhostUri, onClose: () {
diff --git a/test/shelf_io_test.dart b/test/shelf_io_test.dart
index fd69efd..25a9875 100644
--- a/test/shelf_io_test.dart
+++ b/test/shelf_io_test.dart
@@ -206,24 +206,24 @@
expect(request.method, 'POST');
request.hijack(expectAsync1((channel) {
- expect(channel.stream.first, completion(equals("Hello".codeUnits)));
+ expect(channel.stream.first, completion(equals('Hello'.codeUnits)));
- channel.sink.add(("HTTP/1.1 404 Not Found\r\n"
- "Date: Mon, 23 May 2005 22:38:34 GMT\r\n"
- "Content-Length: 13\r\n"
- "\r\n"
- "Hello, world!")
+ channel.sink.add(('HTTP/1.1 404 Not Found\r\n'
+ 'Date: Mon, 23 May 2005 22:38:34 GMT\r\n'
+ 'Content-Length: 13\r\n'
+ '\r\n'
+ 'Hello, world!')
.codeUnits);
channel.sink.close();
}));
return null;
});
- var response = await _post(body: "Hello");
+ var response = await _post(body: 'Hello');
expect(response.statusCode, HttpStatus.notFound);
- expect(response.headers["date"], "Mon, 23 May 2005 22:38:34 GMT");
+ expect(response.headers['date'], 'Mon, 23 May 2005 22:38:34 GMT');
expect(
- response.stream.bytesToString(), completion(equals("Hello, world!")));
+ response.stream.bytesToString(), completion(equals('Hello, world!')));
});
test('reports an error if a HijackException is thrown without hijacking',
@@ -387,14 +387,14 @@
() async {
await _scheduleServer((request) {
return Response.ok(
- Stream.fromIterable(["2\r\nhi\r\n0\r\n\r\n".codeUnits]),
+ Stream.fromIterable(['2\r\nhi\r\n0\r\n\r\n'.codeUnits]),
headers: {HttpHeaders.transferEncodingHeader: 'chunked'});
});
var response = await _get();
expect(response.headers,
containsPair(HttpHeaders.transferEncodingHeader, 'chunked'));
- expect(response.body, equals("hi"));
+ expect(response.body, equals('hi'));
});
group('is not added when', () {
@@ -451,24 +451,24 @@
test('respects the "shelf.io.buffer_output" context parameter', () async {
var controller = StreamController<String>();
await _scheduleServer((request) {
- controller.add("Hello, ");
+ controller.add('Hello, ');
return Response.ok(utf8.encoder.bind(controller.stream),
- context: {"shelf.io.buffer_output": false});
+ context: {'shelf.io.buffer_output': false});
});
var request =
- http.Request("GET", Uri.parse('http://localhost:$_serverPort/'));
+ http.Request('GET', Uri.parse('http://localhost:$_serverPort/'));
var response = await request.send();
var stream = StreamQueue(utf8.decoder.bind(response.stream));
var data = await stream.next;
- expect(data, equals("Hello, "));
- controller.add("world!");
+ expect(data, equals('Hello, '));
+ controller.add('world!');
data = await stream.next;
- expect(data, equals("world!"));
+ expect(data, equals('world!'));
await controller.close();
expect(stream.hasNext, completion(isFalse));
});
diff --git a/test/ssl_certs.dart b/test/ssl_certs.dart
index be86de3..d5a3625 100644
--- a/test/ssl_certs.dart
+++ b/test/ssl_certs.dart
@@ -4,7 +4,7 @@
import 'dart:convert';
-List<int> certChainBytes = utf8.encode("""
+List<int> certChainBytes = utf8.encode('''
-----BEGIN CERTIFICATE-----
MIIDZDCCAkygAwIBAgIBATANBgkqhkiG9w0BAQsFADAgMR4wHAYDVQQDDBVpbnRl
cm1lZGlhdGVhdXRob3JpdHkwHhcNMTUxMDI3MTAyNjM1WhcNMjUxMDI0MTAyNjM1
@@ -64,9 +64,9 @@
UnlU2l5vZrh1PTCqZxvC/IdRESUfW80LdHaeyizRUP+6vKxGgSz2MRuYINjbd6GO
hGiCpWlwziW2xLV1l2qSRLko2kIafLZP18N0ThM9zKbU5ps9NgFOf//wqSGtLaE=
-----END CERTIFICATE-----
-""");
+''');
-List<int> certKeyBytes = utf8.encode("""
+List<int> certKeyBytes = utf8.encode('''
-----BEGIN ENCRYPTED PRIVATE KEY-----
MIIE4zAcBgoqhkiG9w0BDAEBMA4ECBMCjlg8JYZ4AgIIAASCBMFd9cBoZ5xcTock
AVQcg/HzYJtMceKn1gtMDdC7mmXuyN0shoxhG4BpQInHkFARL+nenesXFxEm4X5e
@@ -96,4 +96,4 @@
s0HRA2VwF/0ypU3OKERM1Ua5NSkTgvnnVTlV9GO90Tkn5v4fxdl8NzIuJLyGguTP
Xc0tRM34Lg==
-----END ENCRYPTED PRIVATE KEY-----
-""");
+''');
diff --git a/test/test_util.dart b/test/test_util.dart
index 8af96fa..9d0f46d 100644
--- a/test/test_util.dart
+++ b/test/test_util.dart
@@ -21,8 +21,7 @@
/// `Hello from ${request.url.path}`.
Response syncHandler(Request request,
{int statusCode, Map<String, String> headers}) {
- if (statusCode == null) statusCode = 200;
- return Response(statusCode,
+ return Response(statusCode ?? 200,
headers: headers, body: 'Hello from ${request.requestedUri.path}');
}