forge/cmd/test/
mod.rs

1use super::{install, test::filter::ProjectPathsAwareFilter, watch::WatchArgs};
2use crate::{
3    MultiContractRunner, MultiContractRunnerBuilder,
4    decode::decode_console_logs,
5    gas_report::GasReport,
6    multi_runner::matches_artifact,
7    result::{SuiteResult, TestOutcome, TestStatus},
8    traces::{
9        CallTraceDecoderBuilder, InternalTraceMode, TraceKind,
10        debug::{ContractSources, DebugTraceIdentifier},
11        decode_trace_arena, folded_stack_trace,
12        identifier::SignaturesIdentifier,
13    },
14};
15use alloy_primitives::U256;
16use chrono::Utc;
17use clap::{Parser, ValueHint};
18use eyre::{Context, OptionExt, Result, bail};
19use foundry_cli::{
20    opts::{BuildOpts, EvmArgs, GlobalArgs},
21    utils::{self, LoadConfig},
22};
23use foundry_common::{EmptyTestFilter, TestFunctionExt, compile::ProjectCompiler, fs, shell};
24use foundry_compilers::{
25    ProjectCompileOutput,
26    artifacts::output_selection::OutputSelection,
27    compilers::{
28        Language,
29        multi::{MultiCompiler, MultiCompilerLanguage},
30    },
31    utils::source_files_iter,
32};
33use foundry_config::{
34    Config, figment,
35    figment::{
36        Metadata, Profile, Provider,
37        value::{Dict, Map},
38    },
39    filter::GlobMatcher,
40};
41use foundry_debugger::Debugger;
42use foundry_evm::{
43    opts::EvmOpts,
44    traces::{backtrace::BacktraceBuilder, identifier::TraceIdentifiers},
45};
46use regex::Regex;
47use std::{
48    collections::{BTreeMap, BTreeSet},
49    fmt::Write,
50    path::{Path, PathBuf},
51    sync::{Arc, mpsc::channel},
52    time::{Duration, Instant},
53};
54use yansi::Paint;
55
56mod filter;
57mod summary;
58use crate::{result::TestKind, traces::render_trace_arena_inner};
59pub use filter::FilterArgs;
60use quick_junit::{NonSuccessKind, Report, TestCase, TestCaseStatus, TestSuite};
61use summary::{TestSummaryReport, format_invariant_metrics_table};
62
63// Loads project's figment and merges the build cli arguments into it
64foundry_config::merge_impl_figment_convert!(TestArgs, build, evm);
65
66/// CLI arguments for `forge test`.
67#[derive(Clone, Debug, Parser)]
68#[command(next_help_heading = "Test options")]
69pub struct TestArgs {
70    // Include global options for users of this struct.
71    #[command(flatten)]
72    pub global: GlobalArgs,
73
74    /// The contract file you want to test, it's a shortcut for --match-path.
75    #[arg(value_hint = ValueHint::FilePath)]
76    pub path: Option<GlobMatcher>,
77
78    /// Run a single test in the debugger.
79    ///
80    /// The matching test will be opened in the debugger regardless of the outcome of the test.
81    ///
82    /// If the matching test is a fuzz test, then it will open the debugger on the first failure
83    /// case. If the fuzz test does not fail, it will open the debugger on the last fuzz case.
84    #[arg(long, conflicts_with_all = ["flamegraph", "flamechart", "decode_internal", "rerun"])]
85    debug: bool,
86
87    /// Generate a flamegraph for a single test. Implies `--decode-internal`.
88    ///
89    /// A flame graph is used to visualize which functions or operations within the smart contract
90    /// are consuming the most gas overall in a sorted manner.
91    #[arg(long)]
92    flamegraph: bool,
93
94    /// Generate a flamechart for a single test. Implies `--decode-internal`.
95    ///
96    /// A flame chart shows the gas usage over time, illustrating when each function is
97    /// called (execution order) and how much gas it consumes at each point in the timeline.
98    #[arg(long, conflicts_with = "flamegraph")]
99    flamechart: bool,
100
101    /// Identify internal functions in traces.
102    ///
103    /// This will trace internal functions and decode stack parameters.
104    ///
105    /// Parameters stored in memory (such as bytes or arrays) are currently decoded only when a
106    /// single function is matched, similarly to `--debug`, for performance reasons.
107    #[arg(long)]
108    decode_internal: bool,
109
110    /// Dumps all debugger steps to file.
111    #[arg(
112        long,
113        requires = "debug",
114        value_hint = ValueHint::FilePath,
115        value_name = "PATH"
116    )]
117    dump: Option<PathBuf>,
118
119    /// Print a gas report.
120    #[arg(long, env = "FORGE_GAS_REPORT")]
121    gas_report: bool,
122
123    /// Check gas snapshots against previous runs.
124    #[arg(long, env = "FORGE_SNAPSHOT_CHECK")]
125    gas_snapshot_check: Option<bool>,
126
127    /// Enable/disable recording of gas snapshot results.
128    #[arg(long, env = "FORGE_SNAPSHOT_EMIT")]
129    gas_snapshot_emit: Option<bool>,
130
131    /// Exit with code 0 even if a test fails.
132    #[arg(long, env = "FORGE_ALLOW_FAILURE")]
133    allow_failure: bool,
134
135    /// Suppress successful test traces and show only traces for failures.
136    #[arg(long, short, env = "FORGE_SUPPRESS_SUCCESSFUL_TRACES", help_heading = "Display options")]
137    suppress_successful_traces: bool,
138
139    /// Output test results as JUnit XML report.
140    #[arg(long, conflicts_with_all = ["quiet", "json", "gas_report", "summary", "list", "show_progress"], help_heading = "Display options")]
141    pub junit: bool,
142
143    /// Stop running tests after the first failure.
144    #[arg(long)]
145    pub fail_fast: bool,
146
147    /// The Etherscan (or equivalent) API key.
148    #[arg(long, env = "ETHERSCAN_API_KEY", value_name = "KEY")]
149    etherscan_api_key: Option<String>,
150
151    /// List tests instead of running them.
152    #[arg(long, short, conflicts_with_all = ["show_progress", "decode_internal", "summary"], help_heading = "Display options")]
153    list: bool,
154
155    /// Set seed used to generate randomness during your fuzz runs.
156    #[arg(long)]
157    pub fuzz_seed: Option<U256>,
158
159    #[arg(long, env = "FOUNDRY_FUZZ_RUNS", value_name = "RUNS")]
160    pub fuzz_runs: Option<u64>,
161
162    /// Timeout for each fuzz run in seconds.
163    #[arg(long, env = "FOUNDRY_FUZZ_TIMEOUT", value_name = "TIMEOUT")]
164    pub fuzz_timeout: Option<u64>,
165
166    /// File to rerun fuzz failures from.
167    #[arg(long)]
168    pub fuzz_input_file: Option<String>,
169
170    /// Show test execution progress.
171    #[arg(long, conflicts_with_all = ["quiet", "json"], help_heading = "Display options")]
172    pub show_progress: bool,
173
174    /// Re-run recorded test failures from last run.
175    /// If no failure recorded then regular test run is performed.
176    #[arg(long)]
177    pub rerun: bool,
178
179    /// Print test summary table.
180    #[arg(long, help_heading = "Display options")]
181    pub summary: bool,
182
183    /// Print detailed test summary table.
184    #[arg(long, help_heading = "Display options", requires = "summary")]
185    pub detailed: bool,
186
187    /// Disables the labels in the traces.
188    #[arg(long, help_heading = "Display options")]
189    pub disable_labels: bool,
190
191    #[command(flatten)]
192    filter: FilterArgs,
193
194    #[command(flatten)]
195    evm: EvmArgs,
196
197    #[command(flatten)]
198    pub build: BuildOpts,
199
200    #[command(flatten)]
201    pub watch: WatchArgs,
202}
203
204impl TestArgs {
205    pub async fn run(mut self) -> Result<TestOutcome> {
206        trace!(target: "forge::test", "executing test command");
207        self.compile_and_run().await
208    }
209
210    /// Returns a list of files that need to be compiled in order to run all the tests that match
211    /// the given filter.
212    ///
213    /// This means that it will return all sources that are not test contracts or that match the
214    /// filter. We want to compile all non-test sources always because tests might depend on them
215    /// dynamically through cheatcodes.
216    #[instrument(target = "forge::test", skip_all)]
217    pub fn get_sources_to_compile(
218        &self,
219        config: &Config,
220        test_filter: &ProjectPathsAwareFilter,
221    ) -> Result<BTreeSet<PathBuf>> {
222        // An empty filter doesn't filter out anything.
223        // We can still optimize slightly by excluding scripts.
224        if test_filter.is_empty() {
225            return Ok(source_files_iter(&config.src, MultiCompilerLanguage::FILE_EXTENSIONS)
226                .chain(source_files_iter(&config.test, MultiCompilerLanguage::FILE_EXTENSIONS))
227                .collect());
228        }
229
230        let mut project = config.create_project(true, true)?;
231        project.update_output_selection(|selection| {
232            *selection = OutputSelection::common_output_selection(["abi".to_string()]);
233        });
234        let output = project.compile()?;
235        if output.has_compiler_errors() {
236            sh_println!("{output}")?;
237            eyre::bail!("Compilation failed");
238        }
239
240        Ok(output
241            .artifact_ids()
242            .filter_map(|(id, artifact)| artifact.abi.as_ref().map(|abi| (id, abi)))
243            .filter(|(id, abi)| {
244                id.source.starts_with(&config.src) || matches_artifact(test_filter, id, abi)
245            })
246            .map(|(id, _)| id.source)
247            .collect())
248    }
249
250    /// Executes all the tests in the project.
251    ///
252    /// This will trigger the build process first. On success all test contracts that match the
253    /// configured filter will be executed
254    ///
255    /// Returns the test results for all matching tests.
256    pub async fn compile_and_run(&mut self) -> Result<TestOutcome> {
257        // Merge all configs.
258        let (mut config, evm_opts) = self.load_config_and_evm_opts()?;
259
260        // Install missing dependencies.
261        if install::install_missing_dependencies(&mut config).await && config.auto_detect_remappings
262        {
263            // need to re-configure here to also catch additional remappings
264            config = self.load_config()?;
265        }
266
267        // Set up the project.
268        let project = config.project()?;
269
270        let filter = self.filter(&config)?;
271        trace!(target: "forge::test", ?filter, "using filter");
272
273        let compiler = ProjectCompiler::new()
274            .dynamic_test_linking(config.dynamic_test_linking)
275            .quiet(shell::is_json() || self.junit)
276            .files(self.get_sources_to_compile(&config, &filter)?);
277        let output = compiler.compile(&project)?;
278
279        self.run_tests(&project.paths.root, config, evm_opts, &output, &filter, false).await
280    }
281
282    /// Executes all the tests in the project.
283    ///
284    /// See [`Self::compile_and_run`] for more details.
285    pub async fn run_tests(
286        &mut self,
287        project_root: &Path,
288        mut config: Config,
289        mut evm_opts: EvmOpts,
290        output: &ProjectCompileOutput,
291        filter: &ProjectPathsAwareFilter,
292        coverage: bool,
293    ) -> Result<TestOutcome> {
294        // Explicitly enable isolation for gas reports for more correct gas accounting.
295        if self.gas_report {
296            evm_opts.isolate = true;
297        } else {
298            // Do not collect gas report traces if gas report is not enabled.
299            config.fuzz.gas_report_samples = 0;
300            config.invariant.gas_report_samples = 0;
301        }
302
303        // Create test options from general project settings and compiler output.
304        let should_debug = self.debug;
305        let should_draw = self.flamegraph || self.flamechart;
306
307        // Determine print verbosity and executor verbosity.
308        let verbosity = evm_opts.verbosity;
309        if (self.gas_report && evm_opts.verbosity < 3) || self.flamegraph || self.flamechart {
310            evm_opts.verbosity = 3;
311        }
312
313        let env = evm_opts.evm_env().await?;
314
315        // Enable internal tracing for more informative flamegraph.
316        if should_draw && !self.decode_internal {
317            self.decode_internal = true;
318        }
319
320        // Choose the internal function tracing mode, if --decode-internal is provided.
321        let decode_internal = if self.decode_internal {
322            // If more than one function matched, we enable simple tracing.
323            // If only one function matched, we enable full tracing. This is done in `run_tests`.
324            InternalTraceMode::Simple
325        } else {
326            InternalTraceMode::None
327        };
328
329        // Prepare the test builder.
330        let config = Arc::new(config);
331        let runner = MultiContractRunnerBuilder::new(config.clone())
332            .set_debug(should_debug)
333            .set_decode_internal(decode_internal)
334            .initial_balance(evm_opts.initial_balance)
335            .evm_spec(config.evm_spec_id())
336            .sender(evm_opts.sender)
337            .with_fork(evm_opts.get_fork(&config, env.clone()))
338            .enable_isolation(evm_opts.isolate)
339            .networks(evm_opts.networks)
340            .fail_fast(self.fail_fast)
341            .set_coverage(coverage)
342            .build::<MultiCompiler>(output, env, evm_opts)?;
343
344        let libraries = runner.libraries.clone();
345        let mut outcome = self.run_tests_inner(runner, config, verbosity, filter, output).await?;
346
347        if should_draw {
348            let (suite_name, test_name, mut test_result) =
349                outcome.remove_first().ok_or_eyre("no tests were executed")?;
350
351            let (_, arena) = test_result
352                .traces
353                .iter_mut()
354                .find(|(kind, _)| *kind == TraceKind::Execution)
355                .unwrap();
356
357            // Decode traces.
358            let decoder = outcome.last_run_decoder.as_ref().unwrap();
359            decode_trace_arena(arena, decoder).await;
360            let mut fst = folded_stack_trace::build(arena);
361
362            let label = if self.flamegraph { "flamegraph" } else { "flamechart" };
363            let contract = suite_name.split(':').next_back().unwrap();
364            let test_name = test_name.trim_end_matches("()");
365            let file_name = format!("cache/{label}_{contract}_{test_name}.svg");
366            let file = std::fs::File::create(&file_name).wrap_err("failed to create file")?;
367            let file = std::io::BufWriter::new(file);
368
369            let mut options = inferno::flamegraph::Options::default();
370            options.title = format!("{label} {contract}::{test_name}");
371            options.count_name = "gas".to_string();
372            if self.flamechart {
373                options.flame_chart = true;
374                fst.reverse();
375            }
376
377            // Generate SVG.
378            inferno::flamegraph::from_lines(&mut options, fst.iter().map(String::as_str), file)
379                .wrap_err("failed to write svg")?;
380            sh_println!("Saved to {file_name}")?;
381
382            // Open SVG in default program.
383            if let Err(e) = opener::open(&file_name) {
384                sh_err!("Failed to open {file_name}; please open it manually: {e}")?;
385            }
386        }
387
388        if should_debug {
389            // Get first non-empty suite result. We will have only one such entry.
390            let (_, _, test_result) =
391                outcome.remove_first().ok_or_eyre("no tests were executed")?;
392
393            let sources =
394                ContractSources::from_project_output(output, project_root, Some(&libraries))?;
395
396            // Run the debugger.
397            let mut builder = Debugger::builder()
398                .traces(
399                    test_result.traces.iter().filter(|(t, _)| t.is_execution()).cloned().collect(),
400                )
401                .sources(sources)
402                .breakpoints(test_result.breakpoints.clone());
403
404            if let Some(decoder) = &outcome.last_run_decoder {
405                builder = builder.decoder(decoder);
406            }
407
408            let mut debugger = builder.build();
409            if let Some(dump_path) = &self.dump {
410                debugger.dump_to_file(dump_path)?;
411            } else {
412                debugger.try_run_tui()?;
413            }
414        }
415
416        Ok(outcome)
417    }
418
419    /// Run all tests that matches the filter predicate from a test runner
420    async fn run_tests_inner(
421        &self,
422        mut runner: MultiContractRunner,
423        config: Arc<Config>,
424        verbosity: u8,
425        filter: &ProjectPathsAwareFilter,
426        output: &ProjectCompileOutput,
427    ) -> eyre::Result<TestOutcome> {
428        if self.list {
429            return list(runner, filter);
430        }
431
432        trace!(target: "forge::test", "running all tests");
433
434        // If we need to render to a serialized format, we should not print anything else to stdout.
435        let silent = self.gas_report && shell::is_json() || self.summary && shell::is_json();
436
437        let num_filtered = runner.matching_test_functions(filter).count();
438
439        if num_filtered == 0 {
440            let mut total_tests = num_filtered;
441            if !filter.is_empty() {
442                total_tests = runner.matching_test_functions(&EmptyTestFilter::default()).count();
443            }
444            if total_tests == 0 {
445                sh_println!(
446                    "No tests found in project! Forge looks for functions that start with `test`"
447                )?;
448            } else {
449                let mut msg = format!("no tests match the provided pattern:\n{filter}");
450                // Try to suggest a test when there's no match.
451                if let Some(test_pattern) = &filter.args().test_pattern {
452                    let test_name = test_pattern.as_str();
453                    // Filter contracts but not test functions.
454                    let candidates = runner.all_test_functions(filter).map(|f| &f.name);
455                    if let Some(suggestion) = utils::did_you_mean(test_name, candidates).pop() {
456                        write!(msg, "\nDid you mean `{suggestion}`?")?;
457                    }
458                }
459                sh_warn!("{msg}")?;
460            }
461            return Ok(TestOutcome::empty(Some(runner), false));
462        }
463
464        if num_filtered != 1 && (self.debug || self.flamegraph || self.flamechart) {
465            let action = if self.flamegraph {
466                "generate a flamegraph"
467            } else if self.flamechart {
468                "generate a flamechart"
469            } else {
470                "run the debugger"
471            };
472            let filter = if filter.is_empty() {
473                String::new()
474            } else {
475                format!("\n\nFilter used:\n{filter}")
476            };
477            eyre::bail!(
478                "{num_filtered} tests matched your criteria, but exactly 1 test must match in order to {action}.\n\n\
479                 Use --match-contract and --match-path to further limit the search.{filter}",
480            );
481        }
482
483        // If exactly one test matched, we enable full tracing.
484        if num_filtered == 1 && self.decode_internal {
485            runner.decode_internal = InternalTraceMode::Full;
486        }
487
488        // Run tests in a non-streaming fashion and collect results for serialization.
489        if !self.gas_report && !self.summary && shell::is_json() {
490            let mut results = runner.test_collect(filter)?;
491            results.values_mut().for_each(|suite_result| {
492                for test_result in suite_result.test_results.values_mut() {
493                    if verbosity >= 2 {
494                        // Decode logs at level 2 and above.
495                        test_result.decoded_logs = decode_console_logs(&test_result.logs);
496                    } else {
497                        // Empty logs for non verbose runs.
498                        test_result.logs = vec![];
499                    }
500                }
501            });
502            sh_println!("{}", serde_json::to_string(&results)?)?;
503            return Ok(TestOutcome::new(Some(runner), results, self.allow_failure));
504        }
505
506        if self.junit {
507            let results = runner.test_collect(filter)?;
508            sh_println!("{}", junit_xml_report(&results, verbosity).to_string()?)?;
509            return Ok(TestOutcome::new(Some(runner), results, self.allow_failure));
510        }
511
512        let remote_chain =
513            if runner.fork.is_some() { runner.env.tx.chain_id.map(Into::into) } else { None };
514        let known_contracts = runner.known_contracts.clone();
515
516        let libraries = runner.libraries.clone();
517
518        // Run tests in a streaming fashion.
519        let (tx, rx) = channel::<(String, SuiteResult)>();
520        let timer = Instant::now();
521        let show_progress = config.show_progress;
522        let handle = tokio::task::spawn_blocking({
523            let filter = filter.clone();
524            move || runner.test(&filter, tx, show_progress).map(|()| runner)
525        });
526
527        // Set up trace identifiers.
528        let mut identifier = TraceIdentifiers::new().with_local(&known_contracts);
529
530        // Avoid using external identifiers for gas report as we decode more traces and this will be
531        // expensive.
532        if !self.gas_report {
533            identifier = identifier.with_external(&config, remote_chain)?;
534        }
535
536        // Build the trace decoder.
537        let mut builder = CallTraceDecoderBuilder::new()
538            .with_known_contracts(&known_contracts)
539            .with_label_disabled(self.disable_labels)
540            .with_verbosity(verbosity);
541        // Signatures are of no value for gas reports.
542        if !self.gas_report {
543            builder =
544                builder.with_signature_identifier(SignaturesIdentifier::from_config(&config)?);
545        }
546
547        if self.decode_internal {
548            let sources =
549                ContractSources::from_project_output(output, &config.root, Some(&libraries))?;
550            builder = builder.with_debug_identifier(DebugTraceIdentifier::new(sources));
551        }
552        let mut decoder = builder.build();
553
554        let mut gas_report = self.gas_report.then(|| {
555            GasReport::new(
556                config.gas_reports.clone(),
557                config.gas_reports_ignore.clone(),
558                config.gas_reports_include_tests,
559            )
560        });
561
562        let mut gas_snapshots = BTreeMap::<String, BTreeMap<String, String>>::new();
563
564        let mut outcome = TestOutcome::empty(None, self.allow_failure);
565
566        let mut any_test_failed = false;
567        let mut backtrace_builder = None;
568        for (contract_name, mut suite_result) in rx {
569            let tests = &mut suite_result.test_results;
570            let has_tests = !tests.is_empty();
571
572            // Clear the addresses and labels from previous test.
573            decoder.clear_addresses();
574
575            // We identify addresses if we're going to print *any* trace or gas report.
576            let identify_addresses = verbosity >= 3
577                || self.gas_report
578                || self.debug
579                || self.flamegraph
580                || self.flamechart;
581
582            // Print suite header.
583            if !silent {
584                sh_println!()?;
585                for warning in &suite_result.warnings {
586                    sh_warn!("{warning}")?;
587                }
588                if has_tests {
589                    let len = tests.len();
590                    let tests = if len > 1 { "tests" } else { "test" };
591                    sh_println!("Ran {len} {tests} for {contract_name}")?;
592                }
593            }
594
595            // Process individual test results, printing logs and traces when necessary.
596            for (name, result) in tests {
597                let show_traces =
598                    !self.suppress_successful_traces || result.status == TestStatus::Failure;
599                if !silent {
600                    sh_println!("{}", result.short_result(name))?;
601
602                    // Display invariant metrics if invariant kind.
603                    if let TestKind::Invariant { metrics, .. } = &result.kind
604                        && !metrics.is_empty()
605                    {
606                        let _ = sh_println!("\n{}\n", format_invariant_metrics_table(metrics));
607                    }
608
609                    // We only display logs at level 2 and above
610                    if verbosity >= 2 && show_traces {
611                        // We only decode logs from Hardhat and DS-style console events
612                        let console_logs = decode_console_logs(&result.logs);
613                        if !console_logs.is_empty() {
614                            sh_println!("Logs:")?;
615                            for log in console_logs {
616                                sh_println!("  {log}")?;
617                            }
618                            sh_println!()?;
619                        }
620                    }
621                }
622
623                // We shouldn't break out of the outer loop directly here so that we finish
624                // processing the remaining tests and print the suite summary.
625                any_test_failed |= result.status == TestStatus::Failure;
626
627                // Clear the addresses and labels from previous runs.
628                decoder.clear_addresses();
629                decoder.labels.extend(result.labels.iter().map(|(k, v)| (*k, v.clone())));
630
631                // Identify addresses and decode traces.
632                let mut decoded_traces = Vec::with_capacity(result.traces.len());
633                for (kind, arena) in &mut result.traces {
634                    if identify_addresses {
635                        decoder.identify(arena, &mut identifier);
636                    }
637
638                    // verbosity:
639                    // - 0..3: nothing
640                    // - 3: only display traces for failed tests
641                    // - 4: also display the setup trace for failed tests
642                    // - 5..: display all traces for all tests, including storage changes
643                    let should_include = match kind {
644                        TraceKind::Execution => {
645                            (verbosity == 3 && result.status.is_failure()) || verbosity >= 4
646                        }
647                        TraceKind::Setup => {
648                            (verbosity == 4 && result.status.is_failure()) || verbosity >= 5
649                        }
650                        TraceKind::Deployment => false,
651                    };
652
653                    if should_include {
654                        decode_trace_arena(arena, &decoder).await;
655                        decoded_traces.push(render_trace_arena_inner(arena, false, verbosity > 4));
656                    }
657                }
658
659                if !silent && show_traces && !decoded_traces.is_empty() {
660                    sh_println!("Traces:")?;
661                    for trace in &decoded_traces {
662                        sh_println!("{trace}")?;
663                    }
664                }
665
666                // Extract and display backtrace for failed tests when verbosity >= 3
667                if !silent
668                    && result.status.is_failure()
669                    && verbosity >= 3
670                    && !result.traces.is_empty()
671                    && let Some((_, arena)) =
672                        result.traces.iter().find(|(kind, _)| matches!(kind, TraceKind::Execution))
673                {
674                    // Lazily initialize the backtrace builder on first failure
675                    let builder = backtrace_builder.get_or_insert_with(|| {
676                        BacktraceBuilder::new(
677                            output,
678                            config.root.clone(),
679                            config.parsed_libraries().ok(),
680                            config.via_ir,
681                        )
682                    });
683
684                    let backtrace = builder.from_traces(arena);
685
686                    if !backtrace.is_empty() {
687                        sh_println!("{}", backtrace)?;
688                    }
689                }
690
691                if let Some(gas_report) = &mut gas_report {
692                    gas_report.analyze(result.traces.iter().map(|(_, a)| &a.arena), &decoder).await;
693
694                    for trace in &result.gas_report_traces {
695                        decoder.clear_addresses();
696
697                        // Re-execute setup and deployment traces to collect identities created in
698                        // setUp and constructor.
699                        for (kind, arena) in &result.traces {
700                            if !matches!(kind, TraceKind::Execution) {
701                                decoder.identify(arena, &mut identifier);
702                            }
703                        }
704
705                        for arena in trace {
706                            decoder.identify(arena, &mut identifier);
707                            gas_report.analyze([arena], &decoder).await;
708                        }
709                    }
710                }
711                // Clear memory.
712                result.gas_report_traces = Default::default();
713
714                // Collect and merge gas snapshots.
715                for (group, new_snapshots) in &result.gas_snapshots {
716                    gas_snapshots.entry(group.clone()).or_default().extend(new_snapshots.clone());
717                }
718            }
719
720            // Write gas snapshots to disk if any were collected.
721            if !gas_snapshots.is_empty() {
722                // By default `gas_snapshot_check` is set to `false` in the config.
723                //
724                // The user can either:
725                // - Set `FORGE_SNAPSHOT_CHECK=true` in the environment.
726                // - Pass `--gas-snapshot-check=true` as a CLI argument.
727                // - Set `gas_snapshot_check = true` in the config.
728                //
729                // If the user passes `--gas-snapshot-check=<bool>` then it will override the config
730                // and the environment variable, disabling the check if `false` is passed.
731                //
732                // Exiting early with code 1 if differences are found.
733                if self.gas_snapshot_check.unwrap_or(config.gas_snapshot_check) {
734                    let differences_found = gas_snapshots.clone().into_iter().fold(
735                        false,
736                        |mut found, (group, snapshots)| {
737                            // If the snapshot file doesn't exist, we can't compare so we skip.
738                            if !&config.snapshots.join(format!("{group}.json")).exists() {
739                                return false;
740                            }
741
742                            let previous_snapshots: BTreeMap<String, String> =
743                                fs::read_json_file(&config.snapshots.join(format!("{group}.json")))
744                                    .expect("Failed to read snapshots from disk");
745
746                            let diff: BTreeMap<_, _> = snapshots
747                                .iter()
748                                .filter_map(|(k, v)| {
749                                    previous_snapshots.get(k).and_then(|previous_snapshot| {
750                                        if previous_snapshot != v {
751                                            Some((
752                                                k.clone(),
753                                                (previous_snapshot.clone(), v.clone()),
754                                            ))
755                                        } else {
756                                            None
757                                        }
758                                    })
759                                })
760                                .collect();
761
762                            if !diff.is_empty() {
763                                let _ = sh_eprintln!(
764                                    "{}",
765                                    format!("\n[{group}] Failed to match snapshots:").red().bold()
766                                );
767
768                                for (key, (previous_snapshot, snapshot)) in &diff {
769                                    let _ = sh_eprintln!(
770                                        "{}",
771                                        format!("- [{key}] {previous_snapshot} → {snapshot}").red()
772                                    );
773                                }
774
775                                found = true;
776                            }
777
778                            found
779                        },
780                    );
781
782                    if differences_found {
783                        sh_eprintln!()?;
784                        eyre::bail!("Snapshots differ from previous run");
785                    }
786                }
787
788                // By default `gas_snapshot_emit` is set to `true` in the config.
789                //
790                // The user can either:
791                // - Set `FORGE_SNAPSHOT_EMIT=false` in the environment.
792                // - Pass `--gas-snapshot-emit=false` as a CLI argument.
793                // - Set `gas_snapshot_emit = false` in the config.
794                //
795                // If the user passes `--gas-snapshot-emit=<bool>` then it will override the config
796                // and the environment variable, enabling the check if `true` is passed.
797                if self.gas_snapshot_emit.unwrap_or(config.gas_snapshot_emit) {
798                    // Create `snapshots` directory if it doesn't exist.
799                    fs::create_dir_all(&config.snapshots)?;
800
801                    // Write gas snapshots to disk per group.
802                    gas_snapshots.clone().into_iter().for_each(|(group, snapshots)| {
803                        fs::write_pretty_json_file(
804                            &config.snapshots.join(format!("{group}.json")),
805                            &snapshots,
806                        )
807                        .expect("Failed to write gas snapshots to disk");
808                    });
809                }
810            }
811
812            // Print suite summary.
813            if !silent && has_tests {
814                sh_println!("{}", suite_result.summary())?;
815            }
816
817            // Add the suite result to the outcome.
818            outcome.results.insert(contract_name, suite_result);
819
820            // Stop processing the remaining suites if any test failed and `fail_fast` is set.
821            if self.fail_fast && any_test_failed {
822                break;
823            }
824        }
825        outcome.last_run_decoder = Some(decoder);
826        let duration = timer.elapsed();
827
828        trace!(target: "forge::test", len=outcome.results.len(), %any_test_failed, "done with results");
829
830        if let Some(gas_report) = gas_report {
831            let finalized = gas_report.finalize();
832            sh_println!("{}", &finalized)?;
833            outcome.gas_report = Some(finalized);
834        }
835
836        if !self.summary && !shell::is_json() {
837            sh_println!("{}", outcome.summary(duration))?;
838        }
839
840        if self.summary && !outcome.results.is_empty() {
841            let summary_report = TestSummaryReport::new(self.detailed, outcome.clone());
842            sh_println!("{}", &summary_report)?;
843        }
844
845        // Reattach the task.
846        match handle.await {
847            Ok(result) => outcome.runner = Some(result?),
848            Err(e) => match e.try_into_panic() {
849                Ok(payload) => std::panic::resume_unwind(payload),
850                Err(e) => return Err(e.into()),
851            },
852        }
853
854        // Persist test run failures to enable replaying.
855        persist_run_failures(&config, &outcome);
856
857        Ok(outcome)
858    }
859
860    /// Returns the flattened [`FilterArgs`] arguments merged with [`Config`].
861    /// Loads and applies filter from file if only last test run failures performed.
862    pub fn filter(&self, config: &Config) -> Result<ProjectPathsAwareFilter> {
863        let mut filter = self.filter.clone();
864        if self.rerun {
865            filter.test_pattern = last_run_failures(config);
866        }
867        if filter.path_pattern.is_some() {
868            if self.path.is_some() {
869                bail!("Can not supply both --match-path and |path|");
870            }
871        } else {
872            filter.path_pattern = self.path.clone();
873        }
874        Ok(filter.merge_with_config(config))
875    }
876
877    /// Returns whether `BuildArgs` was configured with `--watch`
878    pub fn is_watch(&self) -> bool {
879        self.watch.watch.is_some()
880    }
881
882    /// Returns the [`watchexec::Config`] necessary to bootstrap a new watch loop.
883    pub(crate) fn watchexec_config(&self) -> Result<watchexec::Config> {
884        self.watch.watchexec_config(|| {
885            let config = self.load_config()?;
886            Ok([config.src, config.test])
887        })
888    }
889}
890
891impl Provider for TestArgs {
892    fn metadata(&self) -> Metadata {
893        Metadata::named("Core Build Args Provider")
894    }
895
896    fn data(&self) -> Result<Map<Profile, Dict>, figment::Error> {
897        let mut dict = Dict::default();
898
899        let mut fuzz_dict = Dict::default();
900        if let Some(fuzz_seed) = self.fuzz_seed {
901            fuzz_dict.insert("seed".to_string(), fuzz_seed.to_string().into());
902        }
903        if let Some(fuzz_runs) = self.fuzz_runs {
904            fuzz_dict.insert("runs".to_string(), fuzz_runs.into());
905        }
906        if let Some(fuzz_timeout) = self.fuzz_timeout {
907            fuzz_dict.insert("timeout".to_string(), fuzz_timeout.into());
908        }
909        if let Some(fuzz_input_file) = self.fuzz_input_file.clone() {
910            fuzz_dict.insert("failure_persist_file".to_string(), fuzz_input_file.into());
911        }
912        dict.insert("fuzz".to_string(), fuzz_dict.into());
913
914        if let Some(etherscan_api_key) =
915            self.etherscan_api_key.as_ref().filter(|s| !s.trim().is_empty())
916        {
917            dict.insert("etherscan_api_key".to_string(), etherscan_api_key.to_string().into());
918        }
919
920        if self.show_progress {
921            dict.insert("show_progress".to_string(), true.into());
922        }
923
924        Ok(Map::from([(Config::selected_profile(), dict)]))
925    }
926}
927
928/// Lists all matching tests
929fn list(runner: MultiContractRunner, filter: &ProjectPathsAwareFilter) -> Result<TestOutcome> {
930    let results = runner.list(filter);
931
932    if shell::is_json() {
933        sh_println!("{}", serde_json::to_string(&results)?)?;
934    } else {
935        for (file, contracts) in &results {
936            sh_println!("{file}")?;
937            for (contract, tests) in contracts {
938                sh_println!("  {contract}")?;
939                sh_println!("    {}\n", tests.join("\n    "))?;
940            }
941        }
942    }
943    Ok(TestOutcome::empty(Some(runner), false))
944}
945
946/// Load persisted filter (with last test run failures) from file.
947fn last_run_failures(config: &Config) -> Option<regex::Regex> {
948    match fs::read_to_string(&config.test_failures_file) {
949        Ok(filter) => Regex::new(&filter)
950            .inspect_err(|e| {
951                _ = sh_warn!(
952                    "failed to parse test filter from {:?}: {e}",
953                    config.test_failures_file
954                )
955            })
956            .ok(),
957        Err(_) => None,
958    }
959}
960
961/// Persist filter with last test run failures (only if there's any failure).
962fn persist_run_failures(config: &Config, outcome: &TestOutcome) {
963    if outcome.failed() > 0 && fs::create_file(&config.test_failures_file).is_ok() {
964        let mut filter = String::new();
965        let mut failures = outcome.failures().peekable();
966        while let Some((test_name, _)) = failures.next() {
967            if test_name.is_any_test()
968                && let Some(test_match) = test_name.split("(").next()
969            {
970                filter.push_str(test_match);
971                if failures.peek().is_some() {
972                    filter.push('|');
973                }
974            }
975        }
976        let _ = fs::write(&config.test_failures_file, filter);
977    }
978}
979
980/// Generate test report in JUnit XML report format.
981fn junit_xml_report(results: &BTreeMap<String, SuiteResult>, verbosity: u8) -> Report {
982    let mut total_duration = Duration::default();
983    let mut junit_report = Report::new("Test run");
984    junit_report.set_timestamp(Utc::now());
985    for (suite_name, suite_result) in results {
986        let mut test_suite = TestSuite::new(suite_name);
987        total_duration += suite_result.duration;
988        test_suite.set_time(suite_result.duration);
989        test_suite.set_system_out(suite_result.summary());
990        for (test_name, test_result) in &suite_result.test_results {
991            let mut test_status = match test_result.status {
992                TestStatus::Success => TestCaseStatus::success(),
993                TestStatus::Failure => TestCaseStatus::non_success(NonSuccessKind::Failure),
994                TestStatus::Skipped => TestCaseStatus::skipped(),
995            };
996            if let Some(reason) = &test_result.reason {
997                test_status.set_message(reason);
998            }
999
1000            let mut test_case = TestCase::new(test_name, test_status);
1001            test_case.set_time(test_result.duration);
1002
1003            let mut sys_out = String::new();
1004            let result_report = test_result.kind.report();
1005            write!(sys_out, "{test_result} {test_name} {result_report}").unwrap();
1006            if verbosity >= 2 && !test_result.logs.is_empty() {
1007                write!(sys_out, "\\nLogs:\\n").unwrap();
1008                let console_logs = decode_console_logs(&test_result.logs);
1009                for log in console_logs {
1010                    write!(sys_out, "  {log}\\n").unwrap();
1011                }
1012            }
1013
1014            test_case.set_system_out(sys_out);
1015            test_suite.add_test_case(test_case);
1016        }
1017        junit_report.add_test_suite(test_suite);
1018    }
1019    junit_report.set_time(total_duration);
1020    junit_report
1021}
1022
1023#[cfg(test)]
1024mod tests {
1025    use super::*;
1026    use foundry_config::Chain;
1027
1028    #[test]
1029    fn watch_parse() {
1030        let args: TestArgs = TestArgs::parse_from(["foundry-cli", "-vw"]);
1031        assert!(args.watch.watch.is_some());
1032    }
1033
1034    #[test]
1035    fn fuzz_seed() {
1036        let args: TestArgs = TestArgs::parse_from(["foundry-cli", "--fuzz-seed", "0x10"]);
1037        assert!(args.fuzz_seed.is_some());
1038    }
1039
1040    // <https://github.com/foundry-rs/foundry/issues/5913>
1041    #[test]
1042    fn fuzz_seed_exists() {
1043        let args: TestArgs =
1044            TestArgs::parse_from(["foundry-cli", "-vvv", "--gas-report", "--fuzz-seed", "0x10"]);
1045        assert!(args.fuzz_seed.is_some());
1046    }
1047
1048    #[test]
1049    fn extract_chain() {
1050        let test = |arg: &str, expected: Chain| {
1051            let args = TestArgs::parse_from(["foundry-cli", arg]);
1052            assert_eq!(args.evm.env.chain, Some(expected));
1053            let (config, evm_opts) = args.load_config_and_evm_opts().unwrap();
1054            assert_eq!(config.chain, Some(expected));
1055            assert_eq!(evm_opts.env.chain_id, Some(expected.id()));
1056        };
1057        test("--chain-id=1", Chain::mainnet());
1058        test("--chain-id=42", Chain::from_id(42));
1059    }
1060}