Skip to content

Commit

Permalink
Added a new "assert_matches" utility macro that can be used to replace
Browse files Browse the repository at this point in the history
`assert!(matches!())`
  • Loading branch information
syan095 committed Feb 19, 2025
1 parent be61eef commit ba0e123
Show file tree
Hide file tree
Showing 27 changed files with 220 additions and 174 deletions.
2 changes: 2 additions & 0 deletions Cargo.lock

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

6 changes: 3 additions & 3 deletions engine/multisig/src/client/ceremony_manager/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ use crate::{
};
use anyhow::Result;
use cf_primitives::{AccountId, CeremonyId};
use cf_utilities::{task_scope::task_scope, threshold_from_share_count};
use cf_utilities::{assert_matches, task_scope::task_scope, threshold_from_share_count};
use client::MultisigMessage;
use futures::{Future, FutureExt};
use rand::SeedableRng;
Expand Down Expand Up @@ -453,8 +453,8 @@ async fn should_route_p2p_message() {

// Check that a broadcast was sent out. Meaning that the ceremony received the message and moved
// to stage 2.
assert!(matches!(
assert_matches!(
outgoing_p2p_receiver.try_recv().unwrap(),
OutgoingMultisigStageMessages::Broadcast(..)
))
);
}
5 changes: 3 additions & 2 deletions engine/multisig/src/client/ceremony_runner/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ use crate::{
Rng,
};

use cf_utilities::assert_matches;
use rand::SeedableRng;
use sp_runtime::AccountId32;
use tokio::sync::mpsc;
Expand Down Expand Up @@ -169,7 +170,7 @@ async fn should_process_delayed_messages_after_finishing_a_stage() {
// Process a stage 1 message. This will cause the ceremony to progress to stage 2 and process
// the delayed message. The processing of the delayed message will cause the completion of stage
// 2 and therefore fail with BroadcastFailure because the data we used was invalid.
assert!(matches!(
assert_matches!(
ceremony_runner
.process_or_delay_message(sender_account_id.clone(), gen_signing_data_stage1(1))
.await,
Expand All @@ -180,7 +181,7 @@ async fn should_process_delayed_messages_after_finishing_a_stage() {
SigningStageName::VerifyCommitmentsBroadcast2
)
)))
));
);
}

// Note: Clippy seems to throw a false positive without this.
Expand Down
6 changes: 3 additions & 3 deletions engine/multisig/src/client/multisig_client_tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ use mockall::predicate;

use crate::client::key_store_api::MockKeyStoreAPI;
use cf_primitives::GENESIS_EPOCH;
use cf_utilities::{assert_err, assert_ok, testing::assert_future_can_complete};
use cf_utilities::{assert_err, assert_matches, assert_ok, testing::assert_future_can_complete};
use client::MultisigClient;

#[tokio::test]
Expand Down Expand Up @@ -47,10 +47,10 @@ async fn should_ignore_rts_for_unknown_key() {
// Check that the signing request fails immediately with an "unknown key" error
let (_, failure_reason) = assert_err!(assert_future_can_complete(signing_request_fut));
assert_eq!(failure_reason, SigningFailureReason::UnknownKey);
assert!(matches!(
assert_matches!(
assert_ok!(assert_future_can_complete(ceremony_request_receiver.recv())),
CeremonyRequest { ceremony_id: DEFAULT_SIGNING_CEREMONY_ID, details: None }
));
);
}

#[tokio::test]
Expand Down
5 changes: 3 additions & 2 deletions engine/src/common.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
use cf_utilities::assert_matches;
use std::ops::{Deref, DerefMut};

struct MutexStateAndPoisonFlag<T> {
Expand Down Expand Up @@ -93,10 +94,10 @@ pub struct Signaller<T> {
}
impl<T: Clone + Send + 'static> Signaller<T> {
pub fn signal(self, t: T) {
assert!(matches!(
assert_matches!(
self.sender.try_broadcast(t),
Ok(None) | Err(async_broadcast::TrySendError::Closed(_))
));
);
}
}

Expand Down
4 changes: 2 additions & 2 deletions engine/src/state_chain_observer/client/error_decoder.rs
Original file line number Diff line number Diff line change
Expand Up @@ -136,10 +136,10 @@ mod tests {
let dispatch_error = sp_runtime::DispatchError::decode(&mut &encoded_error[..]).unwrap();

// Message should be erased.
assert!(matches!(
cf_utilities::assert_matches!(
dispatch_error,
sp_runtime::DispatchError::Module(ModuleError { message: None, .. })
));
);

match ErrorDecoder::default().decode_dispatch_error(dispatch_error) {
super::DispatchError::KnownModuleError { pallet, name, error } => {
Expand Down
13 changes: 7 additions & 6 deletions foreign-chains/solana/sol-prim/src/tests/pda.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,20 +7,21 @@ mod failures {
pda::{Pda, PdaError},
Address, PdaAndBump,
};
use cf_utilities::assert_matches;

#[test]
fn seed_too_long() {
let public_key: Address =
"J4mK4RXAuizk5aMZw8Vz8W3y7mrCy6dcgniZ4qwZimZE".parse().expect("public key");
assert!(matches!(
assert_matches!(
Pda::from_address(public_key)
.expect("derive")
.chain_seed("01234567890123456789012345678912")
.expect("32 should be still okay")
.chain_seed("012345678901234567890123456789123")
.expect_err("33 should be too much"),
PdaError::SeedTooLarge
));
);
}

#[test]
Expand All @@ -31,13 +32,13 @@ mod failures {
.map(|i| [i])
.try_fold(Pda::from_address(public_key).expect("derive"), Pda::chain_seed)
.expect("15 should be okay");
assert!(matches!(
assert_matches!(
(1..=consts::SOLANA_PDA_MAX_SEEDS)
.map(|i| [i])
.try_fold(Pda::from_address(public_key).expect("derive"), Pda::chain_seed)
.expect_err("16 should be too many"),
PdaError::TooManySeeds
));
);
}

#[test]
Expand All @@ -46,10 +47,10 @@ mod failures {
"J4mK4RXAuizk5aMZw8Vz8W3y7mrCy6dcgniZ4qwZimZE".parse().expect("public key");
let PdaAndBump { address, .. } =
Pda::from_address(public_key).expect("derive").finish().expect("finish");
assert!(matches!(
assert_matches!(
Pda::from_address(address).expect_err("PDA can't be a valid point on a curve"),
PdaError::NotAValidPoint,
))
);
}
}

Expand Down
24 changes: 12 additions & 12 deletions state-chain/amm/src/limit_orders/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ use cf_amm_math::{

use super::*;

use cf_utilities::{assert_ok, assert_panics};
use cf_utilities::{assert_matches, assert_ok, assert_panics};
use rand::{Rng, SeedableRng};

type LiquidityProvider = cf_primitives::AccountId;
Expand Down Expand Up @@ -276,7 +276,7 @@ fn test_float() {
#[test]
fn fee_hundredth_pips() {
for bad in [u32::MAX, ONE_IN_HUNDREDTH_PIPS, (ONE_IN_HUNDREDTH_PIPS / 2) + 1] {
assert!(matches!(PoolState::new(bad), Err(NewError::InvalidFeeAmount)));
assert_matches!(PoolState::new(bad), Err(NewError::InvalidFeeAmount));
}

for good in [0, 1, ONE_IN_HUNDREDTH_PIPS / 2] {
Expand Down Expand Up @@ -390,14 +390,14 @@ fn mint() {

for bad in [MIN_TICK - 1, MAX_TICK + 1] {
let mut pool_state = PoolState::new(0).unwrap();
assert!(matches!(
assert_matches!(
pool_state.collect_and_mint::<SD>(
&LiquidityProvider::from([0; 32]),
bad,
1000.into()
),
Err(PositionError::InvalidTick)
));
);
}

for good in [MAX_FIXED_POOL_LIQUIDITY, MAX_FIXED_POOL_LIQUIDITY - 1, 1.into()] {
Expand All @@ -414,10 +414,10 @@ fn mint() {

for bad in [MAX_FIXED_POOL_LIQUIDITY + 1, MAX_FIXED_POOL_LIQUIDITY + 2] {
let mut pool_state = PoolState::new(0).unwrap();
assert!(matches!(
assert_matches!(
pool_state.collect_and_mint::<SD>(&LiquidityProvider::from([0; 32]), 0, bad),
Err(PositionError::Other(MintError::MaximumLiquidity))
));
);
}
}

Expand All @@ -430,33 +430,33 @@ fn burn() {
fn inner<SD: SwapDirection + limit_orders::SwapDirection + range_orders::SwapDirection>() {
{
let mut pool_state = PoolState::new(0).unwrap();
assert!(matches!(
assert_matches!(
pool_state.collect_and_burn::<SD>(
&LiquidityProvider::from([0; 32]),
MIN_TICK - 1,
1000.into()
),
Err(PositionError::InvalidTick)
));
assert!(matches!(
);
assert_matches!(
pool_state.collect_and_burn::<SD>(
&LiquidityProvider::from([0; 32]),
MAX_TICK + 1,
1000.into()
),
Err(PositionError::InvalidTick)
));
);
}
{
let mut pool_state = PoolState::new(0).unwrap();
assert!(matches!(
assert_matches!(
pool_state.collect_and_burn::<SD>(
&LiquidityProvider::from([0; 32]),
120,
1000.into()
),
Err(PositionError::NonExistent)
));
);
}
{
let mut pool_state = PoolState::new(0).unwrap();
Expand Down
Loading

0 comments on commit ba0e123

Please sign in to comment.