Skip to content

Commit

Permalink
Add tests for B256
Browse files Browse the repository at this point in the history
  • Loading branch information
michaelsproul committed Aug 15, 2024
1 parent c4667a0 commit 2fea24d
Showing 1 changed file with 66 additions and 0 deletions.
66 changes: 66 additions & 0 deletions src/b256_hex.rs
Original file line number Diff line number Diff line change
Expand Up @@ -32,3 +32,69 @@ where
array.copy_from_slice(&decoded);
Ok(array.into())
}

#[cfg(test)]
mod test {
use super::*;
use serde::{Deserialize, Serialize};

#[derive(Debug, PartialEq, Serialize, Deserialize)]
#[serde(transparent)]
struct Wrapper {
#[serde(with = "super")]
val: B256,
}

#[test]
fn encoding() {
assert_eq!(
&serde_json::to_string(&Wrapper { val: B256::ZERO }).unwrap(),
"\"0x0000000000000000000000000000000000000000000000000000000000000000\""
);
assert_eq!(
&serde_json::to_string(&Wrapper {
val: B256::with_last_byte(0x03)
})
.unwrap(),
"\"0x0000000000000000000000000000000000000000000000000000000000000003\""
);
assert_eq!(
&serde_json::to_string(&Wrapper {
val: B256::repeat_byte(0x03)
})
.unwrap(),
"\"0x0303030303030303030303030303030303030303030303030303030303030303\""
);
}

#[test]
fn decoding() {
assert_eq!(
serde_json::from_str::<Wrapper>(
"\"0x0000000000000000000000000000000000000000000000000000000000000000\""
)
.unwrap(),
Wrapper { val: B256::ZERO },
);
assert_eq!(
serde_json::from_str::<Wrapper>(
"\"0x0000000000000000000000000000000000000000000000000000000000000003\""
)
.unwrap(),
Wrapper {
val: B256::with_last_byte(0x03)
},
);

// Require 0x.
serde_json::from_str::<Wrapper>(
"\"0000000000000000000000000000000000000000000000000000000000000000\"",
)
.unwrap_err();
// Wrong length.
serde_json::from_str::<Wrapper>(
"\"0x00000000000000000000000000000000000000000000000000000000000000\"",
)
.unwrap_err();
}
}

0 comments on commit 2fea24d

Please sign in to comment.