feat(net): mock matcher no longer uses a prebuilt request
All checks were successful
Rust / build (map[name:stable]) (push) Successful in 2m3s
Rust / build (map[name:nightly]) (push) Successful in 4m15s
Release Please / Release-plz (push) Successful in 44s

This commit is contained in:
Paul Campbell 2024-11-12 07:13:59 +00:00
parent 8b6bfefbf2
commit 212aa7e0ae
6 changed files with 197 additions and 255 deletions

View file

@ -22,6 +22,7 @@ derive_more = { version = "1.0", features = [
http = "1.1" http = "1.1"
path-clean = "1.0" path-clean = "1.0"
reqwest = "0.12" reqwest = "0.12"
url = "2.5"
tempfile = "3.10" tempfile = "3.10"
[dev-dependencies] [dev-dependencies]

View file

@ -114,14 +114,11 @@ mod tests {
let url = "http://localhost:8080"; let url = "http://localhost:8080";
// declare what response should be made for a given request // declare what response should be made for a given request
let response = mock_net.response().body("contents"); let response = mock_net.response().body("contents").expect("response body");
let request = mock_net.client().get(url);
mock_net mock_net
.on(request) .on(http::Method::GET)
// By default, the METHOD and URL must match, equivalent to: .url(url::Url::parse(url).expect("parse url"))
//.match_on(vec![MatchOn::Method, MatchOn::Url]) .respond(response);
.respond_with_body(response)
.expect("mock");
// Create a temporary directory that will be deleted with `fs` goes out of scope // Create a temporary directory that will be deleted with `fs` goes out of scope
let fs = kxio::fs::temp().expect("temp fs"); let fs = kxio::fs::temp().expect("temp fs");
@ -146,7 +143,7 @@ mod tests {
// not needed for this test, but should it be needed, we can avoid checking for any // not needed for this test, but should it be needed, we can avoid checking for any
// unconsumed request matches. // unconsumed request matches.
let mock_net = kxio::net::MockNet::try_from(net).expect("recover mock"); // let mock_net = kxio::net::MockNet::try_from(net).expect("recover mock");
mock_net.reset(); // mock_net.reset();
} }
} }

View file

@ -82,19 +82,12 @@
//! # #[tokio::main] //! # #[tokio::main]
//! # async fn main() -> net::Result<()> { //! # async fn main() -> net::Result<()> {
//! # let mock_net = net::mock(); //! # let mock_net = net::mock();
//! # let client = mock_net.client(); //! mock_net.on(http::Method::GET)
//! mock_net.on(client.get("https://example.com")) //! .url(url::Url::parse("https://example.com")?)
//! .match_on(vec![ //! .respond(mock_net.response().status(200).body("")?);
//! MatchOn::Url, //! mock_net.on(http::Method::GET)
//! MatchOn::Method //! .url(url::Url::parse("https://example.com/foo")?)
//! ]) //! .respond(mock_net.response().status(500).body("Mocked response")?);
//! .respond(mock_net.response().status(200))?;
//! mock_net.on(client.get("https://example.com/foo"))
//! .match_on(vec![
//! MatchOn::Url,
//! MatchOn::Method
//! ])
//! .respond_with_body(mock_net.response().status(500).body("Mocked response"))?;
//! # mock_net.reset(); //! # mock_net.reset();
//! # Ok(()) //! # Ok(())
//! # } //! # }
@ -231,12 +224,9 @@
//! # async fn main() -> net::Result<()> { //! # async fn main() -> net::Result<()> {
//! # let mock_net = net::mock(); //! # let mock_net = net::mock();
//! # let client = mock_net.client(); //! # let client = mock_net.client();
//! mock_net.on(client.get("https://example.com")) //! mock_net.on(http::Method::GET)
//! .match_on(vec![ //! .url(url::Url::parse("https://example.com")?)
//! MatchOn::Url, //! .respond(mock_net.response().status(200).body("Mocked response")?);
//! MatchOn::Method
//! ])
//! .respond_with_body(mock_net.response().status(200).body("Mocked response"))?;
//! # mock_net.reset(); //! # mock_net.reset();
//! # Ok(()) //! # Ok(())
//! # } //! # }
@ -297,7 +287,7 @@ mod system;
pub use result::{Error, Result}; pub use result::{Error, Result};
pub use system::{MatchOn, MockNet, Net, OnRequest}; pub use system::{MatchOn, MockNet, Net};
/// Creates a new `Net`. /// Creates a new `Net`.
pub const fn new() -> Net { pub const fn new() -> Net {

View file

@ -16,6 +16,8 @@ pub enum Error {
/// The cause has been converted to a String. /// The cause has been converted to a String.
Request(String), Request(String),
Url(url::ParseError),
/// There was network request that doesn't match any that were expected /// There was network request that doesn't match any that were expected
#[display("Unexpected request: {0}", 0.to_string())] #[display("Unexpected request: {0}", 0.to_string())]
UnexpectedMockRequest(reqwest::Request), UnexpectedMockRequest(reqwest::Request),

View file

@ -1,7 +1,7 @@
// //
use std::cell::RefCell; use std::cell::RefCell;
use reqwest::Client; use reqwest::{Body, Client};
use super::{Error, Result}; use super::{Error, Result};
@ -27,11 +27,31 @@ pub enum MatchOn {
/// A planned request and the response to return /// A planned request and the response to return
/// ///
/// Contains a list of the criteria that a request must meet before being considered a match. /// Contains a list of the criteria that a request must meet before being considered a match.
#[derive(Debug)]
struct Plan { struct Plan {
request: reqwest::Request, match_request: Vec<MatchRequest>,
response: reqwest::Response, response: reqwest::Response,
match_on: Vec<MatchOn>, }
impl Plan {
fn matches(&self, request: &reqwest::Request) -> bool {
self.match_request.iter().all(|criteria| match criteria {
MatchRequest::Method(method) => request.method() == method,
MatchRequest::Url(uri) => request.url() == uri,
MatchRequest::Header { name, value } => {
request
.headers()
.iter()
.any(|(request_header_name, request_header_value)| {
let Ok(request_header_value) = request_header_value.to_str() else {
return false;
};
request_header_name.as_str() == name && request_header_value == value
})
}
MatchRequest::Body(body) => {
request.body().and_then(Body::as_bytes) == Some(body.as_bytes())
}
})
}
} }
/// An abstraction for the network /// An abstraction for the network
@ -93,36 +113,10 @@ impl Net {
return request.into().send().await.map_err(Error::from); return request.into().send().await.map_err(Error::from);
}; };
let request = request.into().build()?; let request = request.into().build()?;
let index = plans.borrow().iter().position(|plan| { let index = plans
// METHOD .borrow()
(if plan.match_on.contains(&MatchOn::Method) { .iter()
plan.request.method() == request.method() .position(|plan| plan.matches(&request));
} else {
true
})
// URL
&& (if plan.match_on.contains(&MatchOn::Url) {
plan.request.url() == request.url()
} else {
true
})
// BODY
&& (if plan.match_on.contains(&MatchOn::Body) {
match (plan.request.body(), request.body()) {
(None, None) => true,
(Some(plan), Some(req)) => plan.as_bytes().eq(&req.as_bytes()),
_ => false,
}
} else {
true
})
// HEADERS
&& (if plan.match_on.contains(&MatchOn::Headers) {
plan.request.headers() == request.headers()
} else {
true
})
});
match index { match index {
Some(i) => { Some(i) => {
let response = plans.borrow_mut().remove(i).response; let response = plans.borrow_mut().remove(i).response;
@ -159,8 +153,9 @@ impl TryFrom<Net> for MockNet {
/// let mock_net = kxio::net::mock(); /// let mock_net = kxio::net::mock();
/// let client = mock_net.client(); /// let client = mock_net.client();
/// // define an expected requet, and the response that should be returned /// // define an expected requet, and the response that should be returned
/// mock_net.on(client.get("https://hyper.rs")) /// mock_net.on(http::Method::GET)
/// .respond_with_body(mock_net.response().status(200).body("Ok"))?; /// .url(url::Url::parse("https://hyper.rs")?)
/// .respond(mock_net.response().status(200).body("Ok")?);
/// let net: kxio::net::Net = mock_net.into(); /// let net: kxio::net::Net = mock_net.into();
/// // use 'net' in your program, by passing it as a reference /// // use 'net' in your program, by passing it as a reference
/// ///
@ -197,34 +192,18 @@ impl MockNet {
/// # fn run() -> Result<()> { /// # fn run() -> Result<()> {
/// let mock_net = kxio::net::mock(); /// let mock_net = kxio::net::mock();
/// let client = mock_net.client(); /// let client = mock_net.client();
/// mock_net.on(client.get("https://hyper.rs")) /// mock_net.on(http::Method::GET)
/// .respond_with_body(mock_net.response().status(200).body("Ok"))?; /// .url(url::Url::parse("https://hyper.rs")?)
/// .respond(mock_net.response().status(200).body("Ok")?);
/// # Ok(()) /// # Ok(())
/// # } /// # }
/// ``` /// ```
pub fn on(&self, request_builder: impl Into<reqwest::RequestBuilder>) -> OnRequest { pub fn on(&self, method: impl Into<http::Method>) -> WhenRequest {
match request_builder.into().build() { WhenRequest::new(self, method)
Ok(request) => OnRequest::Valid {
net: self,
request,
match_on: vec![MatchOn::Method, MatchOn::Url],
},
Err(err) => OnRequest::Error(err.into()),
}
} }
fn _on( fn _when(&self, plan: Plan) {
&self, self.plans.borrow_mut().push(plan);
request: reqwest::Request,
response: reqwest::Response,
match_on: Vec<MatchOn>,
) -> Result<()> {
self.plans.borrow_mut().push(Plan {
request,
response,
match_on,
});
Ok(())
} }
/// Creates a [http::response::Builder] to be extended and returned by a mocked network request. /// Creates a [http::response::Builder] to be extended and returned by a mocked network request.
@ -276,77 +255,48 @@ impl Drop for Net {
} }
} }
/// Intermediate struct used while declaring an expected request and its response. pub enum MatchRequest {
pub enum OnRequest<'net> { Method(http::Method),
Valid { Url(reqwest::Url),
Header { name: String, value: String },
Body(String),
}
pub struct WhenRequest<'net> {
net: &'net MockNet, net: &'net MockNet,
request: reqwest::Request, match_on: Vec<MatchRequest>,
match_on: Vec<MatchOn>,
},
Error(super::Error),
} }
impl<'net> OnRequest<'net> {
/// Specify the criteria that a request should be compared against. impl<'net> WhenRequest<'net> {
/// pub fn url(mut self, url: impl Into<reqwest::Url>) -> Self {
/// Given an candidate request, it will be matched against the current request if it has the self.match_on.push(MatchRequest::Url(url.into()));
/// same HTTP Method and Url by default. i.e. if this method is not called.
///
/// All criteria must be met for the match to be made.
///
/// Calling this method replaces the default criteria with the new criteria.
pub fn match_on(self, match_on: Vec<MatchOn>) -> Self {
if let OnRequest::Valid {
net,
request,
match_on: _,
} = self
{
Self::Valid {
net,
request,
match_on,
}
} else {
self self
} }
pub fn header(mut self, name: impl Into<String>, value: impl Into<String>) -> Self {
self.match_on.push(MatchRequest::Header {
name: name.into(),
value: value.into(),
});
self
} }
pub fn body(mut self, body: impl Into<String>) -> Self {
/// Constructs the response to be returned when a request matched the criteria. self.match_on.push(MatchRequest::Body(body.into()));
/// self
/// The response will have an empty HTTP Body.
///
/// Each request and response pair can only be matched once each.
pub fn respond(self, response: impl Into<http::response::Builder>) -> Result<()> {
match self {
OnRequest::Valid {
net: _,
request: _,
match_on: _,
} => self.respond_with_body(response.into().body("")),
OnRequest::Error(error) => Err(error),
} }
} pub fn respond<T>(self, response: http::Response<T>)
/// Constructs the response to be returned when a request matched the criteria.
///
/// Each request and response pair can only be matched once each.
pub fn respond_with_body<T>(
self,
body_result: std::result::Result<http::Response<T>, http::Error>,
) -> Result<()>
where where
T: Into<reqwest::Body>, T: Into<reqwest::Body>,
{ {
match body_result { self.net._when(Plan {
Ok(response) => match self { match_request: self.match_on,
OnRequest::Valid { response: response.into(),
});
}
fn new(net: &'net MockNet, method: impl Into<http::Method>) -> Self {
Self {
net, net,
request, match_on: vec![MatchRequest::Method(method.into())],
match_on,
} => net._on(request, response.into(), match_on),
OnRequest::Error(error) => Err(error),
},
Err(err) => Err(err.into()),
} }
} }
} }

View file

@ -1,23 +1,29 @@
use assert2::let_assert; use assert2::let_assert;
use http::Method;
// //
use kxio::net::{Error, MatchOn, MockNet, Net}; use kxio::net::{Error, MockNet, Net};
use reqwest::Url;
#[tokio::test] #[tokio::test]
async fn test_get_url() { async fn test_get_url() {
//given //given
let net = kxio::net::mock(); let mock_net = kxio::net::mock();
let client = net.client(); let client = mock_net.client();
let url = "https://www.example.com"; let url = "https://www.example.com";
let request = client.get(url); let my_response = mock_net
let my_response = net.response().status(200).body("Get OK"); .response()
.status(200)
.body("Get OK")
.expect("body");
net.on(request) mock_net
.respond_with_body(my_response) .on(Method::GET)
.expect("on request, respond"); .url(Url::parse(url).expect("parse url"))
.respond(my_response);
//when //when
let response = Net::from(net) let response = Net::from(mock_net)
.send(client.get(url)) .send(client.get(url))
.await .await
.expect("response"); .expect("response");
@ -34,13 +40,16 @@ async fn test_get_wrong_url() {
let client = mock_net.client(); let client = mock_net.client();
let url = "https://www.example.com"; let url = "https://www.example.com";
let request = client.get(url); let my_response = mock_net
let my_response = mock_net.response().status(200).body("Get OK"); .response()
.status(200)
.body("Get OK")
.expect("body");
mock_net mock_net
.on(request) .on(Method::GET)
.respond_with_body(my_response) .url(Url::parse(url).expect("parse url"))
.expect("on request, respond"); .respond(my_response);
let net = Net::from(mock_net); let net = Net::from(mock_net);
@ -65,12 +74,11 @@ async fn test_post_url() {
let client = net.client(); let client = net.client();
let url = "https://www.example.com"; let url = "https://www.example.com";
let request = client.post(url); let my_response = net.response().status(200).body("Post OK").expect("body");
let my_response = net.response().status(200).body("Post OK");
net.on(request) net.on(Method::POST)
.respond_with_body(my_response) .url(Url::parse(url).expect("parse url"))
.expect("on request, respond"); .respond(my_response);
//when //when
let response = Net::from(net) let response = Net::from(net)
@ -89,20 +97,13 @@ async fn test_post_by_method() {
let net = kxio::net::mock(); let net = kxio::net::mock();
let client = net.client(); let client = net.client();
let url = "https://www.example.com"; let my_response = net.response().status(200).body("").expect("response body");
let request = client.post(url);
let my_response = net.response().status(200);
net.on(request) net.on(Method::POST)
.match_on(vec![ // NOTE: No URL specified - so shou∂ match any URL
MatchOn::Method, .respond(my_response);
// MatchOn::Url
])
.respond(my_response)
.expect("on request, respond");
//when //when
// This request is a different url - but should still match
let response = Net::from(net) let response = Net::from(net)
.send(client.post("https://some.other.url")) .send(client.post("https://some.other.url"))
.await .await
@ -113,59 +114,26 @@ async fn test_post_by_method() {
assert_eq!(response.bytes().await.expect("response body"), ""); assert_eq!(response.bytes().await.expect("response body"), "");
} }
#[tokio::test]
async fn test_post_by_url() {
//given
let net = kxio::net::mock();
let client = net.client();
let url = "https://www.example.com";
let request = client.post(url);
let my_response = net.response().status(200).body("Post OK");
net.on(request)
.match_on(vec![
// MatchOn::Method,
MatchOn::Url,
])
.respond_with_body(my_response)
.expect("on request, respond");
//when
// This request is a GET, not POST - but should still match
let response = Net::from(net)
.send(client.get(url))
.await
.expect("response");
//then
assert_eq!(response.status(), http::StatusCode::OK);
assert_eq!(response.bytes().await.expect("response body"), "Post OK");
}
#[tokio::test] #[tokio::test]
async fn test_post_by_body() { async fn test_post_by_body() {
//given //given
let net = kxio::net::mock(); let net = kxio::net::mock();
let client = net.client(); let client = net.client();
let url = "https://www.example.com"; let my_response = net
let request = client.post(url).body("match on body"); .response()
let my_response = net.response().status(200).body("response body"); .status(200)
.body("response body")
.expect("body");
net.on(request) net.on(Method::POST)
.match_on(vec![ // No URL - so any POST with a matching body
// MatchOn::Method, .body("match on body")
// MatchOn::Url .respond(my_response);
MatchOn::Body,
])
.respond_with_body(my_response)
.expect("on request, respond");
//when //when
// This request is a GET, not POST - but should still match
let response = Net::from(net) let response = Net::from(net)
.send(client.get("https://some.other.url").body("match on body")) .send(client.post("https://some.other.url").body("match on body"))
.await .await
.expect("response"); .expect("response");
@ -178,31 +146,27 @@ async fn test_post_by_body() {
} }
#[tokio::test] #[tokio::test]
async fn test_post_by_headers() { async fn test_post_by_header() {
//given //given
let net = kxio::net::mock(); let net = kxio::net::mock();
let client = net.client(); let client = net.client();
let url = "https://www.example.com"; let my_response = net
let request = client.post(url).body("foo").header("test", "match"); .response()
let my_response = net.response().status(200).body("response body"); .status(200)
.body("response body")
.expect("body");
net.on(request) net.on(Method::POST)
.match_on(vec![ .header("test", "match")
// MatchOn::Method, .respond(my_response);
// MatchOn::Url
MatchOn::Headers,
])
.respond_with_body(my_response)
.expect("on request, respond");
//when //when
// This request is a GET, not POST - but should still match
let response = Net::from(net) let response = Net::from(net)
.send( .send(
client client
.get("https://some.other.url") .post("https://some.other.url")
.body("match on body") .body("nay body")
.header("test", "match"), .header("test", "match"),
) )
.await .await
@ -217,20 +181,56 @@ async fn test_post_by_headers() {
} }
#[tokio::test] #[tokio::test]
#[should_panic] async fn test_post_by_header_wrong_value() {
async fn test_unused_post_as_net() {
//given //given
let mock_net = kxio::net::mock(); let mock_net = kxio::net::mock();
let client = mock_net.client(); let client = mock_net.client();
let url = "https://www.example.com"; let my_response = mock_net
let request = client.post(url); .response()
let my_response = mock_net.response().status(200).body("Post OK"); .status(200)
.body("response body")
.expect("body");
mock_net mock_net
.on(request) .on(Method::POST)
.respond_with_body(my_response) .header("test", "match")
.expect("on request, respond"); .respond(my_response);
let net = Net::from(mock_net);
//when
let response = net
.send(
client
.post("https://some.other.url")
.body("nay body")
.header("test", "no match"),
)
.await;
//then
let_assert!(Err(kxio::net::Error::UnexpectedMockRequest(_)) = response);
MockNet::try_from(net).expect("recover mock").reset();
}
#[tokio::test]
#[should_panic]
async fn test_unused_post_as_net() {
//given
let mock_net = kxio::net::mock();
let url = "https://www.example.com";
let my_response = mock_net
.response()
.status(200)
.body("Post OK")
.expect("body");
mock_net
.on(Method::POST)
.url(Url::parse(url).expect("prase url"))
.respond(my_response);
let _net = Net::from(mock_net); let _net = Net::from(mock_net);
@ -247,16 +247,18 @@ async fn test_unused_post_as_net() {
async fn test_unused_post_as_mocknet() { async fn test_unused_post_as_mocknet() {
//given //given
let mock_net = kxio::net::mock(); let mock_net = kxio::net::mock();
let client = mock_net.client();
let url = "https://www.example.com"; let url = "https://www.example.com";
let request = client.post(url); let my_response = mock_net
let my_response = mock_net.response().status(200).body("Post OK"); .response()
.status(200)
.body("Post OK")
.expect("body");
mock_net mock_net
.on(request) .on(Method::POST)
.respond_with_body(my_response) .url(Url::parse(url).expect("parse url"))
.expect("on request, respond"); .respond(my_response);
//when //when
// don't send the planned request // don't send the planned request