Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add assert_de_tokens_error2 that shows deserialized value in the message #5

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
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
53 changes: 52 additions & 1 deletion src/assert.rs
Original file line number Diff line number Diff line change
Expand Up @@ -128,7 +128,11 @@ where
{
let mut ser = Serializer::new(tokens);
match value.serialize(&mut ser) {
Ok(()) => panic!("value serialized successfully"),
Ok(()) => assert_eq!(
None,
Some(error),
"value serialized successfully, but error expected (right)"
),
Err(e) => assert_eq!(e, *error),
}

Expand Down Expand Up @@ -233,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;
Loading