Skip to main content

ef_test_runner/
main.rs

1//! Command-line interface for running tests.
2use std::{
3    fs,
4    path::{Path, PathBuf},
5    sync::{
6        atomic::{AtomicBool, Ordering},
7        Mutex,
8    },
9};
10
11use clap::{Args, Parser, Subcommand};
12use ef_tests::{
13    cases::{
14        blockchain_test::{remove_shared_rocksdb, BlockTestOptions, BlockchainTests},
15        engine_test,
16    },
17    result::FixtureResult,
18    suite::find_all_files_with_extension,
19    Error, Suite,
20};
21use reth_node_core::{
22    args::StorageArgs,
23    version::{try_init_version_metadata, version_metadata},
24};
25use reth_provider::StorageSettings;
26
27mod report;
28
29/// Command-line arguments for the test runner.
30#[derive(Debug, Parser)]
31#[command(
32    name = "ef-test-runner",
33    version = version_metadata().short_version.as_ref(),
34    after_help = "Set RUST_LOG to write client logs to stderr (for example, info,engine::tree=debug).",
35    propagate_version = true,
36    args_conflicts_with_subcommands = true,
37    arg_required_else_help = true
38)]
39pub struct TestRunnerCommand {
40    #[command(subcommand)]
41    command: Option<Command>,
42    /// Path to a test suite that contains a `blockchain_tests` directory, when no command is
43    /// given.
44    suite_path: Option<PathBuf>,
45}
46
47#[derive(Debug, Subcommand)]
48enum Command {
49    /// Run blockchain tests by importing their blocks. Exits 1 if any fixture fails, and 2 if no
50    /// fixture ran, a path cannot be read, or a fixture file cannot be loaded.
51    #[command(name = "blocktest", display_name = "ef-test-runner")]
52    BlockTest(BlockTestArgs),
53    /// Run blockchain tests in the engine format through reth's Engine API handler, each on a
54    /// datadir in the system temporary directory (`TMPDIR`; a tmpfs avoids disk syncs). Exits 1
55    /// if any fixture fails, and 2 if no fixture ran, a path cannot be read, or a fixture file
56    /// cannot be loaded.
57    #[command(name = "enginetest", display_name = "ef-test-runner")]
58    EngineTest(EngineTestArgs),
59}
60
61#[derive(Debug, Args)]
62struct RunArgs {
63    /// Fixture files, or directories searched for fixture files, all run in one process.
64    #[arg(required = true)]
65    paths: Vec<PathBuf>,
66    /// Run blocks on the sequential executor instead of the BAL-driven parallel one, as the
67    /// node's `--engine.disable-bal-parallel-execution` does. Block import has only the
68    /// sequential executor, so for `blocktest` this only changes the reported reason.
69    #[arg(long)]
70    bal_sequential: bool,
71    /// Print a `balExecution` JSON line on stderr for each executed block, saying which executor
72    /// ran it and, for the sequential one, why.
73    #[arg(long)]
74    bal_report: bool,
75    /// Print each fixture's verdict and full error to stderr as soon as it finishes.
76    #[arg(long)]
77    progress: bool,
78    /// How many fixture files run at once.
79    #[arg(long, default_value_t = default_workers())]
80    workers: usize,
81}
82
83#[derive(Debug, Args)]
84struct BlockTestArgs {
85    #[command(flatten)]
86    run: RunArgs,
87    /// Never deliver a block's access list, so every block executes without one, as a block
88    /// received without its list does.
89    #[arg(long)]
90    bal_withhold: bool,
91}
92
93#[derive(Debug, Args)]
94struct EngineTestArgs {
95    #[command(flatten)]
96    run: RunArgs,
97    #[command(flatten)]
98    storage: StorageArgs,
99}
100
101/// Returns the storage settings a node writes with the genesis of a new database.
102const fn storage_settings(storage: StorageArgs) -> StorageSettings {
103    if storage.v2 {
104        StorageSettings::v2()
105    } else {
106        StorageSettings::v1()
107    }
108}
109
110fn default_workers() -> usize {
111    std::thread::available_parallelism().map_or(1, |n| n.get())
112}
113
114fn main() {
115    // Deep EVM calls also run on engine and speculative workers with Rust's default stack.
116    let minimum_stack_size = 8 * 1024 * 1024;
117    if !matches!(std::env::var("RUST_MIN_STACK"), Ok(value) if value.parse::<usize>().is_ok_and(|size| size >= minimum_stack_size))
118    {
119        // SAFETY: This runs at process startup, before the runner creates any threads or runtimes.
120        unsafe { std::env::set_var("RUST_MIN_STACK", minimum_stack_size.to_string()) };
121    }
122    try_init_version_metadata(reth_node_core::reth_version_metadata!())
123        .expect("runner version metadata is initialized once before parsing arguments");
124    let cmd = TestRunnerCommand::parse();
125    let Some(command) = cmd.command else {
126        report::init(false);
127        let suite_path = cmd.suite_path.expect("a suite path or a command is required");
128        BlockchainTests::new(suite_path.join("blockchain_tests")).run();
129        return
130    };
131
132    let args = match &command {
133        Command::BlockTest(BlockTestArgs { run, .. }) |
134        Command::EngineTest(EngineTestArgs { run, .. }) => run,
135    };
136    report::init(args.bal_report);
137    let progress = args.progress;
138    let results = Mutex::new(Vec::new());
139    let load_failed = AtomicBool::new(false);
140    let on_result = |result: Result<FixtureResult, Error>| {
141        let result = match result {
142            Ok(result) => result,
143            Err(err) => {
144                eprintln!("error: {err}");
145                load_failed.store(true, Ordering::Relaxed);
146                return
147            }
148        };
149        if progress {
150            eprintln!(
151                "{} {}{}",
152                if result.pass { "PASS" } else { "FAIL" },
153                result.name,
154                if result.error.is_empty() { String::new() } else { format!(": {}", result.error) }
155            );
156        }
157        results.lock().unwrap().push(result);
158    };
159    let run_result = match command {
160        Command::BlockTest(BlockTestArgs { run: args, bal_withhold }) => {
161            let options = BlockTestOptions { bal_sequential: args.bal_sequential, bal_withhold };
162            let files = checked_fixture_files(&args.paths, "blockchain_tests");
163            BlockchainTests::run_fixtures(files, options, args.workers, &on_result);
164            // Every fixture ran, so nothing uses the shared RocksDB instance anymore.
165            remove_shared_rocksdb();
166            Ok(())
167        }
168        Command::EngineTest(EngineTestArgs { run: args, storage }) => {
169            let files = checked_fixture_files(&args.paths, "blockchain_tests_engine");
170            engine_test::run_fixtures(
171                files,
172                args.bal_sequential,
173                storage_settings(storage),
174                args.workers,
175                &on_result,
176            )
177        }
178    };
179    let results = results.into_inner().unwrap();
180    println!("{}", serde_json::to_string(&results).expect("results serialize"));
181    if let Err(err) = run_result {
182        eprintln!("error: {err}");
183        std::process::exit(2);
184    }
185    if load_failed.load(Ordering::Relaxed) {
186        std::process::exit(2);
187    }
188    if results.is_empty() {
189        eprintln!("error: no fixtures found in the supplied paths");
190        std::process::exit(2);
191    }
192    if !results.iter().all(|result| result.pass) {
193        std::process::exit(1);
194    }
195}
196
197/// Resolves and opens every fixture path before execution, exiting 2 on any discovery error.
198fn checked_fixture_files(paths: &[PathBuf], format: &str) -> Vec<PathBuf> {
199    fixture_files(paths, format).unwrap_or_else(|err| {
200        eprintln!("error: cannot read fixtures: {err}");
201        std::process::exit(2)
202    })
203}
204
205/// Collects every fixture without discarding directory traversal errors.
206fn fixture_files(paths: &[PathBuf], format: &str) -> Result<Vec<PathBuf>, Error> {
207    let mut files = Vec::new();
208    for path in paths {
209        if path.is_dir() {
210            let mut found = find_all_files_with_extension(&fixtures_path(path, format), ".json")?;
211            found.sort();
212            files.extend(found);
213        } else {
214            fs::File::open(path).map_err(|error| Error::Io { path: path.clone(), error })?;
215            files.push(path.clone());
216        }
217    }
218    Ok(files)
219}
220
221/// Returns the `format` directory of a fixtures release if `path` is one, otherwise `path`.
222fn fixtures_path(path: &Path, format: &str) -> PathBuf {
223    let candidate = path.join(format);
224    if candidate.is_dir() {
225        candidate
226    } else {
227        path.to_path_buf()
228    }
229}
230
231#[cfg(test)]
232mod tests {
233    use super::*;
234
235    #[test]
236    fn enginetest_takes_the_node_storage_layout_flag() {
237        let settings = |args: &[&str]| {
238            let cmd = TestRunnerCommand::parse_from(
239                ["ef-test-runner", "enginetest", "fixtures"].iter().chain(args),
240            );
241            let Some(Command::EngineTest(args)) = cmd.command else { panic!("{cmd:?}") };
242            storage_settings(args.storage)
243        };
244        assert_eq!(settings(&[]), StorageSettings::v2());
245        assert_eq!(settings(&["--storage.v2"]), StorageSettings::v2());
246        assert_eq!(settings(&["--storage.v2=false"]), StorageSettings::v1());
247    }
248}