HTTP Test Server

Documentation Build Status

Programatically create end-points that listen for connections and return pre-defined responses.

NOTE: This is not intended to work as a full featured server. For this reason many validations and behaviours are not implemented. e.g: A request with Accept header with not supported Content-Type won't trigger a 406 Not Acceptable.

As this crate was devised to be used in tests, smart behaviours could be confusing and misleading.

Having said that, there are some default behaviours implemented:

Example:

Accept POST requests: ```rust extern crate httptestserver;

use httptestserver::{TestServer, Resource}; use httptestserver::http::{Status, Method};

let server = TestServer::new().unwrap(); let resource = server.create_resource("/some-endpoint/new");

resource .status(Status::Created) .method(Method::POST) .header("Content-Type", "application/json") .header("Cache-Control", "no-cache") .body("{ \"message\": \"this is a message\" }");

// request: POST /some-endpoint/new

// HTTP/1.1 201 Created\r\n // Content-Type: application/json\r\n // Cache-Control: no-cache\r\n // \r\n // { "message": "this is a message" } ```

Expose a persistent stream: ```rust let server = TestServer::new().unwrap(); let resource = server.create_resource("/sub");

resource .header("Content-Type", "text/event-stream") .header("Cache-Control", "no-cache") .stream() .body(": initial data");

// ...

resource .send("some data") .send(" some extra data\n") .sendline("some extra data with line break") .closeopen_connections();

// request: GET /sub

// HTTP/1.1 200 Ok\r\n // Content-Type: text/event-stream\r\n // Cache-Control: no-cache\r\n // \r\n // : initial data // some data some extra data\n // some extra data with line break\n ```

Redirects: ```rust let server = TestServer::new().unwrap(); let resourceredirect = server.createresource("/original"); let resourcetarget = server.createresource("/new");

resource_redirect .status(Status::SeeOther) .header("Location", "/new" );

resource_target.body("Hi!");

// request: GET /original

// HTTP/1.1 303 See Other\r\n // Location: /new\r\n // \r\n ```

Check /tests/integration_test.rs for more usage examples.