Skip to content

Commit

Permalink
test(code): Add unit tests to consensus crate
Browse files Browse the repository at this point in the history
  • Loading branch information
romac committed Dec 12, 2024
1 parent 53a9d9e commit cf36a58
Show file tree
Hide file tree
Showing 8 changed files with 160 additions and 6 deletions.
2 changes: 2 additions & 0 deletions code/Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 2 additions & 0 deletions code/crates/consensus/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -29,3 +29,5 @@ workspace = true

[dev-dependencies]
malachite-test = { workspace = true }
rand = { workspace = true }
eyre = { workspace = true }
2 changes: 1 addition & 1 deletion code/crates/consensus/src/effect.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ use crate::ConsensusMsg;
///
/// [process]: crate::process
#[must_use]
#[derive_where(Debug)]
#[derive_where(Debug, PartialEq, Eq)]
pub enum Effect<Ctx>
where
Ctx: Context,
Expand Down
2 changes: 1 addition & 1 deletion code/crates/consensus/src/macros.rs
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@ macro_rules! process {
co_result = gen.resume_with(resume)
}
$crate::gen::CoResult::Complete(result) => {
return result.map_err(Into::into);
break result.map_err(Into::into);
}
}
}
Expand Down
4 changes: 4 additions & 0 deletions code/crates/consensus/src/state.rs
Original file line number Diff line number Diff line change
Expand Up @@ -71,6 +71,10 @@ where
self.driver.address()
}

pub fn validator_set(&self) -> &Ctx::ValidatorSet {
self.driver.validator_set()
}

pub fn get_proposer(&self, height: Ctx::Height, round: Round) -> &Ctx::Address {
self.ctx
.select_proposer(self.driver.validator_set(), height, round)
Expand Down
6 changes: 3 additions & 3 deletions code/crates/consensus/src/types.rs
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
use derive_where::derive_where;

use malachite_core_types::{
Context, Proposal, Round, Signature, SignedExtension, SignedProposal, SignedVote, Validity,
Vote,
pub use malachite_core_types::{
Context, Proposal, Round, Signature, SignedExtension, SignedProposal, SignedVote, Timeout,
Validity, Vote,
};

pub use malachite_peer::PeerId;
Expand Down
138 changes: 138 additions & 0 deletions code/crates/consensus/tests/basic.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,138 @@
use eyre::{eyre, Result};
use rand::rngs::StdRng;
use rand::SeedableRng;

use malachite_consensus::{process, Params, Round, ThresholdParams, Timeout, ValuePayload};
use malachite_metrics::Metrics;
use malachite_test::utils::validators::make_validator_set;
use malachite_test::{Address, Height, PrivateKey, TestContext};

type State = malachite_consensus::State<TestContext>;
type Resume = malachite_consensus::Resume<TestContext>;
type Effect = malachite_consensus::Effect<TestContext>;
type Input = malachite_consensus::Input<TestContext>;

fn setup(height: Height) -> (State, Metrics) {
let mut rng = StdRng::seed_from_u64(42);
let private_key = PrivateKey::generate(&mut rng);
let address = Address::from_public_key(&private_key.public_key());
let ctx = TestContext::new(private_key);
let validator_set = make_validator_set([1, 1, 1]);
let params = Params {
start_height: height,
initial_validator_set: validator_set.clone(),
address,
threshold_params: ThresholdParams::default(),
value_payload: ValuePayload::ProposalAndParts,
};

let state = State::new(ctx, params);
let metrics = Metrics::default();

(state, metrics)
}

#[test]
fn start_height() -> Result<()> {
let height = Height::new(1);
let (mut state, metrics) = setup(height);
let validator_set = state.validator_set().clone();

let mut expected = vec![
(Effect::CancelAllTimeouts, Resume::Continue),
(Effect::ResetTimeouts, Resume::Continue),
(Effect::CancelAllTimeouts, Resume::Continue),
(
Effect::StartRound(height, Round::new(0), *state.address()),
Resume::Continue,
),
(
Effect::ScheduleTimeout(Timeout::propose(Round::new(0))),
Resume::Continue,
),
]
.into_iter();

let mut handle_effect = |effect: Effect| -> Result<Resume> {
match expected.next() {
Some((expected, resume)) if expected == effect => Ok(resume),

Some((expected, _)) => Err(eyre!(
"unexpected effect: got {effect:?}, expected {expected:?}"
)),

None => Err(eyre!("unexpected effect: {effect:?}")),
}
};

process!(
input: Input::StartHeight(height, validator_set),
state: &mut state,
metrics: &metrics,
with: effect => handle_effect(effect)
)
}

#[test]
fn timeout_elapsed_propose() -> Result<()> {
let height = Height::new(1);
let (mut state, metrics) = setup(height);

let handle_effect =
|effect: Effect| -> Result<Resume> { Err(eyre!("unexpected effect: {effect:?}")) };

process!(
input: Input::TimeoutElapsed(Timeout::propose(Round::new(0))),
state: &mut state,
metrics: &metrics,
with: effect => handle_effect(effect)
)
}

#[test]
fn timeout_elapsed_prevote() -> Result<()> {
let height = Height::new(1);
let (mut state, metrics) = setup(height);

let handle_effect =
|effect: Effect| -> Result<Resume> { Err(eyre!("unexpected effect: {effect:?}")) };

process!(
input: Input::TimeoutElapsed(Timeout::prevote(Round::new(0))),
state: &mut state,
metrics: &metrics,
with: effect => handle_effect(effect)
)
}

#[test]
fn timeout_elapsed_precommit() -> Result<()> {
let height = Height::new(1);
let (mut state, metrics) = setup(height);

let handle_effect =
|effect: Effect| -> Result<Resume> { Err(eyre!("unexpected effect: {effect:?}")) };

process!(
input: Input::TimeoutElapsed(Timeout::precommit(Round::new(0))),
state: &mut state,
metrics: &metrics,
with: effect => handle_effect(effect)
)
}

// #[test]
// fn timeout_elapsed_commit() -> Result<()> {
// let height = Height::new(1);
// let (mut state, metrics) = setup(height);
//
// let handle_effect =
// |effect: Effect| -> Result<Resume> { Err(eyre!("unexpected effect: {effect:?}")) };
//
// process!(
// input: Input::TimeoutElapsed(Timeout::commit(Round::new(0))),
// state: &mut state,
// metrics: &metrics,
// with: effect => handle_effect(effect)
// )
// }
10 changes: 9 additions & 1 deletion code/crates/test/src/utils/validators.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ use rand::SeedableRng;

use malachite_core_types::VotingPower;

use crate::{PrivateKey, Validator};
use crate::{PrivateKey, Validator, ValidatorSet};

pub fn make_validators<const N: usize>(
voting_powers: [VotingPower; N],
Expand All @@ -20,3 +20,11 @@ pub fn make_validators<const N: usize>(

validators.try_into().expect("N validators")
}

pub fn make_validator_set<const N: usize>(voting_powers: [VotingPower; N]) -> ValidatorSet {
let validators = make_validators::<N>(voting_powers)
.into_iter()
.map(|(v, _)| v);

ValidatorSet::new(validators)
}

0 comments on commit cf36a58

Please sign in to comment.