Improve mock_impl_runtime_apis! (#7370)

* Improve `mock_impl_runtime_apis!`

This adds a new attribute for functions being implemented in the
`mock_impl_runtime_apis!` macro, the `advanced` attribute. When this
attribute is given the user gets access to the `at` parameter and is
able to return a `Result`, instead of letting the macro generate this
stuff.

* Use the `at_param_name` directly

* Prevent clashing of `params`
This commit is contained in:
Bastian Köcher
2020-10-22 21:09:13 +02:00
committed by GitHub
parent d847c9b019
commit 79be077774
9 changed files with 287 additions and 46 deletions
@@ -19,9 +19,8 @@ use sp_api::{
RuntimeApiInfo, decl_runtime_apis, impl_runtime_apis, mock_impl_runtime_apis,
ApiExt,
};
use sp_runtime::{traits::{GetNodeBlockType, Block as BlockT}, generic::BlockId};
use sp_core::NativeOrEncoded;
use substrate_test_runtime_client::runtime::Block;
use sp_blockchain::Result;
@@ -103,9 +102,20 @@ mock_impl_runtime_apis! {
unimplemented!()
}
fn same_name() {}
#[advanced]
fn same_name(_: &BlockId<Block>) -> std::result::Result<NativeOrEncoded<()>, String> {
Ok(().into())
}
fn wild_card(_: u32) {}
#[advanced]
fn wild_card(at: &BlockId<Block>, _: u32) -> std::result::Result<NativeOrEncoded<()>, String> {
if let BlockId::Number(1337) = at {
// yeah
Ok(().into())
} else {
Err("Ohh noooo".into())
}
}
}
impl ApiWithCustomVersion<Block> for MockApi {
@@ -180,3 +190,12 @@ fn mock_runtime_api_panics_on_calling_old_version() {
#[allow(deprecated)]
let _ = mock.same_name_before_version_2(&BlockId::Number(0));
}
#[test]
fn mock_runtime_api_works_with_advanced() {
let mock = MockApi { block: None };
Api::<Block>::same_name(&mock, &BlockId::Number(0)).unwrap();
mock.wild_card(&BlockId::Number(1337), 1).unwrap();
assert_eq!(String::from("Ohh noooo"), mock.wild_card(&BlockId::Number(1336), 1).unwrap_err());
}