From 467af0da4c800302fff739e941e17ea822a32bbe Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?No=C3=ABl=20Martignoni?= Date: Mon, 13 Jan 2020 23:24:33 +0100 Subject: [PATCH] mocks matching the same request are called one after the other --- src/server.rs | 28 +++++++++++++++++++++++++++- tests/lib.rs | 19 +++++++++++++++++++ 2 files changed, 46 insertions(+), 1 deletion(-) diff --git a/src/server.rs b/src/server.rs index 625a644..87ef4ce 100644 --- a/src/server.rs +++ b/src/server.rs @@ -27,6 +27,15 @@ impl Mock { self.body .matches_value(&String::from_utf8_lossy(&request.body)) } + + fn is_missing_hits(&self) -> bool { + match (self.expected_hits_at_least, self.expected_hits_at_most) { + (Some(_at_least), Some(at_most)) => self.hits < at_most, + (Some(at_least), None) => self.hits < at_least, + (None, Some(at_most)) => self.hits < at_most, + (None, None) => self.hits < 1, + } + } } impl<'a> PartialEq for &'a mut Mock { @@ -137,7 +146,24 @@ fn handle_match_mock(request: Request, stream: TcpStream) { let mut state = STATE.lock().unwrap(); - if let Some(mock) = state.mocks.iter_mut().rev().find(|mock| mock == &request) { + let mut mocks_matched = state + .mocks + .iter_mut() + .rev() + .filter(|mock| mock == &request) + .collect::>(); + + let mock = if let Some(mock) = mocks_matched + .iter_mut() + .rev() + .find(|mock| mock.is_missing_hits()) + { + Some(mock) + } else { + mocks_matched.last_mut() + }; + + if let Some(mock) = mock { debug!("Mock found"); found = true; mock.hits += 1; diff --git a/tests/lib.rs b/tests/lib.rs index de16f2d..b3dce48 100644 --- a/tests/lib.rs +++ b/tests/lib.rs @@ -1257,3 +1257,22 @@ fn test_anyof_exact_path_and_query_matcher() { mock.assert(); } + +#[test] +fn test_same_endpoint_responses() { + let mock_200 = mock("GET", "/hello").with_status(200).create(); + let mock_404 = mock("GET", "/hello").with_status(404).create(); + let mock_500 = mock("GET", "/hello").with_status(500).create(); + + let response_200 = request("GET /hello", ""); + let response_404 = request("GET /hello", ""); + let response_500 = request("GET /hello", ""); + + mock_200.assert(); + mock_404.assert(); + mock_500.assert(); + + assert_eq!(response_200.0, "HTTP/1.1 200 OK\r\n"); + assert_eq!(response_404.0, "HTTP/1.1 404 Not Found\r\n"); + assert_eq!(response_500.0, "HTTP/1.1 500 Internal Server Error\r\n"); +}