1use super::getrandom_impl;
2
3#[cfg(all(target_arch = "wasm32", target_os = "unknown"))]
4use wasm_bindgen_test::wasm_bindgen_test as test;
5
6#[cfg(feature = "test-in-browser")]
7wasm_bindgen_test::wasm_bindgen_test_configure!(run_in_browser);
8
9#[test]
10fn test_zero() {
11 // Test that APIs are happy with zero-length requests
12 getrandom_impl(&mut [0u8; 0]).unwrap();
13}
14
15// Return the number of bits in which s1 and s2 differ
16#[cfg(not(feature = "custom"))]
17fn num_diff_bits(s1: &[u8], s2: &[u8]) -> usize {
18 assert_eq!(s1.len(), s2.len());
19 s1.iter()
20 .zip(s2.iter())
21 .map(|(a, b)| (a ^ b).count_ones() as usize)
22 .sum()
23}
24
25// Tests the quality of calling getrandom on two large buffers
26#[test]
27#[cfg(not(feature = "custom"))]
28fn test_diff() {
29 let mut v1 = [0u8; 1000];
30 getrandom_impl(&mut v1).unwrap();
31
32 let mut v2 = [0u8; 1000];
33 getrandom_impl(&mut v2).unwrap();
34
35 // Between 3.5 and 4.5 bits per byte should differ. Probability of failure:
36 // ~ 2^(-94) = 2 * CDF[BinomialDistribution[8000, 0.5], 3500]
37 let d = num_diff_bits(&v1, &v2);
38 assert!(d > 3500);
39 assert!(d < 4500);
40}
41
42// Tests the quality of calling getrandom repeatedly on small buffers
43#[test]
44#[cfg(not(feature = "custom"))]
45fn test_small() {
46 // For each buffer size, get at least 256 bytes and check that between
47 // 3 and 5 bits per byte differ. Probability of failure:
48 // ~ 2^(-91) = 64 * 2 * CDF[BinomialDistribution[8*256, 0.5], 3*256]
49 for size in 1..=64 {
50 let mut num_bytes = 0;
51 let mut diff_bits = 0;
52 while num_bytes < 256 {
53 let mut s1 = vec![0u8; size];
54 getrandom_impl(&mut s1).unwrap();
55 let mut s2 = vec![0u8; size];
56 getrandom_impl(&mut s2).unwrap();
57
58 num_bytes += size;
59 diff_bits += num_diff_bits(&s1, &s2);
60 }
61 assert!(diff_bits > 3 * num_bytes);
62 assert!(diff_bits < 5 * num_bytes);
63 }
64}
65
66#[test]
67fn test_huge() {
68 let mut huge = [0u8; 100_000];
69 getrandom_impl(&mut huge).unwrap();
70}
71
72// On WASM, the thread API always fails/panics
73#[cfg(not(target_arch = "wasm32"))]
74#[test]
75fn test_multithreading() {
76 extern crate std;
77 use std::{sync::mpsc::channel, thread, vec};
78
79 let mut txs = vec![];
80 for _ in 0..20 {
81 let (tx, rx) = channel();
82 txs.push(tx);
83
84 thread::spawn(move || {
85 // wait until all the tasks are ready to go.
86 rx.recv().unwrap();
87 let mut v = [0u8; 1000];
88
89 for _ in 0..100 {
90 getrandom_impl(&mut v).unwrap();
91 thread::yield_now();
92 }
93 });
94 }
95
96 // start all the tasks
97 for tx in txs.iter() {
98 tx.send(()).unwrap();
99 }
100}
101