Skip to content

Commit 97c1789

Browse files
authored
Merge pull request #300 from rust-random/custom_test
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).
2 parents ce5c2d9 + cf85546 commit 97c1789

File tree

2 files changed

+16
-11
lines changed

2 files changed

+16
-11
lines changed

tests/common/mod.rs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@ fn test_zero() {
1313
}
1414

1515
#[test]
16+
#[cfg(not(feature = "custom"))]
1617
fn test_diff() {
1718
let mut v1 = [0u8; 1000];
1819
getrandom_impl(&mut v1).unwrap();

tests/custom.rs

Lines changed: 15 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -7,41 +7,45 @@
77
))]
88

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

13-
use core::{
14-
num::NonZeroU32,
15-
sync::atomic::{AtomicU8, Ordering},
16-
};
11+
use core::num::NonZeroU32;
1712
use getrandom::{getrandom, register_custom_getrandom, Error};
1813

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

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

3635
register_custom_getrandom!(super_insecure_rng);
3736

37+
use getrandom::getrandom as getrandom_impl;
38+
mod common;
39+
3840
#[test]
3941
fn custom_rng_output() {
4042
let mut buf = [0u8; 4];
4143
assert_eq!(getrandom(&mut buf), Ok(()));
42-
assert_eq!(buf, [0, 1, 2, 3]);
44+
assert_eq!(buf, [4, 12, 36, 108]);
45+
46+
let mut buf = [0u8; 3];
4347
assert_eq!(getrandom(&mut buf), Ok(()));
44-
assert_eq!(buf, [4, 5, 6, 7]);
48+
assert_eq!(buf, [3, 9, 27]);
4549
}
4650

4751
#[test]

0 commit comments

Comments
 (0)