Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Proposal: multiple mock matching #99

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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");
}