OLD | NEW |
| (Empty) |
1 // Copyright (c) 2015, the Dart project authors. Please see the AUTHORS file | |
2 // for details. All rights reserved. Use of this source code is governed by a | |
3 // BSD-style license that can be found in the LICENSE file. | |
4 | |
5 import "dart:io"; | |
6 | |
7 const sampleText = "Sample text file."; | |
8 | |
9 main() async { | |
10 var server = await startServer(); | |
11 var uriText = "http://localhost:${server.port}/sample.txt?query#fragment"; | |
12 var resource = new Resource(uriText); | |
13 | |
14 if (resource.uri != Uri.parse(uriText)) { | |
15 throw "Incorrect URI: ${resource.uri}"; | |
16 } | |
17 | |
18 var text = await resource.readAsString(); | |
19 if (text != sampleText) { | |
20 throw "Incorrect reading of text file: $text"; | |
21 } | |
22 | |
23 var bytes = await resource.readAsBytes(); | |
24 if (!compareBytes(bytes, sampleText.codeUnits)) { | |
25 throw "Incorrect reading of bytes: $bytes"; | |
26 } | |
27 | |
28 var streamBytes = []; | |
29 await for (var byteSlice in resource.openRead()) { | |
30 streamBytes.addAll(byteSlice); | |
31 } | |
32 if (!compareBytes(streamBytes, sampleText.codeUnits)) { | |
33 throw "Incorrect reading of bytes: $bytes"; | |
34 } | |
35 | |
36 await server.close(); | |
37 } | |
38 | |
39 /// Checks that [bytes] and [expectedBytes] have the same contents. | |
40 bool compareBytes(bytes, expectedBytes) { | |
41 if (bytes.length != expectedBytes.length) return false; | |
42 for (int i = 0; i < expectedBytes.length; i++) { | |
43 if (bytes[i] != expectedBytes[i]) return false; | |
44 } | |
45 return true; | |
46 } | |
47 | |
48 startServer() async { | |
49 var server = await HttpServer.bind(InternetAddress.LOOPBACK_IP_V4, 0); | |
50 var expectedUri = new Uri(path: "/sample.txt", query: "query"); | |
51 server.forEach((request) async { | |
52 await request.drain(); | |
53 var response = request.response; | |
54 if (request.uri == expectedUri) { | |
55 response.write(sampleText); | |
56 } else { | |
57 response.write("INCORRECT PATH!: ${request.uri}"); | |
58 } | |
59 response.close(); | |
60 }); | |
61 return server; | |
62 } | |
OLD | NEW |