#required_auth() test

5 messages · Page 1 of 1 (latest)

acoustic flicker
#

Hi Team, I have some code looks like:

#[test]
#[should_panic(expected = "HostError: Error(Auth, InvalidAction)")] // Unauthorized
fn transfer_ownership() {
    client
        .mock_auths(&[MockAuth {
            address: &user,
            invoke: &MockAuthInvoke {
                contract: &contract_id,
                fn_name: "transfer_ownership",
                args: (&new_owner,).into_val(&env),
                sub_invokes: &[],
            },
        }])
        .transfer_ownership(&new_owner);
}

Q1. Can I define the error string "HostError: Error(Auth, InvalidAction)" as a const, so that I can use it for all auth failure test? I tried something like the example below, but it doesn't allow me to use the variable name in the expected section.

const ERROR_STRING: &str = "HostError: Error(Auth, InvalidAction)";
#[should_panic(expected = ERROR_STRING)] 

Q2. Can I return a custom-defined error when require_auth() fails, such as Error::Unauthorized, to handle the auth failure more efficiently. If not, is there any future plans to do this?

burnt moth
#

U need to make an error enum for custom errors take a look at errors example contract

acoustic flicker
#

@burnt moth I already looked up the custom errors page, but my question is specifically about the Auth error, and question about how to make the expected = ERROR_STRING statement. Could you review my question again?

burnt moth
#
// Verify that the user indeed had to authorize a call of `increment` with
    // the expected arguments:
    assert_eq!(
        env.auths(),
        [(
            // Address for which auth is performed
            user_1.clone(),
            // Identifier 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)
        )]
    );```