mock_web_server 4.0.0

  • README.md
  • CHANGELOG.md
  • Installing
  • Versions
  • 74

MockWebServer

build status

A flexible Dart web server that can be used to script tests and web server interactions

Summary

The best way to do integration tests, or to reproduce specific edge cases, is to be able to script the interaction between the software that is being tested and the web server.

MockWebServer aims to facility testing by offering a flexible stand alone Server that will respond with a given script (or forward the request to your dispatcher).

MockWebServer is based on the library of the same name created by Square for Java.

Usage

Starting it

MockWebServer can run in a given port or an ephemeral one

new MockWebServer(); // Will use an ephemeral port picked by the system
new MockWebServer(port: 8081); // Will use 8081

To start it just do

MockWebServer server = new MockWebServer();
server.start();

Once you have the server running you will want to get the url of it, so that you can configure your app to connect there

server.url; // will return http://127.0.0.1:8081
server.port; // 8081
server.host; // 127.0.0.1

Adding responses to the queue

Once the server is started, you can queue the responses that you want. The response queue is First In First Out

// Enqueue an empty body with response code 401
server.enqueue(httpCode: 401);

// Response code defaults to 200, so this will be a 200 with the given json as the body
server.enqueue(body: '{ "message" : "hi"}');

// HTTP 200 with empty body and some header
Map<String, String> headers = new Map();
headers["X-Server"] = "MockDart";
server.enqueue(headers: headers);

// All the parameters are optional so you can mix and match according to what you need
server.enqueue(httpCode: 201, body: "answer", headers: headers, duration: duration);

// You can always call enqueueResponse() to directly enqueue a MockResponse
Map<String, String> headers = new Map();
headers["X-Server"] = "MockDart";

var mockResponse = new MockResponse()
  ..httpCode = 201
  ..body = "Created"
  ..headers = headers
  ..delay = new Duration(seconds: 2);

server.enqueueResponse(mockResponse);

Delaying the response

To test timeouts or race conditions you may want to have the server take some time

server.enqueue(delay: new Duration(seconds: 2), httpCode: 201);
Stopwatch stopwatch = new Stopwatch();
stopwatch.start();

HttpClientResponse response = request(path: "");

stopwatch.stop();
expect(stopwatch.elapsed.inMilliseconds, greaterThanOrEqualTo(2000));
expect(response.statusCode, 201);

Validating that the request was correct

You may want to check that your app is sending the correct requests. To do so you can obtain the requests that have been made to the server. The request queue is Last In First Out

server.enqueue(body: "a");
server.enqueue(body: "b");
server.enqueue(body: "c");

request(path: "first");
request(path: "second");
request(path: "third");

// takeRequest is FIFO
// You should probably assign takeRequest() to a var so that you can 
// validate multiple things.
expect(server.takeRequest().headers['x-header'], "nosniff");
expect(server.takeRequest().method, "GET");
expect(server.takeRequest().uri.path, "/third");

Using a dispatcher for fine-grained routing

If you want more control than what the FIFO queue offers, you can set a dispatcher and set the logic there.

var dispatcher = (HttpRequest request) {
  if (request.uri.path == "/users") {
    return new MockResponse()
      ..httpCode = 200
      ..body = "working";
  } else if (request.uri.path == "/users/1") {
    return new MockResponse()..httpCode = 201;
  }

  return new MockResponse()..httpCode = 404;
};

server.dispatcher = dispatcher;

HttpClientResponse response = request(path: "unknown");
expect(response.statusCode, 404);

response = request(path: "users");
expect(response.statusCode, 200);
expect(read(response), "working");

response = request(path: "users/1");
expect(response.statusCode, 201);

TLS

You can start the server using TLS by passing the certificate parameter when creating the instance of MockWebServer. For example using the included certificates and the resource library you would do

var chainRes =
    new Resource('package:mock_web_server/certificates/server_chain.pem');
List<int> chain = await chainRes.readAsBytes();

var keyRes =
    new Resource('package:mock_web_server/certificates/server_key.pem');
List<int> key = await keyRes.readAsBytes();

Certificate certificate = new Certificate()
  ..password = "dartdart"
  ..key = key
  ..chain = chain;

MockWebServer _server =
    new MockWebServer(certificate: certificate);

If you do so, and your client validates the certs, you will need to use a proper SecurityContext, for example using the included trusted_certs.pem

var certRes =
    new Resource('package:mock_web_server/certificates/trusted_certs.pem');
List<int> cert = await certRes.readAsBytes();

SecurityContext clientContext = new SecurityContext()
   ..setTrustedCertificatesBytes(cert);
    
var client = new HttpClient(context: clientContext);

Please check the tests of MockWebServer to see a complete example of this.

IPv6

If want to use IPv6, you can pass addressType: InternetAddressType.IP_V6 in the constructor to have the server use it. Keep in mind that the host property will then be ::1 instead of 127.0.0.1.

MockWebServer _server =
        new MockWebServer(port: 8030, addressType: InternetAddressType.IP_V6);

Stopping

During the tearDown of your tests you should stop the server. server.shutdown() will do.

Changelog

4.0.0 - Dec 06, 2018

  • Changed takeRequest() to be FIFO like Square's implementation

Breaking

  • All your tests need to be updated to use takeRequest() according to above

3.0.0 - Nov 27, 2018

Changed

  • Updated code to support Dart 2
  • Added SDK constraint to Dart 2

Breaking

  • Dart 2 is required

2.1.0 - Oct 21, 2017

Changed

  • Using a MockWebServer class to return the stored requests
  • Loading the body of stored requests to facilitate validation
  • Using a queue

2.0.1 - Oct 15, 2017

Changed

  • Better request count management to avoid external modifications

2.0.0 - Oct 15, 2017

Breaking

  • Support for TLS now receives the cert config for better flexibility and also to remove resource from the dependencies

1.3.0 - Oct 11, 2017

Added

  • Support for TLS
  • Support to set the Inet Address type to IPv6, default value is IPv4

Changed

  • Better property handling

1.2.0 - Aug 25, 2017

Added

  • Support for async dispatcher

1.1.0 - Aug 20, 2017

Added

  • Request count
  • Comprehensive documentation

Fixed

  • Bug when delaying would be ignored if a Dispatcher was set

1.0.0 - Aug 17, 2017

Added

  • All the basic functionality

Use this package as a library

1. Depend on it

Add this to your package's pubspec.yaml file:


dependencies:
  mock_web_server: ^4.0.0

2. Install it

You can install packages from the command line:

with pub:


$ pub get

with Flutter:


$ flutter packages get

Alternatively, your editor might support pub get or flutter packages get. Check the docs for your editor to learn more.

3. Import it

Now in your Dart code, you can use:


import 'package:mock_web_server/mock_web_server.dart';
  
Version Uploaded Documentation Archive
4.0.0 Dec 7, 2018 Go to the documentation of mock_web_server 4.0.0 Download mock_web_server 4.0.0 archive
3.0.0 Nov 27, 2018 Go to the documentation of mock_web_server 3.0.0 Download mock_web_server 3.0.0 archive
2.1.0 Oct 21, 2017 Go to the documentation of mock_web_server 2.1.0 Download mock_web_server 2.1.0 archive
2.0.1 Oct 15, 2017 Go to the documentation of mock_web_server 2.0.1 Download mock_web_server 2.0.1 archive
2.0.0 Oct 15, 2017 Go to the documentation of mock_web_server 2.0.0 Download mock_web_server 2.0.0 archive
1.3.0 Oct 12, 2017 Go to the documentation of mock_web_server 1.3.0 Download mock_web_server 1.3.0 archive
1.2.0 Aug 25, 2017 Go to the documentation of mock_web_server 1.2.0 Download mock_web_server 1.2.0 archive
1.1.0 Aug 20, 2017 Go to the documentation of mock_web_server 1.1.0 Download mock_web_server 1.1.0 archive
1.0.0 Aug 17, 2017 Go to the documentation of mock_web_server 1.0.0 Download mock_web_server 1.0.0 archive
Popularity:
Describes how popular the package is relative to other packages. [more]
60
Health:
Code health derived from static analysis. [more]
100
Maintenance:
Reflects how tidy and up-to-date the package is. [more]
70
Overall:
Weighted score of the above. [more]
74
Learn more about scoring.

We analyzed this package on Dec 7, 2018, and provided a score, details, and suggestions below. Analysis was completed with status completed using:

  • Dart: 2.1.0
  • pana: 0.12.7

Platforms

Detected platforms: Flutter, other

Primary library: package:mock_web_server/mock_web_server.dart with components: io.

Maintenance issues and suggestions

Homepage does not exists. (-20 points)

We were unable to access https://git.starcarr.co/Dart/MockWebServer at the time of the analysis.

Maintain an example. (-10 points)

Create a short demo in the example/ directory to show how to use this package. Common file name patterns include: main.dart, example.dart or you could also use mock_web_server.dart.

Dependencies

Package Constraint Resolved Available
Direct dependencies
Dart SDK >=2.0.0 <3.0.0
Dev dependencies
resource >=2.1.5 <3.0.0
test >=1.5.1 <2.0.0