Skip to main content

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                    .logs(self.config.live_logs)
381                    .cheatcodes(cheats_config)
382                    .trace_mode(self.trace_mode())
383                    .line_coverage(self.line_coverage)
384                    .enable_isolation(self.isolation)
385                    .networks(self.networks)
386                    .create2_deployer(self.evm_opts.create2_deployer)
387                    .set_analysis(analysis)
388            })
389            .spec_id(self.spec_id)
390            .gas_limit(self.evm_opts.gas_limit())
391            .legacy_assertions(self.config.legacy_assertions)
392            .build(self.env.clone(), db)
393    }
394
395    fn trace_mode(&self) -> TraceMode {
396        TraceMode::default()
397            .with_debug(self.debug)
398            .with_decode_internal(self.decode_internal)
399            .with_verbosity(self.evm_opts.verbosity)
400            .with_state_changes(verbosity() > 4)
401    }
402}
403
404/// Builder used for instantiating the multi-contract runner
405#[derive(Clone)]
406#[must_use = "builders do nothing unless you call `build` on them"]
407pub struct MultiContractRunnerBuilder {
408    /// The address which will be used to deploy the initial contracts and send all
409    /// transactions
410    pub sender: Option<Address>,
411    /// The initial balance for each one of the deployed smart contracts
412    pub initial_balance: U256,
413    /// The EVM spec to use
414    pub evm_spec: Option<SpecId>,
415    /// The fork to use at launch
416    pub fork: Option<CreateFork>,
417    /// Project config.
418    pub config: Arc<Config>,
419    /// Whether or not to collect line coverage info
420    pub line_coverage: bool,
421    /// Whether or not to collect debug info
422    pub debug: bool,
423    /// Whether to enable steps tracking in the tracer.
424    pub decode_internal: InternalTraceMode,
425    /// Whether to enable call isolation
426    pub isolation: bool,
427    /// Networks with enabled features.
428    pub networks: NetworkConfigs,
429    /// Whether to exit early on test failure.
430    pub fail_fast: bool,
431}
432
433impl MultiContractRunnerBuilder {
434    pub fn new(config: Arc<Config>) -> Self {
435        Self {
436            config,
437            sender: Default::default(),
438            initial_balance: Default::default(),
439            evm_spec: Default::default(),
440            fork: Default::default(),
441            line_coverage: Default::default(),
442            debug: Default::default(),
443            isolation: Default::default(),
444            decode_internal: Default::default(),
445            networks: Default::default(),
446            fail_fast: false,
447        }
448    }
449
450    pub fn sender(mut self, sender: Address) -> Self {
451        self.sender = Some(sender);
452        self
453    }
454
455    pub fn initial_balance(mut self, initial_balance: U256) -> Self {
456        self.initial_balance = initial_balance;
457        self
458    }
459
460    pub fn evm_spec(mut self, spec: SpecId) -> Self {
461        self.evm_spec = Some(spec);
462        self
463    }
464
465    pub fn with_fork(mut self, fork: Option<CreateFork>) -> Self {
466        self.fork = fork;
467        self
468    }
469
470    pub fn set_coverage(mut self, enable: bool) -> Self {
471        self.line_coverage = enable;
472        self
473    }
474
475    pub fn set_debug(mut self, enable: bool) -> Self {
476        self.debug = enable;
477        self
478    }
479
480    pub fn set_decode_internal(mut self, mode: InternalTraceMode) -> Self {
481        self.decode_internal = mode;
482        self
483    }
484
485    pub fn fail_fast(mut self, fail_fast: bool) -> Self {
486        self.fail_fast = fail_fast;
487        self
488    }
489
490    pub fn enable_isolation(mut self, enable: bool) -> Self {
491        self.isolation = enable;
492        self
493    }
494
495    pub fn networks(mut self, networks: NetworkConfigs) -> Self {
496        self.networks = networks;
497        self
498    }
499
500    /// Given an EVM, proceeds to return a runner which is able to execute all tests
501    /// against that evm
502    pub fn build<C: Compiler<CompilerContract = Contract>>(
503        self,
504        output: &ProjectCompileOutput,
505        env: Env,
506        evm_opts: EvmOpts,
507    ) -> Result<MultiContractRunner> {
508        let root = &self.config.root;
509        let contracts = output
510            .artifact_ids()
511            .map(|(id, v)| (id.with_stripped_file_prefixes(root), v))
512            .collect();
513        let linker = Linker::new(root, contracts);
514
515        // Build revert decoder from ABIs of all artifacts.
516        let abis = linker
517            .contracts
518            .values()
519            .filter_map(|contract| contract.abi.as_ref().map(|abi| abi.borrow()));
520        let revert_decoder = RevertDecoder::new().with_abis(abis);
521
522        let LinkOutput { libraries, libs_to_deploy } = linker.link_with_nonce_or_address(
523            Default::default(),
524            LIBRARY_DEPLOYER,
525            0,
526            linker.contracts.keys(),
527        )?;
528
529        let linked_contracts = linker.get_linked_artifacts_cow(&libraries)?;
530
531        // Create a mapping of name => (abi, deployment code, Vec<library deployment code>)
532        let mut deployable_contracts = DeployableContracts::default();
533
534        for (id, contract) in linked_contracts.iter() {
535            let Some(abi) = contract.abi.as_ref() else { continue };
536
537            // if it's a test, link it and add to deployable contracts
538            if abi.constructor.as_ref().map(|c| c.inputs.is_empty()).unwrap_or(true)
539                && abi.functions().any(|func| func.name.is_any_test())
540            {
541                linker.ensure_linked(contract, id)?;
542
543                let Some(bytecode) =
544                    contract.get_bytecode_bytes().map(|b| b.into_owned()).filter(|b| !b.is_empty())
545                else {
546                    continue;
547                };
548
549                deployable_contracts
550                    .insert(id.clone(), TestContract { abi: abi.clone().into_owned(), bytecode });
551            }
552        }
553
554        // Create known contracts from linked contracts and storage layout information (if any).
555        let known_contracts =
556            ContractsByArtifactBuilder::new(linked_contracts).with_output(output, root).build();
557
558        // Initialize and configure the solar compiler.
559        let mut analysis = solar::sema::Compiler::new(
560            solar::interface::Session::builder().with_stderr_emitter().build(),
561        );
562        let dcx = analysis.dcx_mut();
563        dcx.set_emitter(Box::new(
564            solar::interface::diagnostics::HumanEmitter::stderr(Default::default())
565                .source_map(Some(dcx.source_map().unwrap())),
566        ));
567        dcx.set_flags_mut(|f| f.track_diagnostics = false);
568
569        // Populate solar's global context by parsing and lowering the sources.
570        let files: Vec<_> =
571            output.output().sources.as_ref().keys().map(|path| path.to_path_buf()).collect();
572
573        analysis.enter_mut(|compiler| -> Result<()> {
574            let mut pcx = compiler.parse();
575            configure_pcx_from_compile_output(
576                &mut pcx,
577                &self.config,
578                output,
579                if files.is_empty() { None } else { Some(&files) },
580            )?;
581            pcx.parse();
582            let _ = compiler.lower_asts();
583            Ok(())
584        })?;
585
586        let analysis = Arc::new(analysis);
587        let fuzz_literals = LiteralsDictionary::new(
588            Some(analysis.clone()),
589            Some(self.config.project_paths()),
590            self.config.fuzz.dictionary.max_fuzz_dictionary_literals,
591        );
592
593        Ok(MultiContractRunner {
594            contracts: deployable_contracts,
595            revert_decoder,
596            known_contracts,
597            libs_to_deploy,
598            libraries,
599            analysis,
600            fuzz_literals,
601
602            tcfg: TestRunnerConfig {
603                evm_opts,
604                env,
605                spec_id: self.evm_spec.unwrap_or_else(|| self.config.evm_spec_id()),
606                sender: self.sender.unwrap_or(self.config.sender),
607                line_coverage: self.line_coverage,
608                debug: self.debug,
609                decode_internal: self.decode_internal,
610                inline_config: Arc::new(InlineConfig::new_parsed(output, &self.config)?),
611                isolation: self.isolation,
612                networks: self.networks,
613                early_exit: EarlyExit::new(self.fail_fast),
614                config: self.config,
615            },
616
617            fork: self.fork,
618        })
619    }
620}
621
622pub fn matches_artifact(filter: &dyn TestFilter, id: &ArtifactId, abi: &JsonAbi) -> bool {
623    matches_contract(filter, &id.source, &id.name, abi.functions())
624}
625
626pub(crate) fn matches_contract(
627    filter: &dyn TestFilter,
628    path: &Path,
629    contract_name: &str,
630    functions: impl IntoIterator<Item = impl std::borrow::Borrow<Function>>,
631) -> bool {
632    (filter.matches_path(path) && filter.matches_contract(contract_name))
633        && functions.into_iter().any(|func| filter.matches_test_function(func.borrow()))
634}