Skip to content

Commit

Permalink
fix check for default values
Browse files Browse the repository at this point in the history
  • Loading branch information
wtachau authored and stepancheg committed Oct 24, 2021
1 parent 96b863b commit b3e7f12
Show file tree
Hide file tree
Showing 3 changed files with 29 additions and 2 deletions.
23 changes: 23 additions & 0 deletions protobuf-test/src/common/v2/test_fmt_json.rs
Original file line number Diff line number Diff line change
Expand Up @@ -301,6 +301,29 @@ fn test_always_output_default_values() {
assert_eq!("{\"iii\": 0, \"sss\": \"asd\"}", json);
}

#[test]
fn test_always_output_default_values_for_repeated_fields() {
let m = TestIncludeDefaultValuesWithRepeatedField::new();
let json = json::print_to_string_with_options(
&m,
&json::PrintOptions {
always_output_default_values: false,
..Default::default()
},
)
.unwrap();
assert_eq!("{}", json);
let json = json::print_to_string_with_options(
&m,
&json::PrintOptions {
always_output_default_values: true,
..Default::default()
},
)
.unwrap();
assert_eq!("{\"rrr\": []}", json);
}

#[test]
fn test_ignore_unknown_fields() {
let mut expected = TestTypes::new();
Expand Down
4 changes: 4 additions & 0 deletions protobuf-test/src/common/v2/test_fmt_json_pb.proto
Original file line number Diff line number Diff line change
Expand Up @@ -85,6 +85,10 @@ message TestIncludeDefaultValues {
}
}

message TestIncludeDefaultValuesWithRepeatedField {
repeated int32 rrr = 1;
}

message TestJsonName {
optional bool field_with_json_name = 1 [json_name = "Field With json_name"];
}
4 changes: 2 additions & 2 deletions protobuf/src/json/print.rs
Original file line number Diff line number Diff line change
Expand Up @@ -499,14 +499,14 @@ impl Printer {
self.print_printable(&v)?;
}
ReflectFieldRef::Repeated(v) => {
if !v.is_empty() {
if !v.is_empty() || self.print_options.always_output_default_values {
self.print_comma_but_first(&mut first)?;
write!(self.buf, "\"{}\": ", json_field_name)?;
self.print_repeated(&v)?;
}
}
ReflectFieldRef::Map(v) => {
if !v.is_empty() {
if !v.is_empty() || self.print_options.always_output_default_values {
self.print_comma_but_first(&mut first)?;
write!(self.buf, "\"{}\": ", json_field_name)?;
self.print_map(&v)?;
Expand Down

0 comments on commit b3e7f12

Please sign in to comment.