Skip to content

Commit

Permalink
Cover ContentRefDeserializer::deserialize_option
Browse files Browse the repository at this point in the history
  • Loading branch information
Mingun committed Aug 23, 2024
1 parent 8514f41 commit 2dddc77
Show file tree
Hide file tree
Showing 2 changed files with 81 additions and 0 deletions.
7 changes: 7 additions & 0 deletions serde/src/private/de.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1898,10 +1898,17 @@ mod content {
where
V: Visitor<'de>,
{
// Covered by tests/test_enum_untagged.rs
// with_optional_field::*
match *self.content {
Content::None => visitor.visit_none(),
Content::Some(ref v) => visitor.visit_some(ContentRefDeserializer::new(v)),
Content::Unit => visitor.visit_unit(),
// This case is necessary for formats which does not store marker of optionality of value,
// for example, JSON. When `deserialize_any` is requested from such formats, they will
// report value without using `Visitor::visit_some`, because they do not known in which
// contexts this value will be used.
// RON is example of format which preserve markers.
_ => visitor.visit_some(self),
}
}
Expand Down
74 changes: 74 additions & 0 deletions test_suite/tests/test_enum_untagged.rs
Original file line number Diff line number Diff line change
Expand Up @@ -191,6 +191,80 @@ fn newtype_enum() {
);
}

// Reaches crate::private::de::content::ContentRefDeserializer::deserialize_option
mod with_optional_field {
use super::*;

#[derive(Debug, PartialEq, Serialize, Deserialize)]
#[serde(untagged)]
enum Enum {
Struct { optional: Option<u32> },
Null,
}

#[test]
fn some() {
assert_tokens(
&Enum::Struct { optional: Some(42) },
&[
Token::Struct {
name: "Enum",
len: 1,
},
Token::Str("optional"),
Token::Some,
Token::U32(42),
Token::StructEnd,
],
);
}

#[test]
fn some_without_marker() {
assert_de_tokens(
&Enum::Struct { optional: Some(42) },
&[
Token::Struct {
name: "Enum",
len: 1,
},
Token::Str("optional"),
Token::U32(42),
Token::StructEnd,
],
);
}

#[test]
fn none() {
assert_tokens(
&Enum::Struct { optional: None },
&[
Token::Struct {
name: "Enum",
len: 1,
},
Token::Str("optional"),
Token::None,
Token::StructEnd,
],
);
}

#[test]
fn unit() {
assert_de_tokens(
&Enum::Struct { optional: None },
&[
Token::Map { len: None },
Token::Str("optional"),
Token::Unit,
Token::MapEnd,
],
);
}
}

#[test]
fn string_and_bytes() {
#[derive(Debug, PartialEq, Deserialize)]
Expand Down

0 comments on commit 2dddc77

Please sign in to comment.