Compare commits

..

No commits in common. "2edfe7d51f39663f44f647845799cd00a7e05703" and "17c1b4ff6df59ea13f7a2189bd614873c173e669" have entirely different histories.

7 changed files with 63 additions and 239 deletions

View file

@ -15,9 +15,9 @@ unexpected_cfgs = { level = "warn", check-cfg = ['cfg(tarpaulin_include)'] }
[dependencies] [dependencies]
derive_more = { version = "1.0", features = [ derive_more = { version = "1.0", features = [
"constructor", "from",
"display", "display",
"from" "constructor"
] } ] }
http = "1.1" http = "1.1"
path-clean = "1.0" path-clean = "1.0"
@ -28,10 +28,7 @@ tempfile = "3.10"
assert2 = "0.3" assert2 = "0.3"
pretty_assertions = "1.4" pretty_assertions = "1.4"
test-log = "0.2" test-log = "0.2"
tokio = { version = "1.41", features = [ tokio = { version = "1.41", features = ["macros"] }
"macros",
"rt-multi-thread"
] }
tokio-test = "0.4" tokio-test = "0.4"
[package.metadata.bin] [package.metadata.bin]

View file

@ -1,82 +0,0 @@
// example to show fetching a URL and saving to a file
use std::path::Path;
#[tokio::main]
async fn main() -> kxio::Result<()> {
let net = kxio::net::new();
let fs = kxio::fs::temp()?;
let url = "https://git.kemitix.net/kemitix/kxio/raw/branch/main/README.md";
let file_path = fs.base().join("README.md");
download_and_save(url, &file_path, &fs, &net).await?;
print_file(&file_path, &fs)?;
Ok(())
}
async fn download_and_save(
url: &str,
file_path: &Path,
fs: &kxio::fs::FileSystem,
net: &kxio::net::Net,
) -> kxio::Result<()> {
println!("fetching: {url}");
let request = net.client().get(url);
let response = net.send(request).await?;
let body = response.text().await?;
println!("fetched {} bytes", body.bytes().len());
println!("writing file: {}", file_path.display());
let file = fs.file(file_path);
file.write(body)?;
Ok(())
}
fn print_file(file_path: &Path, fs: &kxio::fs::FileSystem) -> kxio::Result<()> {
println!("reading file: {}", file_path.display());
let file = fs.file(file_path);
let reader = file.reader()?;
let contents = reader.as_str();
println!("{contents}");
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
#[tokio::test]
async fn should_save_remote_body() {
//given
let net = kxio::net::mock();
let url = "http://localhost:8080";
net.on(net.client().get(url).build().expect("request"))
.respond(
net.response()
.body("contents")
.expect("response body")
.into(),
)
.expect("mock");
let fs = kxio::fs::temp().expect("temp fs");
let file_path = fs.base().join("foo");
//when
download_and_save(url, &file_path, &fs, &net.into())
.await
.expect("system under test");
//then
let file = fs.file(&file_path);
let reader = file.reader().expect("reader");
let contents = reader.as_str();
assert_eq!(contents, "contents");
}
}

View file

@ -7,7 +7,6 @@ build:
cargo hack build cargo hack build
cargo hack test cargo hack test
cargo doc cargo doc
cargo test --example get
install-hooks: install-hooks:
@echo "Installing git hooks" @echo "Installing git hooks"

View file

@ -7,14 +7,15 @@ mod system;
pub use result::{Error, Result}; pub use result::{Error, Result};
pub use system::{MatchOn, MockNet, Net}; pub use system::{MatchOn, Net};
use system::{Mocked, Unmocked};
/// Creates a new `Net`. /// Creates a new `Net`.
pub const fn new() -> Net { pub const fn new() -> Net<Unmocked> {
Net::new() Net::<Unmocked>::new()
} }
/// Creates a new `MockNet` for use in tests. /// Creates a new `MockNet` for use in tests.
pub fn mock() -> MockNet { pub fn mock() -> Net<Mocked> {
Net::mock() Net::<Mocked>::new()
} }

View file

@ -1,4 +1,5 @@
// //
use derive_more::derive::From; use derive_more::derive::From;
/// Represents a error accessing the network. /// Represents a error accessing the network.
@ -8,14 +9,14 @@ pub enum Error {
Request(String), Request(String),
#[display("Unexpected request: {0}", 0.to_string())] #[display("Unexpected request: {0}", 0.to_string())]
UnexpectedMockRequest(reqwest::Request), UnexpectedMockRequest(reqwest::Request),
RwLockLocked,
} }
impl std::error::Error for Error {} impl std::error::Error for Error {}
impl Clone for Error { impl Clone for Error {
fn clone(&self) -> Self { fn clone(&self) -> Self {
match self { match self {
Self::Reqwest(req) => Self::Request(req.to_string()), Self::Reqwest(req) => Self::Request(req.to_string()),
err => err.clone(), Self::Request(req) => Self::Request(req.clone()),
Self::UnexpectedMockRequest(_) => todo!(),
} }
} }
} }

View file

@ -1,15 +1,12 @@
// //
use std::{marker::PhantomData, ops::Deref, sync::RwLock}; use std::marker::PhantomData;
use super::{Error, Result}; use super::{Error, Result};
pub trait NetType {} pub trait NetType {}
#[derive(Debug)]
pub struct Mocked; pub struct Mocked;
impl NetType for Mocked {} impl NetType for Mocked {}
#[derive(Debug)]
pub struct Unmocked; pub struct Unmocked;
impl NetType for Unmocked {} impl NetType for Unmocked {}
@ -24,101 +21,44 @@ pub enum MatchOn {
} }
#[derive(Debug)] #[derive(Debug)]
struct Plan { pub struct Plan {
request: reqwest::Request, request: reqwest::Request,
response: reqwest::Response, response: reqwest::Response,
match_on: Vec<MatchOn>, match_on: Vec<MatchOn>,
} }
#[derive(Debug)] pub struct Net<T: NetType> {
pub struct Net {
inner: InnerNet<Unmocked>,
mock: Option<InnerNet<Mocked>>,
}
impl Net {
// constructors
pub(super) const fn new() -> Self {
Self {
inner: InnerNet::<Unmocked>::new(),
mock: None,
}
}
pub(super) const fn mock() -> MockNet {
MockNet {
inner: InnerNet::<Mocked>::new(),
}
}
}
impl Net {
// public interface
pub fn client(&self) -> reqwest::Client {
self.inner.client()
}
pub async fn send(&self, request: reqwest::RequestBuilder) -> Result<reqwest::Response> {
match &self.mock {
Some(mock) => mock.send(request).await,
None => self.inner.send(request).await,
}
}
}
#[derive(Debug)]
pub struct MockNet {
inner: InnerNet<Mocked>,
}
impl Deref for MockNet {
type Target = InnerNet<Mocked>;
fn deref(&self) -> &Self::Target {
&self.inner
}
}
impl From<MockNet> for Net {
fn from(mock_net: MockNet) -> Self {
Self {
inner: InnerNet::<Unmocked>::new(),
mock: Some(mock_net.inner),
}
}
}
#[derive(Debug)]
pub struct InnerNet<T: NetType> {
_type: PhantomData<T>, _type: PhantomData<T>,
plans: RwLock<Plans>, plans: Plans,
} }
impl InnerNet<Unmocked> { impl Net<Unmocked> {
const fn new() -> Self { pub(crate) const fn new() -> Self {
Self { Self {
_type: PhantomData, _type: PhantomData,
plans: RwLock::new(vec![]), plans: vec![],
} }
} }
pub async fn send(&self, request: reqwest::RequestBuilder) -> Result<reqwest::Response> { pub async fn send(&mut self, request: reqwest::RequestBuilder) -> Result<reqwest::Response> {
request.send().await.map_err(Error::from) request.send().await.map_err(Error::from)
} }
} }
impl<T: NetType> InnerNet<T> { impl<T: NetType> Net<T> {
pub fn client(&self) -> reqwest::Client { pub fn client(&self) -> reqwest::Client {
Default::default() Default::default()
} }
} }
impl InnerNet<Mocked> { impl Net<Mocked> {
const fn new() -> Self { pub(crate) const fn new() -> Self {
Self { Self {
_type: PhantomData, _type: PhantomData,
plans: RwLock::new(vec![]), plans: vec![],
} }
} }
pub async fn send(&mut self, request: reqwest::RequestBuilder) -> Result<reqwest::Response> {
pub async fn send(&self, request: reqwest::RequestBuilder) -> Result<reqwest::Response> {
let request = request.build()?; let request = request.build()?;
let read_plans = self.plans.read().map_err(|_| Error::RwLockLocked)?; let index = self.plans.iter().position(|plan| {
let index = read_plans.iter().position(|plan| {
// METHOD // METHOD
(if plan.match_on.contains(&MatchOn::Method) { (if plan.match_on.contains(&MatchOn::Method) {
plan.request.method() == request.method() plan.request.method() == request.method()
@ -148,12 +88,8 @@ impl InnerNet<Mocked> {
true true
}) })
}); });
drop(read_plans);
match index { match index {
Some(i) => { Some(i) => Ok(self.plans.remove(i).response),
let mut write_plans = self.plans.write().map_err(|_| Error::RwLockLocked)?;
Ok(write_plans.remove(i).response)
}
None => Err(Error::UnexpectedMockRequest(request)), None => Err(Error::UnexpectedMockRequest(request)),
} }
} }
@ -163,7 +99,7 @@ impl InnerNet<Mocked> {
Default::default() Default::default()
} }
pub fn on(&self, request: reqwest::Request) -> OnRequest { pub fn on(&mut self, request: reqwest::Request) -> OnRequest {
OnRequest { OnRequest {
net: self, net: self,
request, request,
@ -172,37 +108,30 @@ impl InnerNet<Mocked> {
} }
fn _on( fn _on(
&self, &mut self,
request: reqwest::Request, request: reqwest::Request,
response: reqwest::Response, response: reqwest::Response,
match_on: Vec<MatchOn>, match_on: Vec<MatchOn>,
) -> Result<()> { ) {
let mut write_plans = self.plans.write().map_err(|_| Error::RwLockLocked)?; self.plans.push(Plan {
write_plans.push(Plan {
request, request,
response, response,
match_on, match_on,
}); })
Ok(())
} }
pub fn reset(&self) -> Result<()> { pub fn reset(&mut self) {
let mut write_plans = self.plans.write().map_err(|_| Error::RwLockLocked)?; self.plans = vec![];
write_plans.clear();
Ok(())
} }
} }
impl<T: NetType> Drop for InnerNet<T> { impl<T: NetType> Drop for Net<T> {
fn drop(&mut self) { fn drop(&mut self) {
let Ok(read_plans) = self.plans.read() else { assert!(self.plans.is_empty())
return;
};
assert!(read_plans.is_empty())
} }
} }
pub struct OnRequest<'net> { pub struct OnRequest<'net> {
net: &'net InnerNet<Mocked>, net: &'net mut Net<Mocked>,
request: reqwest::Request, request: reqwest::Request,
match_on: Vec<MatchOn>, match_on: Vec<MatchOn>,
} }
@ -214,7 +143,7 @@ impl<'net> OnRequest<'net> {
match_on, match_on,
} }
} }
pub fn respond(self, response: reqwest::Response) -> Result<()> { pub fn respond(self, response: reqwest::Response) {
self.net._on(self.request, response, self.match_on) self.net._on(self.request, response, self.match_on)
} }
} }

View file

@ -1,11 +1,11 @@
use assert2::let_assert; use assert2::let_assert;
// //
use kxio::net::{Error, MatchOn, Net}; use kxio::net::{Error, MatchOn};
#[tokio::test] #[tokio::test]
async fn test_get_url() { async fn test_get_url() {
//given //given
let net = kxio::net::mock(); let mut net = kxio::net::mock();
let client = net.client(); let client = net.client();
let url = "https://www.example.com"; let url = "https://www.example.com";
@ -16,15 +16,10 @@ async fn test_get_url() {
.body("Get OK") .body("Get OK")
.expect("request body"); .expect("request body");
net.on(request) net.on(request).respond(my_response.into());
.respond(my_response.into())
.expect("on request, respond");
//when //when
let response = Net::from(net) let response = net.send(client.get(url)).await.expect("response");
.send(client.get(url))
.await
.expect("response");
//then //then
assert_eq!(response.status(), http::StatusCode::OK); assert_eq!(response.status(), http::StatusCode::OK);
@ -34,7 +29,7 @@ async fn test_get_url() {
#[tokio::test] #[tokio::test]
async fn test_get_wrong_url() { async fn test_get_wrong_url() {
//given //given
let net = kxio::net::mock(); let mut net = kxio::net::mock();
let client = net.client(); let client = net.client();
let url = "https://www.example.com"; let url = "https://www.example.com";
@ -45,9 +40,7 @@ async fn test_get_wrong_url() {
.body("Get OK") .body("Get OK")
.expect("request body"); .expect("request body");
net.on(request) net.on(request).respond(my_response.into());
.respond(my_response.into())
.expect("on request, respond");
//when //when
let_assert!( let_assert!(
@ -59,13 +52,13 @@ async fn test_get_wrong_url() {
assert_eq!(invalid_request.url().to_string(), "https://some.other.url/"); assert_eq!(invalid_request.url().to_string(), "https://some.other.url/");
// remove pending unmatched request - we never meant to match against it // remove pending unmatched request - we never meant to match against it
net.reset().expect("reset"); net.reset();
} }
#[tokio::test] #[tokio::test]
async fn test_post_url() { async fn test_post_url() {
//given //given
let net = kxio::net::mock(); let mut net = kxio::net::mock();
let client = net.client(); let client = net.client();
let url = "https://www.example.com"; let url = "https://www.example.com";
@ -76,15 +69,10 @@ async fn test_post_url() {
.body("Post OK") .body("Post OK")
.expect("request body"); .expect("request body");
net.on(request) net.on(request).respond(my_response.into());
.respond(my_response.into())
.expect("on request, respond");
//when //when
let response = Net::from(net) let response = net.send(client.post(url)).await.expect("reponse");
.send(client.post(url))
.await
.expect("reponse");
//then //then
assert_eq!(response.status(), http::StatusCode::OK); assert_eq!(response.status(), http::StatusCode::OK);
@ -94,7 +82,7 @@ async fn test_post_url() {
#[tokio::test] #[tokio::test]
async fn test_post_by_method() { async fn test_post_by_method() {
//given //given
let net = kxio::net::mock(); let mut net = kxio::net::mock();
let client = net.client(); let client = net.client();
let url = "https://www.example.com"; let url = "https://www.example.com";
@ -110,12 +98,11 @@ async fn test_post_by_method() {
MatchOn::Method, MatchOn::Method,
// MatchOn::Url // MatchOn::Url
]) ])
.respond(my_response.into()) .respond(my_response.into());
.expect("on request, respond");
//when //when
// This request is a different url - but should still match // This request is a different url - but should still match
let response = Net::from(net) let response = net
.send(client.post("https://some.other.url")) .send(client.post("https://some.other.url"))
.await .await
.expect("response"); .expect("response");
@ -128,7 +115,7 @@ async fn test_post_by_method() {
#[tokio::test] #[tokio::test]
async fn test_post_by_url() { async fn test_post_by_url() {
//given //given
let net = kxio::net::mock(); let mut net = kxio::net::mock();
let client = net.client(); let client = net.client();
let url = "https://www.example.com"; let url = "https://www.example.com";
@ -144,15 +131,11 @@ async fn test_post_by_url() {
// MatchOn::Method, // MatchOn::Method,
MatchOn::Url, MatchOn::Url,
]) ])
.respond(my_response.into()) .respond(my_response.into());
.expect("on request, respond");
//when //when
// This request is a GET, not POST - but should still match // This request is a GET, not POST - but should still match
let response = Net::from(net) let response = net.send(client.get(url)).await.expect("response");
.send(client.get(url))
.await
.expect("response");
//then //then
assert_eq!(response.status(), http::StatusCode::OK); assert_eq!(response.status(), http::StatusCode::OK);
@ -162,7 +145,7 @@ async fn test_post_by_url() {
#[tokio::test] #[tokio::test]
async fn test_post_by_body() { async fn test_post_by_body() {
//given //given
let net = kxio::net::mock(); let mut net = kxio::net::mock();
let client = net.client(); let client = net.client();
let url = "https://www.example.com"; let url = "https://www.example.com";
@ -183,12 +166,11 @@ async fn test_post_by_body() {
// MatchOn::Url // MatchOn::Url
MatchOn::Body, MatchOn::Body,
]) ])
.respond(my_response.into()) .respond(my_response.into());
.expect("on request, respond");
//when //when
// This request is a GET, not POST - but should still match // This request is a GET, not POST - but should still match
let response = Net::from(net) let response = net
.send(client.get("https://some.other.url").body("match on body")) .send(client.get("https://some.other.url").body("match on body"))
.await .await
.expect("response"); .expect("response");
@ -204,7 +186,7 @@ async fn test_post_by_body() {
#[tokio::test] #[tokio::test]
async fn test_post_by_headers() { async fn test_post_by_headers() {
//given //given
let net = kxio::net::mock(); let mut net = kxio::net::mock();
let client = net.client(); let client = net.client();
let url = "https://www.example.com"; let url = "https://www.example.com";
@ -226,12 +208,11 @@ async fn test_post_by_headers() {
// MatchOn::Url // MatchOn::Url
MatchOn::Headers, MatchOn::Headers,
]) ])
.respond(my_response.into()) .respond(my_response.into());
.expect("on request, respond");
//when //when
// This request is a GET, not POST - but should still match // This request is a GET, not POST - but should still match
let response = Net::from(net) let response = net
.send( .send(
client client
.get("https://some.other.url") .get("https://some.other.url")
@ -253,7 +234,7 @@ async fn test_post_by_headers() {
#[should_panic] #[should_panic]
async fn test_unused_post() { async fn test_unused_post() {
//given //given
let net = kxio::net::mock(); let mut net = kxio::net::mock();
let client = net.client(); let client = net.client();
let url = "https://www.example.com"; let url = "https://www.example.com";
@ -264,13 +245,11 @@ async fn test_unused_post() {
.body("Post OK") .body("Post OK")
.expect("request body"); .expect("request body");
net.on(request) net.on(request).respond(my_response.into());
.respond(my_response.into())
.expect("on request, respond");
//when //when
// don't send the planned request // don't send the planned request
// let _response = Net::from(net).send(client.post(url)).await.expect("send"); // let _response = net.send(client.post(url)).await.expect("send");
//then //then
// Drop implementation for net should panic // Drop implementation for net should panic