Macro sp_api::mock_impl_runtime_apis
source · mock_impl_runtime_apis!() { /* proc-macro */ }
Expand description
Mocks given trait implementations as runtime apis.
Accepts similar syntax as impl_runtime_apis!
and generates simplified mock
implementations of the given runtime apis. The difference in syntax is that the trait does
not need to be referenced by a qualified path, methods accept the &self
parameter and the
error type can be specified as associated type. If no error type is specified String
is
used as error type.
Besides implementing the given traits, the Core
and ApiExt
are implemented
automatically.
§Example
struct MockApi {
balance: u64,
}
/// All runtime api mock implementations need to be done in one call of the macro!
sp_api::mock_impl_runtime_apis! {
impl Balance<Block> for MockApi {
/// Here we take the `&self` to access the instance.
fn get_balance(&self) -> u64 {
self.balance
}
fn set_balance(_bal: u64) {
// Store the balance
}
}
impl BlockBuilder<Block> for MockApi {
fn build_block() -> Block {
unimplemented!("Not Required in tests")
}
}
}
§advanced
attribute
This attribute can be placed above individual function in the mock implementation to
request more control over the function declaration. From the client side each runtime api
function is called with the at
parameter that is a Hash
.
When using the advanced
attribute, the macro expects that the first parameter of the
function is this at
parameter. Besides that the macro also doesn’t do the automatic
return value rewrite, which means that full return value must be specified. The full return
value is constructed like Result
<<ReturnValue>, Error>
while ReturnValue
being the
return value that is specified in the trait declaration.
§Example
struct MockApi {
balance: u64,
}
sp_api::mock_impl_runtime_apis! {
impl Balance<Block> for MockApi {
#[advanced]
fn get_balance(&self, at: <Block as BlockT>::Hash) -> Result<u64, sp_api::ApiError> {
println!("Being called at: {}", at);
Ok(self.balance.into())
}
#[advanced]
fn set_balance(at: <Block as BlockT>::Hash, val: u64) -> Result<(), sp_api::ApiError> {
println!("Being called at: {}", at);
Ok(().into())
}
}
}