Skip to main content

ef_tests/
case.rs

1//! Test case definitions
2
3use 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
13/// Stack size of the worker threads that run test cases.
14///
15/// The EVM recurses natively per call frame, so a 1024-deep call chain needs more than the 2 MiB
16/// default.
17const 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
26/// A single test case, capable of loading a JSON description of itself and running it.
27///
28/// See <https://ethereum-tests.readthedocs.io/> for test specs.
29pub trait Case: Debug + Send + Sync + Sized + 'static {
30    /// A description of the test.
31    fn description(&self) -> String {
32        "no description".to_string()
33    }
34
35    /// Load the test from the given file path.
36    ///
37    /// The file can be assumed to be a valid EF test case as described on <https://ethereum-tests.readthedocs.io/>.
38    fn load(path: &Path) -> Result<Self, Error>;
39
40    /// Run the test.
41    fn run(self) -> Result<(), Error>;
42}
43
44/// A container for multiple test cases.
45#[derive(Debug)]
46pub struct Cases<T> {
47    /// The contained test cases and the path to each test.
48    pub test_cases: Vec<(PathBuf, T)>,
49}
50
51impl<T: Case> Cases<T> {
52    /// Run the contained test cases.
53    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
63/// Reads the JSON test file at `path`.
64pub 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
71/// Runs file workers with one shared queue and bounded thread stacks.
72pub(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}