Who call the functions in sway unit testing?

I am writing a contract’s unit test

#[test]
fn test_foo(){
    let caller = abi(Mycontract,CONTRACT_ID);
    caller.foo()
}

In function foo, I add a check as:

require(msg_sender().unwrap()==Idenfity::Address(Address::from(0x12345678...))));

so, who is the msg_sender? and how can I get it ?

1 Like

msg_sender is the caller of the function. If you are using Rust SDK for the testing, then you can set up test wallets to simulate the function caller.
Here is the basic example for the same

use fuels::{prelude::*, types::Identity};

// Load abi from json
abigen!(Contract(
    name = "MyContract",
    abi = "out/debug/my-contract-abi.json"
));

#[tokio::test]
async fn test_foo() {
    // Launch a local network and deploy the contract
    let mut wallets = launch_custom_provider_and_get_wallets(
        WalletsConfig::new(
            Some(1),             /* Single wallet */
            Some(1),             /* Single coin (UTXO) */
            Some(1_000_000_000), /* Amount per coin */
        ),
        None,
        None,
    )
    .await
    .unwrap();
    
    let wallet = wallets.pop().unwrap();

    // Deploy the contract
    let id = Contract::load_from(
        "./out/debug/my-contract.bin",
        LoadConfiguration::default(),
    )
    .unwrap()
    .deploy(&wallet, TxPolicies::default())
    .await
    .unwrap();

    let instance = MyContract::new(id.clone(), wallet.clone());

    // Call the foo function
    let result = instance.methods().foo().call().await.unwrap();

    // Assert that the msg_sender is the wallet address
    assert_eq!(Identity::Address(wallet.address().into()), result.value);
}

In this example, launch_custom_provider_and_get_wallets is used to set up a wallet and a local network. The contract is deployed through this wallet, which acts as the caller. When foo() is called, msg_sender() returns this wallet’s address.

you can refer to the docs here for more info.
Lmk if this what you are looking for.

1 Like

Thank you for your response. I want to write unit tests in a Sway contract. The tests are written in Sway and run using the forc test command.

I wanna figure out who calls the function when I run the unit test with froc test.

1 Like