Compare commits
5 commits
Author | SHA1 | Date | |
---|---|---|---|
25fd976ed5 | |||
|
cfae6623de | ||
ed590552c7 | |||
5169da03dc | |||
c0cb868dc5 |
9 changed files with 285 additions and 48 deletions
14
CHANGELOG.md
14
CHANGELOG.md
|
@ -7,6 +7,20 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
|
|||
|
||||
## [Unreleased]
|
||||
|
||||
## [3.1.0](https://git.kemitix.net/kemitix/kxio/compare/v3.0.0...v3.1.0) - 2024-11-21
|
||||
|
||||
### Added
|
||||
|
||||
- *(net)* mock request builder adds .with and .with_{option,result}
|
||||
|
||||
### Fixed
|
||||
|
||||
- impl Display for path, file and dir
|
||||
|
||||
### Other
|
||||
|
||||
- *(example)* clean up get example
|
||||
|
||||
## [3.0.0](https://git.kemitix.net/kemitix/kxio/compare/v2.1.1...v3.0.0) - 2024-11-20
|
||||
|
||||
### Added
|
||||
|
|
|
@ -1,6 +1,6 @@
|
|||
[package]
|
||||
name = "kxio"
|
||||
version = "3.0.0"
|
||||
version = "3.1.0"
|
||||
edition = "2021"
|
||||
authors = ["Paul Campbell <pcampbell@kemitix.net>"]
|
||||
description = "Provides injectable Filesystem and Network resources to make code more testable"
|
||||
|
|
|
@ -10,6 +10,8 @@
|
|||
/// `example-readme.md` in the current directory.
|
||||
use std::path::Path;
|
||||
|
||||
use kxio::fs::FileHandle;
|
||||
|
||||
#[tokio::main]
|
||||
async fn main() -> kxio::Result<()> {
|
||||
// Create a `Net` object for making real network requests.
|
||||
|
@ -18,7 +20,8 @@ async fn main() -> kxio::Result<()> {
|
|||
// Create a `FileSystem` object for accessing files within the current directory.
|
||||
// The object created will return a `PathTraveral` error result if there is an attempt to\
|
||||
// access a file outside of this directory.
|
||||
let fs: kxio::fs::FileSystem = kxio::fs::new("./");
|
||||
let current_dir = std::env::current_dir().map_err(kxio::fs::Error::Io)?;
|
||||
let fs: kxio::fs::FileSystem = kxio::fs::new(current_dir);
|
||||
|
||||
// The URL we will fetch - the readme for this library.
|
||||
let url = "https://git.kemitix.net/kemitix/kxio/raw/branch/main/README.md";
|
||||
|
@ -27,7 +30,7 @@ async fn main() -> kxio::Result<()> {
|
|||
let file_path = fs.base().join("example-readme.md");
|
||||
|
||||
// Create a generic handle for the file. This doesn't open the file, and always succeeds.
|
||||
let path: kxio::fs::PathReal<kxio::fs::PathMarker> = fs.path(&file_path);
|
||||
let path = fs.path(&file_path);
|
||||
|
||||
// Other options are;
|
||||
// `fs.file(&file_path)` - for a file
|
||||
|
@ -35,17 +38,16 @@ async fn main() -> kxio::Result<()> {
|
|||
|
||||
// Checks if the path exists (whether a file, directory, etc)
|
||||
if path.exists()? {
|
||||
// extracts the path from the handle
|
||||
let pathbuf = path.as_pathbuf();
|
||||
eprintln!("The file {} already exists. Aborting!", pathbuf.display());
|
||||
eprintln!("The file {path} already exists. Aborting!");
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
// Passes a reference to the `fs` and `net` objects for use by your program.
|
||||
// Your programs should not know whether they are handling a mock or the real thing.
|
||||
// Any file or network access should be made using these handlers to be properly testable.
|
||||
download_and_save_to_file(url, &file_path, &fs, &net).await?;
|
||||
delete_file(&file_path, &fs)?;
|
||||
let file = download_and_save_to_file(url, &file_path, &fs, &net).await?;
|
||||
read_file(&file)?;
|
||||
delete_file(file)?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
@ -58,42 +60,33 @@ async fn download_and_save_to_file(
|
|||
fs: &kxio::fs::FileSystem,
|
||||
// The network abstraction
|
||||
net: &kxio::net::Net,
|
||||
) -> kxio::Result<()> {
|
||||
) -> kxio::Result<FileHandle> {
|
||||
println!("fetching: {url}");
|
||||
|
||||
// Rather than calling `.build().send()?` on the request, pass it to the `net`
|
||||
// This allows the `net` to either make the network request as normal, or, if we are
|
||||
// under test, to handle the request as the test dictates.
|
||||
// NOTE: if the `.build().send()` is called on the `request` then that WILL result in
|
||||
// a real network request being made, even under test conditions. Only ever use the
|
||||
// `net.send(...)` function to keep your code testable.
|
||||
// `kxio::net::Response` is an alias for `reqwest::Response`.
|
||||
let response: kxio::net::Response = net.get(url).header("key", "value").send().await?;
|
||||
// Other options:
|
||||
// Uses the network abstraction to create a perfectly normal `reqwest::ResponseBuilder`.
|
||||
// `kxio::net::RequestBuilder` is an alias.
|
||||
// let response = net.send(net.client().get(url)).await?;
|
||||
// Makes a GET request that can be mocked in a test
|
||||
let response: reqwest::Response = net.get(url).header("key", "value").send().await?;
|
||||
|
||||
// As you can see, we use [reqwest] under the hood.
|
||||
//
|
||||
// let response = net.post(url).body("{}").send().await?;
|
||||
// If you need to create a more complex request than the [kxio] fluent API allows, you
|
||||
// can create a request using [reqwest] and pass it to [net.send(request)].
|
||||
|
||||
let body = response.text().await?;
|
||||
println!("fetched {} bytes", body.bytes().len());
|
||||
|
||||
println!("writing file: {}", file_path.display());
|
||||
// Uses the file system abstraction to create a handle for a file.
|
||||
let file: kxio::fs::PathReal<kxio::fs::FileMarker> = fs.file(file_path);
|
||||
println!("writing file: {file}");
|
||||
// Writes the body to the file.
|
||||
file.write(body)?;
|
||||
|
||||
Ok(())
|
||||
Ok(file)
|
||||
}
|
||||
|
||||
/// An function that uses a `FileSystem` object to interact with the outside world.
|
||||
fn delete_file(file_path: &Path, fs: &kxio::fs::FileSystem) -> kxio::Result<()> {
|
||||
println!("reading file: {}", file_path.display());
|
||||
/// A function that reads the file contents
|
||||
fn read_file(file: &FileHandle) -> kxio::Result<()> {
|
||||
println!("reading file: {file}");
|
||||
|
||||
// Uses the file system abstraction to create a handle for a file.
|
||||
let file: kxio::fs::PathReal<kxio::fs::FileMarker> = fs.file(file_path);
|
||||
// Creates a `Reader` which loaded the file into memory.
|
||||
let reader: kxio::fs::Reader = file.reader()?;
|
||||
let contents: &str = reader.as_str();
|
||||
|
@ -102,6 +95,15 @@ fn delete_file(file_path: &Path, fs: &kxio::fs::FileSystem) -> kxio::Result<()>
|
|||
Ok(())
|
||||
}
|
||||
|
||||
/// A function that deletes the file
|
||||
fn delete_file(file: FileHandle) -> kxio::Result<()> {
|
||||
println!("deleting file: {file}");
|
||||
|
||||
file.remove()?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use http::StatusCode;
|
||||
|
|
|
@ -1,3 +1,5 @@
|
|||
use std::fmt::Display;
|
||||
|
||||
//
|
||||
use crate::fs::{DirItem, DirItemIterator, Result};
|
||||
|
||||
|
@ -106,3 +108,9 @@ impl TryFrom<PathHandle<PathMarker>> for DirHandle {
|
|||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Display for DirHandle {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
write!(f, "{}/", self.as_pathbuf().display())
|
||||
}
|
||||
}
|
||||
|
|
|
@ -1,7 +1,9 @@
|
|||
use std::fmt::Display;
|
||||
|
||||
//
|
||||
use crate::fs::Result;
|
||||
|
||||
use super::{reader::Reader, Error, FileHandle, PathHandle, PathMarker};
|
||||
use super::{reader::Reader, Error, FileHandle, FileMarker, PathHandle, PathMarker, PathReal};
|
||||
|
||||
impl FileHandle {
|
||||
/// Returns a [Reader] for the file.
|
||||
|
@ -112,3 +114,9 @@ impl TryFrom<PathHandle<PathMarker>> for FileHandle {
|
|||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Display for PathReal<FileMarker> {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
write!(f, "{}", self.as_pathbuf().display())
|
||||
}
|
||||
}
|
||||
|
|
|
@ -1,5 +1,6 @@
|
|||
//
|
||||
use std::{
|
||||
fmt::Display,
|
||||
marker::PhantomData,
|
||||
path::{Path, PathBuf},
|
||||
};
|
||||
|
@ -367,3 +368,9 @@ impl From<FileHandle> for PathHandle<PathMarker> {
|
|||
PathReal::new(file.base, file.path)
|
||||
}
|
||||
}
|
||||
|
||||
impl Display for PathReal<PathMarker> {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
write!(f, "{}", self.as_pathbuf().display())
|
||||
}
|
||||
}
|
||||
|
|
|
@ -146,10 +146,8 @@ mod system;
|
|||
|
||||
pub use result::{Error, Result};
|
||||
|
||||
pub use system::{MockNet, Net};
|
||||
pub use system::{MockNet, Net, ReqBuilder, WithOption, WithResult};
|
||||
|
||||
pub use http::HeaderMap;
|
||||
pub use http::Method;
|
||||
pub use http::StatusCode;
|
||||
pub use reqwest::Client;
|
||||
pub use reqwest::Error as RequestError;
|
||||
|
|
|
@ -97,6 +97,9 @@ impl Net {
|
|||
/// then the request will be matched and any stored response returned, or an
|
||||
/// error if no matched request was found.
|
||||
///
|
||||
/// This method provides an escape-hatch from `kxio`'s fluent API, and allows you
|
||||
/// to create a request using [reqwest] directly.
|
||||
///
|
||||
/// # Errors
|
||||
///
|
||||
/// This method fails if there was an error while sending request,
|
||||
|
@ -237,6 +240,102 @@ impl<'net> ReqBuilder<'net> {
|
|||
}
|
||||
}
|
||||
|
||||
/// Use the function to modify the request in-line.
|
||||
///
|
||||
/// # Example
|
||||
///
|
||||
/// ```rust
|
||||
/// # use kxio::net::Result;
|
||||
/// # async fn run() -> Result<()> {
|
||||
/// let net = kxio::net::new();
|
||||
/// let response= net
|
||||
/// .get("http://localhost/")
|
||||
/// .with(|request| add_std_headers(request))
|
||||
/// .send()
|
||||
/// .await?;
|
||||
/// # Ok(())
|
||||
/// # }
|
||||
/// fn add_std_headers(request: kxio::net::ReqBuilder) -> kxio::net::ReqBuilder {
|
||||
/// request
|
||||
/// .header("ClientVersion", "1.23.45")
|
||||
/// .header("Agent", "MyApp/1.1")
|
||||
/// }
|
||||
/// ````
|
||||
#[must_use]
|
||||
pub fn with(self, f: impl FnOnce(Self) -> Self) -> Self {
|
||||
f(self)
|
||||
}
|
||||
|
||||
/// Starts an Option clause for the supplied option.
|
||||
///
|
||||
/// Must be followed by [WithOption::some], [WithOption::none] or [WithOption::either]
|
||||
/// to resume the with the [ReqBuilder].
|
||||
///
|
||||
/// # Example
|
||||
///
|
||||
/// ```rust
|
||||
/// # use kxio::net::Result;
|
||||
/// # async fn run() -> Result<()> {
|
||||
/// let net = kxio::net::new();
|
||||
/// let response= net
|
||||
/// .get("http://localhost/")
|
||||
/// .with_option(Some("value"))
|
||||
/// .some(|request, value| request.header("optional-header", value))
|
||||
/// .with_option(Some("value"))
|
||||
/// .none(|request| request.header("special-header", "not-found"))
|
||||
/// .with_option(Some("value"))
|
||||
/// .either(
|
||||
/// /* some */ |request, value| request.header("Setting", value),
|
||||
/// /* none */ |request| request.header("Setting", "missing")
|
||||
/// )
|
||||
/// .send()
|
||||
/// .await?;
|
||||
/// # Ok(())
|
||||
/// # }
|
||||
/// ```
|
||||
#[must_use]
|
||||
pub fn with_option<T>(self, option: Option<T>) -> WithOption<'net, T> {
|
||||
WithOption {
|
||||
req_builder: self,
|
||||
option,
|
||||
}
|
||||
}
|
||||
|
||||
/// Starts a Result clause for the supplied result.
|
||||
///
|
||||
/// Must be followed by [WithResult::ok], [WithResult::err] or [WithResult::either]
|
||||
/// to resume the with the [ReqBuilder].
|
||||
///
|
||||
/// # Example
|
||||
///
|
||||
/// ```rust
|
||||
/// # use kxio::net::Result;
|
||||
/// # async fn run() -> Result<()> {
|
||||
/// let net = kxio::net::new();
|
||||
/// let response = net
|
||||
/// .get("http://localhost/")
|
||||
/// .with_result::<&str, ()>(Ok("value"))
|
||||
/// .ok(|request, value| request.header("good-header", value))
|
||||
/// .with_result::<(), &str>(Err("value"))
|
||||
/// .err(|request, err| request.header("bad-header", err))
|
||||
/// .with_result::<&str, &str>(Ok("value"))
|
||||
/// .either(
|
||||
/// /* ok */ |request, ok| request.header("Setting", ok),
|
||||
/// /* err */ |request, err| request.header("SettingError", err)
|
||||
/// )
|
||||
/// .send()
|
||||
/// .await?;
|
||||
/// # Ok(())
|
||||
/// # }
|
||||
/// ```
|
||||
#[must_use]
|
||||
pub fn with_result<T, E>(self, result: std::result::Result<T, E>) -> WithResult<'net, T, E> {
|
||||
WithResult {
|
||||
req_builder: self,
|
||||
result,
|
||||
}
|
||||
}
|
||||
|
||||
/// Constructs the Request and sends it to the target URL, returning a
|
||||
/// future Response.
|
||||
///
|
||||
|
@ -650,6 +749,98 @@ impl<'net> WhenRequest<'net, WhenBuildResponse> {
|
|||
}
|
||||
}
|
||||
|
||||
/// Option clause for building a request with [ReqBuilder].
|
||||
///
|
||||
/// See: [ReqBuilder::with_option].
|
||||
pub struct WithOption<'net, T> {
|
||||
req_builder: ReqBuilder<'net>,
|
||||
option: Option<T>,
|
||||
}
|
||||
impl<'net, T> WithOption<'net, T> {
|
||||
/// Handles when the preceeding [Option] is [Some].
|
||||
///
|
||||
/// The function is passed the [ReqBuilder] and the value in the [Some].
|
||||
///
|
||||
/// Returns the [ReqBuilder].
|
||||
pub fn some(
|
||||
self,
|
||||
f_some: impl FnOnce(ReqBuilder<'net>, T) -> ReqBuilder<'net>,
|
||||
) -> ReqBuilder<'net> {
|
||||
match self.option {
|
||||
Some(value) => f_some(self.req_builder, value),
|
||||
None => self.req_builder,
|
||||
}
|
||||
}
|
||||
|
||||
/// Handles when the preceeding [Option] is [None].
|
||||
///
|
||||
/// The function is passed the [ReqBuilder].
|
||||
///
|
||||
/// Returns the [ReqBuilder].
|
||||
pub fn none(
|
||||
self,
|
||||
f_none: impl FnOnce(ReqBuilder<'net>) -> ReqBuilder<'net>,
|
||||
) -> ReqBuilder<'net> {
|
||||
match self.option {
|
||||
None => f_none(self.req_builder),
|
||||
Some(_) => self.req_builder,
|
||||
}
|
||||
}
|
||||
|
||||
/// Handles the preceeding [Option].
|
||||
///
|
||||
/// If the [Option] is [Some], then the `f_some` function is passed the [ReqBuilder] and the value in the [Some].
|
||||
///
|
||||
/// If the [Option] is [None], then the `f_none` function is passed the [ReqBuilder].
|
||||
///
|
||||
/// Returns the [ReqBuilder].
|
||||
pub fn either(
|
||||
self,
|
||||
f_some: impl FnOnce(ReqBuilder<'net>, T) -> ReqBuilder<'net>,
|
||||
f_none: impl FnOnce(ReqBuilder<'net>) -> ReqBuilder<'net>,
|
||||
) -> ReqBuilder<'net> {
|
||||
match self.option {
|
||||
Some(value) => f_some(self.req_builder, value),
|
||||
None => f_none(self.req_builder),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub struct WithResult<'net, T, E> {
|
||||
req_builder: ReqBuilder<'net>,
|
||||
result: std::result::Result<T, E>,
|
||||
}
|
||||
impl<'net, T, E> WithResult<'net, T, E> {
|
||||
pub fn ok(
|
||||
self,
|
||||
f_ok: impl FnOnce(ReqBuilder<'net>, T) -> ReqBuilder<'net>,
|
||||
) -> ReqBuilder<'net> {
|
||||
match self.result {
|
||||
Ok(ok) => f_ok(self.req_builder, ok),
|
||||
Err(_) => self.req_builder,
|
||||
}
|
||||
}
|
||||
pub fn err(
|
||||
self,
|
||||
f_err: impl FnOnce(ReqBuilder<'net>, E) -> ReqBuilder<'net>,
|
||||
) -> ReqBuilder<'net> {
|
||||
match self.result {
|
||||
Err(err) => f_err(self.req_builder, err),
|
||||
Ok(_) => self.req_builder,
|
||||
}
|
||||
}
|
||||
pub fn either(
|
||||
self,
|
||||
f_ok: impl FnOnce(ReqBuilder<'net>, T) -> ReqBuilder<'net>,
|
||||
f_err: impl FnOnce(ReqBuilder<'net>, E) -> ReqBuilder<'net>,
|
||||
) -> ReqBuilder<'net> {
|
||||
match self.result {
|
||||
Ok(ok) => f_ok(self.req_builder, ok),
|
||||
Err(err) => f_err(self.req_builder, err),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
|
37
tests/fs.rs
37
tests/fs.rs
|
@ -16,6 +16,14 @@ mod path {
|
|||
|
||||
assert_eq!(read.base(), fs.base());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn display() {
|
||||
let fs = fs::temp().expect("temp fs");
|
||||
let path = fs.base().join("foo");
|
||||
let path_handle = fs.path(&path);
|
||||
assert_eq!(path_handle.to_string(), format!("{}", path.display()));
|
||||
}
|
||||
mod is_link {
|
||||
use super::*;
|
||||
|
||||
|
@ -456,20 +464,13 @@ mod path {
|
|||
mod file {
|
||||
use super::*;
|
||||
|
||||
// // test for reading the symlink metadata
|
||||
// #[test]
|
||||
// fn symlink_metadata() -> TestResult {
|
||||
// let fs = fs::temp().expect("temp fs");
|
||||
// let file_path = fs.base().join("foo");
|
||||
// let file = fs.file(&file_path);
|
||||
// file.write("bar").expect("write");
|
||||
// let link_path = fs.base().join("bar");
|
||||
// let link = fs.path(&link_path);
|
||||
// file.soft_link(&link).expect("soft_link");
|
||||
// let md = link.symlink_metadata().expect("symlink metadata");
|
||||
// assert!(md.is_file());
|
||||
// Ok(())
|
||||
// }
|
||||
#[test]
|
||||
fn display() {
|
||||
let fs = fs::temp().expect("temp fs");
|
||||
let path = fs.base().join("foo");
|
||||
let file_handle = fs.file(&path);
|
||||
assert_eq!(file_handle.to_string(), format!("{}", path.display()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn create_hard_link() -> TestResult {
|
||||
|
@ -793,6 +794,14 @@ mod dir {
|
|||
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn display() {
|
||||
let fs = fs::temp().expect("temp fs");
|
||||
let path = fs.base().join("foo");
|
||||
let dir_handle = fs.dir(&path);
|
||||
assert_eq!(dir_handle.to_string(), format!("{}/", path.display()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn path_is_dir() {
|
||||
let fs = fs::temp().expect("temp fs");
|
||||
|
|
Loading…
Reference in a new issue