From 6820f5140873813e7d74c19d4725578dba1d5cec Mon Sep 17 00:00:00 2001 From: "Tobin C. Harding" Date: Wed, 28 Feb 2024 09:32:08 +1100 Subject: [PATCH] hashes: Add fmt roundtrip tests Different hashes output to hex strings differently depending on whether they display backward or not but we are not currently testing that our parsing and formatting impls both correctly handle backwards/forwards. Add unit tests to roundtrip through a hex string, do so for one forwards printing hash (sha256), on backwards printing hash (sha256d), and also test that the `hash_newtype!` macro correctly passes on display backward. --- hashes/src/lib.rs | 8 ++++++++ hashes/src/sha256.rs | 17 +++++++++++++++++ hashes/src/sha256d.rs | 14 +++++++++++--- 3 files changed, 36 insertions(+), 3 deletions(-) diff --git a/hashes/src/lib.rs b/hashes/src/lib.rs index d2e7b850..d612493f 100644 --- a/hashes/src/lib.rs +++ b/hashes/src/lib.rs @@ -273,4 +273,12 @@ mod tests { let h2: TestNewtype = h.to_string().parse().unwrap(); assert_eq!(h2.to_raw_hash(), h); } + + #[test] + fn newtype_fmt_roundtrip() { + let orig = TestNewtype::hash(&[]); + let hex = format!("{}", orig); + let rinsed = hex.parse::().expect("failed to parse hex"); + assert_eq!(rinsed, orig) + } } diff --git a/hashes/src/sha256.rs b/hashes/src/sha256.rs index 19d166f8..8405232e 100644 --- a/hashes/src/sha256.rs +++ b/hashes/src/sha256.rs @@ -883,6 +883,15 @@ mod tests { } } + #[test] + #[cfg(feature = "alloc")] + fn fmt_roundtrips() { + let hash = sha256::Hash::hash(b"some arbitrary bytes"); + let hex = format!("{}", hash); + let rinsed = hex.parse::().expect("failed to parse hex"); + assert_eq!(rinsed, hash) + } + #[test] #[rustfmt::skip] fn midstate() { @@ -990,6 +999,14 @@ mod tests { ) } + #[test] + fn midstate_fmt_roundtrip() { + let midstate = Midstate::hash_tag(b"ArbitraryTag"); + let hex = format!("{}", midstate); + let rinsed = hex.parse::().expect("failed to parse hex"); + assert_eq!(rinsed, midstate) + } + #[cfg(feature = "serde")] #[test] fn sha256_serde() { diff --git a/hashes/src/sha256d.rs b/hashes/src/sha256d.rs index 4fb813bd..fb3b0c5e 100644 --- a/hashes/src/sha256d.rs +++ b/hashes/src/sha256d.rs @@ -30,10 +30,12 @@ fn from_engine(e: sha256::HashEngine) -> Hash { #[cfg(test)] mod tests { + use crate::{sha256d, Hash as _}; + #[test] #[cfg(feature = "alloc")] fn test() { - use crate::{sha256, sha256d, Hash, HashEngine}; + use crate::{sha256, HashEngine}; #[derive(Clone)] struct Test { @@ -81,13 +83,19 @@ mod tests { } } + #[test] + fn fmt_roundtrips() { + let hash = sha256d::Hash::hash(b"some arbitrary bytes"); + let hex = format!("{}", hash); + let rinsed = hex.parse::().expect("failed to parse hex"); + assert_eq!(rinsed, hash) + } + #[cfg(feature = "serde")] #[test] fn sha256_serde() { use serde_test::{assert_tokens, Configure, Token}; - use crate::{sha256d, Hash}; - #[rustfmt::skip] static HASH_BYTES: [u8; 32] = [ 0xef, 0x53, 0x7f, 0x25, 0xc8, 0x95, 0xbf, 0xa7,