Skip to content

Commit

Permalink
Add assert_de_tokens_error2 which assert_de_tokens_error that sho…
Browse files Browse the repository at this point in the history
…ws deserialized value in the message
  • Loading branch information
Mingun committed Aug 7, 2024
1 parent 437499f commit e1ceced
Show file tree
Hide file tree
Showing 2 changed files with 49 additions and 2 deletions.
47 changes: 47 additions & 0 deletions src/assert.rs
Original file line number Diff line number Diff line change
Expand Up @@ -237,3 +237,50 @@ where
panic!("{} remaining tokens", de.remaining());
}
}

/// Asserts that the given `tokens` yield `error` when deserializing.
///
/// The same, as [`assert_de_tokens_error`], but produces an error message which
/// contains result of deserialization in case if tokens deserialized to something.
///
/// ```
/// # use serde_derive::{Deserialize, Serialize};
/// # use serde_test::{assert_de_tokens_error2, Token};
/// #
/// #[derive(Serialize, Deserialize, PartialEq, Debug)]
/// #[serde(deny_unknown_fields)]
/// struct S {
/// a: u8,
/// b: u8,
/// }
///
/// assert_de_tokens_error2::<S>(
/// &[
/// Token::Struct { name: "S", len: 2 },
/// Token::Str("x"),
/// ],
/// "unknown field `x`, expected `a` or `b`",
/// );
/// ```
#[cfg_attr(not(no_track_caller), track_caller)]
pub fn assert_de_tokens_error2<'de, T>(tokens: &'de [Token], error: &str)
where
T: Deserialize<'de> + Debug,
{
let mut de = Deserializer::new(tokens);
match T::deserialize(&mut de) {
Ok(x) => assert_eq!(
error,
format!("{:?}", x),
"expected error (left) but tokens deserialized successfully (right)"
),
Err(e) => assert_eq!(e, *error),
}

// There may be one token left if a peek caused the error
de.next_token_opt();

if de.remaining() > 0 {
panic!("{} remaining tokens", de.remaining());
}
}
4 changes: 2 additions & 2 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -163,8 +163,8 @@ mod ser;
mod token;

pub use crate::assert::{
assert_de_tokens, assert_de_tokens_error, assert_ser_tokens, assert_ser_tokens_error,
assert_tokens,
assert_de_tokens, assert_de_tokens_error, assert_de_tokens_error2, assert_ser_tokens,
assert_ser_tokens_error, assert_tokens,
};
pub use crate::configure::{Compact, Configure, Readable};
pub use crate::token::Token;

0 comments on commit e1ceced

Please sign in to comment.