4

Imagine I have a on_initialize hook like this:

    impl<T: Config> Hooks<BlockNumberFor<T>> for Pallet<T> {
        fn on_initialize(n: T::BlockNumber) -> Weight {
            return T::DbWeight::get().writes(1);
        }
    }

I'd like a test that can verify the hook, something like this:

    #[test]
    fn valid_weights() {
        new_test_ext().execute_with(|| {
            assert_eq!(
                <MyPallet as OnInitialize<u64>>::on_initialize(1),
                <TestRuntime as sp_weights>::DbWeight::get().writes(2) //<-- sp_weight is unknown
            );
        })
    }
}

/!\ I use substrate branch polkadot-v0.9.22, where sp_weight is not available as a package, so I can't import it

the problem is... That I can't find a way to do it. I couldn't find a way to use something like Test::DbWeight::get().writes(1), the closest I could get was this:

    <<TestRuntime as frame_system::Config>::DbWeight>::get().reads(1)

but I get this error:

   type annotations needed
   cannot infer type for type parameter `T` declared on the trait `Get`

1 Answer 1

2

You are very close, but the sp_weights is not needed.
I think in your case the Rust compiler is just being annoying.
You can write it more explicit like this to help the type-interference understand what you want:

#[test]
fn valid_weights() {
    use frame_support::pallet_prelude::*;
    use frame_support::weights::RuntimeDbWeight;

    new_test_ext().execute_with(|| {
        let db_weights: RuntimeDbWeight = <TestRuntime as frame_system::Config>::DbWeight::get();

        assert_eq!(
            MyPallet::on_initialize(1),
            db_weights.writes(2)
        );
    })
}
1
  • 1
    I was so close omg, i was just searching in the wrong direction ! Thanks a lot for helping me out !
    – Nathan
    Sep 14, 2022 at 18:54

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.