Skip to content

Commit

Permalink
Merge pull request #300 from rust-random/custom_test
Browse files Browse the repository at this point in the history
Tests: Use custom tests to verify operations on empty slices are no-ops.

Reworking of #299 to keep our custom tests in a single file (and keep things better organized in general).
  • Loading branch information
josephlr committed Oct 22, 2022
2 parents ce5c2d9 + cf85546 commit 97c1789
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 11 deletions.
1 change: 1 addition & 0 deletions tests/common/mod.rs
Expand Up @@ -13,6 +13,7 @@ fn test_zero() {
}

#[test]
#[cfg(not(feature = "custom"))]
fn test_diff() {
let mut v1 = [0u8; 1000];
getrandom_impl(&mut v1).unwrap();
Expand Down
26 changes: 15 additions & 11 deletions tests/custom.rs
Expand Up @@ -7,41 +7,45 @@
))]

use wasm_bindgen_test::wasm_bindgen_test as test;
#[cfg(feature = "test-in-browser")]
wasm_bindgen_test::wasm_bindgen_test_configure!(run_in_browser);

use core::{
num::NonZeroU32,
sync::atomic::{AtomicU8, Ordering},
};
use core::num::NonZeroU32;
use getrandom::{getrandom, register_custom_getrandom, Error};

fn len7_err() -> Error {
NonZeroU32::new(Error::INTERNAL_START + 7).unwrap().into()
}

fn super_insecure_rng(buf: &mut [u8]) -> Result<(), Error> {
// `getrandom` guarantees it will not call any implementation if the output
// buffer is empty.
assert!(!buf.is_empty());
// Length 7 buffers return a custom error
if buf.len() == 7 {
return Err(len7_err());
}
// Otherwise, increment an atomic counter
static COUNTER: AtomicU8 = AtomicU8::new(0);
// Otherwise, fill bytes based on input length
let mut start = buf.len() as u8;
for b in buf {
*b = COUNTER.fetch_add(1, Ordering::Relaxed);
*b = start;
start = start.wrapping_mul(3);
}
Ok(())
}

register_custom_getrandom!(super_insecure_rng);

use getrandom::getrandom as getrandom_impl;
mod common;

#[test]
fn custom_rng_output() {
let mut buf = [0u8; 4];
assert_eq!(getrandom(&mut buf), Ok(()));
assert_eq!(buf, [0, 1, 2, 3]);
assert_eq!(buf, [4, 12, 36, 108]);

let mut buf = [0u8; 3];
assert_eq!(getrandom(&mut buf), Ok(()));
assert_eq!(buf, [4, 5, 6, 7]);
assert_eq!(buf, [3, 9, 27]);
}

#[test]
Expand Down

0 comments on commit 97c1789

Please sign in to comment.