1 // Copyright 2015-2019 Brian Smith.
2 //
3 // Permission to use, copy, modify, and/or distribute this software for any
4 // purpose with or without fee is hereby granted, provided that the above
5 // copyright notice and this permission notice appear in all copies.
6 //
7 // THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHORS DISCLAIM ALL WARRANTIES
8 // WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
9 // MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY
10 // SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
11 // WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION
12 // OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
13 // CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
14 
15 use ring::{
16     rand::{self, SecureRandom as _},
17     test,
18 };
19 
20 #[cfg(target_arch = "wasm32")]
21 use wasm_bindgen_test::{wasm_bindgen_test as test, wasm_bindgen_test_configure};
22 
23 #[cfg(target_arch = "wasm32")]
24 wasm_bindgen_test_configure!(run_in_browser);
25 
26 #[test]
test_system_random_lengths()27 fn test_system_random_lengths() {
28     const LINUX_LIMIT: usize = 256;
29     const WEB_LIMIT: usize = 65536;
30 
31     // Test that `fill` succeeds for various interesting lengths. `256` and
32     // multiples thereof are interesting because that's an edge case for
33     // `getrandom` on Linux.
34     let lengths = [
35         0,
36         1,
37         2,
38         3,
39         96,
40         LINUX_LIMIT - 1,
41         LINUX_LIMIT,
42         LINUX_LIMIT + 1,
43         LINUX_LIMIT * 2,
44         511,
45         512,
46         513,
47         4096,
48         WEB_LIMIT - 1,
49         WEB_LIMIT,
50         WEB_LIMIT + 1,
51         WEB_LIMIT * 2,
52     ];
53 
54     for len in lengths.iter() {
55         let mut buf = vec![0; *len];
56 
57         let rng = rand::SystemRandom::new();
58         assert!(rng.fill(&mut buf).is_ok());
59 
60         // If `len` < 96 then there's a big chance of false positives, but
61         // otherwise the likelihood of a false positive is so too low to
62         // worry about.
63         if *len >= 96 {
64             assert!(buf.iter().any(|x| *x != 0));
65         }
66     }
67 }
68 
69 #[test]
test_system_random_traits()70 fn test_system_random_traits() {
71     test::compile_time_assert_clone::<rand::SystemRandom>();
72     test::compile_time_assert_send::<rand::SystemRandom>();
73 
74     assert_eq!(
75         "SystemRandom(())",
76         format!("{:?}", rand::SystemRandom::new())
77     );
78 }
79