Skip to content

Commit ce28b30

Browse files
committed
Cleanup Custom Tests
This moves the tests for the custom RNG registration into custom.rs. It also: - Simplifies the registered custom RNG - Makes sure the custom RNG _is not_ used on supported platforms - Makes sure the custom RNG _is_ used on unsupported platforms Signed-off-by: Joe Richey <[email protected]>
1 parent 79c29da commit ce28b30

File tree

2 files changed

+36
-54
lines changed

2 files changed

+36
-54
lines changed

src/custom.rs

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -103,3 +103,39 @@ pub fn getrandom_inner(dest: &mut [MaybeUninit<u8>]) -> Result<(), Error> {
103103
Some(code) => Err(Error::from(code)),
104104
}
105105
}
106+
107+
#[cfg(test)]
108+
mod tests {
109+
use super::*;
110+
111+
const LEN7_CODE: u32 = Error::CUSTOM_START + 7;
112+
// Returns a custom error if input is length 7, otherwise fills with 0x55.
113+
fn insecure_rng(dest: &mut [u8]) -> Result<(), Error> {
114+
if dest.len() == 7 {
115+
return Err(NonZeroU32::new(LEN7_CODE).unwrap().into());
116+
}
117+
dest.fill(0x55);
118+
Ok(())
119+
}
120+
121+
// Test registering a custom implementation, even on supported platforms.
122+
register_custom_getrandom!(insecure_rng);
123+
124+
// On a supported platform, make sure the custom implementation isn't used.
125+
#[cfg(target_os = "linux")]
126+
#[test]
127+
fn custom_not_used() {
128+
crate::getrandom(&mut [0; 7]).unwrap();
129+
}
130+
// On an unsupported platform, make sure the custom implementation is used.
131+
#[cfg(all(target_arch = "wasm32", target_os = "unknown", not(feature = "js")))]
132+
#[wasm_bindgen_test::wasm_bindgen_test]
133+
fn custom_used() {
134+
let err = crate::getrandom(&mut [0; 7]).unwrap_err();
135+
assert_eq!(err.code().get(), LEN7_CODE);
136+
137+
let mut buf = [0; 12];
138+
crate::getrandom(&mut buf).unwrap();
139+
assert_eq!(buf, [0x55; 12]);
140+
}
141+
}

tests/custom.rs

Lines changed: 0 additions & 54 deletions
This file was deleted.

0 commit comments

Comments
 (0)