-
-
Notifications
You must be signed in to change notification settings - Fork 1.5k
/
Copy pathutils.dart
210 lines (184 loc) · 6.12 KB
/
utils.dart
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
import 'dart:async';
import 'dart:convert';
import 'dart:io';
import 'dart:typed_data';
import 'package:dio/dio.dart';
import 'package:test/test.dart';
/// The current server instance.
HttpServer? _server;
Encoding requiredEncodingForCharset(String charset) =>
Encoding.getByName(charset) ??
(throw FormatException('Unsupported encoding "$charset".'));
/// The URL for the current server instance.
Uri get serverUrl => Uri.parse('http://localhost:${_server?.port}');
/// Starts a new HTTP server.
Future<void> startServer() async {
_server = (await HttpServer.bind('localhost', 0))
..listen((request) async {
final path = request.uri.path;
final response = request.response;
if (path == '/error') {
const content = 'error';
response
..statusCode = 400
..contentLength = content.length
..write(content);
response.close();
return;
}
if (path == '/loop') {
final n = int.parse(request.uri.query);
response
..statusCode = 302
..headers
.set('location', serverUrl.resolve('/loop?${n + 1}').toString())
..contentLength = 0;
response.close();
return;
}
if (path == '/redirect') {
response
..statusCode = 302
..headers.set('location', serverUrl.resolve('/').toString())
..contentLength = 0;
response.close();
return;
}
if (path == '/no-content-length') {
response
..statusCode = 200
..contentLength = -1
..write('body');
response.close();
return;
}
if (path == '/list') {
response.headers.contentType = ContentType('application', 'json');
response
..statusCode = 200
..contentLength = -1
..write('[1,2,3]');
response.close();
return;
}
if (path == '/multi-value-header') {
response.headers.contentType = ContentType('application', 'json');
response.headers.add(
'x-multi-value-request-header-echo',
request.headers.value('x-multi-value-request-header').toString(),
);
response
..statusCode = 200
..contentLength = -1
..write('');
response.close();
return;
}
if (path == '/download') {
final count = int.parse(request.uri.queryParameters['count'] ?? '1');
final gap = int.parse(request.uri.queryParameters['gap'] ?? '0');
const content = 'I am a text file';
final contentBytes = utf8.encode(content);
response
..bufferOutput = gap <= 0
..contentLength = contentBytes.length * count
..headers.set('content-encoding', 'plain')
..statusCode = 200;
for (int i = 0; i < count; i++) {
response.add(contentBytes);
await response.flush();
if (i < count - 1 && gap > 0) {
await Future.delayed(Duration(seconds: gap));
}
}
await Future.delayed(const Duration(milliseconds: 300));
await response.close();
return;
}
final requestBodyBytes = await ByteStream(request).toBytes();
final encodingName = request.uri.queryParameters['response-encoding'];
final outputEncoding = encodingName == null
? ascii
: requiredEncodingForCharset(encodingName);
response.headers.contentType =
ContentType('application', 'json', charset: outputEncoding.name);
response.headers.set('single', 'value');
dynamic requestBody;
if (requestBodyBytes.isEmpty) {
requestBody = null;
} else {
final encoding = requiredEncodingForCharset(
request.headers.contentType?.charset ?? 'utf-8',
);
requestBody = encoding.decode(requestBodyBytes);
}
final content = <String, dynamic>{
'method': request.method,
'path': request.uri.path,
'query': request.uri.query,
'headers': {},
};
if (requestBody != null) {
content['body'] = requestBody;
}
request.headers.forEach((name, values) {
// These headers are automatically generated by dart:io, so we don't
// want to test them here.
if (name == 'cookie' || name == 'host') {
return;
}
content['headers'][name] = values;
});
final body = json.encode(content);
response
..contentLength = body.length
..write(body);
response.close();
});
}
/// Stops the current HTTP server.
void stopServer() {
if (_server != null) {
_server!.close();
_server = null;
}
}
/// A matcher for functions that throw SocketException.
final Matcher throwsSocketException =
throwsA(const TypeMatcher<SocketException>());
/// A matcher for functions that throw DioException of type connectionError.
final Matcher throwsDioExceptionConnectionError = throwsA(
allOf([
isA<DioException>(),
(DioException e) => e.type == DioExceptionType.connectionError,
]),
);
/// A stream of chunks of bytes representing a single piece of data.
class ByteStream extends StreamView<List<int>> {
ByteStream(super.stream);
/// Returns a single-subscription byte stream that will emit the given bytes
/// in a single chunk.
factory ByteStream.fromBytes(List<int> bytes) =>
ByteStream(Stream.fromIterable([bytes]));
/// Collects the data of this stream in a [Uint8List].
Future<Uint8List> toBytes() {
@pragma('vm:awaiter-link')
final completer = Completer<Uint8List>();
final sink = ByteConversionSink.withCallback(
(bytes) => completer.complete(Uint8List.fromList(bytes)),
);
listen(
sink.add,
onError: completer.completeError,
onDone: sink.close,
cancelOnError: true,
);
return completer.future;
}
/// Collect the data of this stream in a [String], decoded according to
/// [encoding], which defaults to `UTF8`.
Future<String> bytesToString([Encoding encoding = utf8]) =>
encoding.decodeStream(this);
Stream<String> toStringStream([Encoding encoding = utf8]) =>
encoding.decoder.bind(this);
}