Skip to content

Commit

Permalink
add tests
Browse files Browse the repository at this point in the history
  • Loading branch information
Raymond committed Dec 2, 2019
1 parent e9fd781 commit 27a745e
Show file tree
Hide file tree
Showing 9 changed files with 265 additions and 10 deletions.
8 changes: 4 additions & 4 deletions node/executor/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ native_executor_instance!(
node_runtime::api::dispatch,
node_runtime::native_version
);

/*
#[cfg(test)]
mod tests {
use substrate_executor::error::Result;
Expand All @@ -54,10 +54,10 @@ mod tests {
use node_runtime::{
Header, Block, UncheckedExtrinsic, CheckedExtrinsic, Call, Runtime, Balances, BuildStorage,
System, TransactionPayment, Event, TransferFee, TransactionBaseFee, TransactionByteFee,
WeightFeeCoefficient, constants::currency::*,
WeightFeeCoefficient,
};
use node_runtime::impls::LinearWeightToFee;
use node_primitives::{Balance, Hash, BlockNumber};
use node_primitives::{Balance, Hash, BlockNumber, constants::currency::*};
use node_testing::keyring::*;
use wabt;
Expand Down Expand Up @@ -1232,4 +1232,4 @@ mod tests {
block_number += 1;
}
}
}
}*/
3 changes: 2 additions & 1 deletion node/modules/stafi-externalrpc/src/tezosrpc/tezos.rs
Original file line number Diff line number Diff line change
Expand Up @@ -191,7 +191,8 @@ impl ProvideInherentData for InherentDataProvider {
&INHERENT_IDENTIFIER
}

fn provide_inherent_data(&self, inherent_data: &mut InherentData) -> Result<(), inherents::Error> {
fn provide_inherent_data(&self, inherent_data: &mut InherentData) -> Result<(), inherents::Error> {
log::info!("{}", "in provide_inherent_data");
use std::time::SystemTime;
let mut now_millis:u64 = SystemTime::now().duration_since(SystemTime::UNIX_EPOCH).unwrap().as_millis() as u64;
let verify_in_batch = false;
Expand Down
5 changes: 5 additions & 0 deletions node/modules/stafi-offchain-worker/src/lib.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,8 @@
#![cfg_attr(not(feature = "std"), no_std)]

#[cfg(test)]
mod mock;
#[cfg(test)]
mod tests;

pub mod tezosworker;
121 changes: 121 additions & 0 deletions node/modules/stafi-offchain-worker/src/mock.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,121 @@
// Copyright 2019 Parity Technologies (UK) Ltd.
// This file is part of Substrate.

// Substrate is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.

// Substrate is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.

// You should have received a copy of the GNU General Public License
// along with Substrate. If not, see <http://www.gnu.org/licenses/>.

//! Test utilities
#![cfg(test)]
extern crate substrate_primitives as primitives;
extern crate sr_io as runtime_io;

use crate::tezosworker::{Module, Trait};
use sr_primitives::Perbill;
use sr_primitives::testing::{Header, UintAuthorityId, TestXt};
use sr_primitives::traits::{IdentityLookup, BlakeTwo256};
use primitives::H256;
use support::{impl_outer_origin, impl_outer_dispatch, parameter_types};
use system;

use node_primitives::{Moment};
use node_primitives::constants::time::*;

impl_outer_origin!{
pub enum Origin for Runtime {}
}

impl_outer_dispatch! {
pub enum Call for Runtime where origin: Origin {
tezosworker::TezosWorker,
}
}

type DummyValidatorId = u64;

/// An extrinsic type used for tests.
pub type Extrinsic = TestXt<Call, ()>;
type SubmitTransaction = system::offchain::TransactionSubmitter<(), Call, Extrinsic>;

#[derive(Clone, PartialEq, Eq, Debug)]
pub struct Runtime;

parameter_types! {
pub const BlockHashCount: u64 = 250;
pub const MaximumBlockWeight: u32 = 1024;
pub const MaximumBlockLength: u32 = 2 * 1024;
pub const AvailableBlockRatio: Perbill = Perbill::one();
pub const MinimumPeriod: u64 = 1;
}

impl system::Trait for Runtime {
type Origin = Origin;
type Index = u64;
type BlockNumber = u64;
type Call = Call;
type Hash = H256;
type Hashing = BlakeTwo256;
type AccountId = u64;
type Lookup = IdentityLookup<Self::AccountId>;
type Header = Header;
type Event = ();
type BlockHashCount = BlockHashCount;
type MaximumBlockWeight = MaximumBlockWeight;
type MaximumBlockLength = MaximumBlockLength;
type AvailableBlockRatio = AvailableBlockRatio;
type Version = ();
}

parameter_types! {
pub const EpochDuration: u64 = EPOCH_DURATION_IN_SLOTS;
pub const ExpectedBlockTime: Moment = MILLISECS_PER_BLOCK;
}

impl babe::Trait for Runtime {
type EpochDuration = EpochDuration;
type ExpectedBlockTime = ExpectedBlockTime;
type EpochChangeTrigger = babe::ExternalTrigger;
}

impl timestamp::Trait for Runtime {
type Moment = u64;
type OnTimestampSet = ();
type MinimumPeriod = MinimumPeriod;
}

impl stafi_staking_storage::Trait for Runtime {

}

impl Trait for Runtime {
type Event = ();
type Call = Call;
type SubmitTransaction = SubmitTransaction;
}

pub fn new_test_ext(authorities: Vec<DummyValidatorId>) -> runtime_io::TestExternalities {
let mut t = system::GenesisConfig::default().build_storage::<Runtime>().unwrap();

babe::GenesisConfig {
authorities: authorities.into_iter().map(|a| (UintAuthorityId(a).to_public_key(), 1)).collect(),
}.assimilate_storage::<Runtime>(&mut t).unwrap();

t.into()
}

/// TezosWorker module.
pub type TezosWorker = Module<Runtime>;
pub type System = system::Module<Runtime>;
pub type Timestamp = timestamp::Module<Runtime>;
pub type Babe = babe::Module<Runtime>;

79 changes: 79 additions & 0 deletions node/modules/stafi-offchain-worker/src/tests.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,79 @@
// Copyright 2019 Parity Technologies (UK) Ltd.
// This file is part of Substrate.

// Substrate is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.

// Substrate is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.

// You should have received a copy of the GNU General Public License
// along with Substrate. If not, see <http://www.gnu.org/licenses/>.

//! Tests for the tezos worker module.
#![cfg(test)]
extern crate substrate_primitives as primitives;

use super::*;
use crate::mock::*;
use primitives::offchain::{
OffchainExt,
TransactionPoolExt,
testing::{TestOffchainExt, TestTransactionPoolExt},
};

use node_primitives::VerifyStatus;
use tezosworker::tezos;

#[test]
fn test_offchain_local_storage() {
let mut ext = new_test_ext(vec![0, 1, 2, 3]);
let (offchain, _state) = TestOffchainExt::new();
let (pool, _state) = TestTransactionPoolExt::new();
ext.register_extension(OffchainExt::new(offchain));
ext.register_extension(TransactionPoolExt::new(pool));

ext.execute_with(|| {
let key = "my_key".as_bytes().to_vec();
let value = (15700 as u64).to_be_bytes().to_vec();
tezos::set_value(&key, &value);

assert_eq!(true, tezos::get_value(&key).is_some());
let val = tezos::get_value(&key).unwrap();
assert_eq!(true, tezos::vec8_to_u64(val) == 15700);

let key = "your_key".as_bytes().to_vec();
assert_eq!(true, tezos::get_value(&key).is_none());
});
}

#[test]
#[ignore]
fn test_offchain_request_tezos() {
let mut ext = new_test_ext(vec![0, 1, 2, 3]);
let (offchain, _state) = TestOffchainExt::new();
let (pool, _state) = TestTransactionPoolExt::new();
ext.register_extension(OffchainExt::new(offchain));
ext.register_extension(TransactionPoolExt::new(pool));

ext.execute_with(|| {
let host = "https://rpc.tezrpc.me".as_bytes().to_vec();
let blockhash = "BKsxzJMXPxxJWRZcsgWG8AAegXNp2uUuUmMr8gzQcoEiGnNeCA6".as_bytes().to_vec();
let txhash = "onv7i9LSacMXjhTdpgzmY4q6PxiZ18TZPq7KrRBRUVX7XJicSDi".as_bytes().to_vec();
let from = "tz1SYq214SCBy9naR6cvycQsYcUGpBqQAE8d".as_bytes().to_vec();
let to = "tz1S4MTpEV356QcuzkjQUdyZdAy36gPwPWXa".as_bytes().to_vec();
let amount = 710391;

let mut level = 0;
let result = tezos::request_tezos(host, blockhash, txhash, from, to, amount, &mut level);

assert_eq!(true, result == VerifyStatus::Confirmed);
assert_eq!(true, level == 642208);
});
}

19 changes: 16 additions & 3 deletions node/modules/stafi-offchain-worker/src/tezosworker.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@ extern crate sr_io as runtime_io;
use support::{decl_module, decl_storage, decl_event, ensure};
use rstd::prelude::*;
use rstd::vec::Vec;
//use rstd::result::Result;
use system::{ensure_signed, ensure_root, ensure_none};
use node_primitives::{OcVerifiedData, VerifyStatus, TxHashType, HostData, XtzStakeData, Balance, AuthIndex};
use sr_primitives::traits::{SaturatedConversion, StaticLookup};
Expand All @@ -19,7 +18,6 @@ use app_crypto::{RuntimeAppPublic};
use babe_primitives::AuthorityId;
use codec::{Encode};
use log::info;

pub mod tezos;

/// only for debug
Expand Down Expand Up @@ -560,4 +558,19 @@ decl_event!(
AddVerified(TxHashType, i8),
RemoveVerified(TxHashType),
}
);
);

#[cfg(test)]
mod test {
use crate::mock;
use sr_primitives::testing::UintAuthorityId;

#[test]
fn test_babe_initial_list() {
mock::new_test_ext(vec![0, 1, 2, 3]).execute_with(|| {
assert_eq!(mock::TezosWorker::get_babe_list().len(), 4);
assert_eq!(mock::TezosWorker::get_babe_list()[0], UintAuthorityId(0).to_public_key());
})
}
}

11 changes: 11 additions & 0 deletions node/modules/stafi-offchain-worker/src/tezosworker/tezos.rs
Original file line number Diff line number Diff line change
Expand Up @@ -256,4 +256,15 @@ pub fn vec8_to_u64(v: Vec<u8>) -> u64 {
a[i] = v[i];
}
u64::from_be_bytes(a)
}

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

#[test]
fn test_vec8_to_u64() {
let v = (123 as u64).to_be_bytes().to_vec();
assert_eq!(123, vec8_to_u64(v));
}
}
26 changes: 25 additions & 1 deletion node/primitives/src/rjson.rs
Original file line number Diff line number Diff line change
Expand Up @@ -599,4 +599,28 @@ pub fn find_object_by_key_and_value(o: &JsonValue, key:&str, value:&str) -> bool
}
None
}*/
}*/

mod test {
use super::*;

#[test]
fn test_rjson() {
let json_str = r#"{"time":{"updated":"Dec 2, 2019 00:36:00 UTC","updatedISO":"2019-12-02T00:36:00+00:00","updateduk":"Dec 2, 2019 at 00:36 GMT"},"disclaimer":"This data was produced from the CoinDesk Bitcoin Price Index (USD). Non-USD currency data converted using hourly conversion rate from openexchangerates.org","bpi":{"USD":{"code":"USD","rate":"7,409.7067","description":"United States Dollar","rate_float":7409.7067}}}"#;

let data_array: Vec<char> = json_str.chars().collect();
let mut index:usize = 0;
let o = parse::<JsonValue, JsonArray, JsonObject, JsonValue>(&*data_array, &mut index).unwrap_or(JsonValue::None);
assert_eq!(false, is_none(&o));

let usd = get_value_by_key_recursively(&o, "USD").unwrap();
assert_eq!(true, is_object(&usd));

let rate = get_value_by_key(&usd, "rate").unwrap();
assert_eq!(true, is_string(&rate));

let rate = get_string(&rate).unwrap();
let price = rate.replace(",","").parse::<f64>().unwrap_or(0.0) as u32;
assert_eq!(true, price == 7409);
}
}
3 changes: 2 additions & 1 deletion node/runtime/src/impls.rs
Original file line number Diff line number Diff line change
Expand Up @@ -117,7 +117,8 @@ mod tests {
use super::*;
use sr_primitives::assert_eq_error_rate;
use crate::{MaximumBlockWeight, AvailableBlockRatio, Runtime};
use crate::{constants::currency::*, TransactionPayment, TargetBlockFullness};
use crate::{TransactionPayment, TargetBlockFullness};
use node_primitives::constants::currency::*;
use support::weights::Weight;

fn max() -> Weight {
Expand Down

0 comments on commit 27a745e

Please sign in to comment.