Browse Source

Restore tests for the extrinsic execution model

- delete custom proposal types
- create test extrinsic
- change ProposalCode type
Shamil Gadelshin 5 years ago
parent
commit
39dafdfb86

+ 8 - 2
runtime-modules/proposals/codex/src/tests/mock.rs

@@ -7,7 +7,7 @@ pub use runtime_primitives::{
     testing::{Digest, DigestItem, Header, UintAuthorityId},
     traits::{BlakeTwo256, Convert, IdentityLookup, OnFinalize},
     weights::Weight,
-    BuildStorage, Perbill,
+    BuildStorage, DispatchError, Perbill,
 };
 
 use proposal_engine::VotersParameters;
@@ -93,7 +93,6 @@ impl proposal_engine::Trait for Test {
     type ProposerOriginValidator = ();
     type VoterOriginValidator = ();
     type TotalVotersCounter = MockVotersParameters;
-    type ProposalCodeDecoder = crate::ProposalType;
     type ProposalId = u32;
     type StakeHandlerProvider = proposal_engine::DefaultStakeHandlerProvider;
     type CancellationFee = CancellationFee;
@@ -101,6 +100,13 @@ impl proposal_engine::Trait for Test {
     type TitleMaxLength = TitleMaxLength;
     type DescriptionMaxLength = DescriptionMaxLength;
     type MaxActiveProposalLimit = MaxActiveProposalLimit;
+    type ProposalCode = crate::Call<Test>;
+}
+
+impl Default for crate::Call<Test> {
+    fn default() -> Self {
+        panic!("shouldn't call default for Call");
+    }
 }
 
 impl governance::council::Trait for Test {

+ 2 - 5
runtime-modules/proposals/engine/src/lib.rs

@@ -44,7 +44,6 @@ mod tests;
 use codec::Decode;
 use rstd::prelude::*;
 use sr_primitives::traits::Zero;
-use sr_primitives::DispatchError;
 use srml_support::traits::{Currency, Get};
 use srml_support::{
     decl_event, decl_module, decl_storage, dispatch, ensure, Parameter, StorageDoubleMap,
@@ -101,9 +100,7 @@ pub trait Trait:
     type MaxActiveProposalLimit: Get<u32>;
 
     /// Proposals executable code. Can be instantiated by external module Call enum members.
-    type ProposalCode: Parameter
-        + Dispatchable<Origin = Self::Origin, Error = DispatchError>
-        + Default;
+    type ProposalCode: Parameter + Dispatchable<Origin = Self::Origin> + Default;
 }
 
 decl_event!(
@@ -374,7 +371,7 @@ impl<T: Trait> Module<T> {
                 Ok(proposal_code) => {
                     if let Err(error) = proposal_code.dispatch(T::Origin::from(RawOrigin::Root)) {
                         ApprovedProposalStatus::failed_execution(
-                            error.message.unwrap_or("Dispatch error"),
+                            error.into().message.unwrap_or("Dispatch error"),
                         )
                     } else {
                         ApprovedProposalStatus::Executed

+ 1 - 1
runtime-modules/proposals/engine/src/tests/mock/balance_manager.rs

@@ -1,6 +1,6 @@
 #![cfg(test)]
 
-pub use runtime_primitives::traits::Zero;
+pub use sr_primitives::traits::Zero;
 use srml_support::traits::{Currency, Imbalance};
 
 use super::*;

+ 21 - 13
runtime-modules/proposals/engine/src/tests/mock/mod.rs

@@ -8,17 +8,17 @@
 
 #![cfg(test)]
 pub use primitives::{Blake2Hasher, H256};
-pub use runtime_primitives::{
+pub use sr_primitives::{
     testing::{Digest, DigestItem, Header, UintAuthorityId},
     traits::{BlakeTwo256, Convert, IdentityLookup, OnFinalize, Zero},
     weights::Weight,
-    BuildStorage, Perbill,
+    BuildStorage, DispatchError, Perbill,
 };
 use srml_support::{impl_outer_dispatch, impl_outer_event, impl_outer_origin, parameter_types};
 pub use system;
 
 mod balance_manager;
-mod proposals;
+pub(crate) mod proposals;
 mod stakes;
 
 use balance_manager::*;
@@ -33,12 +33,6 @@ impl_outer_origin! {
     pub enum Origin for Test {}
 }
 
-impl_outer_dispatch! {
-    pub enum Call for Test where origin: Origin {
-        proposals::ProposalsEngine,
-    }
-}
-
 mod engine {
     pub use crate::Event;
 }
@@ -51,6 +45,12 @@ mod council_mod {
     pub use governance::council::Event;
 }
 
+// impl_outer_dispatch! {
+//     pub enum Call for Test where origin: Origin {
+//         engine::ProposalsEngine,
+//     }
+// }
+
 impl_outer_event! {
     pub enum TestEvent for Test {
         balances<T>,
@@ -74,10 +74,10 @@ impl balances::Trait for Test {
     /// What to do if a new account is created.
     type OnNewAccount = ();
 
-    type Event = TestEvent;
+    type TransferPayment = ();
 
     type DustRemoval = ();
-    type TransferPayment = ();
+    type Event = TestEvent;
     type ExistentialDeposit = ExistentialDeposit;
     type TransferFee = TransferFee;
     type CreationFee = CreationFee;
@@ -92,6 +92,8 @@ impl governance::council::Trait for Test {
     type CouncilTermEnded = ();
 }
 
+impl proposals::Trait for Test {}
+
 impl stake::Trait for Test {
     type Currency = Balances;
     type StakePoolId = StakePoolId;
@@ -122,7 +124,6 @@ impl crate::Trait for Test {
     type ProposerOriginValidator = ();
     type VoterOriginValidator = ();
     type TotalVotersCounter = ();
-    type ProposalCodeDecoder = ProposalType;
     type ProposalId = u32;
     type StakeHandlerProvider = stakes::TestStakeHandlerProvider;
     type CancellationFee = CancellationFee;
@@ -130,6 +131,13 @@ impl crate::Trait for Test {
     type TitleMaxLength = TitleMaxLength;
     type DescriptionMaxLength = DescriptionMaxLength;
     type MaxActiveProposalLimit = MaxActiveProposalLimit;
+    type ProposalCode = proposals::Call<Test>;
+}
+
+impl Default for proposals::Call<Test> {
+    fn default() -> Self {
+        panic!("shouldn't call default for Call");
+    }
 }
 
 impl common::origin_validator::ActorOriginValidator<Origin, u64, u64> for () {
@@ -159,9 +167,9 @@ parameter_types! {
 
 impl system::Trait for Test {
     type Origin = Origin;
+    type Call = ();
     type Index = u64;
     type BlockNumber = u64;
-    type Call = ();
     type Hash = H256;
     type Hashing = BlakeTwo256;
     type AccountId = u64;

+ 15 - 79
runtime-modules/proposals/engine/src/tests/mock/proposals.rs

@@ -1,83 +1,19 @@
-use codec::{Decode, Encode};
-use num_enum::{IntoPrimitive, TryFromPrimitive};
-use rstd::convert::TryFrom;
-use rstd::prelude::*;
-
-use srml_support::dispatch;
-
-use crate::{ProposalCodeDecoder, ProposalExecutable};
-
-use super::*;
-
-/// Defines allowed proposals types. Integer value serves as proposal_type_id.
-#[derive(Debug, Eq, PartialEq, TryFromPrimitive, IntoPrimitive)]
-#[repr(u32)]
-pub enum ProposalType {
-    /// Dummy(Text) proposal type
-    Dummy = 1,
-
-    /// Testing proposal type for faults
-    Faulty = 10001,
-}
+//! Contains executable proposal extrinsic mocks
 
-impl ProposalType {
-    fn compose_executable(
-        &self,
-        proposal_data: Vec<u8>,
-    ) -> Result<Box<dyn ProposalExecutable>, &'static str> {
-        match self {
-            ProposalType::Dummy => DummyExecutable::decode(&mut &proposal_data[..])
-                .map_err(|err| err.what())
-                .map(|obj| Box::new(obj) as Box<dyn ProposalExecutable>),
-            ProposalType::Faulty => FaultyExecutable::decode(&mut &proposal_data[..])
-                .map_err(|err| err.what())
-                .map(|obj| Box::new(obj) as Box<dyn ProposalExecutable>),
+use rstd::prelude::*;
+use rstd::vec::Vec;
+use sr_primitives::DispatchError;
+use srml_support::decl_module;
+pub trait Trait: system::Trait {}
+
+decl_module! {
+    pub struct Module<T: Trait> for enum Call where origin: T::Origin {
+    	/// Working extrinsic test
+        pub fn dummy_proposal(_origin, _title: Vec<u8>, _description: Vec<u8>) {}
+
+		/// Broken extrinsic test
+        pub fn faulty_proposal(_origin, _title: Vec<u8>, _description: Vec<u8>,) {
+             Err("ExecutionFailed")?
         }
     }
 }
-
-impl ProposalCodeDecoder<Test> for ProposalType {
-    fn decode_proposal(
-        proposal_type: u32,
-        proposal_code: Vec<u8>,
-    ) -> Result<Box<dyn ProposalExecutable>, &'static str> {
-        Self::try_from(proposal_type)
-            .map_err(|_| "Unsupported proposal type")?
-            .compose_executable(proposal_code)
-    }
-}
-
-/// Testing proposal type
-#[derive(Encode, Decode, Clone, PartialEq, Eq, Debug, Default)]
-pub struct DummyExecutable {
-    pub title: Vec<u8>,
-    pub description: Vec<u8>,
-}
-
-impl DummyExecutable {
-    pub fn proposal_type(&self) -> u32 {
-        ProposalType::Dummy.into()
-    }
-}
-
-impl ProposalExecutable for DummyExecutable {
-    fn execute(&self) -> dispatch::Result {
-        Ok(())
-    }
-}
-
-/// Faulty proposal executable code wrapper. Used for failed proposal execution tests.
-#[derive(Encode, Decode, Clone, PartialEq, Eq, Debug, Default)]
-pub struct FaultyExecutable;
-impl ProposalExecutable for FaultyExecutable {
-    fn execute(&self) -> dispatch::Result {
-        Err("ExecutionFailed")
-    }
-}
-
-impl FaultyExecutable {
-    /// Converts faulty proposal type to proposal_type_id
-    pub fn proposal_type(&self) -> u32 {
-        ProposalType::Faulty.into()
-    }
-}

+ 16 - 23
runtime-modules/proposals/engine/src/tests/mod.rs

@@ -5,7 +5,7 @@ use mock::*;
 
 use codec::Encode;
 use rstd::rc::Rc;
-use runtime_primitives::traits::{OnFinalize, OnInitialize};
+use sr_primitives::traits::{OnFinalize, OnInitialize};
 use srml_support::{dispatch, StorageMap, StorageValue};
 use system::RawOrigin;
 use system::{EventRecord, Phase};
@@ -60,7 +60,6 @@ struct DummyProposalFixture {
     parameters: ProposalParameters<u64, u64>,
     origin: RawOrigin<u64>,
     proposer_id: u64,
-    proposal_type: u32,
     proposal_code: Vec<u8>,
     title: Vec<u8>,
     description: Vec<u8>,
@@ -69,10 +68,12 @@ struct DummyProposalFixture {
 
 impl Default for DummyProposalFixture {
     fn default() -> Self {
-        let dummy_proposal = DummyExecutable {
-            title: b"title".to_vec(),
-            description: b"description".to_vec(),
-        };
+        let title = b"title".to_vec();
+        let description = b"description".to_vec();
+        let dummy_proposal = mock::proposals::Call::<Test>::dummy_proposal(
+            title.clone(),
+            description.clone(),
+        );
 
         DummyProposalFixture {
             parameters: ProposalParameters {
@@ -86,10 +87,9 @@ impl Default for DummyProposalFixture {
             },
             origin: RawOrigin::Signed(1),
             proposer_id: 1,
-            proposal_type: dummy_proposal.proposal_type(),
             proposal_code: dummy_proposal.encode(),
-            title: dummy_proposal.title,
-            description: dummy_proposal.description,
+            title,
+            description,
             stake_balance: None,
         }
     }
@@ -119,9 +119,8 @@ impl DummyProposalFixture {
         }
     }
 
-    fn with_proposal_type_and_code(self, proposal_type: u32, proposal_code: Vec<u8>) -> Self {
+    fn with_proposal_code(self, proposal_code: Vec<u8>) -> Self {
         DummyProposalFixture {
-            proposal_type,
             proposal_code,
             ..self
         }
@@ -135,7 +134,6 @@ impl DummyProposalFixture {
             self.title,
             self.description,
             self.stake_balance,
-            self.proposal_type,
             self.proposal_code,
         );
         assert_eq!(proposal_id_result, result);
@@ -340,7 +338,6 @@ fn proposal_execution_succeeds() {
         assert_eq!(
             proposal,
             Proposal {
-                proposal_type: 1,
                 parameters: parameters_fixture.params(),
                 proposer_id: 1,
                 created_at: 1,
@@ -366,11 +363,15 @@ fn proposal_execution_succeeds() {
 fn proposal_execution_failed() {
     initial_test_ext().execute_with(|| {
         let parameters_fixture = ProposalParametersFixture::default();
-        let faulty_proposal = FaultyExecutable;
+
+        let faulty_proposal = mock::proposals::Call::<Test>::faulty_proposal(
+            b"title".to_vec(),
+            b"description".to_vec(),
+        );
 
         let dummy_proposal = DummyProposalFixture::default()
             .with_parameters(parameters_fixture.params())
-            .with_proposal_type_and_code(faulty_proposal.proposal_type(), faulty_proposal.encode());
+            .with_proposal_code(faulty_proposal.encode());
 
         let proposal_id = dummy_proposal.create_proposal_and_assert(Ok(1)).unwrap();
 
@@ -387,7 +388,6 @@ fn proposal_execution_failed() {
         assert_eq!(
             proposal,
             Proposal {
-                proposal_type: faulty_proposal.proposal_type(),
                 parameters: parameters_fixture.params(),
                 proposer_id: 1,
                 created_at: 1,
@@ -579,7 +579,6 @@ fn cancel_proposal_succeeds() {
         assert_eq!(
             proposal,
             Proposal {
-                proposal_type: 1,
                 parameters: parameters_fixture.params(),
                 proposer_id: 1,
                 created_at: 1,
@@ -649,7 +648,6 @@ fn veto_proposal_succeeds() {
         assert_eq!(
             proposal,
             Proposal {
-                proposal_type: 1,
                 parameters: parameters_fixture.params(),
                 proposer_id: 1,
                 created_at: 1,
@@ -781,7 +779,6 @@ fn create_proposal_and_expire_it() {
         assert_eq!(
             proposal,
             Proposal {
-                proposal_type: 1,
                 parameters: parameters_fixture.params(),
                 proposer_id: 1,
                 created_at: 1,
@@ -823,7 +820,6 @@ fn proposal_execution_postponed_because_of_grace_period() {
         assert_eq!(
             proposal,
             Proposal {
-                proposal_type: 1,
                 parameters: parameters_fixture.params(),
                 proposer_id: 1,
                 created_at: 1,
@@ -866,7 +862,6 @@ fn proposal_execution_succeeds_after_the_grace_period() {
         let mut proposal = <crate::Proposals<Test>>::get(proposal_id);
 
         let mut expected_proposal = Proposal {
-            proposal_type: 1,
             parameters: parameters_fixture.params(),
             proposer_id: 1,
             created_at: 1,
@@ -970,7 +965,6 @@ fn create_dummy_proposal_succeeds_with_stake() {
         assert_eq!(
             proposal,
             Proposal {
-                proposal_type: 1,
                 parameters: parameters_fixture.params(),
                 proposer_id: 1,
                 created_at: 1,
@@ -1231,7 +1225,6 @@ fn finalize_proposal_using_stake_mocks_failed() {
             assert_eq!(
                 proposal,
                 Proposal {
-                    proposal_type: 1,
                     parameters: parameters_fixture.params(),
                     proposer_id: 1,
                     created_at: 1,