diff --git a/pact_mock_server/README.md b/pact_mock_server/README.md index 3cb5d346..f2c0c7bd 100644 --- a/pact_mock_server/README.md +++ b/pact_mock_server/README.md @@ -6,6 +6,69 @@ and [V4 Pact specification](https://github.com/pact-foundation/pact-specificatio [Online rust docs](https://docs.rs/pact_mock_server/latest/pact_mock_server/) +## Creating a mock server +Mock servers can be created by using the mock server builder in the `builder` package. The +builder can create both standard HTTP and HTTPS servers. + +The following example loads a Pact file, starts the mock server and then shuts it down later. +```rust +tokio_test::block_on(async { + use pact_models::prelude::{Pact, RequestResponsePact}; + use pact_mock_server::builder::MockServerBuilder; + + // Setup a Pact file for the mock server + let pact_json = r#" + { + "provider": { + "name": "Example Provider" + }, + "consumer": { + "name": "Example Consumer" + }, + "interactions": [ + { + "description": "a GET request", + "request": { + "method": "GET", + "path": "/path" + }, + "response": { + "status": 200, + "headers": { + "Content-Type": "text/plain" + }, + "body": "Hello from the mock server" + } + } + ] + } + "#; + let pact = RequestResponsePact::from_json(&"JSON sample".to_string(), &serde_json::from_str(pact_json)?)?; + + // Create the mock server. Note that the async version requires a Tokio runtime. + let mut mock_server = MockServerBuilder::new() + .bind_to("127.0.0.1:0") + .with_pact(pact.boxed()) + .start() + .await?; + + // We can now make any requests to the mock server + let http_client = reqwest::Client::new(); + let response = http_client.get(format!("http://127.0.0.1:{}/path", mock_server.port()).as_str()) + .send() + .await?; + assert_eq!(response.text().await?, "Hello from the mock server"); + + // Shut the mock server down. This will dispose of the running background tasks. + mock_server.shutdown()?; + + // Finally we can now check the status of the mock server. + assert_eq!(mock_server.all_matched(), true); + + Ok::<(), anyhow::Error>(()) +}); +``` + ## Legacy functions The following deprecated functions from the 1.x version exist in the `legacy` module. diff --git a/pact_mock_server/src/lib.rs b/pact_mock_server/src/lib.rs index 154e2794..98473d1f 100644 --- a/pact_mock_server/src/lib.rs +++ b/pact_mock_server/src/lib.rs @@ -63,6 +63,7 @@ //! let response = http_client.get(format!("http://127.0.0.1:{}/path", mock_server.port()).as_str()) //! .send() //! .await?; +//! assert_eq!(response.text().await?, "Hello from the mock server"); //! //! // Shut the mock server down. This will dispose of the running background tasks. //! mock_server.shutdown()?; @@ -76,6 +77,10 @@ #![warn(missing_docs)] +#[doc = include_str!("../README.md")] +#[cfg(doctest)] +struct Readme; + use std::sync::Mutex; #[cfg(feature = "plugins")] use maplit::hashmap;