Skip to content

Commit

Permalink
mocks matching the same request are called one after the other (#99)
Browse files Browse the repository at this point in the history
Co-authored-by: Florin Lipan <[email protected]>
  • Loading branch information
Noël Martignoni and lipanski authored Apr 5, 2020
1 parent 89aff71 commit 7bb0b8d
Show file tree
Hide file tree
Showing 2 changed files with 46 additions and 1 deletion.
28 changes: 27 additions & 1 deletion src/server.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<Request> for &'a mut Mock {
Expand Down Expand Up @@ -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::<Vec<_>>();

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;
Expand Down
19 changes: 19 additions & 0 deletions tests/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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");
}

0 comments on commit 7bb0b8d

Please sign in to comment.