rand_tests.rs 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  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. use ring::{
  15. rand::{self, SecureRandom as _},
  16. test,
  17. };
  18. #[cfg(target_arch = "wasm32")]
  19. use wasm_bindgen_test::{wasm_bindgen_test, wasm_bindgen_test_configure};
  20. #[cfg(target_arch = "wasm32")]
  21. wasm_bindgen_test_configure!(run_in_browser);
  22. #[test]
  23. #[cfg_attr(target_arch = "wasm32", wasm_bindgen_test)]
  24. fn test_system_random_lengths() {
  25. const LINUX_LIMIT: usize = 256;
  26. const WEB_LIMIT: usize = 65536;
  27. // Test that `fill` succeeds for various interesting lengths. `256` and
  28. // multiples thereof are interesting because that's an edge case for
  29. // `getrandom` on Linux.
  30. let lengths = [
  31. 0,
  32. 1,
  33. 2,
  34. 3,
  35. 96,
  36. LINUX_LIMIT - 1,
  37. LINUX_LIMIT,
  38. LINUX_LIMIT + 1,
  39. LINUX_LIMIT * 2,
  40. 511,
  41. 512,
  42. 513,
  43. 4096,
  44. WEB_LIMIT - 1,
  45. WEB_LIMIT,
  46. WEB_LIMIT + 1,
  47. WEB_LIMIT * 2,
  48. ];
  49. for len in lengths.iter() {
  50. let mut buf = vec![0; *len];
  51. let rng = rand::SystemRandom::new();
  52. assert!(rng.fill(&mut buf).is_ok());
  53. // If `len` < 96 then there's a big chance of false positives, but
  54. // otherwise the likelihood of a false positive is so too low to
  55. // worry about.
  56. if *len >= 96 {
  57. assert!(buf.iter().any(|x| *x != 0));
  58. }
  59. }
  60. }
  61. #[test]
  62. #[cfg_attr(target_arch = "wasm32", wasm_bindgen_test)]
  63. fn test_system_random_traits() {
  64. test::compile_time_assert_clone::<rand::SystemRandom>();
  65. test::compile_time_assert_send::<rand::SystemRandom>();
  66. assert_eq!(
  67. "SystemRandom(())",
  68. format!("{:?}", rand::SystemRandom::new())
  69. );
  70. }