Compare commits
18 commits
Author | SHA1 | Date | |
---|---|---|---|
25fd976ed5 | |||
|
cfae6623de | ||
ed590552c7 | |||
5169da03dc | |||
c0cb868dc5 | |||
|
a58796f2f0 | ||
fab5c1ba11 | |||
e25531df61 | |||
d58ec0eba2 | |||
7da221bfde | |||
a84643e6ae | |||
711c76a600 | |||
2ddc79d826 | |||
|
d664090648 | ||
89f39b8ad4 | |||
|
7e1b3de984 | ||
40a45f32da | |||
32ba3c00c7 |
16 changed files with 1191 additions and 408 deletions
45
CHANGELOG.md
45
CHANGELOG.md
|
@ -7,6 +7,51 @@ 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
|
||||
|
||||
- *(net)* [**breaking**] net api: net.{get,post,etc..}(url) alternative to net.send(request)
|
||||
- *(fs)* add TempFileSystem::as_real()
|
||||
- *(net)* [**breaking**] new api: .on().respond().{status,header{s},body}(_)?, replacing respond(response)
|
||||
- *(net)* [**breaking**] new api: .on().{get,post, etc}(url), replacing .on(method).get(url)
|
||||
- re-export http::HeaderMap
|
||||
- Add Debug, Clone, Default, PartialEq, Eq, Send, Sync to as many or our types as possible.
|
||||
|
||||
### Fixed
|
||||
|
||||
- *(net)* [**breaking**] Remove MatchOn
|
||||
|
||||
## [2.1.1](https://git.kemitix.net/kemitix/kxio/compare/v2.1.0...v2.1.1) - 2024-11-15
|
||||
|
||||
### Fixed
|
||||
|
||||
- impl Clone for Net
|
||||
|
||||
## [2.1.0](https://git.kemitix.net/kemitix/kxio/compare/v2.0.0...v2.1.0) - 2024-11-15
|
||||
|
||||
### Added
|
||||
|
||||
- re-export Method, Url, Request, Response and RequestBuilder from http, url and reqwest crates
|
||||
|
||||
### Other
|
||||
|
||||
- remove duplicated section
|
||||
|
||||
## [2.0.0](https://git.kemitix.net/kemitix/kxio/compare/v1.2.0...v2.0.0) - 2024-11-14
|
||||
|
||||
### Added
|
||||
|
|
|
@ -1,6 +1,6 @@
|
|||
[package]
|
||||
name = "kxio"
|
||||
version = "2.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"
|
||||
|
@ -14,6 +14,7 @@ unexpected_cfgs = { level = "warn", check-cfg = ['cfg(tarpaulin_include)'] }
|
|||
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
|
||||
|
||||
[dependencies]
|
||||
bytes = "1.8"
|
||||
derive_more = { version = "1.0", features = [
|
||||
"constructor",
|
||||
"display",
|
||||
|
@ -21,9 +22,10 @@ derive_more = { version = "1.0", features = [
|
|||
] }
|
||||
http = "1.1"
|
||||
path-clean = "1.0"
|
||||
reqwest = "0.12"
|
||||
reqwest = { version = "0.12", features = [ "json" ] }
|
||||
url = "2.5"
|
||||
tempfile = "3.10"
|
||||
tokio = { version = "1.41", features = [ "sync" ] }
|
||||
|
||||
[dev-dependencies]
|
||||
assert2 = "0.3"
|
||||
|
|
|
@ -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(())
|
||||
}
|
||||
|
@ -54,42 +56,37 @@ async fn main() -> kxio::Result<()> {
|
|||
async fn download_and_save_to_file(
|
||||
url: &str,
|
||||
file_path: &Path,
|
||||
// The file system abstraction
|
||||
// The filesystem abstraction
|
||||
fs: &kxio::fs::FileSystem,
|
||||
// The network abstraction
|
||||
net: &kxio::net::Net,
|
||||
) -> kxio::Result<()> {
|
||||
) -> kxio::Result<FileHandle> {
|
||||
println!("fetching: {url}");
|
||||
|
||||
// Uses the network abstraction to create a perfectly normal `reqwest::ResponseBuilder`.
|
||||
let request: reqwest::RequestBuilder = net.client().get(url);
|
||||
// Makes a GET request that can be mocked in a test
|
||||
let response: reqwest::Response = net.get(url).header("key", "value").send().await?;
|
||||
|
||||
// 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.
|
||||
let response: reqwest::Response = net.send(request).await?;
|
||||
// As you can see, we use [reqwest] under the hood.
|
||||
//
|
||||
// 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();
|
||||
|
@ -98,8 +95,19 @@ 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;
|
||||
|
||||
use super::*;
|
||||
|
||||
// This test demonstrates how to use the `kxio` to test your program.
|
||||
|
@ -114,11 +122,12 @@ mod tests {
|
|||
let url = "http://localhost:8080";
|
||||
|
||||
// declare what response should be made for a given request
|
||||
let response = mock_net.response().body("contents").expect("response body");
|
||||
mock_net
|
||||
.on(http::Method::GET)
|
||||
.url(url::Url::parse(url).expect("parse url"))
|
||||
.respond(response);
|
||||
.on()
|
||||
.get(url)
|
||||
.respond(StatusCode::OK)
|
||||
.body("contents")
|
||||
.expect("valid mock");
|
||||
|
||||
// Create a temporary directory that will be deleted with `fs` goes out of scope
|
||||
let fs = kxio::fs::temp().expect("temp fs");
|
||||
|
|
|
@ -1,7 +1,9 @@
|
|||
use std::fmt::Display;
|
||||
|
||||
//
|
||||
use crate::fs::{DirItem, DirItemIterator, Result};
|
||||
|
||||
use super::{DirHandle, Error, FileHandle, PathHandle, PathMarker};
|
||||
use super::{DirHandle, Error, PathHandle, PathMarker};
|
||||
|
||||
impl DirHandle {
|
||||
/// Creates a new, empty directory at the path
|
||||
|
@ -93,19 +95,6 @@ impl DirHandle {
|
|||
std::fs::remove_dir_all(self.as_pathbuf()).map_err(Error::Io)
|
||||
}
|
||||
}
|
||||
impl TryFrom<PathHandle<PathMarker>> for FileHandle {
|
||||
type Error = crate::fs::Error;
|
||||
|
||||
fn try_from(path: PathHandle<PathMarker>) -> std::result::Result<Self, Self::Error> {
|
||||
match path.as_file() {
|
||||
Ok(Some(dir)) => Ok(dir.clone()),
|
||||
Ok(None) => Err(crate::fs::Error::NotADirectory {
|
||||
path: path.as_pathbuf(),
|
||||
}),
|
||||
Err(err) => Err(err),
|
||||
}
|
||||
}
|
||||
}
|
||||
impl TryFrom<PathHandle<PathMarker>> for DirHandle {
|
||||
type Error = crate::fs::Error;
|
||||
|
||||
|
@ -119,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())
|
||||
}
|
||||
}
|
||||
|
|
|
@ -7,7 +7,7 @@ use std::{
|
|||
use super::Error;
|
||||
|
||||
/// Represents an item in a directory
|
||||
#[derive(Debug, PartialEq, Eq, PartialOrd, Ord)]
|
||||
#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord)]
|
||||
pub enum DirItem {
|
||||
File(PathBuf),
|
||||
Dir(PathBuf),
|
||||
|
|
|
@ -1,7 +1,9 @@
|
|||
use std::fmt::Display;
|
||||
|
||||
//
|
||||
use crate::fs::Result;
|
||||
|
||||
use super::{reader::Reader, Error, FileHandle};
|
||||
use super::{reader::Reader, Error, FileHandle, FileMarker, PathHandle, PathMarker, PathReal};
|
||||
|
||||
impl FileHandle {
|
||||
/// Returns a [Reader] for the file.
|
||||
|
@ -99,3 +101,22 @@ impl FileHandle {
|
|||
std::fs::hard_link(self.as_pathbuf(), dest.as_pathbuf()).map_err(Error::Io)
|
||||
}
|
||||
}
|
||||
impl TryFrom<PathHandle<PathMarker>> for FileHandle {
|
||||
type Error = crate::fs::Error;
|
||||
|
||||
fn try_from(path: PathHandle<PathMarker>) -> std::result::Result<Self, Self::Error> {
|
||||
match path.as_file() {
|
||||
Ok(Some(dir)) => Ok(dir.clone()),
|
||||
Ok(None) => Err(crate::fs::Error::NotAFile {
|
||||
path: path.as_pathbuf(),
|
||||
}),
|
||||
Err(err) => Err(err),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Display for PathReal<FileMarker> {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
write!(f, "{}", self.as_pathbuf().display())
|
||||
}
|
||||
}
|
||||
|
|
|
@ -98,3 +98,25 @@ pub fn new(base: impl Into<PathBuf>) -> FileSystem {
|
|||
pub fn temp() -> Result<temp::TempFileSystem> {
|
||||
temp::TempFileSystem::new()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn is_normal<T: Sized + Send + Sync + Unpin>() {}
|
||||
|
||||
#[test]
|
||||
fn normal_types() {
|
||||
is_normal::<FileSystem>();
|
||||
is_normal::<DirItem>();
|
||||
is_normal::<DirItemIterator>();
|
||||
is_normal::<Reader>();
|
||||
is_normal::<PathReal<PathMarker>>();
|
||||
is_normal::<DirMarker>();
|
||||
is_normal::<FileMarker>();
|
||||
is_normal::<PathMarker>();
|
||||
is_normal::<DirHandle>();
|
||||
is_normal::<FileHandle>();
|
||||
is_normal::<PathHandle<PathMarker>>();
|
||||
}
|
||||
}
|
||||
|
|
|
@ -1,5 +1,6 @@
|
|||
//
|
||||
use std::{
|
||||
fmt::Display,
|
||||
marker::PhantomData,
|
||||
path::{Path, PathBuf},
|
||||
};
|
||||
|
@ -12,24 +13,24 @@ use super::{DirHandle, FileHandle, PathHandle};
|
|||
pub trait PathType {}
|
||||
|
||||
/// Path marker for the type of [PathReal].
|
||||
#[derive(Clone, Debug)]
|
||||
#[derive(Clone, Debug, Default, PartialEq, Eq)]
|
||||
pub struct PathMarker;
|
||||
impl PathType for PathMarker {}
|
||||
|
||||
/// File marker for the type of [PathReal].
|
||||
#[derive(Clone, Debug)]
|
||||
#[derive(Clone, Debug, Default, PartialEq, Eq)]
|
||||
pub struct FileMarker;
|
||||
impl PathType for FileMarker {}
|
||||
|
||||
/// Dir marker for the type of [PathReal].
|
||||
#[derive(Clone, Debug)]
|
||||
#[derive(Clone, Debug, Default, PartialEq, Eq)]
|
||||
pub struct DirMarker;
|
||||
impl PathType for DirMarker {}
|
||||
|
||||
/// Represents a path in the filesystem.
|
||||
///
|
||||
/// It can be a simple path, or it can be a file or a directory.
|
||||
#[derive(Clone, Debug)]
|
||||
#[derive(Clone, Debug, Default)]
|
||||
pub struct PathReal<T: PathType> {
|
||||
base: PathBuf,
|
||||
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())
|
||||
}
|
||||
}
|
||||
|
|
|
@ -6,6 +6,7 @@ use crate::fs::Result;
|
|||
use super::Error;
|
||||
|
||||
/// A reader for a file.
|
||||
#[derive(Clone, Debug, Default, PartialEq, Eq)]
|
||||
pub struct Reader {
|
||||
contents: String,
|
||||
}
|
||||
|
|
|
@ -9,7 +9,7 @@ use super::{
|
|||
};
|
||||
|
||||
/// Represents to base of a section of a file system.
|
||||
#[derive(Clone, Debug)]
|
||||
#[derive(Clone, Debug, Default, PartialEq, Eq)]
|
||||
pub struct FileSystem {
|
||||
base: PathBuf,
|
||||
}
|
||||
|
|
|
@ -21,6 +21,11 @@ impl TempFileSystem {
|
|||
_temp_dir: temp_dir,
|
||||
})
|
||||
}
|
||||
|
||||
/// Create a clone of the wrapped [FileSystem].
|
||||
pub fn as_real(&self) -> FileSystem {
|
||||
self.real.clone()
|
||||
}
|
||||
}
|
||||
impl std::ops::Deref for TempFileSystem {
|
||||
type Target = FileSystem;
|
||||
|
|
180
src/net/mod.rs
180
src/net/mod.rs
|
@ -21,7 +21,7 @@
|
|||
//!
|
||||
//! 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.
|
||||
//! Use the [Net::client] functionto create a [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
|
||||
|
@ -62,12 +62,14 @@
|
|||
//! let mock_net = net::mock();
|
||||
//! ```
|
||||
//!
|
||||
//! Create a [reqwest::Client] using [MockNet::client()].
|
||||
//! Create a [Client] using [MockNet::client()].
|
||||
//!
|
||||
//! ```rust
|
||||
//! # let mock_net = kxio::net::mock();
|
||||
//! let client = mock_net.client();
|
||||
//! // this is the same as:
|
||||
//! let client = kxio::net::Client::new();
|
||||
//! // this is also the same as:
|
||||
//! let client = reqwest::Client::new();
|
||||
//! ```
|
||||
//!
|
||||
|
@ -77,28 +79,19 @@
|
|||
//!
|
||||
//! ```rust
|
||||
//! use kxio::net;
|
||||
//! use kxio::net::MatchOn;
|
||||
//!
|
||||
//! use kxio::net::StatusCode;
|
||||
//! # #[tokio::main]
|
||||
//! # async fn main() -> net::Result<()> {
|
||||
//! # let mock_net = net::mock();
|
||||
//! mock_net.on(http::Method::GET)
|
||||
//! .url(url::Url::parse("https://example.com")?)
|
||||
//! .respond(mock_net.response().status(200).body("")?);
|
||||
//! mock_net.on(http::Method::GET)
|
||||
//! .url(url::Url::parse("https://example.com/foo")?)
|
||||
//! .respond(mock_net.response().status(500).body("Mocked response")?);
|
||||
//! mock_net.on().get("https://example.com")
|
||||
//! .respond(StatusCode::OK).body("");
|
||||
//! mock_net.on().get("https://example.com/foo")
|
||||
//! .respond(StatusCode::INTERNAL_SERVER_ERROR).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
|
||||
|
@ -132,10 +125,14 @@
|
|||
//!
|
||||
//! ```rust
|
||||
//! # use kxio::net;
|
||||
//! # #[tokio::main]
|
||||
//! # async fn main() -> net::Result<()> {
|
||||
//! # let mock_net = net::mock();
|
||||
//! # let net = net::Net::from(mock_net);
|
||||
//! let mock_net = kxio::net::MockNet::try_from(net).expect("recover mock");
|
||||
//! let mock_net = kxio::net::MockNet::try_from(net).await.expect("recover mock");
|
||||
//! mock_net.reset();
|
||||
//! # Ok(())
|
||||
//! # }
|
||||
//! ````
|
||||
//!
|
||||
//! ## Error Handling
|
||||
|
@ -143,151 +140,20 @@
|
|||
//! 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(http::Method::GET)
|
||||
//! .url(url::Url::parse("https://example.com")?)
|
||||
//! .respond(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};
|
||||
pub use system::{MockNet, Net, ReqBuilder, WithOption, WithResult};
|
||||
|
||||
pub use http::StatusCode;
|
||||
pub use reqwest::Client;
|
||||
pub use reqwest::Error as RequestError;
|
||||
pub use reqwest::Request;
|
||||
pub use reqwest::RequestBuilder;
|
||||
pub use reqwest::Response;
|
||||
|
||||
/// Creates a new `Net`.
|
||||
pub const fn new() -> Net {
|
||||
|
@ -296,5 +162,5 @@ pub const fn new() -> Net {
|
|||
|
||||
/// Creates a new `MockNet` for use in tests.
|
||||
pub fn mock() -> MockNet {
|
||||
Net::mock()
|
||||
Default::default()
|
||||
}
|
||||
|
|
|
@ -1,6 +1,10 @@
|
|||
//
|
||||
use derive_more::derive::From;
|
||||
|
||||
use crate::net::Request;
|
||||
|
||||
use super::system::MockError;
|
||||
|
||||
/// The Errors that may occur within [kxio::net][crate::net].
|
||||
#[derive(Debug, From, derive_more::Display)]
|
||||
pub enum Error {
|
||||
|
@ -20,7 +24,7 @@ pub enum Error {
|
|||
|
||||
/// There was network request that doesn't match any that were expected
|
||||
#[display("Unexpected request: {0}", 0.to_string())]
|
||||
UnexpectedMockRequest(reqwest::Request),
|
||||
UnexpectedMockRequest(Request),
|
||||
|
||||
/// There was an error accessing the list of expected requests.
|
||||
RwLockLocked,
|
||||
|
@ -30,6 +34,14 @@ pub enum Error {
|
|||
|
||||
/// Attempted to extract a [MockNet][super::MockNet] from a [Net][super::Net] that does not contain one.
|
||||
NetIsNotAMock,
|
||||
|
||||
InvalidMock(MockError),
|
||||
|
||||
/// The returned response is has an error status code (i.e. 4xx or 5xx)
|
||||
#[display("response error: {}", response.status())]
|
||||
ResponseError {
|
||||
response: reqwest::Response,
|
||||
},
|
||||
}
|
||||
impl std::error::Error for Error {}
|
||||
impl Clone for Error {
|
||||
|
|
|
@ -1,40 +1,41 @@
|
|||
//
|
||||
use std::cell::RefCell;
|
||||
|
||||
use reqwest::{Body, Client};
|
||||
use std::{
|
||||
cell::RefCell,
|
||||
collections::HashMap,
|
||||
fmt::{Debug, Display},
|
||||
marker::PhantomData,
|
||||
ops::Deref,
|
||||
rc::Rc,
|
||||
sync::Arc,
|
||||
};
|
||||
|
||||
use bytes::Bytes;
|
||||
use derive_more::derive::{Display, From};
|
||||
use http::StatusCode;
|
||||
use reqwest::{Client, RequestBuilder};
|
||||
use tokio::sync::Mutex;
|
||||
use url::Url;
|
||||
|
||||
use crate::net::{Request, Response};
|
||||
|
||||
use super::{Error, Result};
|
||||
|
||||
/// A list of planned requests and responses
|
||||
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 {
|
||||
match_request: Vec<MatchRequest>,
|
||||
response: reqwest::Response,
|
||||
}
|
||||
impl Plan {
|
||||
fn matches(&self, request: &reqwest::Request) -> bool {
|
||||
fn matches(&self, request: &Request) -> bool {
|
||||
self.match_request.iter().all(|criteria| match criteria {
|
||||
MatchRequest::Method(method) => request.method() == method,
|
||||
MatchRequest::Method(method) => request.method() == http::Method::from(method),
|
||||
MatchRequest::Url(uri) => request.url() == uri,
|
||||
MatchRequest::Header { name, value } => {
|
||||
request
|
||||
|
@ -48,31 +49,33 @@ impl Plan {
|
|||
})
|
||||
}
|
||||
MatchRequest::Body(body) => {
|
||||
request.body().and_then(Body::as_bytes) == Some(body.as_bytes())
|
||||
request.body().and_then(reqwest::Body::as_bytes) == Some(body)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
impl Display for Plan {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
for m in &self.match_request {
|
||||
write!(f, "{m} ")?;
|
||||
}
|
||||
writeln!(f, "=> {:?}", self.response)
|
||||
}
|
||||
}
|
||||
|
||||
/// An abstraction for the network
|
||||
#[derive(Debug, Clone, Default)]
|
||||
pub struct Net {
|
||||
plans: Option<RefCell<Plans>>,
|
||||
plans: Option<Arc<Mutex<RefCell<Plans>>>>,
|
||||
}
|
||||
impl Net {
|
||||
/// Creates a new unmocked [Net] for creating real network requests.
|
||||
pub(super) const fn new() -> Self {
|
||||
Self { plans: None }
|
||||
}
|
||||
|
||||
/// Creats a new [MockNet] for use in tests.
|
||||
pub(super) const fn mock() -> MockNet {
|
||||
MockNet {
|
||||
plans: RefCell::new(vec![]),
|
||||
}
|
||||
}
|
||||
}
|
||||
impl Net {
|
||||
/// Helper to create a default [reqwest::Client].
|
||||
/// Helper to create a default [Client].
|
||||
///
|
||||
/// # Example
|
||||
///
|
||||
|
@ -82,17 +85,27 @@ impl Net {
|
|||
/// let client = net.client();
|
||||
/// let request = client.get("https://hyper.rs");
|
||||
/// ```
|
||||
pub fn client(&self) -> reqwest::Client {
|
||||
#[must_use]
|
||||
pub fn client(&self) -> Client {
|
||||
Default::default()
|
||||
}
|
||||
|
||||
/// Constructs the Request and sends it to the target URL, returning a
|
||||
/// future Response.
|
||||
///
|
||||
/// However, if this request is from a [Net] that was created from a [MockNet],
|
||||
/// 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,
|
||||
/// redirect loop was detected or redirect limit was exhausted.
|
||||
/// If the response has a Status Code of `4xx` or `5xx` then the
|
||||
/// response will be returned as an [Error::ResponseError].
|
||||
///
|
||||
/// # Example
|
||||
///
|
||||
|
@ -105,40 +118,296 @@ impl Net {
|
|||
/// # Ok(())
|
||||
/// # }
|
||||
/// ```
|
||||
pub async fn send(
|
||||
&self,
|
||||
request: impl Into<reqwest::RequestBuilder>,
|
||||
) -> Result<reqwest::Response> {
|
||||
pub async fn send(&self, request: impl Into<RequestBuilder>) -> Result<Response> {
|
||||
let Some(plans) = &self.plans else {
|
||||
return request.into().send().await.map_err(Error::from);
|
||||
};
|
||||
let request = request.into().build()?;
|
||||
eprintln!(
|
||||
"? {} {} {:?}",
|
||||
request.method(),
|
||||
request.url(),
|
||||
request.headers()
|
||||
);
|
||||
let index = plans
|
||||
.lock()
|
||||
.await
|
||||
.deref()
|
||||
.borrow()
|
||||
.iter()
|
||||
.position(|plan| plan.matches(&request));
|
||||
match index {
|
||||
Some(i) => {
|
||||
let response = plans.borrow_mut().remove(i).response;
|
||||
Ok(response)
|
||||
let plan = plans.lock().await.borrow_mut().remove(i);
|
||||
eprintln!("- matched: {plan}");
|
||||
let response = plan.response;
|
||||
if response.status().is_success() {
|
||||
Ok(response)
|
||||
} else {
|
||||
Err(crate::net::Error::ResponseError { 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> {
|
||||
/// Starts building an http DELETE request for the URL.
|
||||
#[must_use]
|
||||
pub fn delete(&self, url: impl Into<String>) -> ReqBuilder {
|
||||
ReqBuilder::new(self, NetMethod::Delete, url)
|
||||
}
|
||||
|
||||
/// Starts building an http GET request for the URL.
|
||||
#[must_use]
|
||||
pub fn get(&self, url: impl Into<String>) -> ReqBuilder {
|
||||
ReqBuilder::new(self, NetMethod::Get, url)
|
||||
}
|
||||
|
||||
/// Starts building an http HEAD request for the URL.
|
||||
#[must_use]
|
||||
pub fn head(&self, url: impl Into<String>) -> ReqBuilder {
|
||||
ReqBuilder::new(self, NetMethod::Head, url)
|
||||
}
|
||||
|
||||
/// Starts building an http PATCH request for the URL.
|
||||
#[must_use]
|
||||
pub fn patch(&self, url: impl Into<String>) -> ReqBuilder {
|
||||
ReqBuilder::new(self, NetMethod::Patch, url)
|
||||
}
|
||||
|
||||
/// Starts building an http POST request for the URL.
|
||||
#[must_use]
|
||||
pub fn post(&self, url: impl Into<String>) -> ReqBuilder {
|
||||
ReqBuilder::new(self, NetMethod::Post, url)
|
||||
}
|
||||
|
||||
/// Starts building an http PUT request for the URL.
|
||||
#[must_use]
|
||||
pub fn put(&self, url: impl Into<String>) -> ReqBuilder {
|
||||
ReqBuilder::new(self, NetMethod::Put, url)
|
||||
}
|
||||
}
|
||||
impl MockNet {
|
||||
pub async fn try_from(net: Net) -> std::result::Result<Self, super::Error> {
|
||||
match &net.plans {
|
||||
Some(plans) => Ok(MockNet {
|
||||
plans: RefCell::new(plans.take()),
|
||||
plans: Rc::new(RefCell::new(plans.lock().await.take())),
|
||||
}),
|
||||
None => Err(Self::Error::NetIsNotAMock),
|
||||
None => Err(super::Error::NetIsNotAMock),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Display, PartialEq, Eq)]
|
||||
pub enum NetMethod {
|
||||
Delete,
|
||||
Get,
|
||||
Head,
|
||||
Patch,
|
||||
Post,
|
||||
Put,
|
||||
}
|
||||
impl From<&NetMethod> for http::Method {
|
||||
fn from(value: &NetMethod) -> Self {
|
||||
match value {
|
||||
NetMethod::Delete => http::Method::DELETE,
|
||||
NetMethod::Get => http::Method::GET,
|
||||
NetMethod::Head => http::Method::HEAD,
|
||||
NetMethod::Patch => http::Method::PATCH,
|
||||
NetMethod::Post => http::Method::POST,
|
||||
NetMethod::Put => http::Method::PUT,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A builder for an http request.
|
||||
pub struct ReqBuilder<'net> {
|
||||
net: &'net Net,
|
||||
url: String,
|
||||
method: NetMethod,
|
||||
headers: Vec<(String, String)>,
|
||||
body: Option<Bytes>,
|
||||
}
|
||||
impl<'net> ReqBuilder<'net> {
|
||||
#[must_use]
|
||||
fn new(net: &'net Net, method: NetMethod, url: impl Into<String>) -> Self {
|
||||
Self {
|
||||
net,
|
||||
url: url.into(),
|
||||
method,
|
||||
headers: vec![],
|
||||
body: None,
|
||||
}
|
||||
}
|
||||
|
||||
/// 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.
|
||||
///
|
||||
/// However, if this request is from a [Net] that was created from a [MockNet],
|
||||
/// then the request will be matched and any stored response returned, or an
|
||||
/// error if no matched request was found.
|
||||
///
|
||||
/// # Errors
|
||||
///
|
||||
/// This method fails if there was an error while sending request,
|
||||
/// redirect loop was detected or redirect limit was exhausted.
|
||||
/// If the response has a Status Code of `4xx` or `5xx` then the
|
||||
/// response will be returned as an [Error::ResponseError].
|
||||
///
|
||||
/// # Example
|
||||
///
|
||||
/// ```no_run
|
||||
/// # use kxio::net::Result;
|
||||
/// # async fn run() -> Result<()> {
|
||||
/// let net = kxio::net::new();
|
||||
/// let response = net.get("https://hyper.rs")
|
||||
/// .header("foo", "bar")
|
||||
/// .body("{}")
|
||||
/// .send().await?;
|
||||
/// # Ok(())
|
||||
/// # }
|
||||
/// ```
|
||||
pub async fn send(self) -> Result<Response> {
|
||||
let client = self.net.client();
|
||||
// Method
|
||||
let mut req = match self.method {
|
||||
NetMethod::Delete => client.delete(self.url),
|
||||
NetMethod::Get => client.get(self.url),
|
||||
NetMethod::Head => client.head(self.url),
|
||||
NetMethod::Patch => client.patch(self.url),
|
||||
NetMethod::Post => client.post(self.url),
|
||||
NetMethod::Put => client.put(self.url),
|
||||
};
|
||||
// Headers
|
||||
for (name, value) in self.headers.into_iter() {
|
||||
req = req.header(name, value);
|
||||
}
|
||||
// Body
|
||||
if let Some(bytes) = self.body {
|
||||
req = req.body(bytes);
|
||||
}
|
||||
|
||||
self.net.send(req).await
|
||||
}
|
||||
|
||||
/// Adds the header and value to the request.
|
||||
#[must_use]
|
||||
pub fn header(mut self, name: impl Into<String>, value: impl Into<String>) -> Self {
|
||||
self.headers.push((name.into(), value.into()));
|
||||
self
|
||||
}
|
||||
|
||||
/// Adds the headers to the request.
|
||||
#[must_use]
|
||||
pub fn headers(mut self, headers: HashMap<String, String>) -> Self {
|
||||
self.headers.extend(headers);
|
||||
self
|
||||
}
|
||||
|
||||
/// Sets the request body.
|
||||
#[must_use]
|
||||
pub fn body(mut self, bytes: impl Into<Bytes>) -> Self {
|
||||
self.body = Some(bytes.into());
|
||||
self
|
||||
}
|
||||
}
|
||||
|
||||
/// A struct for defining the expected requests and their responses that should be made
|
||||
/// during a test.
|
||||
///
|
||||
|
@ -149,28 +418,30 @@ impl TryFrom<Net> for MockNet {
|
|||
///
|
||||
/// ```rust
|
||||
/// # use kxio::net::Result;
|
||||
/// # fn run() -> Result<()> {
|
||||
/// use kxio::net::StatusCode;
|
||||
/// # #[tokio::main]
|
||||
/// # async 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(http::Method::GET)
|
||||
/// .url(url::Url::parse("https://hyper.rs")?)
|
||||
/// .respond(mock_net.response().status(200).body("Ok")?);
|
||||
/// mock_net.on().get("https://hyper.rs")
|
||||
/// .respond(StatusCode::OK).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)?;
|
||||
/// let mock_net = kxio::net::MockNet::try_from(net).await?;
|
||||
/// mock_net.reset(); // only if explicitly needed
|
||||
/// # Ok(())
|
||||
/// # }
|
||||
/// ```
|
||||
#[derive(Debug, Clone, Default)]
|
||||
pub struct MockNet {
|
||||
plans: RefCell<Plans>,
|
||||
plans: Rc<RefCell<Plans>>,
|
||||
}
|
||||
impl MockNet {
|
||||
/// Helper to create a default [reqwest::Client].
|
||||
/// Helper to create a default [Client].
|
||||
///
|
||||
/// # Example
|
||||
///
|
||||
|
@ -188,29 +459,25 @@ impl MockNet {
|
|||
/// # Example
|
||||
///
|
||||
/// ```rust
|
||||
/// use kxio::net::StatusCode;
|
||||
/// # use kxio::net::Result;
|
||||
/// # fn run() -> Result<()> {
|
||||
/// let mock_net = kxio::net::mock();
|
||||
/// let client = mock_net.client();
|
||||
/// mock_net.on(http::Method::GET)
|
||||
/// .url(url::Url::parse("https://hyper.rs")?)
|
||||
/// .respond(mock_net.response().status(200).body("Ok")?);
|
||||
/// mock_net.on().get("https://hyper.rs")
|
||||
/// .respond(StatusCode::OK).body("Ok");
|
||||
/// # Ok(())
|
||||
/// # }
|
||||
/// ```
|
||||
pub fn on(&self, method: impl Into<http::Method>) -> WhenRequest {
|
||||
WhenRequest::new(self, method)
|
||||
#[must_use]
|
||||
pub fn on(&self) -> WhenRequest<WhenBuildRequest> {
|
||||
WhenRequest::new(self)
|
||||
}
|
||||
|
||||
fn _when(&self, plan: Plan) {
|
||||
self.plans.borrow_mut().push(plan);
|
||||
}
|
||||
|
||||
/// 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
|
||||
|
@ -220,10 +487,11 @@ impl MockNet {
|
|||
///
|
||||
/// ```rust
|
||||
/// # use kxio::net::Result;
|
||||
/// # fn run() -> Result<()> {
|
||||
/// # #[tokio::main]
|
||||
/// # async 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)?;
|
||||
/// let mock_net = kxio::net::MockNet::try_from(net).await?;
|
||||
/// mock_net.reset(); // only if explicitly needed
|
||||
/// # Ok(())
|
||||
/// # }
|
||||
|
@ -237,41 +505,156 @@ impl From<MockNet> for Net {
|
|||
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())),
|
||||
plans: Some(Arc::new(Mutex::new(RefCell::new(mock_net.plans.take())))),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for MockNet {
|
||||
fn drop(&mut self) {
|
||||
assert!(self.plans.borrow().is_empty())
|
||||
let unused = self.plans.take();
|
||||
if unused.is_empty() {
|
||||
return; // all good
|
||||
}
|
||||
panic_with_unused_plans(unused);
|
||||
}
|
||||
}
|
||||
impl Drop for Net {
|
||||
fn drop(&mut self) {
|
||||
if let Some(plans) = &self.plans {
|
||||
assert!(plans.borrow().is_empty())
|
||||
let unused = plans.try_lock().expect("lock plans").take();
|
||||
if unused.is_empty() {
|
||||
return; // all good
|
||||
}
|
||||
panic_with_unused_plans(unused);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub enum MatchRequest {
|
||||
Method(http::Method),
|
||||
Url(reqwest::Url),
|
||||
Header { name: String, value: String },
|
||||
Body(String),
|
||||
fn panic_with_unused_plans(unused: Vec<Plan>) {
|
||||
eprintln!("These requests were expected, but not made:");
|
||||
for plan in unused {
|
||||
eprintln!("- {plan}");
|
||||
}
|
||||
panic!("There were expected requests that were not made.");
|
||||
}
|
||||
|
||||
pub struct WhenRequest<'net> {
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub enum MatchRequest {
|
||||
Method(NetMethod),
|
||||
Url(Url),
|
||||
Header { name: String, value: String },
|
||||
Body(bytes::Bytes),
|
||||
}
|
||||
impl Display for MatchRequest {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
match self {
|
||||
Self::Method(method) => write!(f, "{method}"),
|
||||
Self::Url(url) => write!(f, "{url}"),
|
||||
Self::Header { name, value } => write!(f, "({name}: {value})"),
|
||||
Self::Body(body) => write!(f, "Body: {body:?}"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub enum RespondWith {
|
||||
Status(StatusCode),
|
||||
Header { name: String, value: String },
|
||||
Body(bytes::Bytes),
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Display, From)]
|
||||
pub enum MockError {
|
||||
#[display("url parse: {}", 0)]
|
||||
UrlParse(#[from] url::ParseError),
|
||||
}
|
||||
impl std::error::Error for MockError {}
|
||||
|
||||
pub trait WhenState {}
|
||||
|
||||
pub struct WhenBuildRequest;
|
||||
impl WhenState for WhenBuildRequest {}
|
||||
|
||||
pub struct WhenBuildResponse;
|
||||
impl WhenState for WhenBuildResponse {}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct WhenRequest<'net, State>
|
||||
where
|
||||
State: WhenState,
|
||||
{
|
||||
_state: PhantomData<State>,
|
||||
net: &'net MockNet,
|
||||
match_on: Vec<MatchRequest>,
|
||||
respond_with: Vec<RespondWith>,
|
||||
error: Option<MockError>,
|
||||
}
|
||||
|
||||
impl<'net> WhenRequest<'net> {
|
||||
pub fn url(mut self, url: impl Into<reqwest::Url>) -> Self {
|
||||
self.match_on.push(MatchRequest::Url(url.into()));
|
||||
impl<'net> WhenRequest<'net, WhenBuildRequest> {
|
||||
fn new(net: &'net MockNet) -> Self {
|
||||
Self {
|
||||
_state: PhantomData,
|
||||
net,
|
||||
match_on: vec![],
|
||||
respond_with: vec![],
|
||||
error: None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Starts mocking a GET http request.
|
||||
#[must_use]
|
||||
pub fn get(self, url: impl Into<String>) -> Self {
|
||||
self._url(NetMethod::Get, url)
|
||||
}
|
||||
|
||||
/// Starts mocking a POST http request.
|
||||
#[must_use]
|
||||
pub fn post(self, url: impl Into<String>) -> Self {
|
||||
self._url(NetMethod::Post, url)
|
||||
}
|
||||
|
||||
/// Starts mocking a PUT http request.
|
||||
#[must_use]
|
||||
pub fn put(self, url: impl Into<String>) -> Self {
|
||||
self._url(NetMethod::Put, url)
|
||||
}
|
||||
|
||||
/// Starts mocking a DELETE http request.
|
||||
#[must_use]
|
||||
pub fn delete(self, url: impl Into<String>) -> Self {
|
||||
self._url(NetMethod::Delete, url)
|
||||
}
|
||||
|
||||
/// Starts mocking a HEAD http request.
|
||||
#[must_use]
|
||||
pub fn head(self, url: impl Into<String>) -> Self {
|
||||
self._url(NetMethod::Head, url)
|
||||
}
|
||||
|
||||
/// Starts mocking a PATCH http request.
|
||||
#[must_use]
|
||||
pub fn patch(self, url: impl Into<String>) -> Self {
|
||||
self._url(NetMethod::Patch, url)
|
||||
}
|
||||
|
||||
fn _url(mut self, method: NetMethod, url: impl Into<String>) -> Self {
|
||||
self.match_on.push(MatchRequest::Method(method));
|
||||
match Url::parse(&url.into()) {
|
||||
Ok(url) => {
|
||||
self.match_on.push(MatchRequest::Url(url));
|
||||
}
|
||||
Err(err) => {
|
||||
self.error.replace(err.into());
|
||||
}
|
||||
}
|
||||
self
|
||||
}
|
||||
|
||||
/// Specifies a header that the mock will match against.
|
||||
///
|
||||
/// Any request that does not have this header will not match the mock.
|
||||
#[must_use]
|
||||
pub fn header(mut self, name: impl Into<String>, value: impl Into<String>) -> Self {
|
||||
self.match_on.push(MatchRequest::Header {
|
||||
name: name.into(),
|
||||
|
@ -279,24 +662,233 @@ impl<'net> WhenRequest<'net> {
|
|||
});
|
||||
self
|
||||
}
|
||||
pub fn body(mut self, body: impl Into<String>) -> Self {
|
||||
|
||||
/// Specifies headers that the mock will match against.
|
||||
///
|
||||
/// Any request that does not have this header will not match the mock.
|
||||
#[must_use]
|
||||
pub fn headers(mut self, headers: HashMap<String, String>) -> Self {
|
||||
for (name, value) in headers {
|
||||
self.match_on.push(MatchRequest::Header { name, value });
|
||||
}
|
||||
self
|
||||
}
|
||||
|
||||
/// Specifies the body that the mock will match against.
|
||||
///
|
||||
/// Any request that does not have this body will not match the mock.
|
||||
#[must_use]
|
||||
pub fn body(mut self, body: impl Into<bytes::Bytes>) -> Self {
|
||||
self.match_on.push(MatchRequest::Body(body.into()));
|
||||
self
|
||||
}
|
||||
pub fn respond<T>(self, response: http::Response<T>)
|
||||
where
|
||||
T: Into<reqwest::Body>,
|
||||
{
|
||||
|
||||
/// Specifies the http Status Code that will be returned for the matching request.
|
||||
#[must_use]
|
||||
pub fn respond(self, status: StatusCode) -> WhenRequest<'net, WhenBuildResponse> {
|
||||
WhenRequest::<WhenBuildResponse> {
|
||||
_state: PhantomData,
|
||||
net: self.net,
|
||||
match_on: self.match_on,
|
||||
respond_with: vec![RespondWith::Status(status)],
|
||||
error: self.error,
|
||||
}
|
||||
}
|
||||
}
|
||||
impl<'net> WhenRequest<'net, WhenBuildResponse> {
|
||||
/// Specifies a header that will be on the response sent for the matching request.
|
||||
#[must_use]
|
||||
pub fn header(mut self, name: impl Into<String>, value: impl Into<String>) -> Self {
|
||||
let name = name.into();
|
||||
let value = value.into();
|
||||
self.respond_with.push(RespondWith::Header { name, value });
|
||||
self
|
||||
}
|
||||
|
||||
/// Specifies headers that will be on the response sent for the matching request.
|
||||
#[must_use]
|
||||
pub fn headers(mut self, headers: impl Into<HashMap<String, String>>) -> Self {
|
||||
let h: HashMap<String, String> = headers.into();
|
||||
for (name, value) in h.into_iter() {
|
||||
self.respond_with.push(RespondWith::Header { name, value });
|
||||
}
|
||||
self
|
||||
}
|
||||
|
||||
/// Specifies the body of the response sent for the matching request.
|
||||
pub fn body(mut self, body: impl Into<bytes::Bytes>) -> Result<()> {
|
||||
self.respond_with.push(RespondWith::Body(body.into()));
|
||||
self.mock()
|
||||
}
|
||||
|
||||
/// Marks a response that has no body as complete.
|
||||
pub fn mock(self) -> Result<()> {
|
||||
if let Some(error) = self.error {
|
||||
return Err(crate::net::Error::InvalidMock(error));
|
||||
}
|
||||
let mut builder = http::response::Builder::default();
|
||||
let mut response_body = None;
|
||||
for part in self.respond_with {
|
||||
builder = match part {
|
||||
RespondWith::Status(status) => builder.status(status),
|
||||
RespondWith::Header { name, value } => builder.header(name, value),
|
||||
RespondWith::Body(body) => {
|
||||
response_body.replace(body);
|
||||
builder
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let body = response_body.unwrap_or_default();
|
||||
let response = builder.body(body)?;
|
||||
self.net._when(Plan {
|
||||
match_request: self.match_on,
|
||||
response: response.into(),
|
||||
});
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
/// 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,
|
||||
}
|
||||
}
|
||||
|
||||
fn new(net: &'net MockNet, method: impl Into<http::Method>) -> Self {
|
||||
Self {
|
||||
net,
|
||||
match_on: vec![MatchRequest::Method(method.into())],
|
||||
/// 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::*;
|
||||
|
||||
fn is_normal<T: Sized + Send + Sync + Unpin>() {}
|
||||
|
||||
#[test]
|
||||
fn normal_types() {
|
||||
is_normal::<Net>();
|
||||
// is_normal::<MockNet>(); // only used in test setup - no need to be Send or Sync
|
||||
is_normal::<MatchRequest>();
|
||||
is_normal::<Plan>();
|
||||
// is_normal::<WhenRequest>(); // only used in test setup - no need to be Send or Sync
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn plan_display() {
|
||||
let plan = Plan {
|
||||
match_request: vec![
|
||||
MatchRequest::Method(NetMethod::Put),
|
||||
MatchRequest::Header {
|
||||
name: "alpha".into(),
|
||||
value: "1".into(),
|
||||
},
|
||||
MatchRequest::Body("req body".into()),
|
||||
],
|
||||
response: http::response::Builder::default()
|
||||
.status(204)
|
||||
.header("foo", "bar")
|
||||
.header("baz", "buck")
|
||||
.body("contents")
|
||||
.expect("body")
|
||||
.into(),
|
||||
};
|
||||
let result = plan.to_string();
|
||||
|
||||
let expected = [
|
||||
"Put",
|
||||
"(alpha: 1)",
|
||||
"Body: b\"req body\"",
|
||||
"=>",
|
||||
"Response {",
|
||||
"url: \"http://no.url.provided.local/\",",
|
||||
"status: 204,",
|
||||
"headers: {\"foo\": \"bar\", \"baz\": \"buck\"}",
|
||||
"}\n",
|
||||
]
|
||||
.join(" ");
|
||||
assert_eq!(result, expected);
|
||||
}
|
||||
}
|
||||
|
|
164
tests/fs.rs
164
tests/fs.rs
|
@ -5,8 +5,25 @@ use kxio::fs;
|
|||
type TestResult = Result<(), fs::Error>;
|
||||
|
||||
mod path {
|
||||
use fs::{PathHandle, PathMarker};
|
||||
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn temp_as_real() {
|
||||
let fs = fs::temp().expect("temp fs");
|
||||
let read = fs.as_real();
|
||||
|
||||
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::*;
|
||||
|
||||
|
@ -418,25 +435,42 @@ mod path {
|
|||
assert_eq!(src_pathbuf, dst_pathbuf);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn from_file() {
|
||||
let fs = fs::temp().expect("temp fs");
|
||||
|
||||
let file_path = fs.base().join("foo");
|
||||
let file = fs.file(&file_path);
|
||||
|
||||
let path: PathHandle<PathMarker> = file.into();
|
||||
|
||||
assert_eq!(path.as_pathbuf(), file_path);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn from_dir() {
|
||||
let fs = fs::temp().expect("temp fs");
|
||||
|
||||
let dir_path = fs.base().join("foo");
|
||||
let dir = fs.dir(&dir_path);
|
||||
|
||||
let path: PathHandle<PathMarker> = dir.into();
|
||||
|
||||
assert_eq!(path.as_pathbuf(), dir_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 {
|
||||
|
@ -518,6 +552,53 @@ mod file {
|
|||
path.remove().expect("remove");
|
||||
}
|
||||
|
||||
mod from_path {
|
||||
use fs::{Error, FileHandle};
|
||||
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn path_is_dir() {
|
||||
let fs = fs::temp().expect("temp fs");
|
||||
let pathbuf = fs.base().join("foo");
|
||||
let dir = fs.dir(&pathbuf);
|
||||
dir.create().expect("create dir");
|
||||
|
||||
let path = fs.path(&pathbuf);
|
||||
|
||||
let_assert!(Err(Error::NotAFile { path: err_path }) = FileHandle::try_from(path));
|
||||
|
||||
assert_eq!(err_path, pathbuf);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn path_is_file() {
|
||||
let fs = fs::temp().expect("temp fs");
|
||||
let pathbuf = fs.base().join("foo");
|
||||
let file = fs.file(&pathbuf);
|
||||
file.write("contents").expect("write file");
|
||||
|
||||
let path = fs.path(&pathbuf);
|
||||
|
||||
let_assert!(Ok(file_result) = FileHandle::try_from(path));
|
||||
|
||||
assert_eq!(file_result.as_pathbuf(), pathbuf);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn path_is_error() {
|
||||
let fs = fs::temp().expect("temp fs");
|
||||
let pathbuf = fs.base().join("foo");
|
||||
// does not exist
|
||||
|
||||
let path = fs.path(&pathbuf);
|
||||
|
||||
let_assert!(Err(Error::NotAFile { path: err_path }) = FileHandle::try_from(path));
|
||||
|
||||
assert_eq!(err_path, pathbuf);
|
||||
}
|
||||
}
|
||||
|
||||
mod remove {
|
||||
use super::*;
|
||||
#[test]
|
||||
|
@ -708,6 +789,61 @@ mod file {
|
|||
mod dir {
|
||||
use super::*;
|
||||
|
||||
mod from_path {
|
||||
use fs::{DirHandle, Error};
|
||||
|
||||
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");
|
||||
let pathbuf = fs.base().join("foo");
|
||||
let dir = fs.dir(&pathbuf);
|
||||
dir.create().expect("create dir");
|
||||
|
||||
let path = fs.path(&pathbuf);
|
||||
|
||||
let_assert!(Ok(dir_result) = DirHandle::try_from(path));
|
||||
|
||||
assert_eq!(dir_result.as_pathbuf(), pathbuf);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn path_is_file() {
|
||||
let fs = fs::temp().expect("temp fs");
|
||||
let pathbuf = fs.base().join("foo");
|
||||
let file = fs.file(&pathbuf);
|
||||
file.write("contents").expect("write file");
|
||||
|
||||
let path = fs.path(&pathbuf);
|
||||
|
||||
let_assert!(Err(Error::NotADirectory { path: err_path }) = DirHandle::try_from(path));
|
||||
|
||||
assert_eq!(err_path, pathbuf);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn path_is_error() {
|
||||
let fs = fs::temp().expect("temp fs");
|
||||
let pathbuf = fs.base().join("foo");
|
||||
// does not exist
|
||||
|
||||
let path = fs.path(&pathbuf);
|
||||
|
||||
let_assert!(Err(Error::NotADirectory { path: err_path }) = DirHandle::try_from(path));
|
||||
|
||||
assert_eq!(err_path, pathbuf);
|
||||
}
|
||||
}
|
||||
|
||||
mod create {
|
||||
use super::*;
|
||||
#[test]
|
||||
|
|
272
tests/net.rs
272
tests/net.rs
|
@ -1,32 +1,29 @@
|
|||
use assert2::let_assert;
|
||||
use http::Method;
|
||||
use std::collections::HashMap;
|
||||
|
||||
use http::StatusCode;
|
||||
//
|
||||
use kxio::net::{Error, MockNet, Net};
|
||||
use reqwest::Url;
|
||||
|
||||
use assert2::let_assert;
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_get_url() {
|
||||
//given
|
||||
let mock_net = kxio::net::mock();
|
||||
let client = mock_net.client();
|
||||
|
||||
let url = "https://www.example.com";
|
||||
let my_response = mock_net
|
||||
.response()
|
||||
.status(200)
|
||||
.body("Get OK")
|
||||
.expect("body");
|
||||
|
||||
mock_net
|
||||
.on(Method::GET)
|
||||
.url(Url::parse(url).expect("parse url"))
|
||||
.respond(my_response);
|
||||
.on()
|
||||
.get(url)
|
||||
.respond(StatusCode::OK)
|
||||
.header("foo", "bar")
|
||||
.headers(HashMap::new())
|
||||
.body("Get OK")
|
||||
.expect("mock");
|
||||
|
||||
//when
|
||||
let response = Net::from(mock_net)
|
||||
.send(client.get(url))
|
||||
.await
|
||||
.expect("response");
|
||||
let response = Net::from(mock_net).get(url).send().await.expect("response");
|
||||
|
||||
//then
|
||||
assert_eq!(response.status(), http::StatusCode::OK);
|
||||
|
@ -34,24 +31,142 @@ async fn test_get_url() {
|
|||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_get_wrong_url() {
|
||||
async fn test_post_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 my_response = mock_net
|
||||
.response()
|
||||
.status(200)
|
||||
|
||||
net.on()
|
||||
.post(url)
|
||||
.respond(StatusCode::OK)
|
||||
.body("post OK")
|
||||
.expect("mock");
|
||||
|
||||
//when
|
||||
let response = Net::from(net)
|
||||
.send(client.post(url))
|
||||
.await
|
||||
.expect("reponse");
|
||||
|
||||
//then
|
||||
assert_eq!(response.status(), http::StatusCode::OK);
|
||||
assert_eq!(response.bytes().await.expect("response body"), "post OK");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_put_url() {
|
||||
//given
|
||||
let net = kxio::net::mock();
|
||||
let client = net.client();
|
||||
|
||||
let url = "https://www.example.com";
|
||||
|
||||
net.on()
|
||||
.put(url)
|
||||
.respond(StatusCode::OK)
|
||||
.body("put OK")
|
||||
.expect("mock");
|
||||
|
||||
//when
|
||||
let response = Net::from(net).send(client.put(url)).await.expect("reponse");
|
||||
|
||||
//then
|
||||
assert_eq!(response.status(), http::StatusCode::OK);
|
||||
assert_eq!(response.bytes().await.expect("response body"), "put OK");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_delete_url() {
|
||||
//given
|
||||
let net = kxio::net::mock();
|
||||
let client = net.client();
|
||||
|
||||
let url = "https://www.example.com";
|
||||
|
||||
net.on()
|
||||
.delete(url)
|
||||
.respond(StatusCode::OK)
|
||||
.body("delete OK")
|
||||
.expect("mock");
|
||||
|
||||
//when
|
||||
let response = Net::from(net)
|
||||
.send(client.delete(url))
|
||||
.await
|
||||
.expect("reponse");
|
||||
|
||||
//then
|
||||
assert_eq!(response.status(), http::StatusCode::OK);
|
||||
assert_eq!(response.bytes().await.expect("response body"), "delete OK");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_head_url() {
|
||||
//given
|
||||
let net = kxio::net::mock();
|
||||
let client = net.client();
|
||||
|
||||
let url = "https://www.example.com";
|
||||
|
||||
net.on()
|
||||
.head(url)
|
||||
.respond(StatusCode::OK)
|
||||
.body("head OK")
|
||||
.expect("mock");
|
||||
|
||||
//when
|
||||
let response = Net::from(net)
|
||||
.send(client.head(url))
|
||||
.await
|
||||
.expect("reponse");
|
||||
|
||||
//then
|
||||
assert_eq!(response.status(), http::StatusCode::OK);
|
||||
assert_eq!(response.bytes().await.expect("response body"), "head OK");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_patch_url() {
|
||||
//given
|
||||
let net = kxio::net::mock();
|
||||
let client = net.client();
|
||||
|
||||
let url = "https://www.example.com";
|
||||
|
||||
net.on()
|
||||
.patch(url)
|
||||
.respond(StatusCode::OK)
|
||||
.body("patch OK")
|
||||
.expect("mock");
|
||||
|
||||
//when
|
||||
let response = Net::from(net)
|
||||
.send(client.patch(url))
|
||||
.await
|
||||
.expect("reponse");
|
||||
|
||||
//then
|
||||
assert_eq!(response.status(), http::StatusCode::OK);
|
||||
assert_eq!(response.bytes().await.expect("response body"), "patch OK");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_get_wrong_url() {
|
||||
//given
|
||||
let net = kxio::net::mock();
|
||||
let client = net.client();
|
||||
|
||||
let url = "https://www.example.com";
|
||||
|
||||
net.on()
|
||||
.get(url)
|
||||
.respond(StatusCode::OK)
|
||||
.body("Get OK")
|
||||
.expect("body");
|
||||
.expect("mock");
|
||||
|
||||
mock_net
|
||||
.on(Method::GET)
|
||||
.url(Url::parse(url).expect("parse url"))
|
||||
.respond(my_response);
|
||||
|
||||
let net = Net::from(mock_net);
|
||||
let net = Net::from(net);
|
||||
|
||||
//when
|
||||
let_assert!(
|
||||
|
@ -63,45 +178,18 @@ 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");
|
||||
let mock_net = MockNet::try_from(net).await.expect("recover net");
|
||||
mock_net.reset();
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_post_url() {
|
||||
//given
|
||||
let net = kxio::net::mock();
|
||||
let client = net.client();
|
||||
|
||||
let url = "https://www.example.com";
|
||||
let my_response = net.response().status(200).body("Post OK").expect("body");
|
||||
|
||||
net.on(Method::POST)
|
||||
.url(Url::parse(url).expect("parse url"))
|
||||
.respond(my_response);
|
||||
|
||||
//when
|
||||
let response = Net::from(net)
|
||||
.send(client.post(url))
|
||||
.await
|
||||
.expect("reponse");
|
||||
|
||||
//then
|
||||
assert_eq!(response.status(), http::StatusCode::OK);
|
||||
assert_eq!(response.bytes().await.expect("response body"), "Post OK");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_post_by_method() {
|
||||
//given
|
||||
let net = kxio::net::mock();
|
||||
let client = net.client();
|
||||
|
||||
let my_response = net.response().status(200).body("").expect("response body");
|
||||
|
||||
net.on(Method::POST)
|
||||
// NOTE: No URL specified - so shou∂ match any URL
|
||||
.respond(my_response);
|
||||
// NOTE: No URL specified - so should match any URL
|
||||
net.on().respond(StatusCode::OK).body("").expect("mock");
|
||||
|
||||
//when
|
||||
let response = Net::from(net)
|
||||
|
@ -120,16 +208,12 @@ async fn test_post_by_body() {
|
|||
let net = kxio::net::mock();
|
||||
let client = net.client();
|
||||
|
||||
let my_response = net
|
||||
.response()
|
||||
.status(200)
|
||||
.body("response body")
|
||||
.expect("body");
|
||||
|
||||
net.on(Method::POST)
|
||||
// No URL - so any POST with a matching body
|
||||
// No URL - so any POST with a matching body
|
||||
net.on()
|
||||
.body("match on body")
|
||||
.respond(my_response);
|
||||
.respond(StatusCode::OK)
|
||||
.body("response body")
|
||||
.expect("mock");
|
||||
|
||||
//when
|
||||
let response = Net::from(net)
|
||||
|
@ -151,15 +235,11 @@ async fn test_post_by_header() {
|
|||
let net = kxio::net::mock();
|
||||
let client = net.client();
|
||||
|
||||
let my_response = net
|
||||
.response()
|
||||
.status(200)
|
||||
.body("response body")
|
||||
.expect("body");
|
||||
|
||||
net.on(Method::POST)
|
||||
net.on()
|
||||
.header("test", "match")
|
||||
.respond(my_response);
|
||||
.respond(StatusCode::OK)
|
||||
.body("response body")
|
||||
.expect("mock");
|
||||
|
||||
//when
|
||||
let response = Net::from(net)
|
||||
|
@ -186,16 +266,12 @@ async fn test_post_by_header_wrong_value() {
|
|||
let mock_net = kxio::net::mock();
|
||||
let client = mock_net.client();
|
||||
|
||||
let my_response = mock_net
|
||||
.response()
|
||||
.status(200)
|
||||
.body("response body")
|
||||
.expect("body");
|
||||
|
||||
mock_net
|
||||
.on(Method::POST)
|
||||
.on()
|
||||
.header("test", "match")
|
||||
.respond(my_response);
|
||||
.respond(StatusCode::OK)
|
||||
.body("response body")
|
||||
.expect("mock");
|
||||
let net = Net::from(mock_net);
|
||||
|
||||
//when
|
||||
|
@ -211,7 +287,7 @@ async fn test_post_by_header_wrong_value() {
|
|||
//then
|
||||
let_assert!(Err(kxio::net::Error::UnexpectedMockRequest(_)) = response);
|
||||
|
||||
MockNet::try_from(net).expect("recover mock").reset();
|
||||
MockNet::try_from(net).await.expect("recover mock").reset();
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
|
@ -221,16 +297,13 @@ async fn test_unused_post_as_net() {
|
|||
let mock_net = kxio::net::mock();
|
||||
|
||||
let url = "https://www.example.com";
|
||||
let my_response = mock_net
|
||||
.response()
|
||||
.status(200)
|
||||
.body("Post OK")
|
||||
.expect("body");
|
||||
|
||||
mock_net
|
||||
.on(Method::POST)
|
||||
.url(Url::parse(url).expect("prase url"))
|
||||
.respond(my_response);
|
||||
.on()
|
||||
.post(url)
|
||||
.respond(StatusCode::OK)
|
||||
.body("Post OK")
|
||||
.expect("mock");
|
||||
|
||||
let _net = Net::from(mock_net);
|
||||
|
||||
|
@ -249,16 +322,13 @@ async fn test_unused_post_as_mocknet() {
|
|||
let mock_net = kxio::net::mock();
|
||||
|
||||
let url = "https://www.example.com";
|
||||
let my_response = mock_net
|
||||
.response()
|
||||
.status(200)
|
||||
.body("Post OK")
|
||||
.expect("body");
|
||||
|
||||
mock_net
|
||||
.on(Method::POST)
|
||||
.url(Url::parse(url).expect("parse url"))
|
||||
.respond(my_response);
|
||||
.on()
|
||||
.post(url)
|
||||
.respond(StatusCode::OK)
|
||||
.body("Post OK")
|
||||
.expect("mock");
|
||||
|
||||
//when
|
||||
// don't send the planned request
|
||||
|
|
Loading…
Reference in a new issue