Test authorized contract invocations
A contract's test functions can be used as a way to ensure the authorization is indeed carried out the way a developer intends. A simple example can be found in the auth example contract. (In the following code block, some code has been omitted for brevity.)
#[test]
fn test() {
let env = Env::default();
env.mock_all_auths();
assert_eq!(client.increment(&user_1, &5), 5);
// Verify that the user indeed had to authorize a call of `increment` with
// the expected arguments:
assert_eq!(
env.auths(),
std::vec![(
// Address for which authorization check is performed
user_1.clone(),
// Invocation tree that needs to be authorized
AuthorizedInvocation {
// Function that is authorized. Can be a contract function or
// a host function that requires authorization.
function: AuthorizedFunction::Contract((
// Address of the called contract
contract_id.clone(),
// Name of the called function
symbol_short!("increment"),
// Arguments used to call `increment` (converted to the
// env-managed vector via `into_val`)
(user_1.clone(), 5_u32).into_val(&env),
)),
// The contract doesn't call any other contracts that require
// authorization,
sub_invocations: std::vec![]
}
)]
)
}
Guides in this category:
📄️ Implement basic tests for a contract
Use the increment example contract to ensure a contract's functions behave as expected
📄️ Detecting Unexpected Changes with Test Snapshots
Use test snapshots to detect unexpected changes in contract behavior
📄️ Test authorized contract invocations
Use the auth example contract to ensure the authorization is carried out as expected