feat(net): add user_agent helper to MockNet
All checks were successful
Test / build (map[name:nightly]) (push) Successful in 8m33s
Test / build (map[name:stable]) (push) Successful in 7m0s
Release Please / Release-plz (push) Successful in 1m18s

This commit is contained in:
Paul Campbell 2024-12-01 20:58:05 +00:00
parent 41973abe18
commit 3b8b260b65
2 changed files with 49 additions and 0 deletions

View file

@ -434,6 +434,12 @@ impl<'net> ReqBuilder<'net> {
self self
} }
/// Sets the User-Agent header to be used by this client.
#[must_use]
pub fn user_agent(self, user_agent: impl Into<String>) -> Self {
self.header(http::header::USER_AGENT.to_string(), user_agent)
}
/// Add query parameter /// Add query parameter
#[must_use] #[must_use]
pub fn query(mut self, key: impl Into<String>, value: impl Into<String>) -> Self { pub fn query(mut self, key: impl Into<String>, value: impl Into<String>) -> Self {
@ -756,6 +762,12 @@ impl<'net> WhenRequest<'net, WhenBuildRequest> {
self self
} }
/// Specifies user agent the mock will match against.
#[must_use]
pub fn user_agent(self, agent: impl Into<String>) -> Self {
self.header(http::header::USER_AGENT.to_string(), agent)
}
/// Specifies the body that the mock will match against. /// Specifies the body that the mock will match against.
/// ///
/// Any request that does not have this body will not match the mock. /// Any request that does not have this body will not match the mock.

View file

@ -531,3 +531,40 @@ async fn test_get_with_duplicate_query_keys() {
"key:value-3,value-4" "key:value-3,value-4"
); );
} }
#[tokio::test]
async fn test_get_with_user_agent() {
//given
let mock_net = kxio::net::mock();
let url = "https://www.example.com/path";
mock_net
.on()
.get(url)
.user_agent("007")
.respond(StatusCode::OK)
.mock()
.expect("mock");
mock_net
.on()
.get(url)
.user_agent("orange")
.respond(StatusCode::FORBIDDEN)
.mock()
.expect("mock");
let net = Net::from(mock_net);
//when
let invalid = net.get(url).user_agent("orange").send().await;
let valid = net
.get(url)
.user_agent("007")
.send()
.await
.expect("valid response");
//then
let_assert!(Err(Error::ResponseError { response }) = invalid);
assert_eq!(response.status(), StatusCode::FORBIDDEN);
assert_eq!(valid.status(), StatusCode::OK);
}