forge/
multi_runner.rs

1//! Forge test runner for multiple contracts.
2
3use crate::{
4    ContractRunner, TestFilter, progress::TestsProgress, result::SuiteResult,
5    runner::LIBRARY_DEPLOYER,
6};
7use alloy_json_abi::{Function, JsonAbi};
8use alloy_primitives::{Address, Bytes, U256};
9use eyre::Result;
10use foundry_cli::opts::configure_pcx_from_compile_output;
11use foundry_common::{
12    ContractsByArtifact, ContractsByArtifactBuilder, TestFunctionExt, get_contract_name,
13    shell::verbosity,
14};
15use foundry_compilers::{
16    Artifact, ArtifactId, Compiler, ProjectCompileOutput,
17    artifacts::{Contract, Libraries},
18};
19use foundry_config::{Config, InlineConfig};
20use foundry_evm::{
21    Env,
22    backend::Backend,
23    decode::RevertDecoder,
24    executors::{EarlyExit, Executor, ExecutorBuilder},
25    fork::CreateFork,
26    fuzz::strategies::LiteralsDictionary,
27    inspectors::CheatsConfig,
28    opts::EvmOpts,
29    traces::{InternalTraceMode, TraceMode},
30};
31use foundry_evm_networks::NetworkConfigs;
32use foundry_linking::{LinkOutput, Linker};
33use rayon::prelude::*;
34use revm::primitives::hardfork::SpecId;
35use std::{
36    borrow::Borrow,
37    collections::BTreeMap,
38    path::Path,
39    sync::{Arc, mpsc},
40    time::Instant,
41};
42
43#[derive(Debug, Clone)]
44pub struct TestContract {
45    pub abi: JsonAbi,
46    pub bytecode: Bytes,
47}
48
49pub type DeployableContracts = BTreeMap<ArtifactId, TestContract>;
50
51/// A multi contract runner receives a set of contracts deployed in an EVM instance and proceeds
52/// to run all test functions in these contracts.
53#[derive(Clone, Debug)]
54pub struct MultiContractRunner {
55    /// Mapping of contract name to JsonAbi, creation bytecode and library bytecode which
56    /// needs to be deployed & linked against
57    pub contracts: DeployableContracts,
58    /// Known contracts linked with computed library addresses.
59    pub known_contracts: ContractsByArtifact,
60    /// Revert decoder. Contains all known errors and their selectors.
61    pub revert_decoder: RevertDecoder,
62    /// Libraries to deploy.
63    pub libs_to_deploy: Vec<Bytes>,
64    /// Library addresses used to link contracts.
65    pub libraries: Libraries,
66    /// Solar compiler instance, to grant syntactic and semantic analysis capabilities
67    pub analysis: Arc<solar::sema::Compiler>,
68    /// Literals dictionary for fuzzing.
69    pub fuzz_literals: LiteralsDictionary,
70
71    /// The fork to use at launch
72    pub fork: Option<CreateFork>,
73
74    /// The base configuration for the test runner.
75    pub tcfg: TestRunnerConfig,
76}
77
78impl std::ops::Deref for MultiContractRunner {
79    type Target = TestRunnerConfig;
80
81    fn deref(&self) -> &Self::Target {
82        &self.tcfg
83    }
84}
85
86impl std::ops::DerefMut for MultiContractRunner {
87    fn deref_mut(&mut self) -> &mut Self::Target {
88        &mut self.tcfg
89    }
90}
91
92impl MultiContractRunner {
93    /// Returns an iterator over all contracts that match the filter.
94    pub fn matching_contracts<'a: 'b, 'b>(
95        &'a self,
96        filter: &'b dyn TestFilter,
97    ) -> impl Iterator<Item = (&'a ArtifactId, &'a TestContract)> + 'b {
98        self.contracts.iter().filter(|&(id, c)| matches_artifact(filter, id, &c.abi))
99    }
100
101    /// Returns an iterator over all test functions that match the filter.
102    pub fn matching_test_functions<'a: 'b, 'b>(
103        &'a self,
104        filter: &'b dyn TestFilter,
105    ) -> impl Iterator<Item = &'a Function> + 'b {
106        self.matching_contracts(filter)
107            .flat_map(|(_, c)| c.abi.functions())
108            .filter(|func| filter.matches_test_function(func))
109    }
110
111    /// Returns an iterator over all test functions in contracts that match the filter.
112    pub fn all_test_functions<'a: 'b, 'b>(
113        &'a self,
114        filter: &'b dyn TestFilter,
115    ) -> impl Iterator<Item = &'a Function> + 'b {
116        self.contracts
117            .iter()
118            .filter(|(id, _)| filter.matches_path(&id.source) && filter.matches_contract(&id.name))
119            .flat_map(|(_, c)| c.abi.functions())
120            .filter(|func| func.is_any_test())
121    }
122
123    /// Returns all matching tests grouped by contract grouped by file (file -> (contract -> tests))
124    pub fn list(&self, filter: &dyn TestFilter) -> BTreeMap<String, BTreeMap<String, Vec<String>>> {
125        self.matching_contracts(filter)
126            .map(|(id, c)| {
127                let source = id.source.as_path().display().to_string();
128                let name = id.name.clone();
129                let tests = c
130                    .abi
131                    .functions()
132                    .filter(|func| filter.matches_test_function(func))
133                    .map(|func| func.name.clone())
134                    .collect::<Vec<_>>();
135                (source, name, tests)
136            })
137            .fold(BTreeMap::new(), |mut acc, (source, name, tests)| {
138                acc.entry(source).or_default().insert(name, tests);
139                acc
140            })
141    }
142
143    /// Executes _all_ tests that match the given `filter`.
144    ///
145    /// The same as [`test`](Self::test), but returns the results instead of streaming them.
146    ///
147    /// Note that this method returns only when all tests have been executed.
148    pub fn test_collect(
149        &mut self,
150        filter: &dyn TestFilter,
151    ) -> Result<BTreeMap<String, SuiteResult>> {
152        Ok(self.test_iter(filter)?.collect())
153    }
154
155    /// Executes _all_ tests that match the given `filter`.
156    ///
157    /// The same as [`test`](Self::test), but returns the results instead of streaming them.
158    ///
159    /// Note that this method returns only when all tests have been executed.
160    pub fn test_iter(
161        &mut self,
162        filter: &dyn TestFilter,
163    ) -> Result<impl Iterator<Item = (String, SuiteResult)>> {
164        let (tx, rx) = mpsc::channel();
165        self.test(filter, tx, false)?;
166        Ok(rx.into_iter())
167    }
168
169    /// Executes _all_ tests that match the given `filter`.
170    ///
171    /// This will create the runtime based on the configured `evm` ops and create the `Backend`
172    /// before executing all contracts and their tests in _parallel_.
173    ///
174    /// Each Executor gets its own instance of the `Backend`.
175    pub fn test(
176        &mut self,
177        filter: &dyn TestFilter,
178        tx: mpsc::Sender<(String, SuiteResult)>,
179        show_progress: bool,
180    ) -> Result<()> {
181        let tokio_handle = tokio::runtime::Handle::current();
182        trace!("running all tests");
183
184        // The DB backend that serves all the data.
185        let db = Backend::spawn(self.fork.take())?;
186
187        let find_timer = Instant::now();
188        let contracts = self.matching_contracts(filter).collect::<Vec<_>>();
189        let find_time = find_timer.elapsed();
190        debug!(
191            "Found {} test contracts out of {} in {:?}",
192            contracts.len(),
193            self.contracts.len(),
194            find_time,
195        );
196
197        if show_progress {
198            let tests_progress = TestsProgress::new(contracts.len(), rayon::current_num_threads());
199            // Collect test suite results to stream at the end of test run.
200            let results: Vec<(String, SuiteResult)> = contracts
201                .par_iter()
202                .map(|&(id, contract)| {
203                    let _guard = tokio_handle.enter();
204                    tests_progress.inner.lock().start_suite_progress(&id.identifier());
205
206                    let result = self.run_test_suite(
207                        id,
208                        contract,
209                        &db,
210                        filter,
211                        &tokio_handle,
212                        Some(&tests_progress),
213                    );
214
215                    tests_progress
216                        .inner
217                        .lock()
218                        .end_suite_progress(&id.identifier(), result.summary());
219
220                    (id.identifier(), result)
221                })
222                .collect();
223
224            tests_progress.inner.lock().clear();
225
226            results.iter().for_each(|result| {
227                let _ = tx.send(result.to_owned());
228            });
229        } else {
230            contracts.par_iter().for_each(|&(id, contract)| {
231                let _guard = tokio_handle.enter();
232                let result = self.run_test_suite(id, contract, &db, filter, &tokio_handle, None);
233                let _ = tx.send((id.identifier(), result));
234            })
235        }
236
237        Ok(())
238    }
239
240    fn run_test_suite(
241        &self,
242        artifact_id: &ArtifactId,
243        contract: &TestContract,
244        db: &Backend,
245        filter: &dyn TestFilter,
246        tokio_handle: &tokio::runtime::Handle,
247        progress: Option<&TestsProgress>,
248    ) -> SuiteResult {
249        let identifier = artifact_id.identifier();
250        let mut span_name = identifier.as_str();
251
252        if !enabled!(tracing::Level::TRACE) {
253            span_name = get_contract_name(&identifier);
254        }
255        let span = debug_span!("suite", name = %span_name);
256        let span_local = span.clone();
257        let _guard = span_local.enter();
258
259        debug!("start executing all tests in contract");
260
261        let executor = self.tcfg.executor(
262            self.known_contracts.clone(),
263            self.analysis.clone(),
264            artifact_id,
265            db.clone(),
266        );
267        let runner = ContractRunner::new(
268            &identifier,
269            contract,
270            executor,
271            progress,
272            tokio_handle,
273            span,
274            self,
275        );
276        let r = runner.run_tests(filter);
277
278        debug!(duration=?r.duration, "executed all tests in contract");
279
280        r
281    }
282}
283
284/// Configuration for the test runner.
285///
286/// This is modified after instantiation through inline config.
287#[derive(Clone, Debug)]
288pub struct TestRunnerConfig {
289    /// Project config.
290    pub config: Arc<Config>,
291    /// Inline configuration.
292    pub inline_config: Arc<InlineConfig>,
293
294    /// EVM configuration.
295    pub evm_opts: EvmOpts,
296    /// EVM environment.
297    pub env: Env,
298    /// EVM version.
299    pub spec_id: SpecId,
300    /// The address which will be used to deploy the initial contracts and send all transactions.
301    pub sender: Address,
302
303    /// Whether to collect line coverage info
304    pub line_coverage: bool,
305    /// Whether to collect debug info
306    pub debug: bool,
307    /// Whether to enable steps tracking in the tracer.
308    pub decode_internal: InternalTraceMode,
309    /// Whether to enable call isolation.
310    pub isolation: bool,
311    /// Networks with enabled features.
312    pub networks: NetworkConfigs,
313    /// Whether to exit early on test failure or if test run interrupted.
314    pub early_exit: EarlyExit,
315}
316
317impl TestRunnerConfig {
318    /// Reconfigures all fields using the given `config`.
319    /// This is for example used to override the configuration with inline config.
320    pub fn reconfigure_with(&mut self, config: Arc<Config>) {
321        debug_assert!(!Arc::ptr_eq(&self.config, &config));
322
323        self.spec_id = config.evm_spec_id();
324        self.sender = config.sender;
325        self.networks = config.networks;
326        self.isolation = config.isolate;
327
328        // Specific to Forge, not present in config.
329        // self.line_coverage = N/A;
330        // self.debug = N/A;
331        // self.decode_internal = N/A;
332
333        // TODO: self.evm_opts
334        self.evm_opts.always_use_create_2_factory = config.always_use_create_2_factory;
335
336        // TODO: self.env
337
338        self.config = config;
339    }
340
341    /// Configures the given executor with this configuration.
342    pub fn configure_executor(&self, executor: &mut Executor) {
343        // TODO: See above
344
345        let inspector = executor.inspector_mut();
346        // inspector.set_env(&self.env);
347        if let Some(cheatcodes) = inspector.cheatcodes.as_mut() {
348            cheatcodes.config =
349                Arc::new(cheatcodes.config.clone_with(&self.config, self.evm_opts.clone()));
350        }
351        inspector.tracing(self.trace_mode());
352        inspector.collect_line_coverage(self.line_coverage);
353        inspector.enable_isolation(self.isolation);
354        inspector.networks(self.networks);
355        // inspector.set_create2_deployer(self.evm_opts.create2_deployer);
356
357        // executor.env_mut().clone_from(&self.env);
358        executor.set_spec_id(self.spec_id);
359        // executor.set_gas_limit(self.evm_opts.gas_limit());
360        executor.set_legacy_assertions(self.config.legacy_assertions);
361    }
362
363    /// Creates a new executor with this configuration.
364    pub fn executor(
365        &self,
366        known_contracts: ContractsByArtifact,
367        analysis: Arc<solar::sema::Compiler>,
368        artifact_id: &ArtifactId,
369        db: Backend,
370    ) -> Executor {
371        let cheats_config = Arc::new(CheatsConfig::new(
372            &self.config,
373            self.evm_opts.clone(),
374            Some(known_contracts),
375            Some(artifact_id.clone()),
376        ));
377        ExecutorBuilder::new()
378            .inspectors(|stack| {
379                stack
380                    .cheatcodes(cheats_config)
381                    .trace_mode(self.trace_mode())
382                    .line_coverage(self.line_coverage)
383                    .enable_isolation(self.isolation)
384                    .networks(self.networks)
385                    .create2_deployer(self.evm_opts.create2_deployer)
386                    .set_analysis(analysis)
387            })
388            .spec_id(self.spec_id)
389            .gas_limit(self.evm_opts.gas_limit())
390            .legacy_assertions(self.config.legacy_assertions)
391            .build(self.env.clone(), db)
392    }
393
394    fn trace_mode(&self) -> TraceMode {
395        TraceMode::default()
396            .with_debug(self.debug)
397            .with_decode_internal(self.decode_internal)
398            .with_verbosity(self.evm_opts.verbosity)
399            .with_state_changes(verbosity() > 4)
400    }
401}
402
403/// Builder used for instantiating the multi-contract runner
404#[derive(Clone)]
405#[must_use = "builders do nothing unless you call `build` on them"]
406pub struct MultiContractRunnerBuilder {
407    /// The address which will be used to deploy the initial contracts and send all
408    /// transactions
409    pub sender: Option<Address>,
410    /// The initial balance for each one of the deployed smart contracts
411    pub initial_balance: U256,
412    /// The EVM spec to use
413    pub evm_spec: Option<SpecId>,
414    /// The fork to use at launch
415    pub fork: Option<CreateFork>,
416    /// Project config.
417    pub config: Arc<Config>,
418    /// Whether or not to collect line coverage info
419    pub line_coverage: bool,
420    /// Whether or not to collect debug info
421    pub debug: bool,
422    /// Whether to enable steps tracking in the tracer.
423    pub decode_internal: InternalTraceMode,
424    /// Whether to enable call isolation
425    pub isolation: bool,
426    /// Networks with enabled features.
427    pub networks: NetworkConfigs,
428    /// Whether to exit early on test failure.
429    pub fail_fast: bool,
430}
431
432impl MultiContractRunnerBuilder {
433    pub fn new(config: Arc<Config>) -> Self {
434        Self {
435            config,
436            sender: Default::default(),
437            initial_balance: Default::default(),
438            evm_spec: Default::default(),
439            fork: Default::default(),
440            line_coverage: Default::default(),
441            debug: Default::default(),
442            isolation: Default::default(),
443            decode_internal: Default::default(),
444            networks: Default::default(),
445            fail_fast: false,
446        }
447    }
448
449    pub fn sender(mut self, sender: Address) -> Self {
450        self.sender = Some(sender);
451        self
452    }
453
454    pub fn initial_balance(mut self, initial_balance: U256) -> Self {
455        self.initial_balance = initial_balance;
456        self
457    }
458
459    pub fn evm_spec(mut self, spec: SpecId) -> Self {
460        self.evm_spec = Some(spec);
461        self
462    }
463
464    pub fn with_fork(mut self, fork: Option<CreateFork>) -> Self {
465        self.fork = fork;
466        self
467    }
468
469    pub fn set_coverage(mut self, enable: bool) -> Self {
470        self.line_coverage = enable;
471        self
472    }
473
474    pub fn set_debug(mut self, enable: bool) -> Self {
475        self.debug = enable;
476        self
477    }
478
479    pub fn set_decode_internal(mut self, mode: InternalTraceMode) -> Self {
480        self.decode_internal = mode;
481        self
482    }
483
484    pub fn fail_fast(mut self, fail_fast: bool) -> Self {
485        self.fail_fast = fail_fast;
486        self
487    }
488
489    pub fn enable_isolation(mut self, enable: bool) -> Self {
490        self.isolation = enable;
491        self
492    }
493
494    pub fn networks(mut self, networks: NetworkConfigs) -> Self {
495        self.networks = networks;
496        self
497    }
498
499    /// Given an EVM, proceeds to return a runner which is able to execute all tests
500    /// against that evm
501    pub fn build<C: Compiler<CompilerContract = Contract>>(
502        self,
503        output: &ProjectCompileOutput,
504        env: Env,
505        evm_opts: EvmOpts,
506    ) -> Result<MultiContractRunner> {
507        let root = &self.config.root;
508        let contracts = output
509            .artifact_ids()
510            .map(|(id, v)| (id.with_stripped_file_prefixes(root), v))
511            .collect();
512        let linker = Linker::new(root, contracts);
513
514        // Build revert decoder from ABIs of all artifacts.
515        let abis = linker
516            .contracts
517            .iter()
518            .filter_map(|(_, contract)| contract.abi.as_ref().map(|abi| abi.borrow()));
519        let revert_decoder = RevertDecoder::new().with_abis(abis);
520
521        let LinkOutput { libraries, libs_to_deploy } = linker.link_with_nonce_or_address(
522            Default::default(),
523            LIBRARY_DEPLOYER,
524            0,
525            linker.contracts.keys(),
526        )?;
527
528        let linked_contracts = linker.get_linked_artifacts_cow(&libraries)?;
529
530        // Create a mapping of name => (abi, deployment code, Vec<library deployment code>)
531        let mut deployable_contracts = DeployableContracts::default();
532
533        for (id, contract) in linked_contracts.iter() {
534            let Some(abi) = contract.abi.as_ref() else { continue };
535
536            // if it's a test, link it and add to deployable contracts
537            if abi.constructor.as_ref().map(|c| c.inputs.is_empty()).unwrap_or(true)
538                && abi.functions().any(|func| func.name.is_any_test())
539            {
540                linker.ensure_linked(contract, id)?;
541
542                let Some(bytecode) =
543                    contract.get_bytecode_bytes().map(|b| b.into_owned()).filter(|b| !b.is_empty())
544                else {
545                    continue;
546                };
547
548                deployable_contracts
549                    .insert(id.clone(), TestContract { abi: abi.clone().into_owned(), bytecode });
550            }
551        }
552
553        // Create known contracts from linked contracts and storage layout information (if any).
554        let known_contracts =
555            ContractsByArtifactBuilder::new(linked_contracts).with_output(output, root).build();
556
557        // Initialize and configure the solar compiler.
558        let mut analysis = solar::sema::Compiler::new(
559            solar::interface::Session::builder().with_stderr_emitter().build(),
560        );
561        let dcx = analysis.dcx_mut();
562        dcx.set_emitter(Box::new(
563            solar::interface::diagnostics::HumanEmitter::stderr(Default::default())
564                .source_map(Some(dcx.source_map().unwrap())),
565        ));
566        dcx.set_flags_mut(|f| f.track_diagnostics = false);
567
568        // Populate solar's global context by parsing and lowering the sources.
569        let files: Vec<_> =
570            output.output().sources.as_ref().keys().map(|path| path.to_path_buf()).collect();
571
572        analysis.enter_mut(|compiler| -> Result<()> {
573            let mut pcx = compiler.parse();
574            configure_pcx_from_compile_output(
575                &mut pcx,
576                &self.config,
577                output,
578                if files.is_empty() { None } else { Some(&files) },
579            )?;
580            pcx.parse();
581            let _ = compiler.lower_asts();
582            Ok(())
583        })?;
584
585        let analysis = Arc::new(analysis);
586        let fuzz_literals = LiteralsDictionary::new(
587            Some(analysis.clone()),
588            Some(self.config.project_paths()),
589            self.config.fuzz.dictionary.max_fuzz_dictionary_literals,
590        );
591
592        Ok(MultiContractRunner {
593            contracts: deployable_contracts,
594            revert_decoder,
595            known_contracts,
596            libs_to_deploy,
597            libraries,
598            analysis,
599            fuzz_literals,
600
601            tcfg: TestRunnerConfig {
602                evm_opts,
603                env,
604                spec_id: self.evm_spec.unwrap_or_else(|| self.config.evm_spec_id()),
605                sender: self.sender.unwrap_or(self.config.sender),
606                line_coverage: self.line_coverage,
607                debug: self.debug,
608                decode_internal: self.decode_internal,
609                inline_config: Arc::new(InlineConfig::new_parsed(output, &self.config)?),
610                isolation: self.isolation,
611                networks: self.networks,
612                early_exit: EarlyExit::new(self.fail_fast || self.config.show_progress),
613                config: self.config,
614            },
615
616            fork: self.fork,
617        })
618    }
619}
620
621pub fn matches_artifact(filter: &dyn TestFilter, id: &ArtifactId, abi: &JsonAbi) -> bool {
622    matches_contract(filter, &id.source, &id.name, abi.functions())
623}
624
625pub(crate) fn matches_contract(
626    filter: &dyn TestFilter,
627    path: &Path,
628    contract_name: &str,
629    functions: impl IntoIterator<Item = impl std::borrow::Borrow<Function>>,
630) -> bool {
631    (filter.matches_path(path) && filter.matches_contract(contract_name))
632        && functions.into_iter().any(|func| filter.matches_test_function(func.borrow()))
633}