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