1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684
#![warn(missing_docs)]
#![doc(
html_logo_url = "https://raw.githubusercontent.com/lipanski/mockito/master/docs/logo-black-100.png"
)]
//!
//! Mockito is a library for **generating and delivering HTTP mocks** in Rust. You can use it for integration testing
//! or offline work. Mockito runs a local pool of HTTP servers which create, deliver and remove the mocks.
//!
//! # Features
//!
//! - Support for HTTP1/2
//! - Multi-threaded
//! - Various request matchers (Regex, JSON etc.)
//! - Mock multiple hosts at the same time
//! - Sync and async interface
//! - Simple, intuitive API
//! - An awesome logo
//!
//! # Getting Started
//!
//! Add `mockito` to your `Cargo.toml` and start mocking:
//!
//! ```
//! #[cfg(test)]
//! mod tests {
//! #[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 _m = 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
//! // m.assert();
//! }
//! }
//! ```
//!
//! Use **matchers** to handle requests to the same endpoint in a different way:
//!
//! ```
//! #[cfg(test)]
//! mod tests {
//! #[test]
//! fn test_something() {
//! let mut server = mockito::Server::new();
//!
//! let m1 = server.mock("GET", "/greetings")
//! .match_header("content-type", "application/json")
//! .match_body(mockito::Matcher::PartialJsonString(
//! "{\"greeting\": \"hello\"}".to_string(),
//! ))
//! .with_body("hello json")
//! .create();
//!
//! let m2 = server.mock("GET", "/greetings")
//! .match_header("content-type", "application/text")
//! .match_body(mockito::Matcher::Regex("greeting=hello".to_string()))
//! .with_body("hello text")
//! .create();
//! }
//! }
//! ```
//!
//! Start **multiple servers** to simulate requests to different hosts:
//!
//! ```
//! #[cfg(test)]
//! mod tests {
//! #[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();
//! }
//! }
//! ```
//!
//! Write **async** tests:
//!
//! ```
//! #[cfg(test)]
//! mod tests {
//! #[tokio::test]
//! async fn test_something() {
//! let mut server = Server::new_async().await;
//! let _m1 = server.mock("GET", "/a").with_body("aaa").create_async();
//! let _m2 = server.mock("GET", "/b").with_body("bbb").create_async();
//!
//! let (_m1, _m2) = futures::join!(_m1, _m2);
//! }
//! }
//! ```
//!
//! # Lifetime
//!
//! Just like any Rust object, a mock is available only through its lifetime. You'll want to assign
//! the mocks to variables in order to extend and control their lifetime.
//!
//! Avoid using the underscore matcher when creating your mocks, as in `let _ = mock("GET", "/")`.
//! This will end your mock's lifetime immediately. You can still use the underscore to prefix your variable
//! names in an assignment, but don't limit it to just this one character.
//!
//! ## Example
//!
//! ```
//! let mut s = mockito::Server::new();
//! let _m1 = s.mock("GET", "/long").with_body("hello").create();
//!
//! {
//! let _m2 = s.mock("GET", "/short").with_body("hi").create();
//!
//! // Requests to GET /short will be mocked til here
//! }
//!
//! // Requests to GET /long will be mocked til here
//! ```
//!
//! # Matchers
//!
//! Mockito can match your request by method, path, query, headers or body.
//!
//! Various matchers are provided by the `Matcher` type: exact (string, binary, JSON), partial (regular expressions,
//! JSON), any or missing. The following guide will walk you through the most common matchers. Check the
//! `Matcher` documentation for all the rest.
//!
//! # Matching by path
//!
//! By default, the request path is compared by its exact value:
//!
//! ## Example
//!
//! ```
//! let mut s = mockito::Server::new();
//!
//! // Matched only calls to GET /hello
//! let _m = s.mock("GET", "/hello").create();
//! ```
//!
//! You can also match the path partially, by using a regular expression:
//!
//! ## Example
//!
//! ```
//! let mut s = mockito::Server::new();
//!
//! // Will match calls to GET /hello/1 and GET /hello/2
//! let _m = s.mock("GET",
//! mockito::Matcher::Regex(r"^/hello/(1|2)$".to_string())
//! ).create();
//! ```
//!
//! Or you can catch all requests, by using the `Matcher::Any` variant:
//!
//! ## Example
//!
//! ```
//! let mut s = mockito::Server::new();
//!
//! // Will match any GET request
//! let _m = s.mock("GET", mockito::Matcher::Any).create();
//! ```
//!
//! # Matching by query
//!
//! You can match the query part by using the `Mock#match_query` function together with the various matchers,
//! most notably `Matcher::UrlEncoded`:
//!
//! ## Example
//!
//! ```
//! let mut s = mockito::Server::new();
//!
//! // This will match requests containing the URL-encoded
//! // query parameter `greeting=good%20day`
//! let _m1 = s.mock("GET", "/test")
//! .match_query(mockito::Matcher::UrlEncoded("greeting".into(), "good day".into()))
//! .create();
//!
//! // This will match requests containing the URL-encoded
//! // query parameters `hello=world` and `greeting=good%20day`
//! let _m2 = s.mock("GET", "/test")
//! .match_query(mockito::Matcher::AllOf(vec![
//! mockito::Matcher::UrlEncoded("hello".into(), "world".into()),
//! mockito::Matcher::UrlEncoded("greeting".into(), "good day".into())
//! ]))
//! .create();
//!
//! // You can achieve similar results with the regex matcher
//! let _m3 = s.mock("GET", "/test")
//! .match_query(mockito::Matcher::Regex("hello=world".into()))
//! .create();
//! ```
//!
//! Note that the key/value arguments for `Matcher::UrlEncoded` should be left in plain (unencoded) format.
//!
//! You can also specify the query as part of the path argument in a `mock` call, in which case an exact
//! match will be performed:
//!
//! ## Example
//!
//! ```
//! use mockito::mock;
//!
//! // This will perform a full match against the query part
//! let _m = mock("GET", "/test?hello=world").create();
//! ```
//!
//! # Matching by header
//!
//! By default, headers are compared by their exact value. The header name letter case is ignored though.
//!
//! ## Example
//!
//! ```
//! let mut s = mockito::Server::new();
//!
//! let _m1 = s.mock("GET", "/hello")
//! .match_header("content-type", "application/json")
//! .with_body(r#"{"hello": "world"}"#)
//! .create();
//!
//! let _m2 = s.mock("GET", "/hello")
//! .match_header("content-type", "text/plain")
//! .with_body("world")
//! .create();
//!
//! // JSON requests to GET /hello will respond with JSON, while plain requests
//! // will respond with text.
//! ```
//!
//! You can also match a header value with a *regular expressions*, by using the `Matcher::Regex` matcher:
//!
//! ## Example
//!
//! ```
//! let mut s = mockito::Server::new();
//!
//! let _m = s.mock("GET", "/hello")
//! .match_header("content-type", mockito::Matcher::Regex(r".*json.*".to_string()))
//! .with_body(r#"{"hello": "world"}"#)
//! .create();
//! ```
//!
//! Or you can match a header *only by its field name*, by setting the `Mock::match_header` value to `Matcher::Any`.
//!
//! ## Example
//!
//! ```
//! let mut s = mockito::Server::new();
//!
//! let _m = s.mock("GET", "/hello")
//! .match_header("content-type", mockito::Matcher::Any)
//! .with_body("something")
//! .create();
//!
//! // Requests containing any content-type header value will be mocked.
//! // Requests not containing this header will return `501 Mock Not Found`.
//! ```
//!
//! You can mock requests that should be *missing a particular header field*, by setting the `Mock::match_header`
//! value to `Matcher::Missing`.
//!
//! ## Example
//!
//! ```
//! let mut s = mockito::Server::new();
//!
//! let _m = s.mock("GET", "/hello")
//! .match_header("authorization", mockito::Matcher::Missing)
//! .with_body("no authorization header")
//! .create();
//!
//! // Requests without the authorization header will be matched.
//! // Requests containing the authorization header will return `501 Mock Not Found`.
//! ```
//!
//! # Matching by body
//!
//! You can match a request by its body by using the `Mock#match_body` method.
//! By default the request body is ignored, similar to passing the `Matcher::Any` argument to the `match_body` method.
//!
//! You can match a body by an exact value:
//!
//! ## Example
//!
//! ```
//! let mut s = mockito::Server::new();
//!
//! // Will match requests to POST / whenever the request body is "hello"
//! let _m = s.mock("POST", "/").match_body("hello").create();
//! ```
//!
//! Or you can match the body by using a regular expression:
//!
//! ## Example
//!
//! ```
//! let mut s = mockito::Server::new();
//!
//! // Will match requests to POST / whenever the request body *contains* the word "hello" (e.g. "hello world")
//! let _m = s.mock("POST", "/").match_body(
//! mockito::Matcher::Regex("hello".to_string())
//! ).create();
//! ```
//!
//! Or you can match the body using a JSON object:
//!
//! ## Example
//!
//! ```
//! # extern crate mockito;
//! #[macro_use]
//! extern crate serde_json;
//!
//! # fn main() {
//! let mut s = mockito::Server::new();
//! // Will match requests to POST / whenever the request body matches the json object
//! let _m = s.mock("POST", "/").match_body(mockito::Matcher::Json(json!({"hello": "world"}))).create();
//! # }
//! ```
//!
//! If `serde_json::json!` is not exposed, you can use `Matcher::JsonString` the same way,
//! but by passing a `String` to the matcher:
//!
//! ```
//! let mut s = mockito::Server::new();
//!
//! // Will match requests to POST / whenever the request body matches the json object
//! let _m = s.mock("POST", "/")
//! .match_body(
//! mockito::Matcher::JsonString(r#"{"hello": "world"}"#.to_string())
//! )
//! .create();
//! ```
//!
//! # The `AnyOf` matcher
//!
//! The `Matcher::AnyOf` construct takes a vector of matchers as arguments and will be enabled
//! if at least one of the provided matchers matches the request.
//!
//! ## Example
//!
//! ```
//! let mut s = mockito::Server::new();
//!
//! // Will match requests to POST / whenever the request body is either `hello=world` or `{"hello":"world"}`
//! let _m = s.mock("POST", "/")
//! .match_body(
//! mockito::Matcher::AnyOf(vec![
//! mockito::Matcher::Exact("hello=world".to_string()),
//! mockito::Matcher::JsonString(r#"{"hello": "world"}"#.to_string()),
//! ])
//! )
//! .create();
//! ```
//!
//! # The `AllOf` matcher
//!
//! The `Matcher::AllOf` construct takes a vector of matchers as arguments and will be enabled
//! if all of the provided matchers match the request.
//!
//! ## Example
//!
//! ```
//! let mut s = mockito::Server::new();
//!
//! // Will match requests to POST / whenever the request body contains both `hello` and `world`
//! let _m = s.mock("POST", "/")
//! .match_body(
//! mockito::Matcher::AllOf(vec![
//! mockito::Matcher::Regex("hello".to_string()),
//! mockito::Matcher::Regex("world".to_string()),
//! ])
//! )
//! .create();
//! ```
//!
//! # Asserts
//!
//! You can use the `Mock::assert` method to **assert that a mock was called**. In other words,
//! `Mock#assert` can validate that your code performed the expected HTTP request.
//!
//! By default, the method expects only **one** request to your mock.
//!
//! ## Example
//!
//! ```no_run
//! use std::net::TcpStream;
//! use std::io::{Read, Write};
//!
//! let mut s = mockito::Server::new();
//! let mock = s.mock("GET", "/hello").create();
//!
//! {
//! // Place a request
//! let mut stream = TcpStream::connect(s.host_with_port()).unwrap();
//! stream.write_all("GET /hello HTTP/1.1\r\n\r\n".as_bytes()).unwrap();
//! let mut response = String::new();
//! stream.read_to_string(&mut response).unwrap();
//! stream.flush().unwrap();
//! }
//!
//! mock.assert();
//! ```
//!
//! When several mocks can match a request, Mockito applies the first one that still expects requests.
//! You can use this behaviour to provide **different responses for subsequent requests to the same endpoint**.
//!
//! ## Example
//!
//! ```
//! use std::net::TcpStream;
//! use std::io::{Read, Write};
//!
//! let mut s = mockito::Server::new();
//! let english_hello_mock = s.mock("GET", "/hello").with_body("good bye").create();
//! let french_hello_mock = s.mock("GET", "/hello").with_body("au revoir").create();
//!
//! {
//! // Place a request to GET /hello
//! let mut stream = TcpStream::connect(s.host_with_port()).unwrap();
//! stream.write_all("GET /hello HTTP/1.1\r\n\r\n".as_bytes()).unwrap();
//! let mut response = String::new();
//! stream.read_to_string(&mut response).unwrap();
//! stream.flush().unwrap();
//! }
//!
//! english_hello_mock.assert();
//!
//! {
//! // Place another request to GET /hello
//! let mut stream = TcpStream::connect(s.host_with_port()).unwrap();
//! stream.write_all("GET /hello HTTP/1.1\r\n\r\n".as_bytes()).unwrap();
//! let mut response = String::new();
//! stream.read_to_string(&mut response).unwrap();
//! stream.flush().unwrap();
//! }
//!
//! french_hello_mock.assert();
//! ```
//!
//! If you're expecting more than 1 request, you can use the `Mock::expect` method to specify the exact amount of requests:
//!
//! ## Example
//!
//! ```no_run
//! use std::net::TcpStream;
//! use std::io::{Read, Write};
//!
//! let mut s = mockito::Server::new();
//!
//! let mock = s.mock("GET", "/hello").expect(3).create();
//!
//! for _ in 0..3 {
//! // Place a request
//! let mut stream = TcpStream::connect(s.host_with_port()).unwrap();
//! stream.write_all("GET /hello HTTP/1.1\r\n\r\n".as_bytes()).unwrap();
//! let mut response = String::new();
//! stream.read_to_string(&mut response).unwrap();
//! stream.flush().unwrap();
//! }
//!
//! mock.assert();
//! ```
//!
//! You can also work with ranges, by using the `Mock::expect_at_least` and `Mock::expect_at_most` methods:
//!
//! ## Example
//!
//! ```no_run
//! use std::net::TcpStream;
//! use std::io::{Read, Write};
//!
//! let mut s = mockito::Server::new();
//!
//! let mock = s.mock("GET", "/hello").expect_at_least(2).expect_at_most(4).create();
//!
//! for _ in 0..3 {
//! // Place a request
//! let mut stream = TcpStream::connect(s.host_with_port()).unwrap();
//! stream.write_all("GET /hello HTTP/1.1\r\n\r\n".as_bytes()).unwrap();
//! let mut response = String::new();
//! stream.read_to_string(&mut response).unwrap();
//! stream.flush().unwrap();
//! }
//!
//! mock.assert();
//! ```
//!
//! The errors produced by the `assert` method contain information about the tested mock, but also about the
//! **last unmatched request**, which can be very useful to track down an error in your implementation or
//! a missing or incomplete mock. A colored diff is also displayed.
//!
//! Color output is enabled by default, but can be toggled with the `color` feature flag.
//!
//! Here's an example of how a `Mock#assert` error looks like:
//!
//! ```text
//! > Expected 1 request(s) to:
//!
//! POST /users?number=one
//! bob
//!
//! ...but received 0
//!
//! > The last unmatched request was:
//!
//! POST /users?number=two
//! content-length: 5
//! alice
//!
//! > Difference:
//!
//! # A colored diff
//!
//! ```
//!
//! You can also use the `matched` method to return a boolean for whether the mock was called the
//! correct number of times without panicking
//!
//! ## Example
//!
//! ```
//! use std::net::TcpStream;
//! use std::io::{Read, Write};
//!
//! let mut s = mockito::Server::new();
//!
//! let mock = s.mock("GET", "/").create();
//!
//! {
//! let mut stream = TcpStream::connect(s.host_with_port()).unwrap();
//! stream.write_all("GET / HTTP/1.1\r\n\r\n".as_bytes()).unwrap();
//! let mut response = String::new();
//! stream.read_to_string(&mut response).unwrap();
//! stream.flush().unwrap();
//! }
//!
//! assert!(mock.matched());
//!
//! {
//! let mut stream = TcpStream::connect(s.host_with_port()).unwrap();
//! stream.write_all("GET / HTTP/1.1\r\n\r\n".as_bytes()).unwrap();
//! let mut response = String::new();
//! stream.read_to_string(&mut response).unwrap();
//! stream.flush().unwrap();
//! }
//! assert!(!mock.matched());
//! ```
//!
//! # Non-matching calls
//!
//! Any calls to the Mockito server that are not matched will return *501 Mock Not Found*.
//!
//! Note that **mocks are matched in reverse order** - the most recent one wins.
//!
//! # Cleaning up
//!
//! As mentioned earlier, mocks are cleaned up at the end of their normal Rust lifetime. However,
//! you can always use the `reset` method to clean up *all* the mocks registered so far.
//!
//! ## Example
//!
//! ```
//! let mut s = mockito::Server::new();
//!
//! let _m1 = s.mock("GET", "/1").create();
//! let _m2 = s.mock("GET", "/2").create();
//! let _m3 = s.mock("GET", "/3").create();
//!
//! s.reset();
//!
//! // Nothing is mocked at this point
//! ```
//!
//! Or you can use `std::mem::drop` to remove a single mock without having to wait for its scope to end:
//!
//! ## Example
//!
//! ```
//! use std::mem;
//!
//! let mut s = mockito::Server::new();
//! let m = s.mock("GET", "/hello").create();
//!
//! // Requests to GET /hello are mocked
//!
//! mem::drop(m);
//!
//! // Still in the scope of `m`, but requests to GET /hello aren't mocked any more
//! ```
//!
//! # Debug
//!
//! Mockito uses the `env_logger` crate under the hood to provide useful debugging information.
//!
//! If you'd like to activate the debug output, introduce the [env_logger](https://crates.rs/crates/env_logger) crate
//! to your project and initialize it before each test that needs debugging:
//!
//! ```
//! #[test]
//! fn example_test() {
//! let _ = env_logger::try_init();
//! // ...
//! }
//! ```
//!
//! Run your tests with:
//!
//! ```sh
//! RUST_LOG=mockito=debug cargo test
//! ```
//!
//! # Sharing the server with other threads
//!
//! If you ever need to share the mock server with another thread, make sure to wrap it inside
//! a Mutex or it might not get cleaned properly:
//!
//! ## Example
//!
//! ```
//! use std::sync::{Arc, Mutex};
//! use std::thread;
//!
//! let mut s = mockito::Server::new();
//! let host = s.host_with_port();
//! let _mock_outside_thread = s.mock("GET", "/").with_body("outside").create();
//!
//! let server_mutex = Arc::new(Mutex::new(s));
//! let server_clone = server_mutex.clone();
//! let process = thread::spawn(move || {
//! let mut s = server_clone.lock().unwrap();
//! let _mock_inside_thread = s.mock("GET", "/").with_body("inside").create();
//! });
//!
//! process.join().unwrap();
//! ```
//!
pub use error::{Error, ErrorKind};
use lazy_static::lazy_static;
#[allow(deprecated)]
pub use legacy::{mock, reset, server_address, server_url};
pub use matcher::Matcher;
pub use mock::Mock;
pub use server::Server;
use tokio::runtime::Runtime;
mod command;
mod diff;
mod error;
mod legacy;
mod matcher;
mod mock;
mod request;
mod response;
mod server;
mod server_pool;
lazy_static! {
pub(crate) static ref RUNTIME: Runtime = tokio::runtime::Builder::new_current_thread()
.enable_all()
.build()
.expect("couldn't start tokio runtime");
}