2

I have an Event (ThingStored) that is deposited in a public function in my custom pallet.

#[derive(Encode, Decode, PartialEq, Clone, RuntimeDebugNoBound, TypeInfo, MaxEncodedLen)]
#[scale_info(skip_type_params(T))]
#[codec(mel_bound())]
pub struct Thing<T: Config> {
    pub id: u64,
    // pub creator: AccountOf<T>
}

#[pallet::event]
#[pallet::generate_deposit(pub(super) fn deposit_event)]
pub enum Event<T: Config> {
    ThingStored(Thing<T>, T::AccountId),
}

Thing contains data that is generated by the pallet (id). In my tests, I call the pallet function that stores a thing and emits the event if successful. How can I read the data of the event that was emited?

In this case, I will read the generated id from the event in order to make a subsequent call to the pallet's storage (by id).

#[test]
fn it_works_for_default_value() {
    new_test_ext().execute_with(|| {
        // Dispatch a signed extrinsic.
        assert_ok!(ThingsModule::create_thing(Origin::signed(1)));
        let emitted_stored_thing_event: Event<Test> = <frame_system::Pallet<Test>>::events().pop().expect("Expected at least one EventRecord to be found").event;
        // let stored_thing: Thing;
        // Read pallet storage and assert an expected result.
        assert_eq!(ThingModule::things(thing.id).unwrap().creator, 1);
    });
}
1

1 Answer 1

3

Here is a working example of a test using the pallet-template from the substrate-node-template:

#[test]
fn stackexchange_question() {
    new_test_ext().execute_with(|| {
        // To emit events, we need to be past block 0
        System::set_block_number(1);
        // Dispatch a signed extrinsic.
        assert_ok!(TemplateModule::do_something(Origin::signed(1), 42));
        System::assert_last_event(crate::Event::SomethingStored(42, 1).into());

        let event_record: frame_system::EventRecord<_, _> = System::events().pop().unwrap();
        let generic_event: crate::mock::Event = event_record.event;
        let pallet_event: crate::Event<Test> = generic_event.try_into().unwrap();

        let (something, who) = match pallet_event {
            crate::Event::SomethingStored(something, who) => (something, who),
            _ => panic!("unexpected error")
        };

        assert_eq!(who, 1);
        // Read pallet storage and assert an expected result.
        assert_eq!(TemplateModule::something(), Some(something));
    });
}

Basically, by the time it gets into storage, it is manipulated in a bunch of ways, and I show you how to do all those un-manipulations above.

1
  • This is fantastic. Thank you 🙏 Jun 21, 2022 at 20:39

Your Answer

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

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