add test for Garde
This commit is contained in:
@@ -238,9 +238,9 @@ pub mod typed_path;
|
||||
|
||||
use crate::{HasValidate, HasValidateArgs};
|
||||
use axum_extra::extract::{Cached, WithRejection};
|
||||
use validator::{Validate, ValidateArgs};
|
||||
use validator::ValidateArgs;
|
||||
|
||||
impl<T: Validate> HasValidate for Cached<T> {
|
||||
impl<T> HasValidate for Cached<T> {
|
||||
type Validate = T;
|
||||
|
||||
fn get_validate(&self) -> &Self::Validate {
|
||||
@@ -255,7 +255,7 @@ impl<'v, T: ValidateArgs<'v>> HasValidateArgs<'v> for Cached<T> {
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: Validate, R> HasValidate for WithRejection<T, R> {
|
||||
impl<T, R> HasValidate for WithRejection<T, R> {
|
||||
type Validate = T;
|
||||
fn get_validate(&self) -> &T {
|
||||
&self.0
|
||||
|
||||
@@ -40,9 +40,9 @@
|
||||
|
||||
use crate::{HasValidate, HasValidateArgs};
|
||||
use axum_extra::extract::Form;
|
||||
use validator::{Validate, ValidateArgs};
|
||||
use validator::ValidateArgs;
|
||||
|
||||
impl<T: Validate> HasValidate for Form<T> {
|
||||
impl<T> HasValidate for Form<T> {
|
||||
type Validate = T;
|
||||
fn get_validate(&self) -> &T {
|
||||
&self.0
|
||||
|
||||
@@ -42,9 +42,9 @@
|
||||
|
||||
use crate::{HasValidate, HasValidateArgs};
|
||||
use axum_extra::protobuf::Protobuf;
|
||||
use validator::{Validate, ValidateArgs};
|
||||
use validator::ValidateArgs;
|
||||
|
||||
impl<T: Validate> HasValidate for Protobuf<T> {
|
||||
impl<T> HasValidate for Protobuf<T> {
|
||||
type Validate = T;
|
||||
fn get_validate(&self) -> &T {
|
||||
&self.0
|
||||
|
||||
@@ -43,9 +43,9 @@
|
||||
|
||||
use crate::{HasValidate, HasValidateArgs};
|
||||
use axum_extra::extract::Query;
|
||||
use validator::{Validate, ValidateArgs};
|
||||
use validator::ValidateArgs;
|
||||
|
||||
impl<T: Validate> HasValidate for Query<T> {
|
||||
impl<T> HasValidate for Query<T> {
|
||||
type Validate = T;
|
||||
fn get_validate(&self) -> &T {
|
||||
&self.0
|
||||
|
||||
@@ -49,6 +49,7 @@
|
||||
//! }
|
||||
//! ```
|
||||
|
||||
use crate::garde::Garde;
|
||||
use crate::{Valid, ValidEx};
|
||||
use axum_extra::routing::TypedPath;
|
||||
use std::fmt::Display;
|
||||
@@ -60,3 +61,7 @@ impl<T: TypedPath + Display> TypedPath for Valid<T> {
|
||||
impl<T: TypedPath + Display, A> TypedPath for ValidEx<T, A> {
|
||||
const PATH: &'static str = T::PATH;
|
||||
}
|
||||
|
||||
impl<T: TypedPath + Display> TypedPath for Garde<T> {
|
||||
const PATH: &'static str = T::PATH;
|
||||
}
|
||||
|
||||
@@ -40,9 +40,9 @@
|
||||
|
||||
use crate::{HasValidate, HasValidateArgs};
|
||||
use axum::Form;
|
||||
use validator::{Validate, ValidateArgs};
|
||||
use validator::ValidateArgs;
|
||||
|
||||
impl<T: Validate> HasValidate for Form<T> {
|
||||
impl<T> HasValidate for Form<T> {
|
||||
type Validate = T;
|
||||
fn get_validate(&self) -> &T {
|
||||
&self.0
|
||||
|
||||
65
src/garde.rs
65
src/garde.rs
@@ -14,9 +14,9 @@ use std::ops::{Deref, DerefMut};
|
||||
/// # `Garde` data extractor
|
||||
///
|
||||
#[derive(Debug, Clone, Copy, Default)]
|
||||
pub struct Garde<E, A>(pub E, pub A);
|
||||
pub struct Garde<E>(pub E);
|
||||
|
||||
impl<E, A> Deref for Garde<E, A> {
|
||||
impl<E> Deref for Garde<E> {
|
||||
type Target = E;
|
||||
|
||||
fn deref(&self) -> &Self::Target {
|
||||
@@ -24,19 +24,19 @@ impl<E, A> Deref for Garde<E, A> {
|
||||
}
|
||||
}
|
||||
|
||||
impl<E, A> DerefMut for Garde<E, A> {
|
||||
impl<E> DerefMut for Garde<E> {
|
||||
fn deref_mut(&mut self) -> &mut Self::Target {
|
||||
&mut self.0
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: Display, A> Display for Garde<T, A> {
|
||||
impl<T: Display> Display for Garde<T> {
|
||||
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
|
||||
self.0.fmt(f)
|
||||
}
|
||||
}
|
||||
|
||||
impl<E, A> Garde<E, A> {
|
||||
impl<E> Garde<E> {
|
||||
/// Consumes the `ValidEx` and returns the validated data within.
|
||||
///
|
||||
/// This returns the `E` type which represents the data that has been
|
||||
@@ -44,18 +44,6 @@ impl<E, A> Garde<E, A> {
|
||||
pub fn into_inner(self) -> E {
|
||||
self.0
|
||||
}
|
||||
|
||||
/// Returns a reference to the validation arguments.
|
||||
///
|
||||
/// This provides access to the `A` type which contains the arguments used
|
||||
/// to validate the data. These arguments were passed to the validation
|
||||
/// function.
|
||||
pub fn arguments<'a>(&'a self) -> <<A as GardeArgument>::T as Validate>::Context
|
||||
where
|
||||
A: GardeArgument,
|
||||
{
|
||||
self.1.get()
|
||||
}
|
||||
}
|
||||
|
||||
fn response_builder(ve: garde::Report) -> Response {
|
||||
@@ -69,23 +57,6 @@ fn response_builder(ve: garde::Report) -> Response {
|
||||
}
|
||||
}
|
||||
|
||||
/// `Arguments` provides the validation arguments for the data type `T`.
|
||||
///
|
||||
/// This trait has an associated type `T` which represents the data type to
|
||||
/// validate. `T` must implement the `ValidateArgs` trait which defines the
|
||||
/// validation logic.
|
||||
///
|
||||
/// It's important to mention that types implementing `Arguments` should be a part of the router's state
|
||||
/// (either through implementing `FromRef<StateType>` or by directly becoming the state)
|
||||
/// to enable automatic arguments retrieval during validation.
|
||||
///
|
||||
pub trait GardeArgument {
|
||||
/// The data type to validate using this arguments
|
||||
type T: Validate;
|
||||
/// This method gets the arguments required by `ValidateArgs::validate_args`
|
||||
fn get(&self) -> <<Self as GardeArgument>::T as Validate>::Context;
|
||||
}
|
||||
|
||||
/// `ValidRejection` is returned when the `Valid` extractor fails.
|
||||
///
|
||||
/// This enumeration captures two types of errors that can occur when using `Valid`: errors related to the validation
|
||||
@@ -93,7 +64,7 @@ pub trait GardeArgument {
|
||||
///
|
||||
#[derive(Debug)]
|
||||
pub enum GardeRejection<E> {
|
||||
/// `Valid` variant captures errors related to the validation logic. It contains `ValidationErrors`
|
||||
/// `Valid` variant captures errors related to the validation logic. It contains `garde::Report`
|
||||
/// which is a collection of validation failures for each field.
|
||||
Report(garde::Report),
|
||||
/// `Inner` variant represents potential errors that might occur within the inner extractor.
|
||||
@@ -134,43 +105,43 @@ impl<E: IntoResponse> IntoResponse for GardeRejection<E> {
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl<State, Body, Extractor, Args> FromRequest<State, Body> for Garde<Extractor, Args>
|
||||
impl<State, Body, Extractor, Context> FromRequest<State, Body> for Garde<Extractor>
|
||||
where
|
||||
State: Send + Sync,
|
||||
Body: Send + Sync + 'static,
|
||||
Args: Send + Sync + FromRef<State> + GardeArgument<T = <Extractor as HasValidate>::Validate>,
|
||||
Context: Send + Sync + FromRef<State>,
|
||||
Extractor: HasValidate + FromRequest<State, Body>,
|
||||
<Extractor as HasValidate>::Validate: garde::Validate,
|
||||
<Extractor as HasValidate>::Validate: garde::Validate<Context = Context>,
|
||||
{
|
||||
type Rejection = GardeRejection<<Extractor as FromRequest<State, Body>>::Rejection>;
|
||||
|
||||
async fn from_request(req: Request<Body>, state: &State) -> Result<Self, Self::Rejection> {
|
||||
let arguments: Args = FromRef::from_ref(state);
|
||||
let context: Context = FromRef::from_ref(state);
|
||||
let inner = Extractor::from_request(req, state)
|
||||
.await
|
||||
.map_err(GardeRejection::Inner)?;
|
||||
|
||||
inner.get_validate().validate(&arguments.get())?;
|
||||
Ok(Garde(inner, arguments))
|
||||
inner.get_validate().validate(&context)?;
|
||||
Ok(Garde(inner))
|
||||
}
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl<State, Extractor, Args> FromRequestParts<State> for Garde<Extractor, Args>
|
||||
impl<State, Extractor, Context> FromRequestParts<State> for Garde<Extractor>
|
||||
where
|
||||
State: Send + Sync,
|
||||
Args: Send + Sync + FromRef<State> + GardeArgument<T = <Extractor as HasValidate>::Validate>,
|
||||
Context: Send + Sync + FromRef<State>,
|
||||
Extractor: HasValidate + FromRequestParts<State>,
|
||||
<Extractor as HasValidate>::Validate: garde::Validate,
|
||||
<Extractor as HasValidate>::Validate: garde::Validate<Context = Context>,
|
||||
{
|
||||
type Rejection = GardeRejection<<Extractor as FromRequestParts<State>>::Rejection>;
|
||||
|
||||
async fn from_request_parts(parts: &mut Parts, state: &State) -> Result<Self, Self::Rejection> {
|
||||
let arguments: Args = FromRef::from_ref(state);
|
||||
let context: Context = FromRef::from_ref(state);
|
||||
let inner = Extractor::from_request_parts(parts, state)
|
||||
.await
|
||||
.map_err(GardeRejection::Inner)?;
|
||||
inner.get_validate().validate(&arguments.get())?;
|
||||
Ok(Garde(inner, arguments))
|
||||
inner.get_validate().validate(&context)?;
|
||||
Ok(Garde(inner))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -40,9 +40,9 @@
|
||||
|
||||
use crate::{HasValidate, HasValidateArgs};
|
||||
use axum::Json;
|
||||
use validator::{Validate, ValidateArgs};
|
||||
use validator::ValidateArgs;
|
||||
|
||||
impl<T: Validate> HasValidate for Json<T> {
|
||||
impl<T> HasValidate for Json<T> {
|
||||
type Validate = T;
|
||||
fn get_validate(&self) -> &T {
|
||||
&self.0
|
||||
|
||||
@@ -215,7 +215,7 @@ impl<E: IntoResponse> IntoResponse for ValidRejection<E> {
|
||||
|
||||
/// Trait for types that can supply a reference that can be validated.
|
||||
///
|
||||
/// Extractor types `T` that implement this trait can be used with `Valid`.
|
||||
/// Extractor types `T` that implement this trait can be used with `Valid` or `Garde`.
|
||||
///
|
||||
pub trait HasValidate {
|
||||
/// Inner type that can be validated for correctness
|
||||
|
||||
@@ -49,9 +49,9 @@
|
||||
|
||||
use crate::{HasValidate, HasValidateArgs};
|
||||
use axum_msgpack::{MsgPack, MsgPackRaw};
|
||||
use validator::{Validate, ValidateArgs};
|
||||
use validator::ValidateArgs;
|
||||
|
||||
impl<T: Validate> HasValidate for MsgPack<T> {
|
||||
impl<T> HasValidate for MsgPack<T> {
|
||||
type Validate = T;
|
||||
fn get_validate(&self) -> &T {
|
||||
&self.0
|
||||
@@ -65,7 +65,7 @@ impl<'v, T: ValidateArgs<'v>> HasValidateArgs<'v> for MsgPack<T> {
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: Validate> HasValidate for MsgPackRaw<T> {
|
||||
impl<T> HasValidate for MsgPackRaw<T> {
|
||||
type Validate = T;
|
||||
fn get_validate(&self) -> &T {
|
||||
&self.0
|
||||
|
||||
@@ -39,9 +39,9 @@
|
||||
|
||||
use crate::{HasValidate, HasValidateArgs};
|
||||
use axum::extract::Path;
|
||||
use validator::{Validate, ValidateArgs};
|
||||
use validator::ValidateArgs;
|
||||
|
||||
impl<T: Validate> HasValidate for Path<T> {
|
||||
impl<T> HasValidate for Path<T> {
|
||||
type Validate = T;
|
||||
fn get_validate(&self) -> &T {
|
||||
&self.0
|
||||
|
||||
@@ -43,9 +43,9 @@
|
||||
|
||||
use crate::{HasValidate, HasValidateArgs};
|
||||
use axum::extract::Query;
|
||||
use validator::{Validate, ValidateArgs};
|
||||
use validator::ValidateArgs;
|
||||
|
||||
impl<T: Validate> HasValidate for Query<T> {
|
||||
impl<T> HasValidate for Query<T> {
|
||||
type Validate = T;
|
||||
fn get_validate(&self) -> &T {
|
||||
&self.0
|
||||
|
||||
64
src/test.rs
64
src/test.rs
@@ -1,3 +1,4 @@
|
||||
use crate::garde::Garde;
|
||||
use crate::tests::{ValidTest, ValidTestParameter};
|
||||
use crate::{Arguments, HasValidate, HasValidateArgs, Valid, ValidEx, VALIDATION_ERROR_STATUS};
|
||||
use axum::extract::{FromRef, Path, Query};
|
||||
@@ -82,6 +83,21 @@ impl Default for ParametersExValidationArgumentsInner {
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Deserialize, Serialize, garde::Validate, Eq, PartialEq)]
|
||||
#[cfg_attr(feature = "extra_protobuf", derive(prost::Message))]
|
||||
#[cfg_attr(
|
||||
feature = "typed_multipart",
|
||||
derive(axum_typed_multipart::TryFromMultipart)
|
||||
)]
|
||||
pub struct ParametersGarde {
|
||||
#[garde(range(min = 5, max = 10))]
|
||||
#[cfg_attr(feature = "extra_protobuf", prost(int32, tag = "1"))]
|
||||
v0: i32,
|
||||
#[garde(length(min = 1, max = 10))]
|
||||
#[cfg_attr(feature = "extra_protobuf", prost(string, tag = "2"))]
|
||||
v1: String,
|
||||
}
|
||||
|
||||
static VALID_PARAMETERS: Lazy<Parameters> = Lazy::new(|| Parameters {
|
||||
v0: 5,
|
||||
v1: String::from("0123456789"),
|
||||
@@ -129,6 +145,10 @@ struct MyState {
|
||||
typed_path_validation_ctx: extra_typed_path::TypedPathParamExValidationArguments,
|
||||
}
|
||||
|
||||
impl FromRef<MyState> for () {
|
||||
fn from_ref(_: &MyState) -> Self {}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_main() -> anyhow::Result<()> {
|
||||
let state = MyState {
|
||||
@@ -144,8 +164,10 @@ async fn test_main() -> anyhow::Result<()> {
|
||||
.route(route::JSON, post(extract_json))
|
||||
.route(route::PATH_EX, get(extract_path_ex))
|
||||
.route(route::QUERY_EX, get(extract_query_ex))
|
||||
.route(route::QUERY_GARDE, get(extract_query_garde))
|
||||
.route(route::FORM_EX, post(extract_form_ex))
|
||||
.route(route::JSON_EX, post(extract_json_ex));
|
||||
.route(route::JSON_EX, post(extract_json_ex))
|
||||
.route(route::JSON_GARDE, post(extract_json_garde));
|
||||
|
||||
#[cfg(feature = "typed_header")]
|
||||
let router = router
|
||||
@@ -344,6 +366,11 @@ async fn test_main() -> anyhow::Result<()> {
|
||||
.execute::<Query<Parameters>>(Method::GET, route::QUERY_EX)
|
||||
.await?;
|
||||
|
||||
// Garde
|
||||
test_executor
|
||||
.execute::<Query<Parameters>>(Method::GET, route::QUERY_GARDE)
|
||||
.await?;
|
||||
|
||||
// Valid
|
||||
test_executor
|
||||
.execute::<Form<Parameters>>(Method::POST, route::FORM)
|
||||
@@ -364,6 +391,11 @@ async fn test_main() -> anyhow::Result<()> {
|
||||
.execute::<Json<Parameters>>(Method::POST, route::JSON_EX)
|
||||
.await?;
|
||||
|
||||
// Garde
|
||||
test_executor
|
||||
.execute::<Json<Parameters>>(Method::POST, route::JSON_GARDE)
|
||||
.await?;
|
||||
|
||||
#[cfg(feature = "typed_header")]
|
||||
{
|
||||
use axum::TypedHeader;
|
||||
@@ -666,10 +698,12 @@ mod route {
|
||||
pub const PATH_EX: &str = "/path_ex/:v0/:v1";
|
||||
pub const QUERY: &str = "/query";
|
||||
pub const QUERY_EX: &str = "/query_ex";
|
||||
pub const QUERY_GARDE: &str = "/query_garde";
|
||||
pub const FORM: &str = "/form";
|
||||
pub const FORM_EX: &str = "/form_ex";
|
||||
pub const JSON: &str = "/json";
|
||||
pub const JSON_EX: &str = "/json_ex";
|
||||
pub const JSON_GARDE: &str = "/json_garde";
|
||||
}
|
||||
|
||||
async fn extract_path(Valid(Path(parameters)): Valid<Path<Parameters>>) -> StatusCode {
|
||||
@@ -692,6 +726,12 @@ async fn extract_query_ex(
|
||||
validate_again_ex(parameters, args.get())
|
||||
}
|
||||
|
||||
async fn extract_query_garde(
|
||||
Garde(Query(parameters)): Garde<Query<ParametersGarde>>,
|
||||
) -> StatusCode {
|
||||
validate_again_garde(parameters, ())
|
||||
}
|
||||
|
||||
async fn extract_form(Valid(Form(parameters)): Valid<Form<Parameters>>) -> StatusCode {
|
||||
validate_again(parameters)
|
||||
}
|
||||
@@ -712,6 +752,10 @@ async fn extract_json_ex(
|
||||
validate_again_ex(parameters, args.get())
|
||||
}
|
||||
|
||||
async fn extract_json_garde(Garde(Json(parameters)): Garde<Json<ParametersGarde>>) -> StatusCode {
|
||||
validate_again_garde(parameters, ())
|
||||
}
|
||||
|
||||
fn validate_again<V: Validate>(validate: V) -> StatusCode {
|
||||
// The `Valid` extractor has validated the `parameters` once,
|
||||
// it should have returned `400 BAD REQUEST` if the `parameters` were invalid,
|
||||
@@ -727,9 +771,9 @@ fn validate_again_ex<'v, V: ValidateArgs<'v>>(
|
||||
validate: V,
|
||||
args: <V as ValidateArgs<'v>>::Args,
|
||||
) -> StatusCode {
|
||||
// The `Valid` extractor has validated the `parameters` once,
|
||||
// The `ValidEx` extractor has validated the `parameters` once,
|
||||
// it should have returned `400 BAD REQUEST` if the `parameters` were invalid,
|
||||
// Let's validate them again to check if the `Valid` extractor works well.
|
||||
// Let's validate them again to check if the `ValidEx` extractor works well.
|
||||
// If it works properly, this function will never return `500 INTERNAL SERVER ERROR`
|
||||
match validate.validate_args(args) {
|
||||
Ok(_) => StatusCode::OK,
|
||||
@@ -737,6 +781,20 @@ fn validate_again_ex<'v, V: ValidateArgs<'v>>(
|
||||
}
|
||||
}
|
||||
|
||||
fn validate_again_garde<V>(validate: V, context: V::Context) -> StatusCode
|
||||
where
|
||||
V: garde::Validate,
|
||||
{
|
||||
// The `Garde` extractor has validated the `parameters` once,
|
||||
// it should have returned `400 BAD REQUEST` if the `parameters` were invalid,
|
||||
// Let's validate them again to check if the `Garde` extractor works well.
|
||||
// If it works properly, this function will never return `500 INTERNAL SERVER ERROR`
|
||||
match validate.validate(&context) {
|
||||
Ok(_) => StatusCode::OK,
|
||||
Err(_) => StatusCode::INTERNAL_SERVER_ERROR,
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(feature = "typed_header")]
|
||||
mod typed_header {
|
||||
|
||||
|
||||
@@ -63,9 +63,9 @@
|
||||
|
||||
use crate::{HasValidate, HasValidateArgs};
|
||||
use axum::TypedHeader;
|
||||
use validator::{Validate, ValidateArgs};
|
||||
use validator::ValidateArgs;
|
||||
|
||||
impl<T: Validate> HasValidate for TypedHeader<T> {
|
||||
impl<T> HasValidate for TypedHeader<T> {
|
||||
type Validate = T;
|
||||
fn get_validate(&self) -> &T {
|
||||
&self.0
|
||||
|
||||
@@ -52,9 +52,9 @@
|
||||
|
||||
use crate::{HasValidate, HasValidateArgs};
|
||||
use axum_typed_multipart::{BaseMultipart, TypedMultipart};
|
||||
use validator::{Validate, ValidateArgs};
|
||||
use validator::ValidateArgs;
|
||||
|
||||
impl<T: Validate, R> HasValidate for BaseMultipart<T, R> {
|
||||
impl<T, R> HasValidate for BaseMultipart<T, R> {
|
||||
type Validate = T;
|
||||
fn get_validate(&self) -> &T {
|
||||
&self.data
|
||||
@@ -68,7 +68,7 @@ impl<'v, T: ValidateArgs<'v>, R> HasValidateArgs<'v> for BaseMultipart<T, R> {
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: Validate> HasValidate for TypedMultipart<T> {
|
||||
impl<T> HasValidate for TypedMultipart<T> {
|
||||
type Validate = T;
|
||||
fn get_validate(&self) -> &T {
|
||||
&self.0
|
||||
|
||||
@@ -44,9 +44,9 @@
|
||||
|
||||
use crate::{HasValidate, HasValidateArgs};
|
||||
use axum_yaml::Yaml;
|
||||
use validator::{Validate, ValidateArgs};
|
||||
use validator::ValidateArgs;
|
||||
|
||||
impl<T: Validate> HasValidate for Yaml<T> {
|
||||
impl<T> HasValidate for Yaml<T> {
|
||||
type Validate = T;
|
||||
fn get_validate(&self) -> &T {
|
||||
&self.0
|
||||
|
||||
Reference in New Issue
Block a user