Browse Source

added tests

ignazio 3 years ago
parent
commit
b9e84548d8

+ 24 - 34
runtime-modules/content/src/tests/fixtures.rs

@@ -3,7 +3,6 @@ use super::mock::*;
 use crate::*;
 use frame_support::assert_ok;
 use frame_support::traits::Currency;
-use sp_runtime::traits::Hash;
 use sp_std::cmp::min;
 
 // fixtures
@@ -872,9 +871,7 @@ impl DeletePostFixture {
             video_id: VideoId::one(),
             actor: ContentActor::Member(DEFAULT_MEMBER_ID),
             params: PostDeletionParameters::<Test> {
-                witness: Some(<Test as frame_system::Trait>::Hashing::hash_of(
-                    &PostId::zero(),
-                )),
+                witness: Some(Hashing::hash_of(&PostId::zero())),
                 rationale: Some(b"rationale".to_vec()),
             },
         }
@@ -1148,22 +1145,18 @@ pub struct UpdateMaximumRewardFixture {
 }
 
 impl UpdateMaximumRewardFixture {
-    fn default() -> Self {
+    pub fn default() -> Self {
         Self {
             sender: LEAD_ACCOUNT_ID,
             new_amount: BalanceOf::<Test>::zero(),
         }
     }
 
-    fn with_sender(self, sender: AccountId) -> Self {
+    pub fn with_sender(self, sender: AccountId) -> Self {
         Self { sender, ..self }
     }
 
-    fn with_amount(self, new_amount: BalanceOf<Test>) -> Self {
-        Self { new_amount, ..self }
-    }
-
-    fn call_and_assert(&self, expected_result: DispatchResult) {
+    pub fn call_and_assert(&self, expected_result: DispatchResult) {
         let origin = Origin::signed(self.sender.clone());
         let max_reward_pre = Content::max_reward_allowed();
 
@@ -1190,28 +1183,24 @@ pub struct UpdateMinCashoutFixture {
 }
 
 impl UpdateMinCashoutFixture {
-    fn default() -> Self {
+    pub fn default() -> Self {
         Self {
             sender: LEAD_ACCOUNT_ID,
             new_amount: BalanceOf::<Test>::zero(),
         }
     }
 
-    fn with_sender(self, sender: AccountId) -> Self {
+    pub fn with_sender(self, sender: AccountId) -> Self {
         Self { sender, ..self }
     }
 
-    fn with_amount(self, new_amount: BalanceOf<Test>) -> Self {
-        Self { new_amount, ..self }
-    }
-
-    fn call_and_assert(&self, expected_result: DispatchResult) {
+    pub fn call_and_assert(&self, expected_result: DispatchResult) {
         let origin = Origin::signed(self.sender.clone());
         let min_cashout_pre = Content::min_cashout_allowed();
 
         let actual_result = Content::update_min_cashout_allowed(origin, self.new_amount.clone());
 
-        let max_reward_post = Content::min_cashout_allowed();
+        let min_cashout_post = Content::min_cashout_allowed();
 
         assert_eq!(actual_result, expected_result);
         if actual_result.is_ok() {
@@ -1228,33 +1217,26 @@ impl UpdateMinCashoutFixture {
 
 pub struct UpdateCommitmentValueFixture {
     sender: AccountId,
-    new_commitment: Hash,
+    new_commitment: HashValue<Test>,
 }
 
 impl UpdateCommitmentValueFixture {
-    fn default() -> Self {
+    pub fn default() -> Self {
         Self {
             sender: LEAD_ACCOUNT_ID,
-            new_commitment: Hashing::hash_of(&Zero::zero()),
+            new_commitment: Hashing::hash_of(&PullPayment::<Test>::default()),
         }
     }
 
-    fn with_sender(self, sender: AccountId) -> Self {
+    pub fn with_sender(self, sender: AccountId) -> Self {
         Self { sender, ..self }
     }
 
-    fn with_commit(self, new_commitment: Hash) -> Self {
-        Self {
-            new_commitment,
-            ..self
-        }
-    }
-
-    fn call_and_assert(&self, expected_result: DispatchResult) {
+    pub fn call_and_assert(&self, expected_result: DispatchResult) {
         let origin = Origin::signed(self.sender.clone());
         let commitment_pre = Content::commitment();
 
-        let actual_result = Content::update_commitment(origin, self.new_amount.clone());
+        let actual_result = Content::update_commitment(origin, self.new_commitment.clone());
 
         let commitment_post = Content::commitment();
 
@@ -1460,6 +1442,12 @@ pub fn create_default_curator_owned_channel_with_video_and_comment() {
         .call_and_assert(Ok(()));
 }
 
+#[derive(Debug)]
+struct IndexItem {
+    index: usize,
+    side: Side,
+}
+
 fn index_path_helper(len: usize, index: usize) -> Vec<IndexItem> {
     // used as a helper function to generate the correct sequence of indexes used to
     // construct the merkle path necessary for membership proof
@@ -1493,7 +1481,9 @@ fn index_path_helper(len: usize, index: usize) -> Vec<IndexItem> {
     }
     return path;
 }
-fn generate_merkle_root_helper<E: Encode>(collection: &[E]) -> Result<Vec<TestHash>, &'static str> {
+fn generate_merkle_root_helper<E: Encode>(
+    collection: &[E],
+) -> Result<Vec<HashValue<Test>>, &'static str> {
     // generates merkle root from the ordered sequence collection.
     // The resulting vector is structured as follows: elements in range
     // [0..collection.len()) will be the tree leaves (layer 0), elements in range
@@ -1540,7 +1530,7 @@ fn generate_merkle_root_helper<E: Encode>(collection: &[E]) -> Result<Vec<TestHa
 fn build_merkle_path_helper<E: Encode + Clone>(
     collection: &[E],
     idx: usize,
-    merkle_tree: &[TestHash],
+    merkle_tree: &[HashValue<Test>],
 ) -> Vec<LemmaItemTest> {
     // builds the actual merkle path with the hashes needed for the proof
     let index_path = index_path_helper(collection.len(), idx + 1);

+ 161 - 162
runtime-modules/content/src/tests/merkle.rs

@@ -5,197 +5,196 @@ use super::mock::*;
 use crate::*;
 
 #[test]
-fn update_maximum_reward_allowed() {
+fn unsuccessful_reward_update_by_non_lead_account() {
     with_default_mock_builder(|| {
         run_to_block(1);
-        let new_amount = BalanceOf::<Test>::from(2_000u32);
-        let origin = Origin::signed(LEAD_ACCOUNT_ID);
-        let _res = Content::update_max_reward_allowed(origin, new_amount);
-        assert_eq!(
-            System::events().last().unwrap().event,
-            MetaEvent::content(RawEvent::MaxRewardUpdated(new_amount))
-        );
+        UpdateMaximumRewardFixture::default()
+            .with_sender(UNAUTHORIZED_LEAD_ACCOUNT_ID)
+            .call_and_assert(Err(Error::<Test>::LeadAuthFailed.into()))
     })
 }
 
 #[test]
-fn update_minimum_cashout_allowed() {
+fn successful_reward_update_by_lead_account() {
     with_default_mock_builder(|| {
         run_to_block(1);
-        let new_amount = BalanceOf::<Test>::from(10u32);
-        let origin = Origin::signed(LEAD_ACCOUNT_ID);
-        let _res = Content::update_min_cashout_allowed(origin, new_amount);
-        assert_eq!(
-            System::events().last().unwrap().event,
-            MetaEvent::content(RawEvent::MinCashoutUpdated(new_amount))
-        );
+        UpdateMaximumRewardFixture::default().call_and_assert(Ok(()))
     })
 }
 
 #[test]
-fn update_commitment_value() {
+fn unsuccessful_cashout_update_by_non_lead_account() {
     with_default_mock_builder(|| {
         run_to_block(1);
-        let origin = Origin::signed(LEAD_ACCOUNT_ID);
-        let commit = TestHashing::hash(&2.encode());
-        let _res = Content::update_commitment(origin, commit);
-        assert_eq!(
-            System::events().last().unwrap().event,
-            MetaEvent::content(RawEvent::CommitmentUpdated(commit))
-        );
+        UpdateMinCashoutFixture::default()
+            .with_sender(UNAUTHORIZED_LEAD_ACCOUNT_ID)
+            .call_and_assert(Err(Error::<Test>::LeadAuthFailed.into()))
     })
 }
 
 #[test]
-fn update_commitment_with_same_value() {
+fn successful_cashout_update_by_lead_account() {
     with_default_mock_builder(|| {
-        let mut commit = TestHashing::hash(&1.encode());
-        let origin = Origin::signed(LEAD_ACCOUNT_ID);
-        let mut _res = Content::update_commitment(origin, commit);
         run_to_block(1);
-        commit = TestHashing::hash(&1.encode());
-        _res = Content::update_commitment(Origin::root(), commit);
-        assert_eq!(System::events().last(), None);
+        UpdateMinCashoutFixture::default().call_and_assert(Ok(()))
     })
 }
 
-fn setup_channels_scenario(
-    num_channels: u64,
-    payments_params: &Vec<(u64, BalanceOf<Test>)>,
-) -> (Vec<PullPayment<Test>>, Vec<TestHash>) {
-    // create payment elements collection
-    // create channels
-
-    for _i in 0..num_channels {
-        let _ = Content::create_channel(
-            Origin::signed(DEFAULT_MEMBER_ACCOUNT_ID),
-            ContentActor::Member(DEFAULT_MEMBER_ID),
-            ChannelCreationParameters::<Test> {
-                assets: None,
-                meta: None,
-                reward_account: Some(DEFAULT_MEMBER_ACCOUNT_ID),
-                collaborators: BTreeSet::new(),
-                moderator_set: BTreeSet::new(),
-            },
-        );
-    }
-
-    let pull_payments_collection: Vec<PullPayment<Test>> = payments_params
-        .iter()
-        .map(|&(c_id, amnt)| PullPayment::<Test> {
-            channel_id: ChannelId::from(c_id),
-            amount_earned: BalanceOf::<Test>::from(amnt),
-            reason: TestHashing::hash(&c_id.encode()),
-        })
-        .collect::<Vec<PullPayment<Test>>>();
-
-    // generate hash tree and get its root
-    let hash_tree = generate_merkle_root(&pull_payments_collection).unwrap();
-    let merkle_root = hash_tree.last().copied().unwrap();
-
-    // set the commitment
-    let origin = Origin::signed(LEAD_ACCOUNT_ID);
-    let mut _res = Content::update_commitment(origin, merkle_root);
-    (pull_payments_collection, hash_tree)
-}
-
-fn setup_candidate_proof(
-    pull_payments_collection: &Vec<PullPayment<Test>>,
-    hash_tree: &Vec<TestHash>,
-    test_params: &(u64, u64, usize),
-) -> TestProof<PullPayment<Test>> {
-    // construct test pull payment
-    let reward_element = PullPayment::<Test> {
-        channel_id: ChannelId::from(test_params.0),
-        amount_earned: BalanceOf::<Test>::from(test_params.1),
-        reason: TestHashing::hash(&test_params.0.encode()),
-    };
-
-    // proof setup
-    let proof_path = helper_build_merkle_path(pull_payments_collection, test_params.2, hash_tree);
-    let proof = TestProof {
-        leaf: reward_element,
-        path: proof_path,
-    };
-    proof
-}
-
 #[test]
-fn channel_reward_update_test() {
+fn unsuccessful_commitment_update_by_non_lead_account() {
     with_default_mock_builder(|| {
-        run_to_block(1); // in order to produce events
-
-        // setup test scenario: 2 channels and 3 (valid) pull payment requests
-        let num_channels = 2u64;
-        let payments_params = vec![
-            (0u64, BalanceOf::<Test>::from(1u64)),
-            (1u64, BalanceOf::<Test>::from(1u64)),
-            (1u64, BalanceOf::<Test>::from(2u64)),
-        ];
-
-        let scenario_out = setup_channels_scenario(num_channels, &payments_params);
-        let pull_payments_collection = &scenario_out.0;
-        let hash_tree = &scenario_out.1;
-
-        // suppose now channel 1 is trying to collect a payment of 2 JOYs
-        // last element is the index in the payments_params vector
-        let test_params = (1u64, 2u64, 2usize);
-        let candidate_proof =
-            setup_candidate_proof(&pull_payments_collection, &hash_tree, &test_params);
-
-        // attempt should succeed
-        let _res = Content::claim_channel_reward(
-            Origin::signed(DEFAULT_MEMBER_ACCOUNT_ID),
-            candidate_proof,
-            ContentActor::Member(DEFAULT_MEMBER_ID),
-        );
-
-        assert_eq!(
-            System::events().last().unwrap().event,
-            MetaEvent::content(RawEvent::ChannelRewardUpdated(
-                BalanceOf::<Test>::from(test_params.1),
-                ChannelId::from(test_params.0),
-            ))
-        );
+        run_to_block(1);
+        UpdateCommitmentValueFixture::default()
+            .with_sender(UNAUTHORIZED_LEAD_ACCOUNT_ID)
+            .call_and_assert(Err(Error::<Test>::LeadAuthFailed.into()))
     })
 }
 
 #[test]
-fn non_existing_channel_reward_update_test() {
+fn successful_commitment_update_by_lead_account() {
     with_default_mock_builder(|| {
-        run_to_block(1); // in order to produce events
-
-        // setup test scenario: 2 channels and 3 (valid) pull payment requests
-        let num_channels = 2u64;
-        let payments_params = vec![
-            (0u64, BalanceOf::<Test>::from(1u64)),
-            (1u64, BalanceOf::<Test>::from(1u64)),
-            (5u64, BalanceOf::<Test>::from(2u64)),
-        ];
-
-        let scenario_out = setup_channels_scenario(num_channels, &payments_params);
-        let pull_payments_collection = &scenario_out.0;
-        let hash_tree = &scenario_out.1;
-
-        // suppose now channel 1 is trying to collect a payment of 2 JOYs
-        // last element is the index in the payments_params vector
-        let test_params = (5u64, 2u64, 2usize);
-        let candidate_proof =
-            setup_candidate_proof(&pull_payments_collection, &hash_tree, &test_params);
-
-        // attempt should NOT succeed
-        let _res = Content::claim_channel_reward(
-            Origin::signed(DEFAULT_MEMBER_ACCOUNT_ID),
-            candidate_proof,
-            ContentActor::Member(DEFAULT_MEMBER_ID),
-        );
-
-        assert_ne!(
-            System::events().last().unwrap().event,
-            MetaEvent::content(RawEvent::ChannelRewardUpdated(
-                BalanceOf::<Test>::from(test_params.1),
-                ChannelId::from(test_params.0),
-            ))
-        );
+        run_to_block(1);
+        UpdateCommitmentValueFixture::default().call_and_assert(Ok(()))
     })
 }
+
+// fn setup_channels_scenario(
+//     num_channels: u64,
+//     payments_params: &Vec<(u64, BalanceOf<Test>)>,
+// ) -> (Vec<PullPayment<Test>>, Vec<TestHash>) {
+//     // create payment elements collection
+//     // create channels
+
+//     for _i in 0..num_channels {
+//         let _ = Content::create_channel(
+//             Origin::signed(DEFAULT_MEMBER_ACCOUNT_ID),
+//             ContentActor::Member(DEFAULT_MEMBER_ID),
+//             ChannelCreationParameters::<Test> {
+//                 assets: None,
+//                 meta: None,
+//                 reward_account: Some(DEFAULT_MEMBER_ACCOUNT_ID),
+//                 collaborators: BTreeSet::new(),
+//                 moderator_set: BTreeSet::new(),
+//             },
+//         );
+//     }
+
+//     let pull_payments_collection: Vec<PullPayment<Test>> = payments_params
+//         .iter()
+//         .map(|&(c_id, amnt)| PullPayment::<Test> {
+//             channel_id: ChannelId::from(c_id),
+//             amount_earned: BalanceOf::<Test>::from(amnt),
+//             reason: TestHashing::hash(&c_id.encode()),
+//         })
+//         .collect::<Vec<PullPayment<Test>>>();
+
+//     // generate hash tree and get its root
+//     let hash_tree = generate_merkle_root(&pull_payments_collection).unwrap();
+//     let merkle_root = hash_tree.last().copied().unwrap();
+
+//     // set the commitment
+//     let origin = Origin::signed(LEAD_ACCOUNT_ID);
+//     let mut _res = Content::update_commitment(origin, merkle_root);
+//     (pull_payments_collection, hash_tree)
+// }
+
+// fn setup_candidate_proof(
+//     pull_payments_collection: &Vec<PullPayment<Test>>,
+//     hash_tree: &Vec<TestHash>,
+//     test_params: &(u64, u64, usize),
+// ) -> TestProof<PullPayment<Test>> {
+//     // construct test pull payment
+//     let reward_element = PullPayment::<Test> {
+//         channel_id: ChannelId::from(test_params.0),
+//         amount_earned: BalanceOf::<Test>::from(test_params.1),
+//         reason: TestHashing::hash(&test_params.0.encode()),
+//     };
+
+//     // proof setup
+//     let proof_path = helper_build_merkle_path(pull_payments_collection, test_params.2, hash_tree);
+//     let proof = TestProof {
+//         leaf: reward_element,
+//         path: proof_path,
+//     };
+//     proof
+// }
+
+// #[test]
+// fn channel_reward_update_test() {
+//     with_default_mock_builder(|| {
+//         run_to_block(1); // in order to produce events
+
+//         // setup test scenario: 2 channels and 3 (valid) pull payment requests
+//         let num_channels = 2u64;
+//         let payments_params = vec![
+//             (0u64, BalanceOf::<Test>::from(1u64)),
+//             (1u64, BalanceOf::<Test>::from(1u64)),
+//             (1u64, BalanceOf::<Test>::from(2u64)),
+//         ];
+
+//         let scenario_out = setup_channels_scenario(num_channels, &payments_params);
+//         let pull_payments_collection = &scenario_out.0;
+//         let hash_tree = &scenario_out.1;
+
+//         // suppose now channel 1 is trying to collect a payment of 2 JOYs
+//         // last element is the index in the payments_params vector
+//         let test_params = (1u64, 2u64, 2usize);
+//         let candidate_proof =
+//             setup_candidate_proof(&pull_payments_collection, &hash_tree, &test_params);
+
+//         // attempt should succeed
+//         let _res = Content::claim_channel_reward(
+//             Origin::signed(DEFAULT_MEMBER_ACCOUNT_ID),
+//             candidate_proof,
+//             ContentActor::Member(DEFAULT_MEMBER_ID),
+//         );
+
+//         assert_eq!(
+//             System::events().last().unwrap().event,
+//             MetaEvent::content(RawEvent::ChannelRewardUpdated(
+//                 BalanceOf::<Test>::from(test_params.1),
+//                 ChannelId::from(test_params.0),
+//             ))
+//         );
+//     })
+// }
+
+// #[test]
+// fn non_existing_channel_reward_update_test() {
+//     with_default_mock_builder(|| {
+//         run_to_block(1); // in order to produce events
+
+//         // setup test scenario: 2 channels and 3 (valid) pull payment requests
+//         let num_channels = 2u64;
+//         let payments_params = vec![
+//             (0u64, BalanceOf::<Test>::from(1u64)),
+//             (1u64, BalanceOf::<Test>::from(1u64)),
+//             (5u64, BalanceOf::<Test>::from(2u64)),
+//         ];
+
+//         let scenario_out = setup_channels_scenario(num_channels, &payments_params);
+//         let pull_payments_collection = &scenario_out.0;
+//         let hash_tree = &scenario_out.1;
+
+//         // suppose now channel 1 is trying to collect a payment of 2 JOYs
+//         // last element is the index in the payments_params vector
+//         let test_params = (5u64, 2u64, 2usize);
+//         let candidate_proof =
+//             setup_candidate_proof(&pull_payments_collection, &hash_tree, &test_params);
+
+//         // attempt should NOT succeed
+//         let _res = Content::claim_channel_reward(
+//             Origin::signed(DEFAULT_MEMBER_ACCOUNT_ID),
+//             candidate_proof,
+//             ContentActor::Member(DEFAULT_MEMBER_ID),
+//         );
+
+//         assert_ne!(
+//             System::events().last().unwrap().event,
+//             MetaEvent::content(RawEvent::ChannelRewardUpdated(
+//                 BalanceOf::<Test>::from(test_params.1),
+//                 ChannelId::from(test_params.0),
+//             ))
+//         );
+//     })
+// }

+ 3 - 10
runtime-modules/content/src/tests/mock.rs

@@ -21,10 +21,9 @@ pub type Content = Module<Test>;
 pub type CollectiveFlip = randomness_collective_flip::Module<Test>;
 
 /// Type aliases
-type Hash = <Test as frame_system::Trait>::Hash;
-type Hashing = <Test as frame_system::Trait>::Hashing;
-type LemmaItemTest = LemmaItem<TestHash>;
-type TestProof<Value> = MerkleProof<TestHashing, Value>;
+pub type Hashing = <Test as frame_system::Trait>::Hashing;
+pub type LemmaItemTest = LemmaItem<HashValue<Test>>;
+pub type Proof<Value> = MerkleProof<Hashing, Value>;
 pub type AccountId = <Test as frame_system::Trait>::AccountId;
 pub type VideoId = <Test as Trait>::VideoId;
 pub type PostId = <Test as Trait>::PostId;
@@ -33,12 +32,6 @@ pub type CuratorGroupId = <Test as ContentActorAuthenticator>::CuratorGroupId;
 pub type MemberId = <Test as MembershipTypes>::MemberId;
 pub type ChannelId = <Test as StorageOwnership>::ChannelId;
 
-#[derive(Debug)]
-struct IndexItem {
-    index: usize,
-    side: Side,
-}
-
 /// Account Ids
 pub const DEFAULT_MEMBER_ACCOUNT_ID: u64 = 101;
 pub const DEFAULT_CURATOR_ACCOUNT_ID: u64 = 102;