Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Important: If you're upgrading snforge to version 0.48.0 or later, please read the 0.48.0 Migration Guide.

Conditional Compilation

📝 Note For more detailed guide on Scarb conditional compilation, please refer to Scarb documentation

It is possible to build some contracts solely for testing purposes. This can be achieved by leveraging Scarb features. Configuration in Scarb.toml is done in the same manner as described in the Scarb documentation. Additionally, for utilizing features the snforge test command exposes the following flags, aligned with scarb flags: --features, --all-features and --no-default-features.

Contracts

Firstly, define a contract in the src directory with a #[cfg(feature: '<FEATURE_NAME>')] attribute:

pub mod contract;
// pub mod function;  // TODO: include this module (issue #2515)

mod dummy {} // trick `scarb fmt -c`

📝 Note To declare mock contracts in tests, these contracts should be defined within the package and not in the tests directory. This requirement is due to the way snforge collects contracts.

Next, create a test that uses the above contract:

use conditional_compilation::contract::{IMockContractDispatcher, IMockContractDispatcherTrait};
use snforge_std::{ContractClassTrait, DeclareResultTrait, declare};

#[test]
fn test_mock_contract() {
    let (contract_address, _) = declare("MockContract")
        .unwrap()
        .contract_class()
        .deploy(@array![])
        .unwrap();

    let dispatcher = IMockContractDispatcher { contract_address };
    let response = dispatcher.response();

    assert_eq!(response, 1);
}

The Scarb.toml file needs to be updated so it includes the following lines:

[features]
enable_for_tests = []

Then, to use the contract in tests snforge test must be provided with a flag defined above:

$ snforge test --features enable_for_tests

Also, we can specify which features are going to be enabled by default:

[features]
default = ["enable_for_tests"]
enable_for_tests = []

📝 Note If snforge test is run without the above feature enabled, it won't build any artifacts for the MockContract and all tests that use this contract will fail.

Functions

Features are not limited to conditionally compiling contracts and can be used with other parts of the code, like functions:

#[cfg(feature: 'enable_for_tests')]
fn foo() -> u32 {
    2
}

#[cfg(feature: 'enable_for_tests')]
#[cfg(test)]
mod tests {
    #[test]
    fn test_using_conditionally_compiled_function() {
        assert_eq!(foo(), 2);
    }
}