diff --git a/src/server.rs b/src/server.rs index 11beb08..d879050 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 { @@ -138,7 +147,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 313ddfe..0d3c184 100644 --- a/tests/lib.rs +++ b/tests/lib.rs @@ -1336,3 +1336,22 @@ fn test_missing_create_good() { assert_eq!(warnings.len(), 0); }); } + +#[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"); +}