Browse Source

[All] First commit, added documentation to the code, renamed some stuff and made sure that the code is good as a start

pull/1/head
Miguel Castiblanco 5 years ago
commit
975b1a6c8e
  1. 13
      .gitignore
  2. 17
      CHANGELOG.md
  3. 201
      LICENSE
  4. 8
      README.md
  5. 325
      lib/simple_client.dart
  6. 10
      pubspec.yaml
  7. 349
      test/simple_client_test.dart

13
.gitignore

@ -0,0 +1,13 @@
# IntelliJ
.idea/
# Files and directories created by pub
.packages
.pub/
build/
# If you're building an application, you may want to check-in your pubspec.lock
pubspec.lock
# Directory created by dartdoc
# If you don't generate documentation locally you can remove this line.
doc/api/

17
CHANGELOG.md

@ -0,0 +1,17 @@
# Changelog
## 0.5.0 - Oct 15, 2017
First public version of the lib
### Added
- Support for interceptors
- Support for authenticator
- Basic requests returning the body
- Basic GET, POST, PUT, and DELETE support
- Timeout support
- Redirection config support
- TLS: config to accept any certificate
- TLS: config to add a certificate to the trusted certs
- Timeout, Unauthorized, and TLS Exceptions

201
LICENSE

@ -0,0 +1,201 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "{}"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright 2017 Miguel Castiblanco
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

8
README.md

@ -0,0 +1,8 @@
# SimpleHttpClient
A flexible Http Client for Flutter and Dart Server. Built on top of `dart:io`,
SimpleHttpClient adds many features that are commonly used like interceptors or
authenticators
## Summary
TBD

325
lib/simple_client.dart

@ -0,0 +1,325 @@
/*
* Copyright (C) 2017 Miguel Castiblanco
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import 'dart:async';
import 'dart:io';
import 'dart:convert';
/// If one or more interceptors are set, they will be called before the request
/// is made in order to allow for modifications of the [HttpClientRequest]
/// See [SimpleHttpClient.addInterceptor]
typedef Future<HttpClientRequest> Interceptor(HttpClientRequest request);
/// Wraps `dart:io` [HttpClient] to provide an easy to use, yet flexible and
/// feature rich implementation of an Http Client.
///
/// SimpleHttpClient client = new SimpleHttpClient();
/// Response response = await client.get("http://localhost:8080/service");
/// if (HttpStatus.OK == response.statusCode) {
/// // OK
/// }
///
/// Set an authenticator to have it called if a request receives a [:401:] response,
/// or set an interceptor if you want to modify all the requests made with this
/// client (e.g adding a header). See [SimpleHttpClient.setAuthenticator],
/// [SimpleHttpClient.addInterceptor], and [Interceptor].
///
/// Set a timeout [Duration] when creating the instance
/// `new SimpleHttpClient(timeout: new Duration(seconds: 7))`.
///
/// You can also configure it to accept any TLS certificate, add a custom
/// self certificate, or accept only certs generated by trusted authorities (default
/// behavior)
///
/// Check the documentation on the constructor and the public methods for more
/// details
class SimpleHttpClient {
/// Used for the `user-agent` header
final String userAgent;
/// Whether or not the client should follow redirects. Default value is [:true:]
final bool followRedirects;
/// Max amount of redirects supported. Default value is [:5:]
final int maxRedirects;
/// If an authenticator is set, how many times should the client retry calling
/// the authenticator and the service before failing. Default value is [:1:]
final int maxAuthRetries;
HttpClient _httpClient;
List<Interceptor> _interceptors = new List();
Interceptor _authenticate;
Duration _timeout;
SecurityContext _securityContext;
/// Creates an instance of [SimpleHttpClient].
/// [userAgent] Will be used when sending the requests. Defaults to library name
/// [allowSelfSignedCerts] Whether or not the app should accept any certificate
/// during secure requests. Consider setting [trustedCertificates] instead if you
/// are connecting to your own self-signed certificates.
/// [timeout] Sets a [Duration] as the timeout for a request to happen. Default
/// is [:10:] seconds.
/// [followRedirects] Whether or not the client should follow redirects, used
/// together with [maxRedirects]. [followRedirects] is true by default, while
/// [maxRedirects] is [:5:] by default.
/// [trustedCertificates] allows you to add a certificate file to the security
/// context, allowing you to set your self signed certificate as trusted. Please
/// try to use [trustedCertificates] instead of [allowSelfSignedCerts] if possible.
SimpleHttpClient(
{this.userAgent: "Starcarr's Simple Client",
allowSelfSignedCerts: false,
Duration timeout,
this.followRedirects: true,
this.maxRedirects: 5,
this.maxAuthRetries: 1,
List<int> trustedCertificates}) {
if (timeout == null) {
_timeout = new Duration(seconds: 10);
} else {
_timeout = timeout;
}
if (trustedCertificates != null) {
_securityContext = new SecurityContext()
..setTrustedCertificatesBytes(new List.from(trustedCertificates));
}
_httpClient = new HttpClient(context: _securityContext);
_httpClient.badCertificateCallback = (_, __, ___) => allowSelfSignedCerts;
}
_setHeaders(HttpClientRequest request) {
request.headers.removeAll("user-agent");
request.headers.add("user-agent", userAgent);
}
_intercept(HttpClientRequest request) async {
if (_interceptors.isNotEmpty) {
for (Interceptor interceptor in _interceptors) {
await interceptor(request);
}
}
}
_setContentType(HttpClientRequest request, {ContentType contentType}) {
if (contentType == null) {
contentType = ContentType.JSON;
}
request.headers.contentType = contentType;
}
Future<Response> _execute(Future<HttpClientRequest> handler(),
{bool authenticate: false,
int requestNumber: 1,
String body,
Map<String, String> headers}) async {
try {
HttpClientRequest request = await handler();
_setHeaders(request);
request.followRedirects = followRedirects;
request.maxRedirects = maxRedirects;
if (headers != null) {
headers.forEach((key, value) {
request.headers.add(key, value);
});
}
if (authenticate) await _authenticate(request);
await _intercept(request);
if (body != null) {
request.write(body);
}
HttpClientResponse response =
await request.close().timeout(_timeout, onTimeout: () {
throw new TimeOutException();
});
if (HttpStatus.UNAUTHORIZED == response.statusCode &&
_authenticate != null &&
requestNumber <= maxAuthRetries) {
return _execute(handler,
authenticate: true,
requestNumber: requestNumber + 1,
body: body,
headers: headers);
} else if (HttpStatus.UNAUTHORIZED == response.statusCode) {
throw new UnauthorizedException();
}
return _read(response);
} on SocketException catch (_) {
throw new CantConnectException();
} on HandshakeException catch (_) {
throw new TLSException();
} on CertificateException catch (_) {
throw new TLSException();
}
}
Future<HttpClientRequest> _get(String url) async {
return await _httpClient.getUrl(Uri.parse(url));
}
Future<HttpClientRequest> _post(String url, {ContentType contentType}) async {
HttpClientRequest request = await _httpClient.postUrl(Uri.parse(url));
_setContentType(request, contentType: contentType);
return request;
}
Future<HttpClientRequest> _put(String url, {ContentType contentType}) async {
HttpClientRequest request = await _httpClient.putUrl(Uri.parse(url));
_setContentType(request, contentType: contentType);
return request;
}
Future<HttpClientRequest> _delete(String url) async {
return await _httpClient.deleteUrl(Uri.parse(url));
}
Future<Response> _read(HttpClientResponse response) async {
StringBuffer body = new StringBuffer();
Completer<String> completer = new Completer();
response.transform(UTF8.decoder).listen((data) {
body.write(data);
}, onDone: () {
completer.complete(body.toString());
});
Map<String, String> headers = new Map();
response.headers.forEach((key, values){
headers[key] = values.join(", ");
});
return new Response()
..statusCode = response.statusCode
..headers = headers
..body = await completer.future;
}
/// Set the authenticator for the client. If an authenticator is set,
/// the app will call it when a response has the HTTP Status Code [:401:].
/// The authenticator will be called with a request identical to the original
/// one, and the authenticator has to modify that request in whichever way
/// needed. After the authenticator is called, the request will be sent and
/// the execution will continue normally. The authenticator will be called
/// until [maxAuthRetries] is reached. After that, or if an authenticator was
/// not set, an [UnauthorizedException] will be thrown.
///
/// The authenticator will be called before any interceptor.
void setAuthenticator(Interceptor authenticator) {
this._authenticate = authenticator;
}
/// Add an [Interceptor]. Each interceptor will be called sequentially in the same
/// order it was added, before executing the request, and after the authenticator
/// if authentication was needed.
void addInterceptor(Interceptor interceptor) {
_interceptors.add(interceptor);
}
/// Remove an interceptor from the list
void removeInterceptor(Interceptor interceptor) {
_interceptors.remove(interceptor);
}
/// Execute a POST call.
/// [url] of the resource
/// [body] of the request
/// [contentType] to be used
/// [headers] if any
/// Will return a [Response]
Future<Response> post(String url, String body,
{ContentType contentType, Map<String, String> headers}) async {
var response = await _execute(() => _post(url, contentType: contentType),
body: body, headers: headers);
print("POST $url [${response.statusCode}]");
return response;
}
/// Execute a PUT call.
/// [url] of the resource
/// [body] of the request
/// [contentType] to be used
/// [headers] if any
/// Will return a [Response]
Future<Response> put(String url, String body,
{ContentType contentType, Map<String, String> headers}) async {
var response = await _execute(() => _put(url, contentType: contentType),
body: body, headers: headers);
print("PUT $url [${response.statusCode}]");
return response;
}
/// Execute a GET call.
/// [url] of the resource
/// [headers] if any
/// Will return a [Response]
Future<Response> get(String url, {Map<String, String> headers}) async {
var response = await _execute(() => _get(url), headers: headers);
print("GET $url [${response.statusCode}]");
return response;
}
/// Execute a GET call.
/// [url] of the resource
/// [headers] if any
/// Will return a [Response]
Future<Response> delete(String url, {Map<String, String> headers}) async {
var response = await _execute(() => _delete(url), headers: headers);
print("DELETE $url [${response.statusCode}]");
return response;
}
}
class Response {
int statusCode;
String body;
Map<String, String> headers;
}
class UnauthorizedException implements Exception {
String toString() {
return "Unauthorized";
}
}
class CantConnectException implements Exception {
String toString() {
return "Can't connect to the server";
}
}
class TLSException implements Exception {
String toString() {
return "SSL error in the given port";
}
}
class TimeOutException implements Exception {
String toString() {
return "Request timed out";
}
}

10
pubspec.yaml

@ -0,0 +1,10 @@
name: simple_http_client
version: 0.5.0
description: Simple HTTP client for Flutter and Dart server
author: Miguel Castiblanco <miguel@starcarr.co>
homepage: https://gitlab.com/Starcarr/SimpleHttpClient
dev_dependencies:
test: "0.12.24+2"
resource: ">=2.1.2 <3.0.0"
mock_web_server: "^2.0.1"

349
test/simple_client_test.dart

@ -0,0 +1,349 @@
/* Copyright (c) 2017 Miguel Castiblanco */
import 'dart:async';
import 'dart:convert';
import 'package:resource/resource.dart' show Resource;
import 'package:test/test.dart';
import 'package:simple_http_client/simple_client.dart';
import 'package:mock_web_server/mock_web_server.dart';
import 'dart:io';
MockWebServer _server;
bool mocked = true;
main() {
setUp(() async {
_server = new MockWebServer();
await _server.start();
});
tearDown(() {
_server.shutdown();
});
test('simple request', () async {
String responseBody = "Hello World";
_server.enqueue(body: responseBody);
SimpleHttpClient client = new SimpleHttpClient();
String response = (await client.get(_server.url)).body;
expect(responseBody, response);
expect(_server.requestCount, 1);
});
test('methods', () async {
_server.enqueue();
_server.enqueue();
_server.enqueue();
_server.enqueue();
SimpleHttpClient client = new SimpleHttpClient();
await client.get(_server.url);
expect(_server.takeRequest().method, "GET");
await client.post(_server.url, "");
expect(_server.takeRequest().method, "POST");
await client.put(_server.url, "");
expect(_server.takeRequest().method, "PUT");
await client.delete(_server.url);
expect(_server.takeRequest().method, "DELETE");
expect(_server.requestCount, 4);
});
test('status code read', () async {
_server.enqueue(httpCode: HttpStatus.NO_CONTENT);
_server.enqueue(httpCode: HttpStatus.ACCEPTED);
_server.enqueue(httpCode: HttpStatus.BAD_REQUEST);
SimpleHttpClient client = new SimpleHttpClient();
var res = await client.get(_server.url);
expect(res.statusCode, HttpStatus.NO_CONTENT);
res = await client.post(_server.url, "");
expect(res.statusCode, HttpStatus.ACCEPTED);
res = await client.put(_server.url, "");
expect(res.statusCode, HttpStatus.BAD_REQUEST);
expect(_server.requestCount, 3);
});
test('simple intercept', () async {
String responseBody = "Intercepted Response";
String headerAuth = "BEARER XAZSA";
_server.enqueue(body: headerAuth, delay: new Duration(milliseconds: 200));
_server.enqueue(body: responseBody);
SimpleHttpClient client = new SimpleHttpClient();
client.addInterceptor((HttpClientRequest request) async {
// Request and add the auth header only to the first request
if ("/user/1" == request.uri.path) {
String token = (await client.get(_server.url)).body;
request.headers.set("Authorization", token);
}
});
String response = (await client.get(_server.url + "user/1")).body;
expect(responseBody, response);
expect(2, _server.requestCount);
HttpRequest request = _server.takeRequest();
expect(headerAuth, request.headers.value("Authorization"));
});
test('useragent', () async {
String responseBody = "Response";
String userAgent = "Awesome client";
_server.enqueue(body: responseBody);
SimpleHttpClient client = new SimpleHttpClient(userAgent: userAgent);
String response = (await client.get(_server.url)).body;
expect(responseBody, response);
expect(1, _server.requestCount);
HttpRequest request = _server.takeRequest();
expect(userAgent, request.headers.value("user-agent"));
});
test('authenticator', () async {
String body = "Welcome!";
String header = "BEARER JAHDHSA";
String requestBody = "Retried";
_server.enqueue(httpCode: HttpStatus.UNAUTHORIZED);
_server.enqueue(body: body);
SimpleHttpClient client = new SimpleHttpClient();
client.setAuthenticator((request) {
request.headers.set("Authorization", header);
});
String response = (await client.post(_server.url, requestBody)).body;
expect(body, response);
expect(_server.requestCount, 2);
HttpRequest success = _server.takeRequest();
HttpRequest unauthorized = _server.takeRequest();
expect(HttpStatus.UNAUTHORIZED, unauthorized.response.statusCode);
expect(unauthorized.headers.value("Authorization"), null);
expect(HttpStatus.OK, success.response.statusCode);
expect(header, success.headers.value("Authorization"));
});
test('max auth retries', () async {
_server.enqueue(httpCode: HttpStatus.UNAUTHORIZED);
_server.enqueue(httpCode: HttpStatus.UNAUTHORIZED);
_server.enqueue(httpCode: HttpStatus.UNAUTHORIZED);
SimpleHttpClient client = new SimpleHttpClient(maxAuthRetries: 2);
client.setAuthenticator((request) {
// Do nothing
});
await expectLater(client.get(_server.url),
throwsA(new isInstanceOf<UnauthorizedException>()));
expect(_server.requestCount, 3);
});
test('UnauthorizedException', () async {
_server.enqueue(httpCode: HttpStatus.UNAUTHORIZED);
SimpleHttpClient client = new SimpleHttpClient();
expect(client.get(_server.url),
throwsA(new isInstanceOf<UnauthorizedException>()));
});
test('CantConnectException', () async {
SimpleHttpClient client = new SimpleHttpClient();
expect(client.get("http://l.o.c.alhost:6453/"),
throwsA(new isInstanceOf<CantConnectException>()));
});
test('timeout', () async {
String body = "51 milliseconds";
_server.enqueue(delay: new Duration(milliseconds: 70), body: body);
SimpleHttpClient client =
new SimpleHttpClient(timeout: new Duration(milliseconds: 50));
expect(
client.get(_server.url), throwsA(new isInstanceOf<TimeOutException>()));
});
test('headers send', () async {
String name = "Awesome header";
_server.enqueue();
_server.enqueue();
_server.enqueue();
_server.enqueue();
SimpleHttpClient client = new SimpleHttpClient();
await client.get(_server.url, headers: {"name" : name});
expect(_server.takeRequest().headers.value("name"), name);
});
test('headers retrieve', () async {
_server.enqueue(headers: {"x-my-header": "awesome"});
_server.enqueue(headers: {"x-my-header": "awesome, double"});
SimpleHttpClient client = new SimpleHttpClient();
var res = await client.get(_server.url);
expect(res.headers["x-my-header"], "awesome");
res = await client.get(_server.url);
expect(res.headers["x-my-header"], "awesome, double");
});
test('headers retry', () async {
String name = "Awesome header";
_server.enqueue(httpCode: HttpStatus.UNAUTHORIZED);
_server.enqueue();
SimpleHttpClient client = new SimpleHttpClient();
client.setAuthenticator((request) {
// Do nothing
});
await client.get(_server.url, headers: {"name" : name});
expect(_server.requestCount, 2);
expect(_server.takeRequest().headers.value("name"), name);
expect(_server.takeRequest().headers.value("name"), name);
});
test('parallel reqs', () async {
String body70 = "70 milliseconds";
String body40 = "40 milliseconds";
String body20 = "20 milliseconds";
_server.enqueue(delay: new Duration(milliseconds: 40), body: body40);
_server.enqueue(delay: new Duration(milliseconds: 70), body: body70);
_server.enqueue(delay: new Duration(milliseconds: 20), body: body20);
Completer completer = new Completer();
List<String> responses = new List();
SimpleHttpClient client = new SimpleHttpClient();
client.get(_server.url).then((res) async {
// 40 milliseconds
responses.add(res.body);
});
client.get(_server.url).then((res) async {
// 70 milliseconds
responses.add(res.body);
// complete on the longer operation
completer.complete();
});
client.get(_server.url).then((res) async {
// 20 milliseconds
responses.add(res.body);
});
await completer.future;
// validate that the responses happened in order 20, 40, 70
expect(responses[0], body20);
expect(responses[1], body40);
expect(responses[2], body70);
});
test('TLS any cert', () async {
var body = "S03E08 You Are Not Safe";
var chainRes =
new Resource('package:mock_web_server/certificates/server_chain.pem');
var chain = chainRes.readAsBytes();
var keyRes =
new Resource('package:mock_web_server/certificates/server_key.pem');
var key = keyRes.readAsBytes();
Certificate certificate = new Certificate()
..password = "dartdart"
..key = await key
..chain = await chain;
var _server = new MockWebServer(certificate: certificate);
await _server.start();
_server.enqueue(body: body);
var client = new SimpleHttpClient(allowSelfSignedCerts: true);
var res = await client.get(_server.url);
expect(res.body, body);
});
test('TLS validate cert and fail', () async {
var body = "S03E08 You Are Not Safe";
var chainRes =
new Resource('package:mock_web_server/certificates/server_chain.pem');
var chain = chainRes.readAsBytes();
var keyRes =
new Resource('package:mock_web_server/certificates/server_key.pem');
var key = keyRes.readAsBytes();
Certificate certificate = new Certificate()
..password = "dartdart"
..key = await key
..chain = await chain;
var _server = new MockWebServer(certificate: certificate);
await _server.start();
_server.enqueue(body: body);
var client = new SimpleHttpClient();
expect(client.get(_server.url), throwsA(new isInstanceOf<TLSException>()));
});
test('TLS custom cert validation', () async {
var body = "S03E08 You Are Not Safe";
var chainRes =
new Resource('package:mock_web_server/certificates/server_chain.pem');
var chain = chainRes.readAsBytes();
var keyRes =
new Resource('package:mock_web_server/certificates/server_key.pem');
var key = keyRes.readAsBytes();
Certificate certificate = new Certificate()
..password = "dartdart"
..key = await key
..chain = await chain;
var _server = new MockWebServer(certificate: certificate);
await _server.start();
_server.enqueue(body: body);
var certRes =
new Resource('package:mock_web_server/certificates/trusted_certs.pem');
List<int> cert = await certRes.readAsBytes();
var client = new SimpleHttpClient(trustedCertificates: cert);
var res = await client.get(_server.url);
expect(res.body, body);
});
}
Loading…
Cancel
Save