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
#![warn(missing_docs)] #![doc(html_logo_url = "http://lipanski.github.io/mockito/logo/logo-black.png", html_root_url = "http://lipanski.github.io/mockito/generated/mockito/index.html")] //! //! Mockito is a library for creating HTTP mocks to be used in integration tests or for offline work. //! It runs an HTTP server on your local port 1234 and can register and remove mocks. //! //! The server is run on a separate thread within the same process and will be cleaned up //! at the end of the run. //! //! # Getting Started //! //! Using compiler flags, set the URL of your web client to `mockito::SERVER_URL` or `mockito::SERVER_ADDRESS`. //! //! ## Example //! //! ``` //! #[cfg(test)] //! use mockito; //! //! #[cfg(not(test))] //! const URL: &'static str = "https://api.twitter.com"; //! //! #[cfg(test)] //! const URL: &'static str = mockito::SERVER_URL; //! ``` //! //! Then start mocking: //! //! ## Example //! //! ``` //! #[cfg(test)] //! mod tests { //! use mockito::mock; //! //! #[test] //! fn test_something() { //! 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". //! } //! } //! ``` //! //! # Run your tests //! //! Due to the nature of this library (all your mocks are recorded on the same server running in background), //! it is highly recommended that you **run your tests on a single thread**: //! //! ```sh //! cargo test -- --test-threads=1 //! //! # Same, but using an environment variable //! RUST_TEST_THREADS=1 cargo test //! ``` //! //! In some situations, when you're *always* testing/mocking different routes and never need to reset //! or override the existing mocks, you might get away with running your tests on multiple threads. //! //! # Matching by header //! //! Mockito currently matches by method and path, but also by headers. The header field letter case is ignored. //! //! ## Example //! //! ``` //! use mockito::mock; //! //! mock("GET", "/hello") //! .match_header("content-type", "application/json") //! .with_body("{'hello': 'world'}") //! .create(); //! //! 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. //! ``` //! //! # Other header matchers //! //! You can match a header *only by its field name*, by setting the `Mock::match_header` value to `Matcher::Any`. //! //! ## Example //! //! ``` //! use mockito::{mock, Matcher}; //! //! mock("GET", "/hello") //! .match_header("content-type", Matcher::Any) //! .with_body("something"); //! //! // Requests containing any content-type header value will be mocked. //! // Requests not containing this header will return `501 Not Implemented`. //! ``` //! //! You can mock requests that should be *missing a particular header field*, by setting the `Mock::match_header` //! value to `Matcher::Missing`. //! //! ## Example //! //! ``` //! use mockito::{mock, Matcher}; //! //! mock("GET", "/hello") //! .match_header("authorization", Matcher::Missing) //! .with_body("no authorization header"); //! //! // Requests without the authorization header will be matched. //! // Requests containing the authorization header will return `501 Not Implemented`. //! ``` //! //! # Non-matching calls //! //! Any calls to the Mockito server that are not matched will return *501 Not Implemented*. //! //! # Cleaning up //! //! Even though **mocks are matched in reverse order** (most recent one wins), in some situations //! it might be useful to clean up right after the test. There are multiple ways of doing this. //! //! By using a closure: //! //! ## Example //! //! ``` //! use mockito::mock; //! //! mock("GET", "/hello") //! .with_body("world") //! .create_for(|| { //! // mock only valid for the lifetime of this closure //! // NOTE: it might still be accessible by separate threads //! }); //! ``` //! //! By calling `remove()` on the mock: //! //! ## Example //! //! ``` //! use mockito::mock; //! //! let mut mock = mock("GET", "/hello"); //! mock.with_body("world").create(); //! //! // do your thing //! //! mock.remove(); //! ``` //! //! By calling `reset()` to **remove all mocks**: //! //! ## Example //! //! ``` //! use mockito::reset; //! //! reset(); //! ``` //! extern crate curl; extern crate http_muncher; #[macro_use] extern crate serde_derive; extern crate serde_json; extern crate rand; mod server; mod request; type Request = request::Request; use std::collections::HashMap; use std::fs::File; use std::io::Read; use std::cmp::PartialEq; use std::convert::{From, Into}; use curl::easy::Easy; use curl::easy::List as HeaderList; use rand::{thread_rng, Rng}; /// /// Points to the address the mock server is running at. /// Can be used with `std::net::TcpStream`. /// pub const SERVER_ADDRESS: &'static str = "127.0.0.1:1234"; /// /// Points to the URL the mock server is running at. /// pub const SERVER_URL: &'static str = "http://127.0.0.1:1234"; /// /// Initializes a mock for the provided `method` and `path`. /// /// The mock is registered to the server only after the `create()` method has been called. /// /// # Example /// /// ``` /// use mockito::mock; /// /// mock("GET", "/"); /// mock("POST", "/users"); /// mock("DELETE", "/users?id=1"); /// ``` /// pub fn mock(method: &str, path: &str) -> Mock { Mock::new(method, path) } /// /// Removes all the mocks stored on the server. /// pub fn reset() { server::try_start(); let mut request = Easy::new(); request.url(&[SERVER_URL, "/mocks"].join("")).unwrap(); request.custom_request("DELETE").unwrap(); request.perform().unwrap(); } #[allow(missing_docs)] pub fn start() { server::try_start(); } /// /// Allows matching headers in multiple ways: matching the exact field name and value, matching only by field name /// or matching that the field name is not present at all. /// /// These matchers are used within the `Mock::match_header` call. /// #[derive(Serialize, Deserialize, PartialEq, Debug)] pub enum Matcher { /// Given the header field, matches the exact header value. There's also an implementation of `From<&str>` /// to keep things simple and backwards compatible. Exact(String), /// Given the header field, matches any header value. Any, /// Matches when the header field is *not* be present in the request. Missing, } impl<'a> From<&'a str> for Matcher { fn from(value: &str) -> Matcher { Matcher::Exact(value.to_string()) } } impl PartialEq<String> for Matcher { fn eq(&self, other: &String) -> bool { match self { &Matcher::Exact(ref value) => { value == other }, &Matcher::Any => true, &Matcher::Missing => false, } } } /// /// Stores information about a mocked request. Should be initialized via `mockito::mock()`. /// #[derive(Serialize, Deserialize, PartialEq, Debug)] pub struct Mock { id: String, method: String, path: String, headers: HashMap<String, Matcher>, response: MockResponse, } impl Mock { fn new(method: &str, path: &str) -> Self { Mock { id: thread_rng().gen_ascii_chars().take(24).collect(), method: method.to_owned().to_uppercase(), path: path.to_owned(), headers: HashMap::new(), response: MockResponse::new(), } } /// /// Allows matching a particular request header when responding with a mock. /// /// When matching a request, the field letter case is ignored. /// /// # Example /// /// ``` /// use mockito::mock; /// /// mock("GET", "/").match_header("content-type", "application/json"); /// ``` /// /// Like most other `Mock` methods, it allows chanining: /// /// # Example /// /// ``` /// use mockito::mock; /// /// mock("GET", "/") /// .match_header("content-type", "application/json") /// .match_header("authorization", "password"); /// ``` /// pub fn match_header<M: Into<Matcher>>(&mut self, field: &str, value: M) -> &mut Self { self.headers.insert(field.to_owned().to_lowercase(), value.into()); self } /// /// Sets the status code of the mock response. The default status code is 200. /// /// # Example /// /// ``` /// use mockito::mock; /// /// mock("GET", "/").with_status(201); /// ``` /// pub fn with_status(&mut self, status: usize) -> &mut Self { self.response.status = status; self } /// /// Sets a header of the mock response. /// /// # Example /// /// ``` /// use mockito::mock; /// /// mock("GET", "/").with_header("content-type", "application/json"); /// ``` /// pub fn with_header(&mut self, field: &str, value: &str) -> &mut Self { self.response.headers.push((field.to_owned(), value.to_owned())); self } /// /// Sets the body of the mock response. Its `Content-Length` is handled automatically. /// /// # Example /// /// ``` /// use mockito::mock; /// /// mock("GET", "/").with_body("hello world"); /// ``` /// pub fn with_body(&mut self, body: &str) -> &mut Self { self.response.body = body.to_owned(); self } /// /// Sets the body of the mock response from the contents of a file stored under `path`. /// Its `Content-Length` is handled automatically. /// /// # Example /// /// ``` /// use mockito::mock; /// /// mock("GET", "/").with_body_from_file("tests/files/simple.http"); /// ``` /// pub fn with_body_from_file(&mut self, path: &str) -> &mut Self { let mut file = File::open(path).unwrap(); let mut body = String::new(); file.read_to_string(&mut body).unwrap(); self.response.body = body; self } /// /// Registers the mock to the server - your mock will be served only after calling this method. /// /// # Example /// /// ``` /// use mockito::mock; /// /// mock("GET", "/").with_body("hello world").create(); /// ``` /// pub fn create(&mut self) -> &mut Self { server::try_start(); let body = serde_json::to_string(&self).unwrap(); let mut request = Easy::new(); request.url(&[SERVER_URL, "/mocks"].join("")).unwrap(); request.post(true).unwrap(); request.post_fields_copy(body.as_bytes()).unwrap(); request.perform().unwrap(); self } /// /// Registers the mock to the server, executes the passed closure and removes the mock afterwards. /// /// **NOTE:** During the closure lifetime, the mock might still be available to seperate threads. /// /// # Example /// /// ``` /// use std::thread::{sleep}; /// use std::time::Duration; /// use mockito::mock; /// /// mock("GET", "/").with_body("hello world").create_for(|| { /// // This mock will only be available for the next 1 second /// sleep(Duration::new(1, 0)); /// }); /// ``` /// pub fn create_for<F: Fn() -> ()>(&mut self, environment: F) -> &mut Self { self.create(); environment(); self.remove(); self } /// /// Removes the current mock from the server. /// /// # Example /// /// ``` /// use mockito::mock; /// /// let mut mock = mock("GET", "/"); /// mock.with_body("hello world").create(); /// /// // stuff /// /// mock.remove(); /// ``` /// pub fn remove(&self) { server::try_start(); let mut request = Easy::new(); request.url(&[SERVER_URL, "/mocks"].join("")).unwrap(); request.custom_request("DELETE").unwrap(); let mut headers = HeaderList::new(); headers.append(&["x-mock-id", &self.id].join(":")).unwrap(); request.http_headers(headers).unwrap(); request.perform().unwrap(); } #[allow(missing_docs)] pub fn matches(&self, request: &Request) -> bool { self.method_matches(request) && self.path_matches(request) && self.headers_match(request) } fn method_matches(&self, request: &Request) -> bool { self.method == request.method } fn path_matches(&self, request: &Request) -> bool { self.path == request.path } fn headers_match(&self, request: &Request) -> bool { for (field, value) in self.headers.iter() { match request.headers.get(field) { Some(request_header_value) => { if value == request_header_value { continue } return false }, None => { if value == &Matcher::Missing { continue } return false }, } } true } } const DEFAULT_RESPONSE_STATUS: usize = 200; #[derive(Serialize, Deserialize, Debug, PartialEq)] struct MockResponse { status: usize, headers: Vec<(String, String)>, body: String, } impl MockResponse { pub fn new() -> Self { MockResponse { status: DEFAULT_RESPONSE_STATUS, headers: Vec::new(), body: String::new(), } } }