1use crate::result::{CaseResult, Error};
4use rayon::{prelude::*, ThreadPool, ThreadPoolBuilder};
5use serde::de::DeserializeOwned;
6use std::{
7 fmt::Debug,
8 fs,
9 path::{Path, PathBuf},
10 sync::{LazyLock, Mutex},
11};
12
13const WORKER_STACK_SIZE: usize = 8 * 1024 * 1024;
18
19static POOL: LazyLock<ThreadPool> = LazyLock::new(|| {
20 ThreadPoolBuilder::new()
21 .stack_size(WORKER_STACK_SIZE)
22 .build()
23 .expect("failed to build the test case thread pool")
24});
25
26pub trait Case: Debug + Send + Sync + Sized + 'static {
30 fn description(&self) -> String {
32 "no description".to_string()
33 }
34
35 fn load(path: &Path) -> Result<Self, Error>;
39
40 fn run(self) -> Result<(), Error>;
42}
43
44#[derive(Debug)]
46pub struct Cases<T> {
47 pub test_cases: Vec<(PathBuf, T)>,
49}
50
51impl<T: Case> Cases<T> {
52 pub fn run(self) -> Vec<CaseResult> {
54 POOL.install(|| {
55 self.test_cases
56 .into_par_iter()
57 .map(|(path, case)| CaseResult::new(&path, case.description(), case.run()))
58 .collect()
59 })
60 }
61}
62
63pub fn load_json<T: DeserializeOwned>(path: &Path) -> Result<T, Error> {
65 let contents =
66 fs::read_to_string(path).map_err(|error| Error::Io { path: path.into(), error })?;
67 serde_json::from_str(&contents)
68 .map_err(|error| Error::CouldNotDeserialize { path: path.into(), error })
69}
70
71pub(crate) fn run_workers(
73 files: Vec<PathBuf>,
74 workers: usize,
75 worker: impl Fn(&mut dyn Iterator<Item = PathBuf>) + Sync,
76) {
77 let workers = workers.max(1).min(files.len());
78 let files = Mutex::new(files.into_iter());
79 std::thread::scope(|scope| {
80 for _ in 0..workers {
81 std::thread::Builder::new()
82 .stack_size(WORKER_STACK_SIZE)
83 .spawn_scoped(scope, || {
84 let mut files = std::iter::from_fn(|| files.lock().unwrap().next());
85 worker(&mut files);
86 })
87 .expect("failed to spawn a fixture worker");
88 }
89 });
90}