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 a [de]serialization unit test for the Bytes #1933

Closed
wants to merge 2 commits into from
Closed
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
16 changes: 12 additions & 4 deletions core/lib/basic_types/src/web3/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -61,9 +61,13 @@ impl Serialize for Bytes {
where
S: Serializer,
{
let mut serialized = "0x".to_owned();
serialized.push_str(&hex::encode(&self.0));
serializer.serialize_str(serialized.as_ref())
if serializer.is_human_readable() {
let mut serialized = "0x".to_owned();
serialized.push_str(&hex::encode(&self.0));
serializer.serialize_str(serialized.as_ref())
} else {
serializer.serialize_bytes(&self.0)
}
}
}

Expand All @@ -72,7 +76,11 @@ impl<'a> Deserialize<'a> for Bytes {
where
D: Deserializer<'a>,
{
deserializer.deserialize_identifier(BytesVisitor)
if deserializer.is_human_readable() {
deserializer.deserialize_identifier(BytesVisitor)
} else {
Vec::<u8>::deserialize(deserializer).map(Bytes)
}
}
}

Expand Down
9 changes: 9 additions & 0 deletions core/lib/basic_types/src/web3/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -83,3 +83,12 @@ fn block_can_be_deserialized() {
let block: Block<H256> = serde_json::from_str(pre_dencun).unwrap();
assert!(block.excess_blob_gas.is_none());
}

#[test]
fn test_bytes_serde() {
Comment on lines +87 to +88
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

If we are to test differences between serializer, it might also make sense to add:

  • Tests for human-readable (de)serialization, e.g. serde_json (though I guess it's kinda covered by the test above).
  • Snapshot tests for bincode serialization (we don't want to accidentally break repr there)

use bincode::{deserialize, serialize};
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Bikeshedding: probably using fully qualified paths here would be more expressive.

let original = Bytes(vec![0, 1, 2, 3, 4]);
let encoded: Vec<u8> = serialize(&original).unwrap();
let decoded: Bytes = deserialize(&encoded).unwrap();
assert_eq!(original, decoded);
}
Loading