From 3f56b378b26cc0f0ca534d1c922d17f81d9a86d9 Mon Sep 17 00:00:00 2001 From: Palash Tyagi <23239946+Magnus167@users.noreply.github.com> Date: Mon, 28 Jul 2025 23:12:20 +0100 Subject: [PATCH] Add unit tests for SliceRandom trait and shuffle functionality --- src/random/seq.rs | 60 +++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 60 insertions(+) diff --git a/src/random/seq.rs b/src/random/seq.rs index 621869c..35c0d0b 100644 --- a/src/random/seq.rs +++ b/src/random/seq.rs @@ -14,3 +14,63 @@ impl SliceRandom for [T] { } } } + +#[cfg(test)] +mod tests { + use super::*; + use crate::random::{CryptoRng, Prng}; + + #[test] + fn test_shuffle_slice() { + let mut rng = Prng::new(3); + let mut arr = [1, 2, 3, 4, 5]; + let orig = arr.clone(); + arr.shuffle(&mut rng); + assert_eq!(arr.len(), orig.len()); + let mut sorted = arr.to_vec(); + sorted.sort(); + assert_eq!(sorted, orig.to_vec()); + } + + #[test] + fn test_slice_shuffle_deterministic_with_prng() { + let mut rng1 = Prng::new(11); + let mut rng2 = Prng::new(11); + let mut a = [1u8, 2, 3, 4, 5, 6, 7, 8, 9]; + let mut b = a.clone(); + a.shuffle(&mut rng1); + b.shuffle(&mut rng2); + assert_eq!(a, b); + } + + #[test] + fn test_slice_shuffle_crypto_random_changes() { + let mut rng1 = CryptoRng::new(); + let mut rng2 = CryptoRng::new(); + let orig = [1u8, 2, 3, 4, 5, 6, 7, 8, 9]; + let mut a = orig.clone(); + let mut b = orig.clone(); + a.shuffle(&mut rng1); + b.shuffle(&mut rng2); + assert!(a != orig || b != orig, "Shuffles did not change order"); + assert_ne!(a, b, "Two Crypto RNG shuffles produced same order"); + } + + #[test] + fn test_shuffle_single_element_no_change() { + let mut rng = Prng::new(1); + let mut arr = [42]; + arr.shuffle(&mut rng); + assert_eq!(arr, [42]); + } + + #[test] + fn test_multiple_shuffles_different_results() { + let mut rng = Prng::new(5); + let mut arr1 = [1, 2, 3, 4]; + let mut arr2 = [1, 2, 3, 4]; + arr1.shuffle(&mut rng); + arr2.shuffle(&mut rng); + assert_ne!(arr1, arr2); + } +}