Skip to content

Commit

Permalink
Merge pull request Joystream#17 from bedeho/test-reorg
Browse files Browse the repository at this point in the history
Improve tests
  • Loading branch information
mnaamani committed Jun 17, 2019
2 parents 53984ca + 5ffe83e commit 5ab4944
Show file tree
Hide file tree
Showing 3 changed files with 399 additions and 320 deletions.
325 changes: 5 additions & 320 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -216,6 +216,9 @@ use rstd::prelude::*;
use parity_codec_derive::{Decode, Encode};
use srml_support::{ decl_event, decl_module, decl_storage, ensure, dispatch, StorageValue, StorageMap};

mod mock;
mod tests;

/*
* MOVE ALL OF THESE OUT TO COMMON LATER
*/
Expand Down Expand Up @@ -303,8 +306,6 @@ const ERROR_POST_MODERATION_RATIONALE_TOO_LONG: &str = "Post moderation rational
use system::{ensure_signed};
use system;

use rstd::collections::btree_map::BTreeMap;

/// Represents a user in this forum.
#[derive(Debug, Copy, Clone)]
pub struct ForumUser<AccountId> {
Expand Down Expand Up @@ -915,7 +916,7 @@ decl_module! {
Self::ensure_is_forum_member(&who)?;

// Make sure there exists a mutable post with post id `post_id`
let mut post = Self::ensure_post_is_mutable(&post_id)?;
let post = Self::ensure_post_is_mutable(&post_id)?;

// Signer does not match creator of post with identifier postId
ensure!(post.author_id == who, ERROR_ACCOUNT_DOES_NOT_MATCH_POST_AUTHOR);
Expand Down Expand Up @@ -1279,320 +1280,4 @@ impl<T: Trait> Module<T> {
new_post
}

}

#[cfg(test)]
mod tests {
use super::*;

use primitives::{Blake2Hasher, H256};
use runtime_io::with_externalities;
use srml_support::{impl_outer_origin, assert_ok}; // assert, assert_eq
// The testing primitives are very useful for avoiding having to work with signatures
// or public keys. `u64` is used as the `AccountId` and no `Signature`s are requried.
use runtime_primitives::{
testing::{Digest, DigestItem, Header},
traits::{BlakeTwo256, IdentityLookup}, //OnFinalize, OnInitialize},
BuildStorage,
};

impl_outer_origin! {
pub enum Origin for Test {}
}

// For testing the module, we construct most of a mock runtime. This means
// first constructing a configuration type (`Test`) which `impl`s each of the
// configuration traits of modules we want to use.
#[derive(Clone, Eq, PartialEq)]
pub struct Test;
impl system::Trait for Test {
type Origin = Origin;
type Index = u64;
type BlockNumber = u64;
type Hash = H256;
type Hashing = BlakeTwo256;
type Digest = Digest;
type AccountId = u64;
type Lookup = IdentityLookup<Self::AccountId>;
type Header = Header;
type Event = ();
type Log = DigestItem;
}
impl balances::Trait for Test {
type Balance = u64;
type OnFreeBalanceZero = ();
type OnNewAccount = ();
type Event = ();
type TransactionPayment = ();
type TransferPayment = ();
type DustRemoval = ();
}
impl timestamp::Trait for Test {
type Moment = u64;
type OnTimestampSet = ();
}
impl Trait for Test {
type Event = ();
type MembershipRegistry = MockForumUserRegistry; //< <Test as system::Trait>::AccountId >;
}

type TestForumModule = Module<Test>;

// Data store for MockForumUserRegistry

static mut forum_user_store: Option<BTreeMap< <Test as system::Trait>::AccountId , ForumUser< <Test as system::Trait>::AccountId > > > = None;

/*
fn initialize_forum_user_store() {
//formUserStore
}
*/

// MockForumUserRegistry
pub struct MockForumUserRegistry { }

impl ForumUserRegistry< <Test as system::Trait>::AccountId > for MockForumUserRegistry {

fn get_forum_user(id: &<Test as system::Trait>::AccountId) -> Option<ForumUser< <Test as system::Trait>::AccountId >> {

let query_result;

unsafe {
query_result = forum_user_store.as_ref().unwrap().get(&id);
}

if let Some(forum_user) = query_result {
Some(forum_user.clone())
} else {
None
}

}

}

// This function basically just builds a genesis storage key/value store according to
// our desired mockup.

// refactor
/// - add each config as parameter, then
///

fn default_genesis_config() -> GenesisConfig<Test> {

GenesisConfig::<Test> {
category_by_id: vec![], // endowed_accounts.iter().cloned().map(|k|(k, 1 << 60)).collect(),
next_category_id: 0,
thread_by_id: vec![],
next_thread_id: 0,
post_by_id: vec![],
next_post_id: 0,

forum_sudo: 33,

category_title_constraint: InputValidationLengthConstraint{
min: 10,
max_min_diff: 140
},

category_description_constraint: InputValidationLengthConstraint{
min: 10,
max_min_diff: 140
},

thread_title_constraint: InputValidationLengthConstraint{
min: 3,
max_min_diff: 43
},

post_text_constraint: InputValidationLengthConstraint{
min: 1,
max_min_diff: 1001
},

thread_moderation_rationale_constraint: InputValidationLengthConstraint{
min: 100,
max_min_diff: 2000
},

post_moderation_rationale_constraint: InputValidationLengthConstraint{
min: 100,
max_min_diff: 2000
}


// JUST GIVING UP ON ALL THIS FOR NOW BECAUSE ITS TAKING TOO LONG

// Extra genesis fields
//initial_forum_sudo: Some(143)
}
}

// Wanted to have payload: a: &GenesisConfig<Test>
// but borrow checker made my life miserabl, so giving up for now.
fn build_test_externalities() -> runtime_io::TestExternalities<Blake2Hasher> {

let t = default_genesis_config()
.build_storage()
.unwrap()
.0;

t.into()
}

/*
* NB!: No test checks for even emission!!!!
*/

/*
* set_forum_sudo
* ==============================================================================
*
* Missing cases
*
* set_forum_bad_origin
*
*/

#[test]
fn set_forum_sudo_unset() {
with_externalities(&mut build_test_externalities(), || {

// Ensure that forum sudo is default
assert_eq!(TestForumModule::forum_sudo(), Some(33));

// Unset forum sudo
assert_ok!(TestForumModule::set_forum_sudo(None));

// Sudo no longer set
assert!(!<ForumSudo<Test>>::exists());

// event emitted?!

});
}

#[test]
fn set_forum_sudo_update() {
with_externalities(&mut build_test_externalities(), || {

// Ensure that forum sudo is default
assert_eq!(TestForumModule::forum_sudo(), Some(default_genesis_config().forum_sudo));

let new_forum_sudo_account_id = 780;

// Unset forum sudo
assert_ok!(TestForumModule::set_forum_sudo(Some(new_forum_sudo_account_id)));

// Sudo no longer set
//assert!(!<ForumSudo<Test>>::exists());
assert_eq!(<ForumSudo<Test>>::get(), Some(new_forum_sudo_account_id));

});
}

/*
* create_category
* ==============================================================================
*
* Missing cases
*
* create_category_bad_origin
* create_category_forum_sudo_not_set
* create_category_origin_not_forum_sudo
* create_category_title_too_short
* create_category_title_too_long
* create_category_description_too_short
* create_category_description_too_long
*/

// Here are a few testing utilities and fixtures, will reorganize
// later with more tests.

enum OriginType {
Signed(<Test as system::Trait>::AccountId),
//Inherent, <== did not find how to make such an origin yet
Root
}

struct CreateCategoryFixture {
origin: OriginType,
parent: Option<CategoryId>,
title: Vec<u8>,
description: Vec<u8>
}

impl CreateCategoryFixture {

fn call_module(&self) -> dispatch::Result {

TestForumModule::create_category(
match self.origin {
OriginType::Signed(account_id) => Origin::signed(account_id),
//OriginType::Inherent => Origin::inherent,
OriginType::Root => system::RawOrigin::Root.into() //Origin::root
},
self.parent,
self.title.clone(),
self.description.clone()
)
}
}

#[test]
fn create_category_successfully() {
with_externalities(&mut build_test_externalities(), || {

// Make some new catg
let f1 = CreateCategoryFixture {
origin: OriginType::Signed(default_genesis_config().forum_sudo),
parent: None,
title: "My new category".as_bytes().to_vec(),
description: "This is a great new category for the forum".as_bytes().to_vec()
};

// let f2 = ...
// let f3 = ...
// let f4 = ...

// Make module call
f1.call_module().is_ok();

// f2.call_module();
// f3.call_module();
// f4.call_module();

// assert state!

});
}

/*
* update_category
* ==============================================================================
*
* Missing cases
*
* create_category_bad_origin
* create_category_forum_sudo_not_set
* create_category_origin_not_forum_sudo
* create_category_immutable_ancestor_category
*/

/*
* create_thread
* ==============================================================================
*
* Missing cases
*
* create_thread_bad_origin
* create_thread_forum_sudo_not_set
* ...
*/




}
}
Loading

0 comments on commit 5ab4944

Please sign in to comment.