| 1 | use std::env; |
| 2 | |
| 3 | /// Returns the seeds a randomized `#[gpui::test]` or `#[gpui::bench]` runs with, in |
| 4 | /// order, and whether there is more than one. |
| 5 | /// |
| 6 | /// With `$SEED` set, runs `$SEED..$SEED + iterations` and ignores `explicit_seeds`. |
| 7 | /// Otherwise runs `0..iterations` followed by `explicit_seeds`, except that the |
| 8 | /// default single iteration is dropped when explicit seeds are given. |
| 9 | /// `$ITERATIONS` overrides `iterations`. |
| 10 | /// Tests and benchmarks share this so that one `SEED` reproduces either. |
| 11 | /// |
| 12 | /// This is intended for use by the `gpui::test` and `gpui::bench` macros and generally |
| 13 | /// should not be used directly. |
| 14 | #[doc(hidden)] |
| 15 | pub fn calculate_seeds( |
| 16 | iterations: u64, |
| 17 | explicit_seeds: &[u64], |
| 18 | ) -> (impl Iterator<Item = u64> + '_, bool) { |
| 19 | let iterations = env::var("ITERATIONS") |
| 20 | .ok() |
| 21 | .map(|var| var.parse().expect("invalid ITERATIONS variable")) |
| 22 | .unwrap_or(iterations); |
| 23 | |
| 24 | let env_seed = env::var("SEED") |
| 25 | .map(|seed| seed.parse().expect("invalid SEED variable as integer")) |
| 26 | .ok(); |
| 27 | |
| 28 | let iter = seeds(iterations, explicit_seeds, env_seed); |
| 29 | let is_multiple_runs = iter.clone().nth(1).is_some(); |
| 30 | (iter, is_multiple_runs) |
| 31 | } |
| 32 | |
| 33 | fn seeds( |
| 34 | iterations: u64, |
| 35 | explicit_seeds: &[u64], |
| 36 | env_seed: Option<u64>, |
| 37 | ) -> impl Iterator<Item = u64> + Clone + '_ { |
| 38 | let (iterations_range, explicit_seeds) = match env_seed { |
| 39 | Some(env_seed) => (env_seed..env_seed + iterations, &[][..]), |
| 40 | None if iterations == 1 && !explicit_seeds.is_empty() => (0..0, explicit_seeds), |
| 41 | None => (0..iterations, explicit_seeds), |
| 42 | }; |
| 43 | iterations_range.chain(explicit_seeds.iter().copied()) |
| 44 | } |
| 45 | |
| 46 | #[cfg(test)] |
| 47 | mod tests { |
| 48 | use super::seeds; |
| 49 | |
| 50 | fn collect(iterations: u64, explicit_seeds: &[u64], env_seed: Option<u64>) -> Vec<u64> { |
| 51 | seeds(iterations, explicit_seeds, env_seed).collect() |
| 52 | } |
| 53 | |
| 54 | #[test] |
| 55 | fn seeds_follow_iterations_explicit_seeds_and_seed_variable() { |
| 56 | assert_eq!(collect(1, &[], None), [0]); |
| 57 | assert_eq!(collect(3, &[], None), [0, 1, 2]); |
| 58 | assert_eq!(collect(1, &[10, 20], None), [10, 20]); |
| 59 | assert_eq!(collect(2, &[10], None), [0, 1, 10]); |
| 60 | assert_eq!(collect(1, &[10], Some(7)), [7]); |
| 61 | assert_eq!( |
| 62 | collect(2, &[10], Some(7)), |
| 63 | [7, 8], |
| 64 | "`SEED` starts the iterations once, without repeating itself" |
| 65 | ); |
| 66 | } |
| 67 | } |