Compare commits

...

3 commits

Author SHA1 Message Date
989233a2ca refactor(net): remove inner from Net 2024-11-11 21:37:56 +00:00
3c50dbd414 doc(net): added 2024-11-11 21:37:56 +00:00
87c67c97d0 feat(net): cleaner mock.on syntax
OTHER
2024-11-11 07:41:41 +00:00
8 changed files with 697 additions and 225 deletions

View file

@ -15,7 +15,7 @@ file system and network operations.
The Filesystem module offers a clean abstraction over `std::fs`, the standard The Filesystem module offers a clean abstraction over `std::fs`, the standard
file system operations. For comprehensive documentation and usage examples, file system operations. For comprehensive documentation and usage examples,
please refer to the <https://docs.rs/kxio/latest/kxio/fs/>. please refer to <https://docs.rs/kxio/latest/kxio/fs/>.
### Key Filesystem Features: ### Key Filesystem Features:

View file

@ -114,14 +114,13 @@ 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: http::Response<&str> = let response = mock_net.response().body("contents");
mock_net.response().body("contents").expect("response body"); let request = mock_net.client().get(url);
let request = mock_net.client().get(url).build().expect("request");
mock_net mock_net
.on(request) .on(request)
// By default, the METHOD and URL must match, equivalent to: // By default, the METHOD and URL must match, equivalent to:
//.match_on(vec![MatchOn::Method, MatchOn::Url]) //.match_on(vec![MatchOn::Method, MatchOn::Url])
.respond(response) .respond_with_body(response)
.expect("mock"); .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
@ -148,6 +147,6 @@ 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().expect("reset mock"); mock_net.reset();
} }
} }

View file

@ -10,6 +10,12 @@ build:
cargo test --example get cargo test --example get
cargo mutants --jobs 4 cargo mutants --jobs 4
doc-test:
cargo doc
cargo test
cargo test --example get
install-hooks: install-hooks:
@echo "Installing git hooks" @echo "Installing git hooks"
git config core.hooksPath .git-hooks git config core.hooksPath .git-hooks

View file

@ -1,4 +1,68 @@
// //! # kxio
//!
//! `kxio` is a Rust library that provides injectable `FileSystem` and `Network`
//! resources to enhance the testability of your code. By abstracting system-level
//! interactions, `kxio` enables easier mocking and testing of code that relies on
//! file system and network operations.
//!
//! ## Features
//!
//! - Filesystem Abstraction
//! - Network Abstraction
//! - Enhanced Testability
//!
//! ## Filesystem
//!
//! The Filesystem module offers a clean abstraction over `std::fs`, the standard
//! file system operations. For comprehensive documentation and usage examples,
//! please refer to <https://docs.rs/kxio/latest/kxio/fs/>.
//!
//! ### Key Filesystem Features:
//!
//! - File reading and writing
//! - Directory operations
//! - File metadata access
//! - Fluent API for operations like `.reader().bytes()`
//!
//! ## Network
//!
//! The Network module offers a testable interface over the `reqwest` crate. For
//! comprehensive documentation and usage examples, please refer to
//! <https://docs.rs/kxio/latest/kxio/net/>
//!
//! ## Getting Started
//!
//! Add `kxio` to your `Cargo.toml`:
//!
//! ```toml
//! [dependencies]
//! kxio = "x.y.z"
//! ```
//!
//! ## Usage
//!
//! See the example [get.rs](https://git.kemitix.net/kemitix/kxio/src/branch/main/examples/get.rs) for an annotated example on how to use the `kxio` library.
//! It covers both the `net` and `fs` modules.
//!
//! ## Development
//!
//! - The project uses [Cargo Mutants](https://crates.io/crates/cargo-mutants) for mutation testing.
//! - [ForgeJo Actions](https://forgejo.org/docs/next/user/actions/) are used for continuous testing and linting.
//!
//! ## Contributing
//!
//! Contributions are welcome! Please check our [issue tracker](https://git.kemitix.net/kemitix/kxio/issues) for open tasks or
//! submit your own ideas.
//!
//! ## License
//!
//! This project is licensed under the terms specified in the `LICENSE` file in the
//! repository root.
//!
//! ---
//!
//! For more information, bug reports, or feature requests, please visit our [repository](https://git.kemitix.net/kemitix/kxio).
pub mod fs; pub mod fs;
pub mod net; pub mod net;
mod result; mod result;

View file

@ -1,13 +1,303 @@
//! Provides a generic interface for network operations. //! Provides a generic interface for network operations.
//! //!
//! //!
//! Provides a testable interface over the [reqwest] crate.
//!
//! ## Overview
//!
//! The `net` module provides a testable interface for network operations.
//! It includes implementations for both real network interactions and mocked network operations for testing purposes.
//!
//! ## Key methods and types:
//!
//! - [kxio::net::new()][new()]: Creates a new `Net` instance
//! - [kxio::net::mock()][mock()]: Creates a new `MockNet` instance for use in tests
//! - [Error]: enum for network-related errors
//! - [Result]: an alias for `core::result::Result<T, Error>`
//! - [Net]: struct for real and mocked network operations
//! - [MockNet]: struct for defining behaviours of mocked network operations
//!
//! ## Usage
//!
//! Write your program to take a reference to [Net].
//!
//! Use the [Net::client] functionto create a [reqwest::RequestBuilder] which you should then pass to the [Net::send] method.
//! This is rather than building the request and calling its own `send` method, doing so would result in the network request being sent, even under-test.
//!
//! ```rust
//! use kxio::net;
//! async fn get_example(net: &net::Net) -> net::Result<()> {
//! let response = net.send(net.client().get("https://example.com")).await?;
//! ///...
//! Ok(())
//! }
//! ```
//!
//! ### Real Network Operations
//!
//! In your production code you will want to make real network requests.
//!
//! Construct a [Net] using [kxio::net::new()][new()]. Then pass as a reference to your program.
//!
//! ```rust
//! use kxio::net;
//! # #[tokio::main]
//! # async fn main() -> net::Result<()> {
//! let net = net::new();
//!
//! get_example(&net).await?;
//! # Ok(())
//! # }
//! # async fn get_example(net: &net::Net) -> net::Result<()> {Ok(())}
//! ```
//!
//! ### Mocked Network Operations
//!
//! In your tests you will want to mock your network requests and responses.
//!
//! Construct a [MockNet] using [kxio::net::mock()][mock()].
//!
//! ```rust
//! use kxio::net;
//! let mock_net = net::mock();
//! ```
//!
//! Create a [reqwest::Client] using [MockNet::client()].
//!
//! ```rust
//! # let mock_net = kxio::net::mock();
//! let client = mock_net.client();
//! // this is the same as:
//! let client = reqwest::Client::new();
//! ```
//!
//! Define the expected responses for each request, using the [MockNet::on],
//! that you expect you program to make during the test. You can choose what each request should be
//! matched against. The default is to the match when both the Method and Url are the same.
//!
//! ```rust
//! use kxio::net;
//! use kxio::net::MatchOn;
//!
//! # #[tokio::main]
//! # async fn main() -> net::Result<()> {
//! # let mock_net = net::mock();
//! # let client = mock_net.client();
//! mock_net.on(client.get("https://example.com"))
//! .match_on(vec![
//! MatchOn::Url,
//! MatchOn::Method
//! ])
//! .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();
//! # Ok(())
//! # }
//! ```
//!
//! All [MatchOn] options:
//! - [MatchOn::Method] (default)
//! - [MatchOn::Url] (default)
//! - [MatchOn::Headers]
//! - [MatchOn::Body].
//!
//! Once you have defined all your expected responses, convert the [MockNet] into a [Net].
//!
//! ```rust
//! # use kxio::net;
//! # let mock_net = net::mock();
//! let net: net::Net = mock_net.into();
//! // or
//! # let mock_net = net::mock();
//! let net = net::Net::from(mock_net);
//! ```
//!
//! Now you can pass a reference to `net` to your program.
//!
//! ```rust
//! # use kxio::net;
//! # #[tokio::main]
//! # async fn main() -> net::Result<()> {
//! # let mock_net = net::mock();
//! # let net = net::Net::from(mock_net);
//! get_example(&net).await?;
//! # Ok(())
//! # }
//! # async fn get_example(net: &net::Net) -> net::Result<()> {Ok(())}
//! ```
//!
//! When your test is finished, the [MockNet] will check that all the expected requests were
//! actually made. If there were any missed, then the test will [panic].
//!
//! If you don't want this to happen, then call [MockNet::reset] before your test finishes.
//! You will need to recover the [MockNet] from the [Net].
//!
//! ```rust
//! # use kxio::net;
//! # let mock_net = net::mock();
//! # let net = net::Net::from(mock_net);
//! let mock_net = kxio::net::MockNet::try_from(net).expect("recover mock");
//! mock_net.reset();
//! ````
//!
//! ## Error Handling
//!
//! The module uses a custom [Result] type that wraps `core::result::Result` with the custom [Error] enum,
//! allowing for specific error handling related to network operations.
//! Provides a testable interface over the [reqwest] crate.
//!
//! ## Overview
//!
//! The `net` module provides a testable interface for network operations.
//! It includes implementations for both real network interactions and mocked network operations for testing purposes.
//!
//! ## Key methods and types:
//!
//! - [kxio::net::new()][new()]: Creates a new `Net` instance
//! - [kxio::net::mock()][mock()]: Creates a new `MockNet` instance for use in tests
//! - [Error]: enum for network-related errors
//! - [Result]: an alias for `core::result::Result<T, Error>`
//! - [Net]: struct for real and mocked network operations
//! - [MockNet]: struct for defining behaviours of mocked network operations
//!
//! ## Usage
//!
//! Write your program to take a reference to [Net].
//!
//! Use the [Net::client] functionto create a [reqwest::RequestBuilder] which you should then pass to the [Net::send] method.
//! This is rather than building the request and calling its own `send` method, doing so would result in the network request being sent, even under-test.
//!
//! ```rust
//! use kxio::net;
//! async fn get_example(net: &net::Net) -> net::Result<()> {
//! let response = net.send(net.client().get("https://example.com")).await?;
//! ///...
//! Ok(())
//! }
//! ```
//!
//! ### Real Network Operations
//!
//! In your production code you will want to make real network requests.
//!
//! Construct a [Net] using [kxio::net::new()][new()]. Then pass as a reference to your program.
//!
//! ```rust
//! use kxio::net;
//! # #[tokio::main]
//! # async fn main() -> net::Result<()> {
//! let net = net::new();
//!
//! get_example(&net).await?;
//! # Ok(())
//! # }
//! # async fn get_example(net: &net::Net) -> net::Result<()> {Ok(())}
//! ```
//!
//! ### Mocked Network Operations
//!
//! In your tests you will want to mock your network requests and responses.
//!
//! Construct a [MockNet] using [kxio::net::mock()][mock()].
//!
//! ```rust
//! use kxio::net;
//! let mock_net = net::mock();
//! ```
//!
//! Create a [reqwest::Client] using [MockNet::client()].
//!
//! ```rust
//! # let mock_net = kxio::net::mock();
//! let client = mock_net.client();
//! // this is the same as:
//! let client = reqwest::Client::new();
//! ```
//!
//! Define the expected responses for each request, using the [MockNet::on],
//! that you expect you program to make during the test. You can choose what each request should be
//! matched against. The default is to the match when both the Method and Url are the same.
//!
//! ```rust
//! use kxio::net;
//! use kxio::net::MatchOn;
//!
//! # #[tokio::main]
//! # async fn main() -> net::Result<()> {
//! # let mock_net = net::mock();
//! # let client = mock_net.client();
//! mock_net.on(client.get("https://example.com"))
//! .match_on(vec![
//! MatchOn::Url,
//! MatchOn::Method
//! ])
//! .respond_with_body(mock_net.response().status(200).body("Mocked response"))?;
//! # mock_net.reset();
//! # Ok(())
//! # }
//! ```
//!
//! All [MatchOn] options:
//! - [MatchOn::Method] (default)
//! - [MatchOn::Url] (default)
//! - [MatchOn::Headers]
//! - [MatchOn::Body].
//!
//! Once you have defined all your expected responses, convert the [MockNet] into a [Net].
//!
//! ```rust
//! # use kxio::net;
//! # let mock_net = net::mock();
//! let net: net::Net = mock_net.into();
//! // or
//! # let mock_net = net::mock();
//! let net = net::Net::from(mock_net);
//! ```
//!
//! Now you can pass a reference to `net` to your program.
//!
//! ```rust
//! # use kxio::net;
//! # #[tokio::main]
//! # async fn main() -> net::Result<()> {
//! # let mock_net = net::mock();
//! # let net = net::Net::from(mock_net);
//! get_example(&net).await?;
//! # Ok(())
//! # }
//! # async fn get_example(net: &net::Net) -> net::Result<()> {Ok(())}
//! ```
//!
//! When your test is finished, the [MockNet] will check that all the expected requests were
//! actually made. If there were any missed, then the test will [panic].
//!
//! If you don't want this to happen, then call [MockNet::reset] before your test finishes.
//! You will need to recover the [MockNet] from the [Net].
//!
//! ```rust
//! # use kxio::net;
//! # let mock_net = net::mock();
//! # let net = net::Net::from(mock_net);
//! let mock_net = kxio::net::MockNet::try_from(net).expect("recover mock");
//! mock_net.reset();
//! ````
//!
//! ## Error Handling
//!
//! The module uses a custom [Result] type that wraps `core::result::Result` with the custom [Error] enum,
//! allowing for specific error handling related to network operations.
mod result; mod result;
mod system; mod system;
pub use result::{Error, Result}; pub use result::{Error, Result};
pub use system::{MatchOn, MockNet, Net}; pub use system::{MatchOn, MockNet, Net, OnRequest};
/// Creates a new `Net`. /// Creates a new `Net`.
pub const fn new() -> Net { pub const fn new() -> Net {

View file

@ -1,15 +1,32 @@
// //
use derive_more::derive::From; use derive_more::derive::From;
/// Represents a error accessing the network. /// The Errors that may occur within [kxio::net][crate::net].
#[derive(Debug, From, derive_more::Display)] #[derive(Debug, From, derive_more::Display)]
pub enum Error { pub enum Error {
/// The Errors that may occur when processing a `Request`.
///
/// Note: Errors may include the full URL used to make the `Request`. If the URL
/// contains sensitive information (e.g. an API key as a query parameter), be
/// sure to remove it ([`without_url`](reqwest::Error::without_url))
Reqwest(reqwest::Error), Reqwest(reqwest::Error),
/// The Errors that may occur when processing a `Request`.
///
/// The cause has been converted to a String.
Request(String), Request(String),
/// 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),
/// There was an error accessing the list of expected requests.
RwLockLocked, RwLockLocked,
/// There was an error making a network request.
Http(http::Error), Http(http::Error),
/// Attempted to extract a [MockNet][super::MockNet] from a [Net][super::Net] that does not contain one.
NetIsNotAMock, NetIsNotAMock,
} }
impl std::error::Error for Error {} impl std::error::Error for Error {}
@ -22,7 +39,7 @@ impl Clone for Error {
} }
} }
/// Represents a success or a failure. /// Represents a success or a failure within [kxio::net][crate::net].
/// ///
/// Any failure is related to `std::io`, a Path Traversal /// Any failure is related to `std::io`, a Path Traversal
/// (i.e. trying to escape the base of the `FileSystem`), /// (i.e. trying to escape the base of the `FileSystem`),

View file

@ -1,30 +1,32 @@
// //
use std::{marker::PhantomData, sync::RwLock}; use std::cell::RefCell;
use reqwest::Client; use reqwest::Client;
use super::{Error, Result}; use super::{Error, Result};
pub trait NetType {} /// A list of planned requests and responses
#[derive(Debug)]
pub struct Mocked;
impl NetType for Mocked {}
#[derive(Debug)]
pub struct Unmocked;
impl NetType for Unmocked {}
type Plans = Vec<Plan>; type Plans = Vec<Plan>;
/// The different ways to match a request.
#[derive(Debug, PartialEq, Eq)] #[derive(Debug, PartialEq, Eq)]
pub enum MatchOn { pub enum MatchOn {
/// The request must have a specific HTTP Request Method.
Method, Method,
/// The request must have a specific URL.
Url, Url,
/// The request must have a specify HTTP Body.
Body, Body,
/// The request must have a specific set of HTTP Headers.
Headers, Headers,
} }
/// A planned request and the response to return
///
/// Contains a list of the criteria that a request must meet before being considered a match.
#[derive(Debug)] #[derive(Debug)]
struct Plan { struct Plan {
request: reqwest::Request, request: reqwest::Request,
@ -32,125 +34,66 @@ struct Plan {
match_on: Vec<MatchOn>, match_on: Vec<MatchOn>,
} }
#[derive(Debug)] /// An abstraction for the network
pub struct Net { pub struct Net {
inner: InnerNet<Unmocked>, plans: Option<RefCell<Plans>>,
mock: Option<InnerNet<Mocked>>,
} }
impl Net { impl Net {
// constructors /// Creates a new unmocked [Net] for creating real network requests.
pub(super) const fn new() -> Self { pub(super) const fn new() -> Self {
Self { Self { plans: None }
inner: InnerNet::<Unmocked>::new(),
mock: None,
}
} }
/// Creats a new [MockNet] for use in tests.
pub(super) const fn mock() -> MockNet { pub(super) const fn mock() -> MockNet {
MockNet { MockNet {
inner: InnerNet::<Mocked>::new(), plans: RefCell::new(vec![]),
} }
} }
} }
impl Net { impl Net {
// public interface /// Helper to create a default [reqwest::Client].
///
/// # Example
///
/// ```rust
/// # use kxio::net::Result;
/// let net = kxio::net::new();
/// let client = net.client();
/// let request = client.get("https://hyper.rs");
/// ```
pub fn client(&self) -> reqwest::Client { pub fn client(&self) -> reqwest::Client {
Default::default() Default::default()
} }
/// Constructs the Request and sends it to the target URL, returning a
/// future Response.
///
/// # Errors
///
/// This method fails if there was an error while sending request,
/// redirect loop was detected or redirect limit was exhausted.
///
/// # Example
///
/// ```no_run
/// # use kxio::net::Result;
/// # async fn run() -> Result<()> {
/// let net = kxio::net::new();
/// let request = net.client().get("https://hyper.rs");
/// let response = net.send(request).await?;
/// # Ok(())
/// # }
/// ```
pub async fn send( pub async fn send(
&self, &self,
request: impl Into<reqwest::RequestBuilder>, request: impl Into<reqwest::RequestBuilder>,
) -> Result<reqwest::Response> { ) -> Result<reqwest::Response> {
match &self.mock { let Some(plans) = &self.plans else {
Some(mock) => mock.send(request).await, return request.into().send().await.map_err(Error::from);
None => self.inner.send(request).await, };
}
}
}
impl TryFrom<Net> for MockNet {
type Error = super::Error;
fn try_from(net: Net) -> std::result::Result<Self, Self::Error> {
match net.mock {
Some(inner_mock) => Ok(MockNet { inner: inner_mock }),
None => Err(Self::Error::NetIsNotAMock),
}
}
}
#[derive(Debug)]
pub struct MockNet {
inner: InnerNet<Mocked>,
}
impl MockNet {
pub fn client(&self) -> Client {
Default::default()
}
pub fn on(&self, request: impl Into<reqwest::Request>) -> OnRequest {
self.inner.on(request)
}
/// Creates a [http::response::Builder] to be extended and returned by a mocked network request.
pub fn response(&self) -> http::response::Builder {
Default::default()
}
pub async fn send(
&self,
request: impl Into<reqwest::RequestBuilder>,
) -> Result<reqwest::Response> {
self.inner.send(request).await
}
pub fn reset(&self) -> Result<()> {
self.inner.reset()
}
}
impl From<MockNet> for Net {
fn from(mock_net: MockNet) -> Self {
Self {
inner: InnerNet::<Unmocked>::new(),
// keep the original `inner` around to allow it's Drop impelmentation to run when we go
// out of scope at the end of the test
mock: Some(mock_net.inner),
}
}
}
#[derive(Debug)]
pub struct InnerNet<T: NetType> {
_type: PhantomData<T>,
plans: RwLock<Plans>,
}
impl InnerNet<Unmocked> {
const fn new() -> Self {
Self {
_type: PhantomData,
plans: RwLock::new(vec![]),
}
}
pub async fn send(
&self,
request: impl Into<reqwest::RequestBuilder>,
) -> Result<reqwest::Response> {
request.into().send().await.map_err(Error::from)
}
}
impl InnerNet<Mocked> {
const fn new() -> Self {
Self {
_type: PhantomData,
plans: RwLock::new(vec![]),
}
}
pub async fn send(
&self,
request: impl Into<reqwest::RequestBuilder>,
) -> Result<reqwest::Response> {
let request = request.into().build()?; let request = request.into().build()?;
let read_plans = self.plans.read().map_err(|_| Error::RwLockLocked)?; let index = plans.borrow().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()
@ -180,21 +123,93 @@ impl InnerNet<Mocked> {
true true
}) })
}); });
drop(read_plans);
match index { match index {
Some(i) => { Some(i) => {
let mut write_plans = self.plans.write().map_err(|_| Error::RwLockLocked)?; let response = plans.borrow_mut().remove(i).response;
Ok(write_plans.remove(i).response) Ok(response)
} }
None => Err(Error::UnexpectedMockRequest(request)), None => Err(Error::UnexpectedMockRequest(request)),
} }
} }
}
impl TryFrom<Net> for MockNet {
type Error = super::Error;
pub fn on(&self, request: impl Into<reqwest::Request>) -> OnRequest { fn try_from(net: Net) -> std::result::Result<Self, Self::Error> {
OnRequest { match &net.plans {
net: self, Some(plans) => Ok(MockNet {
request: request.into(), plans: RefCell::new(plans.take()),
match_on: vec![MatchOn::Method, MatchOn::Url], }),
None => Err(Self::Error::NetIsNotAMock),
}
}
}
/// A struct for defining the expected requests and their responses that should be made
/// during a test.
///
/// When the [MockNet] goes out of scope it will verify that all expected requests were consumed,
/// otherwise it will `panic`.
///
/// # Example
///
/// ```rust
/// # use kxio::net::Result;
/// # fn run() -> Result<()> {
/// let mock_net = kxio::net::mock();
/// let client = mock_net.client();
/// // define an expected requet, and the response that should be returned
/// mock_net.on(client.get("https://hyper.rs"))
/// .respond_with_body(mock_net.response().status(200).body("Ok"))?;
/// let net: kxio::net::Net = mock_net.into();
/// // use 'net' in your program, by passing it as a reference
///
/// // In some rare cases you don't want to assert that all expected requests were made.
/// // You should recover the `MockNet` from the `Net` and `MockNet::reset` it.
/// let mock_net = kxio::net::MockNet::try_from(net)?;
/// mock_net.reset(); // only if explicitly needed
/// # Ok(())
/// # }
/// ```
pub struct MockNet {
plans: RefCell<Plans>,
}
impl MockNet {
/// Helper to create a default [reqwest::Client].
///
/// # Example
///
/// ```rust
/// let mock_net = kxio::net::mock();
/// let client = mock_net.client();
/// let request = client.get("https://hyper.rs");
/// ```
pub fn client(&self) -> Client {
Default::default()
}
/// Specify an expected request.
///
/// # Example
///
/// ```rust
/// # use kxio::net::Result;
/// # fn run() -> Result<()> {
/// let mock_net = kxio::net::mock();
/// let client = mock_net.client();
/// mock_net.on(client.get("https://hyper.rs"))
/// .respond_with_body(mock_net.response().status(200).body("Ok"))?;
/// # Ok(())
/// # }
/// ```
pub fn on(&self, request_builder: impl Into<reqwest::RequestBuilder>) -> OnRequest {
match request_builder.into().build() {
Ok(request) => OnRequest::Valid {
net: self,
request,
match_on: vec![MatchOn::Method, MatchOn::Url],
},
Err(err) => OnRequest::Error(err.into()),
} }
} }
@ -204,8 +219,7 @@ impl InnerNet<Mocked> {
response: reqwest::Response, response: reqwest::Response,
match_on: Vec<MatchOn>, match_on: Vec<MatchOn>,
) -> Result<()> { ) -> Result<()> {
let mut write_plans = self.plans.write().map_err(|_| Error::RwLockLocked)?; self.plans.borrow_mut().push(Plan {
write_plans.push(Plan {
request, request,
response, response,
match_on, match_on,
@ -213,35 +227,127 @@ impl InnerNet<Mocked> {
Ok(()) Ok(())
} }
pub fn reset(&self) -> Result<()> { /// Creates a [http::response::Builder] to be extended and returned by a mocked network request.
let mut write_plans = self.plans.write().map_err(|_| Error::RwLockLocked)?; pub fn response(&self) -> http::response::Builder {
write_plans.clear(); Default::default()
Ok(()) }
/// Clears all the expected requests and responses from the [MockNet].
///
/// When the [MockNet] goes out of scope it will assert that all expected requests and
/// responses were consumed. If there are any left unconsumed, then it will `panic`.
///
/// # Example
///
/// ```rust
/// # use kxio::net::Result;
/// # fn run() -> Result<()> {
/// # let mock_net = kxio::net::mock();
/// # let net: kxio::net::Net = mock_net.into();
/// let mock_net = kxio::net::MockNet::try_from(net)?;
/// mock_net.reset(); // only if explicitly needed
/// # Ok(())
/// # }
/// ```
pub fn reset(&self) {
self.plans.take();
} }
} }
impl<T: NetType> Drop for InnerNet<T> { impl From<MockNet> for Net {
fn drop(&mut self) { fn from(mock_net: MockNet) -> Self {
let Ok(read_plans) = self.plans.read() else { Self {
return; // keep the original `inner` around to allow it's Drop impelmentation to run when we go
}; // out of scope at the end of the test
assert!(read_plans.is_empty()) plans: Some(RefCell::new(mock_net.plans.take())),
}
} }
} }
pub struct OnRequest<'net> { impl Drop for MockNet {
net: &'net InnerNet<Mocked>, fn drop(&mut self) {
request: reqwest::Request, assert!(self.plans.borrow().is_empty())
match_on: Vec<MatchOn>, }
} }
impl<'net> OnRequest<'net> { impl Drop for Net {
pub fn match_on(self, match_on: Vec<MatchOn>) -> Self { fn drop(&mut self) {
Self { if let Some(plans) = &self.plans {
net: self.net, assert!(plans.borrow().is_empty())
request: self.request,
match_on,
} }
} }
pub fn respond(self, response: impl Into<reqwest::Response>) -> Result<()> { }
self.net._on(self.request, response.into(), self.match_on)
/// Intermediate struct used while declaring an expected request and its response.
pub enum OnRequest<'net> {
Valid {
net: &'net MockNet,
request: reqwest::Request,
match_on: Vec<MatchOn>,
},
Error(super::Error),
}
impl<'net> OnRequest<'net> {
/// Specify the criteria that a request should be compared against.
///
/// Given an candidate request, it will be matched against the current request if it has the
/// 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
}
}
/// Constructs the response to be returned when a request matched the criteria.
///
/// The response will have an empty HTTP Body.
///
/// Each request and response 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),
}
}
/// Constructs the response to be returned when a request matched the criteria.
///
/// Each request and response 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
T: Into<reqwest::Body>,
{
match body_result {
Ok(response) => match self {
OnRequest::Valid {
net,
request,
match_on,
} => net._on(request, response.into(), match_on),
OnRequest::Error(error) => Err(error),
},
Err(err) => Err(err.into()),
}
} }
} }

View file

@ -1,6 +1,6 @@
use assert2::let_assert; use assert2::let_assert;
// //
use kxio::net::{Error, MatchOn, Net}; use kxio::net::{Error, MatchOn, MockNet, Net};
#[tokio::test] #[tokio::test]
async fn test_get_url() { async fn test_get_url() {
@ -9,15 +9,11 @@ async fn test_get_url() {
let client = net.client(); let client = net.client();
let url = "https://www.example.com"; let url = "https://www.example.com";
let request = client.get(url).build().expect("build request"); let request = client.get(url);
let my_response = net let my_response = net.response().status(200).body("Get OK");
.response()
.status(200)
.body("Get OK")
.expect("request body");
net.on(request) net.on(request)
.respond(my_response) .respond_with_body(my_response)
.expect("on request, respond"); .expect("on request, respond");
//when //when
@ -34,21 +30,20 @@ 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 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).build().expect("build request"); let request = client.get(url);
let my_response = net let my_response = mock_net.response().status(200).body("Get OK");
.response()
.status(200)
.body("Get OK")
.expect("request body");
net.on(request) mock_net
.respond(my_response) .on(request)
.respond_with_body(my_response)
.expect("on request, respond"); .expect("on request, respond");
let net = Net::from(mock_net);
//when //when
let_assert!( let_assert!(
Err(Error::UnexpectedMockRequest(invalid_request)) = Err(Error::UnexpectedMockRequest(invalid_request)) =
@ -59,7 +54,8 @@ 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"); let mock_net = MockNet::try_from(net).expect("recover net");
mock_net.reset();
} }
#[tokio::test] #[tokio::test]
@ -69,15 +65,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).build().expect("build request"); let request = client.post(url);
let my_response = net let my_response = net.response().status(200).body("Post OK");
.response()
.status(200)
.body("Post OK")
.expect("request body");
net.on(request) net.on(request)
.respond(my_response) .respond_with_body(my_response)
.expect("on request, respond"); .expect("on request, respond");
//when //when
@ -98,12 +90,8 @@ async fn test_post_by_method() {
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).build().expect("build request"); let request = client.post(url);
let my_response = net let my_response = net.response().status(200);
.response()
.status(200)
.body("Post OK")
.expect("request body");
net.on(request) net.on(request)
.match_on(vec![ .match_on(vec![
@ -122,7 +110,7 @@ async fn test_post_by_method() {
//then //then
assert_eq!(response.status(), http::StatusCode::OK); assert_eq!(response.status(), http::StatusCode::OK);
assert_eq!(response.bytes().await.expect("response body"), "Post OK"); assert_eq!(response.bytes().await.expect("response body"), "");
} }
#[tokio::test] #[tokio::test]
@ -132,19 +120,15 @@ async fn test_post_by_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).build().expect("build request"); let request = client.post(url);
let my_response = net let my_response = net.response().status(200).body("Post OK");
.response()
.status(200)
.body("Post OK")
.expect("request body");
net.on(request) net.on(request)
.match_on(vec![ .match_on(vec![
// MatchOn::Method, // MatchOn::Method,
MatchOn::Url, MatchOn::Url,
]) ])
.respond(my_response) .respond_with_body(my_response)
.expect("on request, respond"); .expect("on request, respond");
//when //when
@ -166,16 +150,8 @@ async fn test_post_by_body() {
let client = net.client(); let client = net.client();
let url = "https://www.example.com"; let url = "https://www.example.com";
let request = client let request = client.post(url).body("match on body");
.post(url) let my_response = net.response().status(200).body("response body");
.body("match on body")
.build()
.expect("build request");
let my_response = net
.response()
.status(200)
.body("response body")
.expect("request body");
net.on(request) net.on(request)
.match_on(vec![ .match_on(vec![
@ -183,7 +159,7 @@ async fn test_post_by_body() {
// MatchOn::Url // MatchOn::Url
MatchOn::Body, MatchOn::Body,
]) ])
.respond(my_response) .respond_with_body(my_response)
.expect("on request, respond"); .expect("on request, respond");
//when //when
@ -208,17 +184,8 @@ async fn test_post_by_headers() {
let client = net.client(); let client = net.client();
let url = "https://www.example.com"; let url = "https://www.example.com";
let request = client let request = client.post(url).body("foo").header("test", "match");
.post(url) let my_response = net.response().status(200).body("response body");
.body("foo")
.header("test", "match")
.build()
.expect("build request");
let my_response = net
.response()
.status(200)
.body("response body")
.expect("request body");
net.on(request) net.on(request)
.match_on(vec![ .match_on(vec![
@ -226,7 +193,7 @@ async fn test_post_by_headers() {
// MatchOn::Url // MatchOn::Url
MatchOn::Headers, MatchOn::Headers,
]) ])
.respond(my_response) .respond_with_body(my_response)
.expect("on request, respond"); .expect("on request, respond");
//when //when
@ -251,23 +218,22 @@ async fn test_post_by_headers() {
#[tokio::test] #[tokio::test]
#[should_panic] #[should_panic]
async fn test_unused_post() { async fn test_unused_post_as_net() {
//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.post(url).build().expect("build request"); let request = client.post(url);
let my_response = net let my_response = mock_net.response().status(200).body("Post OK");
.response()
.status(200)
.body("Post OK")
.expect("request body");
net.on(request) mock_net
.respond(my_response) .on(request)
.respond_with_body(my_response)
.expect("on request, respond"); .expect("on request, respond");
let _net = Net::from(mock_net);
//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::from(net).send(client.post(url)).await.expect("send");
@ -275,3 +241,27 @@ async fn test_unused_post() {
//then //then
// Drop implementation for net should panic // Drop implementation for net should panic
} }
#[tokio::test]
#[should_panic]
async fn test_unused_post_as_mocknet() {
//given
let mock_net = kxio::net::mock();
let client = mock_net.client();
let url = "https://www.example.com";
let request = client.post(url);
let my_response = mock_net.response().status(200).body("Post OK");
mock_net
.on(request)
.respond_with_body(my_response)
.expect("on request, respond");
//when
// don't send the planned request
// let _response = Net::from(net).send(client.post(url)).await.expect("send");
//then
// Drop implementation for mock_net should panic
}