Skip to main content

ef_tests/
result.rs

1//! Test results and errors
2
3use crate::models::FixtureConfigError;
4use alloy_primitives::B256;
5use reth_db::DatabaseError;
6use reth_evm::{BlockExecutionError, InternalBlockExecutionError};
7use reth_provider::ProviderError;
8use serde::Serialize;
9use std::path::{Path, PathBuf};
10use thiserror::Error;
11
12/// Test errors
13///
14/// # Note
15///
16/// `Error::Skipped` should not be treated as a test failure.
17#[derive(Debug, Error)]
18#[non_exhaustive]
19pub enum Error {
20    /// The test was skipped
21    #[error("test was skipped")]
22    Skipped,
23    /// Block processing failed
24    /// Note: This includes but is not limited to execution.
25    /// For example, the header number could be incorrect.
26    #[error("block {block_number} failed to process: {err}")]
27    BlockProcessingFailed {
28        /// The block number for the block that failed
29        block_number: u64,
30        /// The specific error
31        #[source]
32        err: Box<dyn std::error::Error + Send + Sync>,
33    },
34    /// An IO error occurred
35    #[error("an error occurred interacting with the file system at {path}: {error}")]
36    Io {
37        /// The path to the file or directory
38        path: PathBuf,
39        /// The specific error
40        #[source]
41        error: std::io::Error,
42    },
43    /// A deserialization error occurred
44    #[error("an error occurred deserializing the test at {path}: {error}")]
45    CouldNotDeserialize {
46        /// The path to the file we wanted to deserialize
47        path: PathBuf,
48        /// The specific error
49        #[source]
50        error: serde_json::Error,
51    },
52    /// A fixture directory could not be traversed.
53    #[error(transparent)]
54    WalkDir(#[from] walkdir::Error),
55    /// An engine operation failed.
56    #[error("{context}: {error}")]
57    Engine {
58        /// The operation that failed.
59        context: String,
60        /// The original error.
61        #[source]
62        error: Box<dyn std::error::Error + Send + Sync>,
63    },
64    /// A database error occurred.
65    #[error(transparent)]
66    Database(#[from] DatabaseError),
67    /// An internal execution failure, which must never count as an invalid block.
68    #[error(transparent)]
69    Execution(#[from] InternalBlockExecutionError),
70    /// The fixture requests a configuration the client cannot execute.
71    #[error(transparent)]
72    FixtureConfig(#[from] FixtureConfigError),
73    /// A test assertion failed.
74    #[error("test failed: {0}")]
75    Assertion(String),
76    /// An error internally in reth occurred.
77    #[error("test failed: {0}")]
78    Provider(#[from] ProviderError),
79    /// An error occurred while decoding RLP.
80    #[error("an error occurred deserializing RLP: {0}")]
81    RlpDecodeError(#[from] alloy_rlp::Error),
82    /// A consensus error occurred.
83    #[error("an error occurred during consensus checks: {0}")]
84    ConsensusError(#[from] reth_consensus::ConsensusError),
85}
86
87impl Error {
88    /// Preserves the source of an engine setup, request, or shutdown failure.
89    pub(crate) fn engine(
90        context: impl Into<String>,
91        error: impl Into<Box<dyn std::error::Error + Send + Sync>>,
92    ) -> Self {
93        Self::Engine { context: context.into(), error: error.into() }
94    }
95
96    /// Separates a consensus-invalid execution from a failure of the executor or its provider.
97    pub(crate) fn block_execution_failed(block_number: u64, error: BlockExecutionError) -> Self {
98        match error {
99            BlockExecutionError::Validation(error) => Self::block_failed(block_number, error),
100            BlockExecutionError::Internal(error) => Self::Execution(error),
101        }
102    }
103
104    /// Create a new [`Error::BlockProcessingFailed`] error.
105    pub fn block_failed(
106        block_number: u64,
107        err: impl std::error::Error + Send + Sync + 'static,
108    ) -> Self {
109        Self::BlockProcessingFailed { block_number, err: Box::new(err) }
110    }
111}
112
113/// The result of running a test.
114#[derive(Debug)]
115pub struct CaseResult {
116    /// A description of the test.
117    pub desc: String,
118    /// The full path to the test.
119    pub path: PathBuf,
120    /// The result of the test.
121    pub result: Result<(), Error>,
122}
123
124impl CaseResult {
125    /// Create a new test result.
126    pub fn new(path: &Path, desc: String, result: Result<(), Error>) -> Self {
127        Self { desc, path: path.into(), result }
128    }
129}
130
131/// The result of one fixture, as printed by the runner's JSON output.
132#[derive(Debug, Serialize)]
133#[serde(rename_all = "camelCase")]
134pub struct FixtureResult {
135    /// The fixture name.
136    pub name: String,
137    /// Whether the fixture passed.
138    pub pass: bool,
139    /// The fixture's network.
140    pub fork: String,
141    /// The hash of the client's head block once the fixture ran.
142    #[serde(skip_serializing_if = "Option::is_none")]
143    pub last_block_hash: Option<B256>,
144    /// The status of the last `engine_newPayload` call, for engine tests.
145    #[serde(skip_serializing_if = "Option::is_none")]
146    pub last_payload_status: Option<String>,
147    /// Why the fixture failed, empty if it passed.
148    pub error: String,
149    /// Every block or payload the client rejected, in fixture order, whether or not the fixture
150    /// expected it.
151    pub rejections: Vec<Rejection>,
152}
153
154/// A block or payload the client rejected, with the client's own error, so that a consumer can
155/// check the reason against the fixture's expected exception.
156#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
157pub struct Rejection {
158    /// The block's position in the fixture's `blocks`, or the payload's in `engineNewPayloads`.
159    pub index: usize,
160    /// The rejected block's hash, when the client computed one.
161    #[serde(skip_serializing_if = "Option::is_none")]
162    pub hash: Option<B256>,
163    /// The client's error, verbatim.
164    pub error: String,
165}
166
167impl FixtureResult {
168    /// Creates the result of a fixture that ran.
169    pub fn new(name: String, fork: String, result: Result<(), Error>) -> Self {
170        let pass = result.is_ok();
171        let error = result.err().map(|err| err.to_string()).unwrap_or_default();
172        Self {
173            name,
174            pass,
175            fork,
176            last_block_hash: None,
177            last_payload_status: None,
178            error,
179            rejections: Vec::new(),
180        }
181    }
182
183    /// Sets the hash of the client's head block.
184    pub const fn with_last_block_hash(mut self, hash: B256) -> Self {
185        self.last_block_hash = Some(hash);
186        self
187    }
188
189    /// Sets the blocks or payloads the client rejected.
190    pub fn with_rejections(mut self, rejections: Vec<Rejection>) -> Self {
191        self.rejections = rejections;
192        self
193    }
194}
195
196/// Assert that all the given tests passed and print the results to stdout.
197pub(crate) fn assert_tests_pass(suite_name: &str, path: &Path, results: &[CaseResult]) {
198    let (passed, failed, skipped) = categorize_results(results);
199
200    print_results(suite_name, path, &passed, &failed, &skipped);
201
202    assert!(failed.is_empty(), "Some tests failed (see above)");
203}
204
205/// Categorize test results into `(passed, failed, skipped)`.
206pub(crate) fn categorize_results(
207    results: &[CaseResult],
208) -> (Vec<&CaseResult>, Vec<&CaseResult>, Vec<&CaseResult>) {
209    let mut passed = Vec::new();
210    let mut failed = Vec::new();
211    let mut skipped = Vec::new();
212
213    for case in results {
214        match case.result.as_ref().err() {
215            Some(Error::Skipped) => skipped.push(case),
216            Some(_) => failed.push(case),
217            None => passed.push(case),
218        }
219    }
220
221    (passed, failed, skipped)
222}
223
224/// Display the given test results to stdout.
225pub(crate) fn print_results(
226    suite_name: &str,
227    path: &Path,
228    passed: &[&CaseResult],
229    failed: &[&CaseResult],
230    skipped: &[&CaseResult],
231) {
232    println!("Suite: {suite_name} (at {})", path.display());
233    println!(
234        "Ran {} tests ({} passed, {} failed, {} skipped)",
235        passed.len() + failed.len() + skipped.len(),
236        passed.len(),
237        failed.len(),
238        skipped.len()
239    );
240
241    for case in skipped {
242        println!("[S] Case {} skipped", case.path.display());
243    }
244
245    for case in failed {
246        let error = case.result.as_ref().unwrap_err();
247        println!("[!] Case {} failed (description: {}): {}", case.path.display(), case.desc, error);
248    }
249}
250
251#[cfg(test)]
252mod tests {
253    use super::*;
254    use reth_evm::BlockValidationError;
255
256    #[test]
257    fn only_validation_errors_can_count_as_expected_invalid_blocks() {
258        let invalid =
259            Error::block_execution_failed(1, BlockValidationError::msg("invalid block").into());
260        assert!(matches!(invalid, Error::BlockProcessingFailed { block_number: 1, .. }));
261        assert_eq!(invalid.to_string(), "block 1 failed to process: invalid block");
262
263        let source = ProviderError::UnsupportedProvider;
264        let expected = source.to_string();
265        let failure = Error::block_execution_failed(1, BlockExecutionError::other(source));
266        assert!(matches!(failure, Error::Execution(_)));
267        assert_eq!(failure.to_string(), expected);
268        let provider_error = Error::from(ProviderError::UnsupportedProvider);
269        assert!(matches!(provider_error, Error::Provider(_)));
270        assert_eq!(provider_error.to_string(), format!("test failed: {expected}"));
271    }
272}