### Install Rustfmt Source: https://github.com/lipanski/mockito/blob/master/README.md Install the rustfmt component, which is used for code formatting in the Mockito project. ```sh rustup component add rustfmt ``` -------------------------------- ### Starting a Stand-alone Server Source: https://github.com/lipanski/mockito/blob/master/README.md Demonstrates how to configure and start a mock server on a specific host and port using `ServerOpts`. This is useful for running a persistent mock server for integration or manual testing. ```rust fn main() { let opts = mockito::ServerOpts { host: "0.0.0.0", port: 1234, ..Default::default() }; let mut server = mockito::Server::new_with_opts(opts); let _m = server.mock("GET", "/").with_body("hello world").create(); loop {} } ``` -------------------------------- ### Starting Multiple Mock Servers Source: https://github.com/lipanski/mockito/blob/master/README.md Illustrates how to start multiple independent mock servers to simulate requests to different hosts simultaneously. This is essential for testing interactions between services or microservices. ```rust #[test] fn test_something() { let mut twitter = mockito::Server::new(); let mut github = mockito::Server::new(); // These mocks will be available at `twitter.url()` let twitter_mock = twitter.mock("GET", "/api").create(); // These mocks will be available at `github.url()` let github_mock = github.mock("GET", "/api").create(); } ``` -------------------------------- ### Install Rust Nightly Source: https://github.com/lipanski/mockito/blob/master/README.md Install the Rust nightly toolchain, which may be required for certain features or benchmarks. ```sh rustup install nightly ``` -------------------------------- ### Create and Assert a Basic Mock Source: https://github.com/lipanski/mockito/blob/master/README.md Demonstrates how to create a new mock server, define a simple GET request mock with status, headers, and body, and then assert that the mock was called. Use this for basic endpoint mocking. ```rust #[test] fn test_something() { // Request a new server from the pool let mut server = mockito::Server::new(); // Use one of these addresses to configure your client let host = server.host_with_port(); let url = server.url(); // Create a mock let mock = server.mock("GET", "/hello") .with_status(201) .with_header("content-type", "text/plain") .with_header("x-api-key", "1234") .with_body("world") .create(); // Any calls to GET /hello beyond this line will respond with 201, the // `content-type: text/plain` header and the body "world". // You can use `Mock::assert` to verify that your mock was called mock.assert(); } ``` -------------------------------- ### Create a server with custom options Source: https://context7.com/lipanski/mockito/llms.txt Use `Server::new_with_opts` to bypass the pool and start a fresh server with custom host, port, or auto-assert behavior. This is useful for stand-alone servers or when a fixed port is required. ```rust fn main() { let opts = mockito::ServerOpts { host: "0.0.0.0", port: 1234, assert_on_drop: false, ..Default::default() }; let mut server = mockito::Server::new_with_opts(opts); let _m = server .mock("GET", "/") .with_status(200) .with_body("hello world") .create(); println!("Mock server running at {}", server.url()); loop { std::thread::sleep(std::time::Duration::from_secs(1)); } } ``` -------------------------------- ### Obtain a server from the pool (sync) Source: https://context7.com/lipanski/mockito/llms.txt Use `Server::new()` to get a ready-to-use mock server with a random port. The server is automatically reset and returned to the pool when the guard drops. This is suitable for synchronous tests. ```rust #[test] fn test_get_user() { let mut server = mockito::Server::new(); // server.url() → "http://127.0.0.1:" // server.host_with_port() → "127.0.0.1:" let _m = server .mock("GET", "/users/42") .with_status(200) .with_header("content-type", "application/json") .with_body(r#"{"id":42,"name":"Alice"}"#) .create(); // Point your HTTP client at server.url() let url = format!("{}/users/42", server.url()); let resp = reqwest::blocking::get(&url).unwrap(); assert_eq!(resp.status(), 200); assert_eq!(resp.text().unwrap(), r#"{"id":42,"name":"Alice"}"#); } ``` -------------------------------- ### Install Clippy Source: https://github.com/lipanski/mockito/blob/master/README.md Install the clippy linter component, used for static analysis and catching common Rust mistakes. ```sh rustup component add clippy ``` -------------------------------- ### Async Mock Testing Source: https://github.com/lipanski/mockito/blob/master/README.md Provides an example of writing asynchronous tests using Mockito. Ensure you use the `_async` methods for server creation, mock creation, and assertions when working with async runtimes like Tokio. ```rust use mockito::Server; #[tokio::test] async fn test_simple_route_mock_async() { let mut server = Server::new_async().await; let m1 = server.mock("GET", "/a").with_body("aaa").create_async().await; let m2 = server.mock("GET", "/b").with_body("bbb").create_async().await; let (m1, m2) = futures::join!(m1, m2); // You can use `Mock::assert_async` to verify that your mock was called // m1.assert_async().await; // m2.assert_async().await; } ``` -------------------------------- ### Mockito Matcher Enum Examples Source: https://context7.com/lipanski/mockito/llms.txt Demonstrates various matching strategies available in the Matcher enum for defining mock server behavior. Includes exact, regex, JSON, URL-encoded, AnyOf, AllOf, and Missing header matching. ```rust use mockito::Matcher; #[test] fn test_all_matchers() { let mut server = mockito::Server::new(); // Exact string server.mock("GET", Matcher::Exact("/exact".to_string())).create(); // Regex path server.mock("GET", Matcher::Regex(r"^/items/\d+$".to_string())).create(); // Any path server.mock("GET", Matcher::Any).with_status(200).create(); // JSON body — exact key/value comparison server.mock("POST", "/json") .match_body(Matcher::JsonString(r#"{"action":"buy","qty":2}"#.to_string())) .create(); // Partial JSON — extra keys in request are allowed server.mock("POST", "/partial") .match_body(Matcher::PartialJsonString(r#"{"action":"buy"}"#.to_string())) .create(); // URL-encoded query param server.mock("GET", "/search") .match_query(Matcher::UrlEncoded("lang".into(), "en".into())) .create(); // AnyOf: body matches either form server.mock("POST", "/flexible") .match_body(Matcher::AnyOf(vec![ Matcher::Exact("hello=world".to_string()), Matcher::JsonString(r#"{"hello":"world"}"#.to_string()), ])) .create(); // AllOf: all conditions must hold server.mock("POST", "/strict") .match_body(Matcher::AllOf(vec![ Matcher::Regex("hello".to_string()), Matcher::Regex("world".to_string()), ])) .create(); // Missing header server.mock("GET", "/no-auth") .match_header("authorization", Matcher::Missing) .with_body("anonymous") .create(); } ``` -------------------------------- ### Format Code with Cargo Source: https://github.com/lipanski/mockito/blob/master/README.md Format the project's code according to the rustfmt style guide using the Cargo command. ```sh cargo fmt ``` -------------------------------- ### Server::new_with_opts Source: https://context7.com/lipanski/mockito/llms.txt Creates a server with custom options, bypassing the pool for a fresh server with specified host, port, or auto-assert behavior. ```APIDOC ## Server::new_with_opts ### Description Creates a server with custom options, bypassing the pool for a fresh server with specified host, port, or auto-assert behavior. Use this for stand-alone mock servers or when a fixed port is required. ### Method `Server::new_with_opts(opts: ServerOpts)` ### Parameters #### Request Body - **opts** (ServerOpts) - Required - Options to configure the server, including host, port, and assert_on_drop. - **host**: (string) - The host address for the server. - **port**: (u16) - The port number for the server. - **assert_on_drop**: (bool) - Whether to assert on mock usage when the server is dropped. ### Example ```rust fn main() { let opts = mockito::ServerOpts { host: "0.0.0.0", port: 1234, assert_on_drop: false, ..Default::default() }; let mut server = mockito::Server::new_with_opts(opts); let _m = server .mock("GET", "/") .with_status(200) .with_body("hello world") .create(); println!("Mock server running at {}", server.url()); loop { std::thread::sleep(std::time::Duration::from_secs(1)); } } ``` ``` -------------------------------- ### Configure Mockito Server Options Source: https://context7.com/lipanski/mockito/llms.txt Illustrates how to configure a Mockito server using `ServerOpts` for custom host, port, and automatic assertion on drop. Defaults are applied when fields are omitted using `..Default::default()`. ```rust // Default opts: host=127.0.0.1, port=random, assert_on_drop=false let default_opts = mockito::ServerOpts::default(); let _s1 = mockito::Server::new_with_opts(default_opts); // Fixed port let _s2 = mockito::Server::new_with_opts(mockito::ServerOpts { port: 8080, ..Default::default() }); // Public interface let _s3 = mockito::Server::new_with_opts(mockito::ServerOpts { host: "0.0.0.0", port: 9000, ..Default::default() }); // Auto-assert on drop: each mock calls assert() when it drops let _s4 = mockito::Server::new_with_opts(mockito::ServerOpts { assert_on_drop: true, ..Default::default() }); ``` -------------------------------- ### Obtain a server from the pool (async) Source: https://context7.com/lipanski/mockito/llms.txt Use `Server::new_async().await` for asynchronous tests. Pair this with `_async` methods on `Mock` for asynchronous mock creation and assertion. ```rust #[tokio::test] async fn test_async_endpoint() { let mut server = mockito::Server::new_async().await; let m = server .mock("POST", "/events") .with_status(201) .with_header("content-type", "application/json") .with_body(r#"{"status":"created"}"#) .create_async() .await; let client = reqwest::Client::new(); let resp = client .post(format!("{}/events", server.url())) .body(r#"{"type":"click"}"#) .send() .await .unwrap(); assert_eq!(resp.status(), 201); m.assert_async().await; } ``` -------------------------------- ### Simulate Independent Hosts with Multiple Servers Source: https://context7.com/lipanski/mockito/llms.txt Shows how to run multiple `Server` instances concurrently for testing multi-service call graphs. Each server has its own address and mock registry. ```rust #[test] fn test_multi_service() { let mut auth_service = mockito::Server::new(); let mut profile_service = mockito::Server::new(); let _auth = auth_service .mock("POST", "/token") .with_status(200) .with_body(r#"{"token":"abc"}"#) .create(); let _profile = profile_service .mock("GET", "/me") .match_header("authorization", "Bearer abc") .with_status(200) .with_body(r#"{"name":"Alice"}"#) .create(); // Configure your application with: // AUTH_URL = auth_service.url() // PROFILE_URL = profile_service.url() } ``` -------------------------------- ### Create a Mock builder for a method and path Source: https://context7.com/lipanski/mockito/llms.txt Use `Server::mock` to initialize a `Mock` builder for a specific HTTP method and path. The mock becomes active only after calling `.create()` or `.create_async()`. Paths can be exact strings or `Matcher` variants. ```rust #[test] fn test_multiple_routes() { let mut server = mockito::Server::new(); let _get = server.mock("GET", "/items").with_body("[]").create(); let _post = server.mock("POST", "/items").with_status(201).create(); let _del = server.mock("DELETE", mockito::Matcher::Regex(r"^/items/\d+$".to_string())) .with_status(204) .create(); // GET /items → 200 "[]" // POST /items → 201 // DELETE /items/7 → 204 } ``` -------------------------------- ### Run Benchmarks with Nightly Toolchain Source: https://github.com/lipanski/mockito/blob/master/README.md Execute project benchmarks using the Rust nightly toolchain. ```sh rustup run nightly cargo bench ``` -------------------------------- ### Mocking with Request Matchers Source: https://github.com/lipanski/mockito/blob/master/README.md Shows how to use different matchers for headers and bodies to handle multiple requests to the same endpoint uniquely. This is useful when an endpoint needs to respond differently based on request details. ```rust #[test] fn test_something() { let mut server = mockito::Server::new(); server.mock("GET", "/greetings") .match_header("content-type", "application/json") .match_body(mockito::Matcher::PartialJsonString( "{\"greeting\": \"hello\"}".to_string(), )) .with_body("hello json") .create(); server.mock("GET", "/greetings") .match_header("content-type", "application/text") .match_body(mockito::Matcher::Regex("greeting=hello".to_string())) .with_body("hello text") .create(); } ``` -------------------------------- ### Serve Response Body from File Source: https://context7.com/lipanski/mockito/llms.txt Use `with_body_from_file` to serve the response body from a specified file. The file's content is read when the mock is created, and `Content-Length` is set automatically. This function will panic if the file cannot be read. ```rust #[test] fn test_body_from_file() { let mut server = mockito::Server::new(); // Serve a fixture file as the response body let _m = server .mock("GET", "/fixture") .with_status(200) .with_header("content-type", "text/plain") .with_body_from_file("tests/files/simple.http") .create(); } ``` -------------------------------- ### Server::new Source: https://context7.com/lipanski/mockito/llms.txt Obtains a server from the pool for synchronous use. The server is automatically reset and returned to the pool when the guard drops. ```APIDOC ## Server::new ### Description Obtains a server from the pool for synchronous use. The server is automatically reset and returned to the pool when the guard drops. ### Method `Server::new()` ### Example ```rust #[test] fn test_get_user() { let mut server = mockito::Server::new(); // server.url() → "http://127.0.0.1:" // server.host_with_port() → "127.0.0.1:" let _m = server .mock("GET", "/users/42") .with_status(200) .with_header("content-type", "application/json") .with_body(r#"{"id":42,"name":"Alice"}"#) .create(); // Point your HTTP client at server.url() let url = format!("{}/users/42", server.url()); let resp = reqwest::blocking::get(&url).unwrap(); assert_eq!(resp.status(), 200); assert_eq!(resp.text().unwrap(), r#"{"id":42,"name":"Alice"}"#); } ``` ``` -------------------------------- ### Run Tests with Cargo Source: https://github.com/lipanski/mockito/blob/master/README.md Execute the project's tests using the standard Cargo command. ```sh cargo test ``` -------------------------------- ### Enable Debug Logging for Request Tracing Source: https://context7.com/lipanski/mockito/llms.txt Demonstrates how to enable Mockito's internal request tracing by initializing `env_logger` and setting the `RUST_LOG` environment variable. This prints received requests and match decisions to stderr. ```rust #[test] fn test_with_debug_logging() { let _ = env_logger::try_init(); // safe to call multiple times let mut server = mockito::Server::new(); let _m = server.mock("GET", "/debug").with_body("logged").create(); // Run with: RUST_LOG=mockito=debug cargo test // Output example: // DEBUG mockito::server > Request received: // GET /debug // DEBUG mockito::server > Mock found } ``` -------------------------------- ### Server::mock Source: https://context7.com/lipanski/mockito/llms.txt Creates a `Mock` builder for a given HTTP method and path. The mock is activated upon calling `.create()` or `.create_async()`. ```APIDOC ## Server::mock ### Description Initializes a new `Mock` bound to the given HTTP method and path. The mock is not active until `.create()` or `.create_async()` is called. The path can be an exact string or a `Matcher` variant. ### Method `server.mock(method: &str, path: impl Into)` ### Parameters #### Path Parameters - **method** (string) - Required - The HTTP method (e.g., "GET", "POST"). - **path** (impl Into) - Required - The path for the mock, can be a string or a `Matcher`. ### Example ```rust #[test] fn test_multiple_routes() { let mut server = mockito::Server::new(); let _get = server.mock("GET", "/items").with_body("[]").create(); let _post = server.mock("POST", "/items").with_status(201).create(); let _del = server.mock("DELETE", mockito::Matcher::Regex(r"^/items/\d+$".to_string())) .with_status(204) .create(); // GET /items → 200 "[]" // POST /items → 201 // DELETE /items/7 → 204 } ``` ``` -------------------------------- ### Publish Release with Cargo Source: https://github.com/lipanski/mockito/blob/master/README.md Publish a new release of the Mockito crate to the crates.io registry using Cargo. ```sh cargo publish ``` -------------------------------- ### Server::new_async Source: https://context7.com/lipanski/mockito/llms.txt The asynchronous counterpart to `Server::new`. Must be used in async tests and paired with `_async` methods on `Mock`. ```APIDOC ## Server::new_async ### Description Asynchronous counterpart to `Server::new`. Must be used in async tests; always pair with `_async` methods on `Mock`. ### Method `Server::new_async()` ### Example ```rust #[tokio::test] async fn test_async_endpoint() { let mut server = mockito::Server::new_async().await; let m = server .mock("POST", "/events") .with_status(201) .with_header("content-type", "application/json") .with_body(r#"{"status":"created"}"#) .create_async() .await; let client = reqwest::Client::new(); let resp = client .post(format!("{}/events", server.url())) .body(r#"{"type":"click"}"#) .send() .await .unwrap(); assert_eq!(resp.status(), 201); m.assert_async().await; } ``` ``` -------------------------------- ### Mock::with_body_from_request Source: https://context7.com/lipanski/mockito/llms.txt Generates the response body via a callback that receives the incoming Request. This enables per-request personalization without requiring multiple mock registrations. ```APIDOC ## `Mock::with_body_from_request` — Dynamic response body per request Generates the response body via a callback receiving the incoming `Request`. Enables per-request personalization without multiple mock registrations. ```rust #[test] fn test_personalized_response() { let mut server = mockito::Server::new(); let _m = server .mock("GET", mockito::Matcher::Regex(r"^/hello/".to_string())) .with_body_from_request(|request| { let name = request.path().trim_start_matches("/hello/"); format!("Hello, {}!", name).into_bytes() }) .create(); // GET /hello/Alice → "Hello, Alice!" // GET /hello/Bob → "Hello, Bob!" } ``` ``` -------------------------------- ### Match Request by Query String with Mockito Source: https://context7.com/lipanski/mockito/llms.txt Use `match_query` to match requests based on their query string. Supports URL-encoded parameters (`Matcher::UrlEncoded`), regex (`Matcher::Regex`), multiple parameters (`Matcher::AllOf`), or ignoring the query (`Matcher::Any`). ```rust #[test] fn test_query_matching() { let mut server = mockito::Server::new(); // Single URL-encoded parameter (values in plain, unencoded form) server.mock("GET", "/search") .match_query(mockito::Matcher::UrlEncoded("q".into(), "hello world".into())) .with_body("results for hello world") .create(); // Multiple parameters — all must be present server.mock("GET", "/filter") .match_query(mockito::Matcher::AllOf(vec![ mockito::Matcher::UrlEncoded("status".into(), "active".into()), mockito::Matcher::UrlEncoded("page".into(), "1".into()), ])) .with_body(r#"{"page":1}""#) .create(); // Ignore query entirely server.mock("GET", "/ping") .match_query(mockito::Matcher::Any) .with_body("pong") .create(); } ``` -------------------------------- ### Run Clippy Linter Source: https://github.com/lipanski/mockito/blob/master/README.md Execute the clippy linter on the project, ensuring code quality and backwards compatibility. This command is run on the minimum supported Rust version. ```sh rustup run --install 1.70.0 cargo clippy-mockito ``` -------------------------------- ### Set Response Headers Source: https://context7.com/lipanski/mockito/llms.txt Use `with_header` to add headers to the mock response. This method can be called multiple times to include several headers. ```rust #[test] fn test_response_headers() { let mut server = mockito::Server::new(); server.mock("GET", "/data") .with_status(200) .with_header("content-type", "application/json") .with_header("cache-control", "no-cache") .with_header("x-request-id", "abc-123") .with_body(r#"{"ok":true}"#) .create(); } ``` -------------------------------- ### Run Tests with Specific Toolchain Source: https://github.com/lipanski/mockito/blob/master/README.md Run tests using a specific Rust toolchain version, useful for compatibility checks. ```sh rustup run --install 1.85.0 cargo test ``` -------------------------------- ### Mock::with_body_from_file Source: https://context7.com/lipanski/mockito/llms.txt Reads the file at the given path at mock creation time and uses its content as the response body. `Content-Length` is set automatically. This method panics if the file cannot be read. ```APIDOC ## `Mock::with_body_from_file` — Serve response body from a file Reads the file at the given path at mock creation time and uses its content as the response body. `Content-Length` is set automatically. Panics if the file cannot be read. ```rust #[test] fn test_body_from_file() { let mut server = mockito::Server::new(); // Serve a fixture file as the response body let _m = server .mock("GET", "/fixture") .with_status(200) .with_header("content-type", "text/plain") .with_body_from_file("tests/files/simple.http") .create(); } ``` ``` -------------------------------- ### Set Response Status Code with Mockito Source: https://context7.com/lipanski/mockito/llms.txt Use `with_status` to set the HTTP status code for a mock response. Invalid status codes will cause a panic at creation time. Defaults to `200 OK`. ```rust #[test] fn test_error_responses() { let mut server = mockito::Server::new(); server.mock("GET", "/not-found").with_status(404).with_body("not found").create(); server.mock("GET", "/error").with_status(500).with_body("internal error").create(); server.mock("POST", "/created").with_status(201).create(); server.mock("DELETE", "/gone").with_status(410).create(); } ``` -------------------------------- ### Set Dynamic Response Body from Request Source: https://context7.com/lipanski/mockito/llms.txt Use `with_body_from_request` to generate the response body using a callback function that receives the incoming `Request`. This allows for personalized responses without needing multiple mock registrations. ```rust #[test] fn test_personalized_response() { let mut server = mockito::Server::new(); let _m = server .mock("GET", mockito::Matcher::Regex(r"^/hello/".to_string())) .with_body_from_request(|request| { let name = request.path().trim_start_matches("/hello/"); format!("Hello, {}!", name).into_bytes() }) .create(); // GET /hello/Alice → "Hello, Alice!" // GET /hello/Bob → "Hello, Bob!" } ``` -------------------------------- ### Verify Mock Calls with Panic Source: https://context7.com/lipanski/mockito/llms.txt Use `Mock::assert` to verify that a mock was called the expected number of times. This method will panic if the expectations are not met, providing detailed failure information. ```rust #[test] fn test_assert_spy() { use std::net::TcpStream; use std::io::{Read, Write}; let mut server = mockito::Server::new(); let mock = server.mock("DELETE", "/resource/1").with_status(204).create(); { let mut stream = TcpStream::connect(server.host_with_port()).unwrap(); stream.write_all(b"DELETE /resource/1 HTTP/1.1\r\nhost: localhost\r\n\r\n").unwrap(); let mut buf = String::new(); stream.read_to_string(&mut buf).unwrap(); } mock.assert(); // If the DELETE was never sent, assert() would panic with: // > Expected 1 request(s) to: // > DELETE /resource/1 // > ...but received 0 // > The last unmatched request was: ... } ``` -------------------------------- ### Mock::with_status Source: https://context7.com/lipanski/mockito/llms.txt Sets the HTTP status code for the mock response. Defaults to `200 OK`. Panics at creation time if the status code is invalid. ```APIDOC ## Mock::with_status ### Description Sets the HTTP status code for the mock response. Defaults to `200 OK`. Panics at creation time if the status code is invalid. ### Method `with_status(status_code: u16)` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```rust server.mock("GET", "/not-found").with_status(404).with_body("not found").create(); server.mock("GET", "/error").with_status(500).with_body("internal error").create(); server.mock("POST", "/created").with_status(201).create(); ``` ### Response #### Success Response (200) None explicitly defined, depends on `with_body`. #### Response Example None ``` -------------------------------- ### Set Static Response Body Source: https://context7.com/lipanski/mockito/llms.txt Use `with_body` to set a static response body from a string or byte slice. The `Content-Length` header is automatically calculated and appended. ```rust #[test] fn test_body_variants() { let mut server = mockito::Server::new(); server.mock("GET", "/text").with_body("hello world").create(); server.mock("GET", "/json").with_body(r#"{"key":"value"}"#).create(); server.mock("GET", "/bytes").with_body(b"\x00\x01\x02\x03".as_ref()).create(); } ``` -------------------------------- ### Set Dynamic Response Header from Request Source: https://context7.com/lipanski/mockito/llms.txt Use `with_header_from_request` to dynamically set a response header value based on the incoming request. This is helpful for echoing request data or generating unique identifiers per request. ```rust #[test] fn test_dynamic_header() { let mut server = mockito::Server::new(); let _m = server .mock("GET", mockito::Matcher::Any) .with_header_from_request("x-served-path", |request| { format!("served:{}", request.path()) }) .with_body("ok") .create(); } ``` -------------------------------- ### Mock::with_body Source: https://context7.com/lipanski/mockito/llms.txt Sets the response body from a string or byte slice. The `Content-Length` header is automatically computed and added to the response. ```APIDOC ## `Mock::with_body` — Set a static response body Sets the response body from a string or byte slice. `Content-Length` is automatically computed and added to the response. ```rust #[test] fn test_body_variants() { let mut server = mockito::Server::new(); server.mock("GET", "/text").with_body("hello world").create(); server.mock("GET", "/json").with_body(r#"{"key":"value"}"#).create(); server.mock("GET", "/bytes").with_body(b"\x00\x01\x02\x03".as_ref()).create(); } ``` ``` -------------------------------- ### Run Tests Disabling Default Features Source: https://github.com/lipanski/mockito/blob/master/README.md Execute tests while disabling default features, such as color output, for a cleaner test run. ```sh cargo test --no-default-features ``` -------------------------------- ### Mock::assert / Mock::assert_async Source: https://context7.com/lipanski/mockito/llms.txt Verifies that a mock was called the expected number of times. Panics if the expectation is not met, providing detailed failure information. ```APIDOC ## `Mock::assert` / `Mock::assert_async` ### Description Panics if the mock was not called the expected number of times. On failure, prints the expected mock definition, actual hit count, the last unmatched request, and a colored diff. ### Example ```rust mock.assert(); // Passes if the mock was called as expected, panics otherwise. ``` ``` -------------------------------- ### Mock::with_header_from_request Source: https://context7.com/lipanski/mockito/llms.txt Sets a response header value using a callback that receives the incoming Request. This is useful for echoing request data or generating per-request identifiers. ```APIDOC ## `Mock::with_header_from_request` — Dynamic response header per request Sets a response header value using a callback that receives the incoming `Request`. Useful for echoing request data or generating per-request identifiers. ```rust #[test] fn test_dynamic_header() { let mut server = mockito::Server::new(); let _m = server .mock("GET", mockito::Matcher::Any) .with_header_from_request("x-served-path", |request| { format!("served:{}", request.path()) }) .with_body("ok") .create(); } ``` ``` -------------------------------- ### Match Request by Body Content with Mockito Source: https://context7.com/lipanski/mockito/llms.txt Use `match_body` to constrain mocks based on request body content. Supports exact strings, JSON (exact or partial), URL-encoded pairs, and regex. Defaults to ignoring the body (`Matcher::Any`). ```rust #[test] fn test_body_matchers() { let mut server = mockito::Server::new(); // Exact string body server.mock("POST", "/echo") .match_body("ping") .with_body("pong") .create(); // Exact JSON (order-independent key comparison) server.mock("POST", "/users") .match_body(mockito::Matcher::JsonString( r#"{"name":"Alice","role":"admin"}""#.to_string() )) .with_status(201) .create(); // Partial JSON — only specified keys must match server.mock("POST", "/events") .match_body(mockito::Matcher::PartialJsonString( r#"{"type":"click"}""#.to_string() )) .with_status(200) .create(); // Regex body match server.mock("POST", "/log") .match_body(mockito::Matcher::Regex(r"level=(info|warn|error)".to_string())) .with_status(204) .create(); } ``` -------------------------------- ### Mock::match_request Source: https://context7.com/lipanski/mockito/llms.txt Provides full access to the incoming `Request` object via a closure returning a boolean for complex matching logic. ```APIDOC ## Mock::match_request ### Description Provides full access to the incoming `Request` object via a closure returning a boolean. Useful for complex or multi-field matching logic that cannot be expressed with standard matchers. ### Method `match_request(matcher: impl Fn(&Request) -> bool)` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```rust server.mock("POST", mockito::Matcher::Any) .match_request(|request| { // Must have x-request-id header AND body must contain "urgent" request.has_header("x-request-id") && request .utf8_lossy_body() .map(|b| b.contains("urgent")) .unwrap_or(false) }) .with_status(202) .with_body("queued") .create(); ``` ### Response #### Success Response (200) None explicitly defined, depends on `with_body` and `with_status`. #### Response Example None ``` -------------------------------- ### Set Dynamic Status Code from Request Source: https://context7.com/lipanski/mockito/llms.txt Use `with_status_code_from_request` to set the HTTP status code based on the incoming request. This is useful for returning different status codes for different request attributes without registering separate mocks. ```rust #[test] fn test_dynamic_status() { let mut server = mockito::Server::new(); let _m = server .mock("GET", mockito::Matcher::Any) .with_status_code_from_request(|request| { match request.path() { "/ok" => 200, "/auth" => 401, "/admin" => 403, _ => 404, } }) .create(); } ``` -------------------------------- ### Match Request Using Custom Closure with Mockito Source: https://context7.com/lipanski/mockito/llms.txt Use `match_request` with a closure for complex matching logic. The closure receives the `Request` object and should return `true` if the request matches. ```rust #[test] fn test_custom_matcher() { let mut server = mockito::Server::new(); server.mock("POST", mockito::Matcher::Any) .match_request(|request| { // Must have x-request-id header AND body must contain "urgent" request.has_header("x-request-id") && request .utf8_lossy_body() .map(|b| b.contains("urgent")) .unwrap_or(false) }) .with_status(202) .with_body("queued") .create(); } ``` -------------------------------- ### Match Request by Header Value with Mockito Source: https://context7.com/lipanski/mockito/llms.txt Use `match_header` to add header constraints to a mock. Header name comparison is case-insensitive. Supports exact strings, regex, checking for presence (`Matcher::Any`), or absence (`Matcher::Missing`). ```rust #[test] fn test_auth_header() { let mut server = mockito::Server::new(); // Exact match server.mock("GET", "/secure") .match_header("authorization", "Bearer secret-token") .with_status(200) .with_body("protected data") .create(); // Any value — just presence check server.mock("GET", "/any-auth") .match_header("authorization", mockito::Matcher::Any) .with_status(200) .create(); // Header must be absent server.mock("GET", "/public") .match_header("authorization", mockito::Matcher::Missing) .with_status(200) .with_body("public data") .create(); // Regex on header value server.mock("GET", "/json-only") .match_header("accept", mockito::Matcher::Regex(r"application/json".to_string())) .with_body(r#"{"ok":true}""#) .create(); } ``` -------------------------------- ### Mock::match_query Source: https://context7.com/lipanski/mockito/llms.txt Matches a request by query string parameters. Supports URL-encoded pairs, Regex, AllOf for multiple parameters, or Any to ignore the query. ```APIDOC ## Mock::match_query ### Description Matches a request by query string parameters. Separates query matching from path matching. Accepts `Matcher::UrlEncoded` for key/value pair checks (decoded), `Matcher::Regex`, `Matcher::AllOf` for multiple parameters, or `Matcher::Any` to ignore the query entirely. ### Method `match_query(matcher: impl Into>)` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```rust server.mock("GET", "/search") .match_query(mockito::Matcher::UrlEncoded("q".into(), "hello world".into())) .with_body("results for hello world") .create(); server.mock("GET", "/filter") .match_query(mockito::Matcher::AllOf(vec![ mockito::Matcher::UrlEncoded("status".into(), "active".into()), mockito::Matcher::UrlEncoded("page".into(), "1".into()), ])) .with_body(r#"{"page":1}"#) .create(); ``` ### Response #### Success Response (200) None explicitly defined, depends on `with_body`. #### Response Example None ``` -------------------------------- ### Mock::with_status_code_from_request Source: https://context7.com/lipanski/mockito/llms.txt Sets the status code via a callback that receives the incoming Request. This allows for different status codes based on request attributes without registering separate mocks. ```APIDOC ## `Mock::with_status_code_from_request` — Dynamic status code per request Sets the status code via a callback that receives the incoming `Request`. Enables returning different status codes based on request attributes without registering separate mocks. ```rust #[test] fn test_dynamic_status() { let mut server = mockito::Server::new(); let _m = server .mock("GET", mockito::Matcher::Any) .with_status_code_from_request(|request| { match request.path() { "/ok" => 200, "/auth" => 401, "/admin" => 403, _ => 404, } }) .create(); } ``` ``` -------------------------------- ### Mock::match_header Source: https://context7.com/lipanski/mockito/llms.txt Adds a header constraint to the mock. The header name comparison is case-insensitive. Supports exact string, Regex, Any (header present), or Missing (header absent) matchers. ```APIDOC ## Mock::match_header ### Description Adds a header constraint to the mock. The header name comparison is case-insensitive. Accepts an exact string, a `Matcher::Regex`, `Matcher::Any` (header present, any value), or `Matcher::Missing` (header absent). ### Method `match_header(header_name: &str, value: impl Into>)` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```rust server.mock("GET", "/secure") .match_header("authorization", "Bearer secret-token") .with_status(200) .with_body("protected data") .create(); server.mock("GET", "/any-auth") .match_header("authorization", mockito::Matcher::Any) .with_status(200) .create(); server.mock("GET", "/json-only") .match_header("accept", mockito::Matcher::Regex(r"application/json".to_string())) .with_body(r#"{"ok":true}"#) .create(); ``` ### Response #### Success Response (200) None explicitly defined, depends on `with_body`. #### Response Example None ``` -------------------------------- ### Mock::with_chunked_body Source: https://context7.com/lipanski/mockito/llms.txt Sends the response using chunked transfer encoding. The callback receives an `io::Write` handle. Sleeping between writes simulates streaming delays. Returning an error from the callback aborts the response. ```APIDOC ## `Mock::with_chunked_body` — Streaming / chunked response body Sends the response using chunked transfer encoding. The callback receives an `io::Write` handle; sleeping between writes simulates streaming delays. Returning an error from the callback aborts the response. ```rust #[test] fn test_chunked_response() { use std::io::Write; let mut server = mockito::Server::new(); let _m = server .mock("GET", "/stream") .with_chunked_body(|w| { w.write_all(b"chunk 1\n")?; w.write_all(b"chunk 2\n")?; w.write_all(b"chunk 3\n") }) .create(); } ``` ``` -------------------------------- ### Mock::with_header Source: https://context7.com/lipanski/mockito/llms.txt Appends a header to the mock response. This method can be called multiple times to add multiple headers. ```APIDOC ## `Mock::with_header` — Set a response header Appends a header to the mock response. Can be called multiple times to add multiple headers. ```rust #[test] fn test_response_headers() { let mut server = mockito::Server::new(); server.mock("GET", "/data") .with_status(200) .with_header("content-type", "application/json") .with_header("cache-control", "no-cache") .with_header("x-request-id", "abc-123") .with_body(r#"{"ok":true}"#) .create(); } ``` ``` -------------------------------- ### Mock::expect / Mock::expect_at_least / Mock::expect_at_most Source: https://context7.com/lipanski/mockito/llms.txt Controls how many times a mock must be called for Mock::assert to pass. `expect(n)` sets an exact count; `expect_at_least` and `expect_at_most` define a range. ```APIDOC ## `Mock::expect` / `Mock::expect_at_least` / `Mock::expect_at_most` ### Description Controls how many times a mock must be called for `Mock::assert` to pass. `expect(n)` sets an exact count; `expect_at_least` and `expect_at_most` define a range. ### Example ```rust // Expect exactly 3 calls let exact_mock = server.mock("GET", "/exact").expect(3).create(); // Expect between 2 and 5 calls let range_mock = server .mock("GET", "/range") .expect_at_least(2) .expect_at_most(5) .create(); ``` ``` -------------------------------- ### Set Mock Call Count Expectations Source: https://context7.com/lipanski/mockito/llms.txt Use `expect(n)` for exact call counts, and `expect_at_least(n)`/`expect_at_most(n)` for range-based expectations. These control how many times a mock must be called for `Mock::assert` to pass. ```rust #[test] fn test_call_count_expectations() { use std::net::TcpStream; use std::io::{Read, Write}; let mut server = mockito::Server::new(); // Expect exactly 3 calls let exact_mock = server.mock("GET", "/exact").expect(3).create(); // Expect between 2 and 5 calls let range_mock = server.mock("GET", "/range").expect_at_least(2).expect_at_most(5).create(); for _ in 0..3 { let mut stream = TcpStream::connect(server.host_with_port()).unwrap(); stream.write_all(b"GET /exact HTTP/1.1\r\nhost: localhost\r\n\r\n").unwrap(); let mut buf = String::new(); stream.read_to_string(&mut buf).unwrap(); } for _ in 0..3 { let mut stream = TcpStream::connect(server.host_with_port()).unwrap(); stream.write_all(b"GET /range HTTP/1.1\r\nhost: localhost\r\n\r\n").unwrap(); let mut buf = String::new(); stream.read_to_string(&mut buf).unwrap(); } exact_mock.assert(); // passes: called exactly 3 times range_mock.assert(); // passes: called 3 times, within [2, 5] } ``` -------------------------------- ### Non-Panicking Mock Call Verification Source: https://context7.com/lipanski/mockito/llms.txt Use `Mock::matched` for a boolean check on whether a mock was called the expected number of times. This is useful when you prefer a conditional check over a panic. ```rust #[test] fn test_matched_boolean() { use std::net::TcpStream; use std::io::{Read, Write}; let mut server = mockito::Server::new(); let mock = server.mock("GET", "/check").create(); { let mut stream = TcpStream::connect(server.host_with_port()).unwrap(); stream.write_all(b"GET /check HTTP/1.1\r\nhost: localhost\r\n\r\n").unwrap(); let mut buf = String::new(); stream.read_to_string(&mut buf).unwrap(); } assert!(mock.matched()); // true after first call (expected 1) { let mut stream = TcpStream::connect(server.host_with_port()).unwrap(); stream.write_all(b"GET /check HTTP/1.1\r\nhost: localhost\r\n\r\n").unwrap(); let mut buf = String::new(); stream.read_to_string(&mut buf).unwrap(); } assert!(!mock.matched()); // false after second call (expected exactly 1) } ``` -------------------------------- ### Server::reset Source: https://context7.com/lipanski/mockito/llms.txt Clears all registered mocks and the unmatched request history from the server. This is useful for resetting the server's state between different test phases or when reusing a server instance. ```APIDOC ## `Server::reset` ### Description Clears all registered mocks and the unmatched request history. Useful in `setup`/`teardown` patterns or when the same server instance is reused across test phases. ### Example ```rust server.reset(); // All previously defined mocks are removed. ``` ```