Compare commits

..

No commits in common. "989233a2cabbbca1670d684694dd66770c4115f5" and "aad02be6cb06f3f2968c52d38467df1948fffab0" have entirely different histories.

8 changed files with 222 additions and 694 deletions

View file

@ -15,7 +15,7 @@ file system and network operations.
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/>.
please refer to the <https://docs.rs/kxio/latest/kxio/fs/>.
### Key Filesystem Features:

View file

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

View file

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

View file

@ -1,68 +1,4 @@
//! # 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 net;
mod result;

View file

@ -1,303 +1,13 @@
//! 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 system;
pub use result::{Error, Result};
pub use system::{MatchOn, MockNet, Net, OnRequest};
pub use system::{MatchOn, MockNet, Net};
/// Creates a new `Net`.
pub const fn new() -> Net {

View file

@ -1,32 +1,15 @@
//
use derive_more::derive::From;
/// The Errors that may occur within [kxio::net][crate::net].
/// Represents a error accessing the network.
#[derive(Debug, From, derive_more::Display)]
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),
/// The Errors that may occur when processing a `Request`.
///
/// The cause has been converted to a String.
Request(String),
/// There was network request that doesn't match any that were expected
#[display("Unexpected request: {0}", 0.to_string())]
UnexpectedMockRequest(reqwest::Request),
/// There was an error accessing the list of expected requests.
RwLockLocked,
/// There was an error making a network request.
Http(http::Error),
/// Attempted to extract a [MockNet][super::MockNet] from a [Net][super::Net] that does not contain one.
NetIsNotAMock,
}
impl std::error::Error for Error {}
@ -39,7 +22,7 @@ impl Clone for Error {
}
}
/// Represents a success or a failure within [kxio::net][crate::net].
/// Represents a success or a failure.
///
/// Any failure is related to `std::io`, a Path Traversal
/// (i.e. trying to escape the base of the `FileSystem`),

View file

@ -1,32 +1,30 @@
//
use std::cell::RefCell;
use std::{marker::PhantomData, sync::RwLock};
use reqwest::Client;
use super::{Error, Result};
/// A list of planned requests and responses
pub trait NetType {}
#[derive(Debug)]
pub struct Mocked;
impl NetType for Mocked {}
#[derive(Debug)]
pub struct Unmocked;
impl NetType for Unmocked {}
type Plans = Vec<Plan>;
/// The different ways to match a request.
#[derive(Debug, PartialEq, Eq)]
pub enum MatchOn {
/// The request must have a specific HTTP Request Method.
Method,
/// The request must have a specific URL.
Url,
/// The request must have a specify HTTP Body.
Body,
/// The request must have a specific set of HTTP 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)]
struct Plan {
request: reqwest::Request,
@ -34,66 +32,125 @@ struct Plan {
match_on: Vec<MatchOn>,
}
/// An abstraction for the network
#[derive(Debug)]
pub struct Net {
plans: Option<RefCell<Plans>>,
inner: InnerNet<Unmocked>,
mock: Option<InnerNet<Mocked>>,
}
impl Net {
/// Creates a new unmocked [Net] for creating real network requests.
// constructors
pub(super) const fn new() -> Self {
Self { plans: None }
Self {
inner: InnerNet::<Unmocked>::new(),
mock: None,
}
}
/// Creats a new [MockNet] for use in tests.
pub(super) const fn mock() -> MockNet {
MockNet {
plans: RefCell::new(vec![]),
inner: InnerNet::<Mocked>::new(),
}
}
}
impl Net {
/// 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");
/// ```
// public interface
pub fn client(&self) -> reqwest::Client {
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(
&self,
request: impl Into<reqwest::RequestBuilder>,
) -> Result<reqwest::Response> {
let Some(plans) = &self.plans else {
return request.into().send().await.map_err(Error::from);
};
match &self.mock {
Some(mock) => mock.send(request).await,
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 index = plans.borrow().iter().position(|plan| {
let read_plans = self.plans.read().map_err(|_| Error::RwLockLocked)?;
let index = read_plans.iter().position(|plan| {
// METHOD
(if plan.match_on.contains(&MatchOn::Method) {
plan.request.method() == request.method()
@ -123,93 +180,21 @@ impl Net {
true
})
});
drop(read_plans);
match index {
Some(i) => {
let response = plans.borrow_mut().remove(i).response;
Ok(response)
let mut write_plans = self.plans.write().map_err(|_| Error::RwLockLocked)?;
Ok(write_plans.remove(i).response)
}
None => Err(Error::UnexpectedMockRequest(request)),
}
}
}
impl TryFrom<Net> for MockNet {
type Error = super::Error;
fn try_from(net: Net) -> std::result::Result<Self, Self::Error> {
match &net.plans {
Some(plans) => Ok(MockNet {
plans: RefCell::new(plans.take()),
}),
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()),
pub fn on(&self, request: impl Into<reqwest::Request>) -> OnRequest {
OnRequest {
net: self,
request: request.into(),
match_on: vec![MatchOn::Method, MatchOn::Url],
}
}
@ -219,7 +204,8 @@ impl MockNet {
response: reqwest::Response,
match_on: Vec<MatchOn>,
) -> Result<()> {
self.plans.borrow_mut().push(Plan {
let mut write_plans = self.plans.write().map_err(|_| Error::RwLockLocked)?;
write_plans.push(Plan {
request,
response,
match_on,
@ -227,127 +213,35 @@ impl MockNet {
Ok(())
}
/// Creates a [http::response::Builder] to be extended and returned by a mocked network request.
pub fn response(&self) -> http::response::Builder {
Default::default()
}
/// 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();
pub fn reset(&self) -> Result<()> {
let mut write_plans = self.plans.write().map_err(|_| Error::RwLockLocked)?;
write_plans.clear();
Ok(())
}
}
impl From<MockNet> for Net {
fn from(mock_net: MockNet) -> Self {
Self {
// 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
plans: Some(RefCell::new(mock_net.plans.take())),
}
}
}
impl Drop for MockNet {
impl<T: NetType> Drop for InnerNet<T> {
fn drop(&mut self) {
assert!(self.plans.borrow().is_empty())
}
}
impl Drop for Net {
fn drop(&mut self) {
if let Some(plans) = &self.plans {
assert!(plans.borrow().is_empty())
}
let Ok(read_plans) = self.plans.read() else {
return;
};
assert!(read_plans.is_empty())
}
}
/// 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),
pub struct OnRequest<'net> {
net: &'net InnerNet<Mocked>,
request: reqwest::Request,
match_on: Vec<MatchOn>,
}
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
Self {
net: self.net,
request: self.request,
match_on,
}
}
/// 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()),
}
pub fn respond(self, response: impl Into<reqwest::Response>) -> Result<()> {
self.net._on(self.request, response.into(), self.match_on)
}
}

View file

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