Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 11 additions & 1 deletion src/one_any_of.rs
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,6 @@ macro_rules! common_one_any_of {
) => {
#[doc = concat!("`", stringify!($t), "` type.\n\nThis allows modelling of ", stringify!($schema), " JSON schemas.")]
#[cfg_attr(feature = "conversion", derive(LabelledGenericEnum))]
#[cfg_attr(feature = "serdevalid", derive(Validate))]
#[derive(Debug, PartialEq, Clone)]
pub enum $t<$($i),*> where
$($i: PartialEq,)*
Expand All @@ -31,6 +30,17 @@ macro_rules! common_one_any_of {
),*
}

#[cfg(feature = "serdevalid")]
impl<$($i),*> Validate for $t<$($i),*> where
$($i: PartialEq + Validate,)*
{
fn validate(&self) -> Result<(), serde_valid::validation::Errors> {
match self {
$(Self::$i(inner) => inner.validate()),*
}
}
}

impl<$($i),*> Serialize for $t<$($i),*> where
$($i: PartialEq + Serialize,)*
{
Expand Down
42 changes: 42 additions & 0 deletions tests/union_validation.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
#![cfg(feature = "serdevalid")]

use serde_valid::Validate;
use swagger::{AnyOf2, OneOf2};

#[derive(Debug, PartialEq, Validate)]
struct Positive {
#[validate(minimum = 1)]
value: i32,
}

#[test]
fn oneof_validates_the_selected_member() {
for value in [0, 1] {
for union in [
OneOf2::<Positive, Positive>::A(Positive { value }),
OneOf2::B(Positive { value }),
] {
assert_eq!(union.validate().is_ok(), value == 1);
}
}
}

#[test]
fn anyof_validates_the_selected_member() {
for value in [0, 1] {
for union in [
AnyOf2::<Positive, Positive>::A(Positive { value }),
AnyOf2::B(Positive { value }),
] {
assert_eq!(union.validate().is_ok(), value == 1);
}
}
}

#[test]
fn unions_with_primitive_members_still_serialize_and_deserialize() {
let oneof: OneOf2<u32, String> = serde_json::from_str("\"future\"").unwrap();
assert_eq!(serde_json::to_string(&oneof).unwrap(), "\"future\"");
let anyof: AnyOf2<u32, String> = serde_json::from_str("42").unwrap();
assert_eq!(serde_json::to_string(&anyof).unwrap(), "42");
}