diff --git a/Cargo.lock b/Cargo.lock index 889e5e15c6..b0fbfab7de 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -5066,6 +5066,7 @@ name = "solana-account-decoder" version = "1.17.0" dependencies = [ "Inflector", + "assert_matches", "base64 0.21.3", "bincode", "bs58", @@ -5377,6 +5378,7 @@ dependencies = [ name = "solana-bpf-loader-program" version = "1.17.0" dependencies = [ + "assert_matches", "bincode", "byteorder", "libsecp256k1", @@ -5476,6 +5478,7 @@ dependencies = [ name = "solana-clap-utils" version = "1.17.0" dependencies = [ + "assert_matches", "chrono", "clap 2.33.3", "rpassword", @@ -5492,6 +5495,7 @@ dependencies = [ name = "solana-clap-v3-utils" version = "1.17.0" dependencies = [ + "assert_matches", "chrono", "clap 3.2.23", "rpassword", @@ -5509,6 +5513,7 @@ dependencies = [ name = "solana-cli" version = "1.17.0" dependencies = [ + "assert_matches", "bincode", "bs58", "clap 2.33.3", @@ -6520,6 +6525,7 @@ dependencies = [ name = "solana-program-runtime" version = "1.17.0" dependencies = [ + "assert_matches", "base64 0.21.3", "bincode", "eager", @@ -6635,6 +6641,7 @@ dependencies = [ name = "solana-remote-wallet" version = "1.17.0" dependencies = [ + "assert_matches", "console", "dialoguer", "hidapi", @@ -7061,6 +7068,7 @@ dependencies = [ name = "solana-streamer" version = "1.17.0" dependencies = [ + "assert_matches", "async-channel", "bytes", "crossbeam-channel", @@ -7150,6 +7158,7 @@ dependencies = [ name = "solana-tokens" version = "1.17.0" dependencies = [ + "assert_matches", "bincode", "chrono", "clap 2.33.3", @@ -7391,6 +7400,7 @@ dependencies = [ name = "solana-vote-program" version = "1.17.0" dependencies = [ + "assert_matches", "bincode", "log", "num-derive", diff --git a/account-decoder/Cargo.toml b/account-decoder/Cargo.toml index 09083a4825..4e6fce49eb 100644 --- a/account-decoder/Cargo.toml +++ b/account-decoder/Cargo.toml @@ -27,5 +27,8 @@ spl-token-2022 = { workspace = true, features = ["no-entrypoint"] } thiserror = { workspace = true } zstd = { workspace = true } +[dev-dependencies] +assert_matches = { workspace = true } + [package.metadata.docs.rs] targets = ["x86_64-unknown-linux-gnu"] diff --git a/account-decoder/src/lib.rs b/account-decoder/src/lib.rs index 67317a4c41..cfba601a7a 100644 --- a/account-decoder/src/lib.rs +++ b/account-decoder/src/lib.rs @@ -214,6 +214,7 @@ fn slice_data(data: &[u8], data_slice_config: Option) -> &[u8 mod test { use { super::*, + assert_matches::assert_matches, solana_sdk::account::{Account, AccountSharedData}, }; @@ -257,10 +258,10 @@ mod test { None, None, ); - assert!(matches!( + assert_matches!( encoded_account.data, UiAccountData::Binary(_, UiAccountEncoding::Base64Zstd) - )); + ); let decoded_account = encoded_account.decode::().unwrap(); assert_eq!(decoded_account.data(), &vec![0; 1024]); diff --git a/accounts-db/src/in_mem_accounts_index.rs b/accounts-db/src/in_mem_accounts_index.rs index e847a97303..c4e486187b 100644 --- a/accounts-db/src/in_mem_accounts_index.rs +++ b/accounts-db/src/in_mem_accounts_index.rs @@ -1512,6 +1512,7 @@ mod tests { use { super::*, crate::accounts_index::{AccountsIndexConfig, IndexLimitMb, BINS_FOR_TESTING}, + assert_matches::assert_matches, itertools::Itertools, }; @@ -2072,12 +2073,12 @@ mod tests { // item is NOT in index at all, still return true from remove_if_slot_list_empty_entry // make sure not initially in index let entry = map.entry(unknown_key); - assert!(matches!(entry, Entry::Vacant(_))); + assert_matches!(entry, Entry::Vacant(_)); let entry = map.entry(unknown_key); assert!(test.remove_if_slot_list_empty_entry(entry)); // make sure still not in index let entry = map.entry(unknown_key); - assert!(matches!(entry, Entry::Vacant(_))); + assert_matches!(entry, Entry::Vacant(_)); } { @@ -2085,11 +2086,11 @@ mod tests { let val = Arc::new(AccountMapEntryInner::::default()); map.insert(key, val); let entry = map.entry(key); - assert!(matches!(entry, Entry::Occupied(_))); + assert_matches!(entry, Entry::Occupied(_)); // should have removed it since it had an empty slot list assert!(test.remove_if_slot_list_empty_entry(entry)); let entry = map.entry(key); - assert!(matches!(entry, Entry::Vacant(_))); + assert_matches!(entry, Entry::Vacant(_)); // return true - item is not in index at all now assert!(test.remove_if_slot_list_empty_entry(entry)); } @@ -2103,7 +2104,7 @@ mod tests { let entry = map.entry(key); assert!(!test.remove_if_slot_list_empty_entry(entry)); let entry = map.entry(key); - assert!(matches!(entry, Entry::Occupied(_))); + assert_matches!(entry, Entry::Occupied(_)); } } diff --git a/accounts-db/src/rent_collector.rs b/accounts-db/src/rent_collector.rs index c14a2a85a3..cea0a07c98 100644 --- a/accounts-db/src/rent_collector.rs +++ b/accounts-db/src/rent_collector.rs @@ -212,6 +212,7 @@ impl std::ops::AddAssign for CollectedInfo { mod tests { use { super::*, + assert_matches::assert_matches, solana_sdk::{account::Account, sysvar}, }; @@ -244,10 +245,10 @@ mod tests { let mut rent_collector = RentCollector::default(); let mut account = AccountSharedData::default(); - assert!(matches!( - rent_collector.calculate_rent_result(&Pubkey::default(), &account, None,), - RentResult::NoRentCollectionNow, - )); + assert_matches!( + rent_collector.calculate_rent_result(&Pubkey::default(), &account, None), + RentResult::NoRentCollectionNow + ); { let mut account_clone = account.clone(); assert_eq!( @@ -263,10 +264,10 @@ mod tests { } account.set_executable(true); - assert!(matches!( - rent_collector.calculate_rent_result(&Pubkey::default(), &account, None,), + assert_matches!( + rent_collector.calculate_rent_result(&Pubkey::default(), &account, None), RentResult::Exempt - )); + ); { let mut account_clone = account.clone(); let mut account_expected = account.clone(); @@ -286,10 +287,10 @@ mod tests { } account.set_executable(false); - assert!(matches!( - rent_collector.calculate_rent_result(&incinerator::id(), &account, None,), + assert_matches!( + rent_collector.calculate_rent_result(&incinerator::id(), &account, None), RentResult::Exempt - )); + ); { let mut account_clone = account.clone(); let mut account_expected = account.clone(); @@ -377,10 +378,10 @@ mod tests { // but, our rent_epoch is set in the future, so we can't know if we are exempt yet or not. // We don't calculate rent amount vs data if the rent_epoch is already in the future. account.set_rent_epoch(1_000_000); - assert!(matches!( - rent_collector.calculate_rent_result(&Pubkey::default(), &account, None,), - RentResult::NoRentCollectionNow, - )); + assert_matches!( + rent_collector.calculate_rent_result(&Pubkey::default(), &account, None), + RentResult::NoRentCollectionNow + ); { let mut account_clone = account.clone(); assert_eq!( @@ -398,14 +399,14 @@ mod tests { // filler accounts are exempt account.set_rent_epoch(1); account.set_lamports(10); - assert!(matches!( + assert_matches!( rent_collector.calculate_rent_result( &filler_account, &account, Some(&filler_account), ), - RentResult::Exempt, - )); + RentResult::Exempt + ); { let mut account_clone = account.clone(); let mut account_expected = account.clone(); diff --git a/clap-utils/Cargo.toml b/clap-utils/Cargo.toml index 7457ca6899..c51dc0f1d4 100644 --- a/clap-utils/Cargo.toml +++ b/clap-utils/Cargo.toml @@ -21,6 +21,7 @@ uriparse = { workspace = true } url = { workspace = true } [dev-dependencies] +assert_matches = { workspace = true } tempfile = { workspace = true } [lib] diff --git a/clap-utils/src/keypair.rs b/clap-utils/src/keypair.rs index 638f485207..ead51c9970 100644 --- a/clap-utils/src/keypair.rs +++ b/clap-utils/src/keypair.rs @@ -370,6 +370,7 @@ impl DefaultSigner { } } +#[derive(Debug)] pub(crate) struct SignerSource { pub kind: SignerSourceKind, pub derivation_path: Option, @@ -1120,6 +1121,7 @@ mod tests { use { super::*, crate::offline::OfflineArgs, + assert_matches::assert_matches, clap::{value_t_or_exit, App, Arg}, solana_remote_wallet::{locator::Manufacturer, remote_wallet::initialize_wallet_manager}, solana_sdk::{signer::keypair::write_keypair_file, system_instruction}, @@ -1168,31 +1170,31 @@ mod tests { #[test] fn test_parse_signer_source() { - assert!(matches!( + assert_matches!( parse_signer_source(STDOUT_OUTFILE_TOKEN).unwrap(), SignerSource { kind: SignerSourceKind::Stdin, derivation_path: None, legacy: false, } - )); + ); let stdin = "stdin:".to_string(); - assert!(matches!( + assert_matches!( parse_signer_source(stdin).unwrap(), SignerSource { kind: SignerSourceKind::Stdin, derivation_path: None, legacy: false, } - )); - assert!(matches!( + ); + assert_matches!( parse_signer_source(ASK_KEYWORD).unwrap(), SignerSource { kind: SignerSourceKind::Prompt, derivation_path: None, legacy: true, } - )); + ); let pubkey = Pubkey::new_unique(); assert!( matches!(parse_signer_source(pubkey.to_string()).unwrap(), SignerSource { @@ -1235,39 +1237,39 @@ mod tests { manufacturer: Manufacturer::Ledger, pubkey: None, }; - assert!(matches!(parse_signer_source(usb).unwrap(), SignerSource { + assert_matches!(parse_signer_source(usb).unwrap(), SignerSource { kind: SignerSourceKind::Usb(u), derivation_path: None, legacy: false, - } if u == expected_locator)); + } if u == expected_locator); let usb = "usb://ledger?key=0/0".to_string(); let expected_locator = RemoteWalletLocator { manufacturer: Manufacturer::Ledger, pubkey: None, }; let expected_derivation_path = Some(DerivationPath::new_bip44(Some(0), Some(0))); - assert!(matches!(parse_signer_source(usb).unwrap(), SignerSource { + assert_matches!(parse_signer_source(usb).unwrap(), SignerSource { kind: SignerSourceKind::Usb(u), derivation_path: d, legacy: false, - } if u == expected_locator && d == expected_derivation_path)); + } if u == expected_locator && d == expected_derivation_path); // Catchall into SignerSource::Filepath fails let junk = "sometextthatisnotapubkeyorfile".to_string(); assert!(Pubkey::from_str(&junk).is_err()); - assert!(matches!( + assert_matches!( parse_signer_source(&junk), Err(SignerSourceError::IoError(_)) - )); + ); let prompt = "prompt:".to_string(); - assert!(matches!( + assert_matches!( parse_signer_source(prompt).unwrap(), SignerSource { kind: SignerSourceKind::Prompt, derivation_path: None, legacy: false, } - )); + ); assert!( matches!(parse_signer_source(format!("file:{absolute_path_str}")).unwrap(), SignerSource { kind: SignerSourceKind::Filepath(p), diff --git a/clap-v3-utils/Cargo.toml b/clap-v3-utils/Cargo.toml index ad406b3cbe..85cc2092ec 100644 --- a/clap-v3-utils/Cargo.toml +++ b/clap-v3-utils/Cargo.toml @@ -22,6 +22,7 @@ uriparse = { workspace = true } url = { workspace = true } [dev-dependencies] +assert_matches = { workspace = true } tempfile = { workspace = true } [lib] diff --git a/clap-v3-utils/src/keypair.rs b/clap-v3-utils/src/keypair.rs index ab61db8fc5..c4e3c6739c 100644 --- a/clap-v3-utils/src/keypair.rs +++ b/clap-v3-utils/src/keypair.rs @@ -371,6 +371,7 @@ impl DefaultSigner { } } +#[derive(Debug)] pub(crate) struct SignerSource { pub kind: SignerSourceKind, pub derivation_path: Option, @@ -1266,6 +1267,7 @@ mod tests { use { super::*, crate::offline::OfflineArgs, + assert_matches::assert_matches, clap::{Arg, Command}, solana_remote_wallet::{locator::Manufacturer, remote_wallet::initialize_wallet_manager}, solana_sdk::{signer::keypair::write_keypair_file, system_instruction}, @@ -1314,31 +1316,31 @@ mod tests { #[test] fn test_parse_signer_source() { - assert!(matches!( + assert_matches!( parse_signer_source(STDOUT_OUTFILE_TOKEN).unwrap(), SignerSource { kind: SignerSourceKind::Stdin, derivation_path: None, legacy: false, } - )); + ); let stdin = "stdin:".to_string(); - assert!(matches!( + assert_matches!( parse_signer_source(stdin).unwrap(), SignerSource { kind: SignerSourceKind::Stdin, derivation_path: None, legacy: false, } - )); - assert!(matches!( + ); + assert_matches!( parse_signer_source(ASK_KEYWORD).unwrap(), SignerSource { kind: SignerSourceKind::Prompt, derivation_path: None, legacy: true, } - )); + ); let pubkey = Pubkey::new_unique(); assert!( matches!(parse_signer_source(pubkey.to_string()).unwrap(), SignerSource { @@ -1381,39 +1383,39 @@ mod tests { manufacturer: Manufacturer::Ledger, pubkey: None, }; - assert!(matches!(parse_signer_source(usb).unwrap(), SignerSource { + assert_matches!(parse_signer_source(usb).unwrap(), SignerSource { kind: SignerSourceKind::Usb(u), derivation_path: None, legacy: false, - } if u == expected_locator)); + } if u == expected_locator); let usb = "usb://ledger?key=0/0".to_string(); let expected_locator = RemoteWalletLocator { manufacturer: Manufacturer::Ledger, pubkey: None, }; let expected_derivation_path = Some(DerivationPath::new_bip44(Some(0), Some(0))); - assert!(matches!(parse_signer_source(usb).unwrap(), SignerSource { + assert_matches!(parse_signer_source(usb).unwrap(), SignerSource { kind: SignerSourceKind::Usb(u), derivation_path: d, legacy: false, - } if u == expected_locator && d == expected_derivation_path)); + } if u == expected_locator && d == expected_derivation_path); // Catchall into SignerSource::Filepath fails let junk = "sometextthatisnotapubkeyorfile".to_string(); assert!(Pubkey::from_str(&junk).is_err()); - assert!(matches!( + assert_matches!( parse_signer_source(&junk), Err(SignerSourceError::IoError(_)) - )); + ); let prompt = "prompt:".to_string(); - assert!(matches!( + assert_matches!( parse_signer_source(prompt).unwrap(), SignerSource { kind: SignerSourceKind::Prompt, derivation_path: None, legacy: false, } - )); + ); assert!( matches!(parse_signer_source(format!("file:{absolute_path_str}")).unwrap(), SignerSource { kind: SignerSourceKind::Filepath(p), diff --git a/cli/Cargo.toml b/cli/Cargo.toml index fe19b6000d..4c10112f40 100644 --- a/cli/Cargo.toml +++ b/cli/Cargo.toml @@ -55,6 +55,7 @@ thiserror = { workspace = true } tiny-bip39 = { workspace = true } [dev-dependencies] +assert_matches = { workspace = true } solana-streamer = { workspace = true } solana-test-validator = { workspace = true } tempfile = { workspace = true } diff --git a/cli/tests/stake.rs b/cli/tests/stake.rs index eb4bac8f95..6b886c86b3 100644 --- a/cli/tests/stake.rs +++ b/cli/tests/stake.rs @@ -1,6 +1,7 @@ #![allow(clippy::integer_arithmetic)] #![allow(clippy::redundant_closure)] use { + assert_matches::assert_matches, solana_cli::{ check_balance, cli::{process_command, request_and_confirm_airdrop, CliCommand, CliConfig}, @@ -2380,5 +2381,5 @@ fn test_stake_minimum_delegation() { }; let result = process_command(&config); - assert!(matches!(result, Ok(..))); + assert_matches!(result, Ok(..)); } diff --git a/core/src/banking_stage/consumer.rs b/core/src/banking_stage/consumer.rs index a0d1a77a11..acac38db43 100644 --- a/core/src/banking_stage/consumer.rs +++ b/core/src/banking_stage/consumer.rs @@ -1242,14 +1242,14 @@ mod tests { // account locking let commit_transactions_result = commit_transactions_result.unwrap(); assert_eq!(commit_transactions_result.len(), 2); - assert!(matches!( - commit_transactions_result.get(0).unwrap(), - CommitTransactionDetails::Committed { .. } - )); - assert!(matches!( - commit_transactions_result.get(1).unwrap(), - CommitTransactionDetails::NotCommitted - )); + assert_matches!( + commit_transactions_result.get(0), + Some(CommitTransactionDetails::Committed { .. }) + ); + assert_matches!( + commit_transactions_result.get(1), + Some(CommitTransactionDetails::NotCommitted) + ); assert_eq!(retryable_transaction_indexes, vec![1]); let expected_block_cost = if !apply_cost_tracker_during_replay_enabled { diff --git a/core/src/banking_stage/decision_maker.rs b/core/src/banking_stage/decision_maker.rs index f042a31fdc..edf67960d6 100644 --- a/core/src/banking_stage/decision_maker.rs +++ b/core/src/banking_stage/decision_maker.rs @@ -163,7 +163,7 @@ mod tests { { poh_recorder.write().unwrap().set_bank(bank.clone(), false); let decision = decision_maker.make_consume_or_forward_decision(); - assert!(matches!(decision, BufferedPacketsDecision::Consume(_))); + assert_matches!(decision, BufferedPacketsDecision::Consume(_)); } // Will be leader shortly - Hold @@ -204,7 +204,7 @@ mod tests { { poh_recorder.write().unwrap().reset(bank, None); let decision = decision_maker.make_consume_or_forward_decision(); - assert!(matches!(decision, BufferedPacketsDecision::Forward)); + assert_matches!(decision, BufferedPacketsDecision::Forward); } exit.store(true, Ordering::Relaxed); diff --git a/program-runtime/Cargo.toml b/program-runtime/Cargo.toml index 13e547f372..ed4b2a60aa 100644 --- a/program-runtime/Cargo.toml +++ b/program-runtime/Cargo.toml @@ -31,6 +31,7 @@ solana_rbpf = { workspace = true } thiserror = { workspace = true } [dev-dependencies] +assert_matches = { workspace = true } libsecp256k1 = { workspace = true } solana-logger = { workspace = true } solana-sdk = { workspace = true, features = ["dev-context-only-utils"] } diff --git a/program-runtime/src/loaded_programs.rs b/program-runtime/src/loaded_programs.rs index c47b2b5798..73b5b8660a 100644 --- a/program-runtime/src/loaded_programs.rs +++ b/program-runtime/src/loaded_programs.rs @@ -28,7 +28,7 @@ const MAX_LOADED_ENTRY_COUNT: usize = 256; pub const DELAY_VISIBILITY_SLOT_OFFSET: Slot = 1; /// Relationship between two fork IDs -#[derive(Copy, Clone, PartialEq)] +#[derive(Copy, Clone, Debug, PartialEq)] pub enum BlockRelation { /// The slot is on the same fork and is an ancestor of the other slot Ancestor, @@ -830,6 +830,7 @@ mod tests { BlockRelation, ForkGraph, LoadedProgram, LoadedProgramMatchCriteria, LoadedProgramType, LoadedPrograms, LoadedProgramsForTxBatch, WorkingSlot, DELAY_VISIBILITY_SLOT_OFFSET, }, + assert_matches::assert_matches, percentage::Percentage, solana_rbpf::vm::{BuiltinProgram, Config}, solana_sdk::{clock::Slot, pubkey::Pubkey}, @@ -1136,16 +1137,13 @@ mod tests { let env = Arc::new(BuiltinProgram::new_loader(Config::default())); let tombstone = LoadedProgram::new_tombstone(0, LoadedProgramType::FailedVerification(env.clone())); - assert!(matches!( - tombstone.program, - LoadedProgramType::FailedVerification(_) - )); + assert_matches!(tombstone.program, LoadedProgramType::FailedVerification(_)); assert!(tombstone.is_tombstone()); assert_eq!(tombstone.deployment_slot, 0); assert_eq!(tombstone.effective_slot, 0); let tombstone = LoadedProgram::new_tombstone(100, LoadedProgramType::Closed); - assert!(matches!(tombstone.program, LoadedProgramType::Closed)); + assert_matches!(tombstone.program, LoadedProgramType::Closed); assert!(tombstone.is_tombstone()); assert_eq!(tombstone.deployment_slot, 100); assert_eq!(tombstone.effective_slot, 100); @@ -1498,10 +1496,7 @@ mod tests { // The effective slot of program4 deployed in slot 15 is 19. So it should not be usable in slot 16. // A delay visibility tombstone should be returned here. let tombstone = found.find(&program4).expect("Failed to find the tombstone"); - assert!(matches!( - tombstone.program, - LoadedProgramType::DelayVisibility - )); + assert_matches!(tombstone.program, LoadedProgramType::DelayVisibility); assert_eq!(tombstone.deployment_slot, 15); assert!(missing.contains(&(program3, 1))); @@ -1564,10 +1559,7 @@ mod tests { assert!(match_slot(&found, &program1, 0, 11)); // program2 was updated at slot 11, but is not effective till slot 12. The result should contain a tombstone. let tombstone = found.find(&program2).expect("Failed to find the tombstone"); - assert!(matches!( - tombstone.program, - LoadedProgramType::DelayVisibility - )); + assert_matches!(tombstone.program, LoadedProgramType::DelayVisibility); assert_eq!(tombstone.deployment_slot, 11); assert!(match_slot(&found, &program4, 5, 11)); diff --git a/programs/bpf_loader/Cargo.toml b/programs/bpf_loader/Cargo.toml index 411d9f3654..f979b73688 100644 --- a/programs/bpf_loader/Cargo.toml +++ b/programs/bpf_loader/Cargo.toml @@ -24,6 +24,7 @@ solana_rbpf = { workspace = true } thiserror = { workspace = true } [dev-dependencies] +assert_matches = { workspace = true } memoffset = { workspace = true } solana-sdk = { workspace = true, features = ["dev-context-only-utils"] } diff --git a/programs/bpf_loader/src/lib.rs b/programs/bpf_loader/src/lib.rs index 57b77559f2..45430a3693 100644 --- a/programs/bpf_loader/src/lib.rs +++ b/programs/bpf_loader/src/lib.rs @@ -1724,6 +1724,7 @@ pub mod test_utils { mod tests { use { super::*, + assert_matches::assert_matches, rand::Rng, solana_program_runtime::{ invoke_context::mock_process_instruction, with_mock_invoke_context, @@ -4117,10 +4118,10 @@ mod tests { .programs_modified_by_tx .replenish(program_id, Arc::new(program)); - assert!(matches!( + assert_matches!( deploy_test_program(&mut invoke_context, program_id,), Ok(()) - )); + ); let updated_program = invoke_context .programs_modified_by_tx @@ -4158,10 +4159,10 @@ mod tests { .replenish(program_id, Arc::new(program)); let program_id2 = Pubkey::new_unique(); - assert!(matches!( + assert_matches!( deploy_test_program(&mut invoke_context, program_id2), Ok(()) - )); + ); let program2 = invoke_context .programs_modified_by_tx diff --git a/programs/bpf_loader/src/syscalls/cpi.rs b/programs/bpf_loader/src/syscalls/cpi.rs index e18052acc0..568be8b6c0 100644 --- a/programs/bpf_loader/src/syscalls/cpi.rs +++ b/programs/bpf_loader/src/syscalls/cpi.rs @@ -1638,6 +1638,7 @@ mod tests { use { super::*, crate::mock_create_vm, + assert_matches::assert_matches, solana_program_runtime::{ invoke_context::SerializedAccountMetadata, with_mock_invoke_context, }, @@ -1991,7 +1992,7 @@ mod tests { callee_account .set_data_length(original_data_len + MAX_PERMITTED_DATA_INCREASE + 1) .unwrap(); - assert!(matches!( + assert_matches!( update_caller_account( &invoke_context, &memory_mapping, @@ -2000,8 +2001,8 @@ mod tests { &mut callee_account, false, ), - Err(error) if error.downcast_ref::().unwrap() == &InstructionError::InvalidRealloc, - )); + Err(error) if error.downcast_ref::().unwrap() == &InstructionError::InvalidRealloc + ); // close the account callee_account.set_data_length(0).unwrap(); @@ -2174,7 +2175,7 @@ mod tests { callee_account .set_data_length(original_data_len + MAX_PERMITTED_DATA_INCREASE + 1) .unwrap(); - assert!(matches!( + assert_matches!( update_caller_account( &invoke_context, &memory_mapping, @@ -2184,7 +2185,7 @@ mod tests { false, ), Err(error) if error.downcast_ref::().unwrap() == &InstructionError::InvalidRealloc - )); + ); // close the account callee_account.set_data_length(0).unwrap(); @@ -2443,7 +2444,7 @@ mod tests { let callee_account = borrow_instruction_account!(invoke_context, 0); caller_account.serialized_data[0] = b'b'; - assert!(matches!( + assert_matches!( update_callee_account( &invoke_context, &memory_mapping, @@ -2453,7 +2454,7 @@ mod tests { false, ), Err(error) if error.downcast_ref::().unwrap() == &InstructionError::ExternalAccountDataModified - )); + ); // without direct mapping let mut data = b"foobarbaz".to_vec(); @@ -2461,7 +2462,7 @@ mod tests { caller_account.serialized_data = &mut data; let callee_account = borrow_instruction_account!(invoke_context, 0); - assert!(matches!( + assert_matches!( update_callee_account( &invoke_context, &memory_mapping, @@ -2471,7 +2472,7 @@ mod tests { false, ), Err(error) if error.downcast_ref::().unwrap() == &InstructionError::AccountDataSizeChanged - )); + ); // with direct mapping let mut data = b"baz".to_vec(); @@ -2479,7 +2480,7 @@ mod tests { caller_account.serialized_data = &mut data; let callee_account = borrow_instruction_account!(invoke_context, 0); - assert!(matches!( + assert_matches!( update_callee_account( &invoke_context, &memory_mapping, @@ -2489,7 +2490,7 @@ mod tests { true, ), Err(error) if error.downcast_ref::().unwrap() == &InstructionError::AccountDataSizeChanged - )); + ); } #[test] diff --git a/programs/bpf_loader/src/syscalls/mem_ops.rs b/programs/bpf_loader/src/syscalls/mem_ops.rs index d8e0b0a0c0..93d5b69cec 100644 --- a/programs/bpf_loader/src/syscalls/mem_ops.rs +++ b/programs/bpf_loader/src/syscalls/mem_ops.rs @@ -488,6 +488,7 @@ impl<'a> DoubleEndedIterator for MemoryChunkIterator<'a> { mod tests { use { super::*, + assert_matches::assert_matches, solana_rbpf::{ebpf::MM_PROGRAM_START, elf::SBPFVersion}, }; @@ -544,10 +545,10 @@ mod tests { let mut src_chunk_iter = MemoryChunkIterator::new(&memory_mapping, AccessType::Load, MM_PROGRAM_START - 1, 42) .unwrap(); - assert!(matches!( + assert_matches!( src_chunk_iter.next().unwrap().unwrap_err().downcast_ref().unwrap(), EbpfError::AccessViolation(0, AccessType::Load, addr, 42, "unknown") if *addr == MM_PROGRAM_START - 1 - )); + ); // check oob at the upper bound. Since the memory mapping isn't empty, // this always happens on the second next(). @@ -555,20 +556,20 @@ mod tests { MemoryChunkIterator::new(&memory_mapping, AccessType::Load, MM_PROGRAM_START, 43) .unwrap(); assert!(src_chunk_iter.next().unwrap().is_ok()); - assert!(matches!( + assert_matches!( src_chunk_iter.next().unwrap().unwrap_err().downcast_ref().unwrap(), EbpfError::AccessViolation(0, AccessType::Load, addr, 43, "program") if *addr == MM_PROGRAM_START - )); + ); // check oob at the upper bound on the first next_back() let mut src_chunk_iter = MemoryChunkIterator::new(&memory_mapping, AccessType::Load, MM_PROGRAM_START, 43) .unwrap() .rev(); - assert!(matches!( + assert_matches!( src_chunk_iter.next().unwrap().unwrap_err().downcast_ref().unwrap(), EbpfError::AccessViolation(0, AccessType::Load, addr, 43, "program") if *addr == MM_PROGRAM_START - )); + ); // check oob at the upper bound on the 2nd next_back() let mut src_chunk_iter = @@ -576,10 +577,10 @@ mod tests { .unwrap() .rev(); assert!(src_chunk_iter.next().unwrap().is_ok()); - assert!(matches!( + assert_matches!( src_chunk_iter.next().unwrap().unwrap_err().downcast_ref().unwrap(), EbpfError::AccessViolation(0, AccessType::Load, addr, 43, "unknown") if *addr == MM_PROGRAM_START - 1 - )); + ); } #[test] @@ -695,7 +696,7 @@ mod tests { .unwrap(); // dst is shorter than src - assert!(matches!( + assert_matches!( iter_memory_pair_chunks( AccessType::Load, MM_PROGRAM_START, @@ -707,10 +708,10 @@ mod tests { |_src, _dst, _len| Ok::<_, Error>(0), ).unwrap_err().downcast_ref().unwrap(), EbpfError::AccessViolation(0, AccessType::Load, addr, 8, "program") if *addr == MM_PROGRAM_START + 8 - )); + ); // src is shorter than dst - assert!(matches!( + assert_matches!( iter_memory_pair_chunks( AccessType::Load, MM_PROGRAM_START + 10, @@ -722,7 +723,7 @@ mod tests { |_src, _dst, _len| Ok::<_, Error>(0), ).unwrap_err().downcast_ref().unwrap(), EbpfError::AccessViolation(0, AccessType::Load, addr, 3, "program") if *addr == MM_PROGRAM_START + 10 - )); + ); } #[test] diff --git a/programs/bpf_loader/src/syscalls/mod.rs b/programs/bpf_loader/src/syscalls/mod.rs index 6bd9b2778d..5f3a420828 100644 --- a/programs/bpf_loader/src/syscalls/mod.rs +++ b/programs/bpf_loader/src/syscalls/mod.rs @@ -1887,6 +1887,7 @@ mod tests { use { super::*, crate::mock_create_vm, + assert_matches::assert_matches, core::slice, solana_program_runtime::{invoke_context::InvokeContext, with_mock_invoke_context}, solana_rbpf::{ @@ -2191,10 +2192,10 @@ mod tests { &mut memory_mapping, &mut result, ); - assert!(matches!( + assert_matches!( result, - ProgramResult::Err(error) if error.downcast_ref::().unwrap() == &InstructionError::ComputationalBudgetExceeded, - )); + ProgramResult::Err(error) if error.downcast_ref::().unwrap() == &InstructionError::ComputationalBudgetExceeded + ); invoke_context.mock_set_remaining(string.len() as u64); let mut result = ProgramResult::Ok(0); @@ -2273,10 +2274,10 @@ mod tests { &mut memory_mapping, &mut result, ); - assert!(matches!( + assert_matches!( result, - ProgramResult::Err(error) if error.downcast_ref::().unwrap() == &InstructionError::ComputationalBudgetExceeded, - )); + ProgramResult::Err(error) if error.downcast_ref::().unwrap() == &InstructionError::ComputationalBudgetExceeded + ); assert_eq!( invoke_context @@ -2358,10 +2359,10 @@ mod tests { &mut memory_mapping, &mut result, ); - assert!(matches!( + assert_matches!( result, - ProgramResult::Err(error) if error.downcast_ref::().unwrap() == &InstructionError::ComputationalBudgetExceeded, - )); + ProgramResult::Err(error) if error.downcast_ref::().unwrap() == &InstructionError::ComputationalBudgetExceeded + ); invoke_context.mock_set_remaining(cost); let mut result = ProgramResult::Ok(0); @@ -2623,10 +2624,10 @@ mod tests { &mut memory_mapping, &mut result, ); - assert!(matches!( + assert_matches!( result, - ProgramResult::Err(error) if error.downcast_ref::().unwrap() == &InstructionError::ComputationalBudgetExceeded, - )); + ProgramResult::Err(error) if error.downcast_ref::().unwrap() == &InstructionError::ComputationalBudgetExceeded + ); } #[test] @@ -2702,10 +2703,10 @@ mod tests { &mut memory_mapping, &mut result, ); - assert!(matches!( + assert_matches!( result, - ProgramResult::Err(error) if error.downcast_ref::().unwrap() == &InstructionError::ComputationalBudgetExceeded, - )); + ProgramResult::Err(error) if error.downcast_ref::().unwrap() == &InstructionError::ComputationalBudgetExceeded + ); } #[test] @@ -2781,10 +2782,10 @@ mod tests { &mut memory_mapping, &mut result, ); - assert!(matches!( + assert_matches!( result, - ProgramResult::Err(error) if error.downcast_ref::().unwrap() == &InstructionError::ComputationalBudgetExceeded, - )); + ProgramResult::Err(error) if error.downcast_ref::().unwrap() == &InstructionError::ComputationalBudgetExceeded + ); } #[test] @@ -2952,10 +2953,10 @@ mod tests { &mut memory_mapping, &mut result, ); - assert!(matches!( + assert_matches!( result, - ProgramResult::Err(error) if error.downcast_ref::().unwrap() == &InstructionError::ComputationalBudgetExceeded, - )); + ProgramResult::Err(error) if error.downcast_ref::().unwrap() == &InstructionError::ComputationalBudgetExceeded + ); } #[test] @@ -3125,10 +3126,10 @@ mod tests { &mut memory_mapping, &mut result, ); - assert!(matches!( + assert_matches!( result, - ProgramResult::Err(error) if error.downcast_ref::().unwrap() == &InstructionError::ComputationalBudgetExceeded, - )); + ProgramResult::Err(error) if error.downcast_ref::().unwrap() == &InstructionError::ComputationalBudgetExceeded + ); } #[test] @@ -3661,10 +3662,10 @@ mod tests { &mut memory_mapping, &mut result, ); - assert!(matches!( + assert_matches!( result, - ProgramResult::Err(error) if error.downcast_ref::().unwrap() == &SyscallError::CopyOverlapping, - )); + ProgramResult::Err(error) if error.downcast_ref::().unwrap() == &SyscallError::CopyOverlapping + ); } #[test] @@ -3814,10 +3815,10 @@ mod tests { &mut memory_mapping, &mut result, ); - assert!(matches!( + assert_matches!( result, - ProgramResult::Err(error) if error.downcast_ref::().unwrap() == &SyscallError::CopyOverlapping, - )); + ProgramResult::Err(error) if error.downcast_ref::().unwrap() == &SyscallError::CopyOverlapping + ); } #[test] @@ -3828,18 +3829,18 @@ mod tests { let address = bpf_loader_upgradeable::id(); let exceeded_seed = &[127; MAX_SEED_LEN + 1]; - assert!(matches!( + assert_matches!( create_program_address(&mut invoke_context, &[exceeded_seed], &address), - Result::Err(error) if error.downcast_ref::().unwrap() == &SyscallError::BadSeeds(PubkeyError::MaxSeedLengthExceeded), - )); - assert!(matches!( + Result::Err(error) if error.downcast_ref::().unwrap() == &SyscallError::BadSeeds(PubkeyError::MaxSeedLengthExceeded) + ); + assert_matches!( create_program_address( &mut invoke_context, &[b"short_seed", exceeded_seed], &address, ), - Result::Err(error) if error.downcast_ref::().unwrap() == &SyscallError::BadSeeds(PubkeyError::MaxSeedLengthExceeded), - )); + Result::Err(error) if error.downcast_ref::().unwrap() == &SyscallError::BadSeeds(PubkeyError::MaxSeedLengthExceeded) + ); let max_seed = &[0; MAX_SEED_LEN]; assert!(create_program_address(&mut invoke_context, &[max_seed], &address).is_ok()); let exceeded_seeds: &[&[u8]] = &[ @@ -3880,10 +3881,10 @@ mod tests { &[16], &[17], ]; - assert!(matches!( + assert_matches!( create_program_address(&mut invoke_context, max_seeds, &address), - Result::Err(error) if error.downcast_ref::().unwrap() == &SyscallError::BadSeeds(PubkeyError::MaxSeedLengthExceeded), - )); + Result::Err(error) if error.downcast_ref::().unwrap() == &SyscallError::BadSeeds(PubkeyError::MaxSeedLengthExceeded) + ); assert_eq!( create_program_address(&mut invoke_context, &[b"", &[1]], &address).unwrap(), "BwqrghZA2htAcqq8dzP1WDAhTXYTYWj7CHxF5j7TDBAe" @@ -3917,10 +3918,10 @@ mod tests { create_program_address(&mut invoke_context, &[b"Talking"], &address).unwrap(), ); invoke_context.mock_set_remaining(0); - assert!(matches!( + assert_matches!( create_program_address(&mut invoke_context, &[b"", &[1]], &address), - Result::Err(error) if error.downcast_ref::().unwrap() == &InstructionError::ComputationalBudgetExceeded, - )); + Result::Err(error) if error.downcast_ref::().unwrap() == &InstructionError::ComputationalBudgetExceeded + ); } #[test] @@ -3956,17 +3957,17 @@ mod tests { invoke_context.mock_set_remaining(cost * (max_tries - bump_seed as u64)); try_find_program_address(&mut invoke_context, seeds, &address).unwrap(); invoke_context.mock_set_remaining(cost * (max_tries - bump_seed as u64 - 1)); - assert!(matches!( + assert_matches!( try_find_program_address(&mut invoke_context, seeds, &address), - Result::Err(error) if error.downcast_ref::().unwrap() == &InstructionError::ComputationalBudgetExceeded, - )); + Result::Err(error) if error.downcast_ref::().unwrap() == &InstructionError::ComputationalBudgetExceeded + ); let exceeded_seed = &[127; MAX_SEED_LEN + 1]; invoke_context.mock_set_remaining(cost * (max_tries - 1)); - assert!(matches!( + assert_matches!( try_find_program_address(&mut invoke_context, &[exceeded_seed], &address), - Result::Err(error) if error.downcast_ref::().unwrap() == &SyscallError::BadSeeds(PubkeyError::MaxSeedLengthExceeded), - )); + Result::Err(error) if error.downcast_ref::().unwrap() == &SyscallError::BadSeeds(PubkeyError::MaxSeedLengthExceeded) + ); let exceeded_seeds: &[&[u8]] = &[ &[1], &[2], @@ -3987,12 +3988,12 @@ mod tests { &[17], ]; invoke_context.mock_set_remaining(cost * (max_tries - 1)); - assert!(matches!( + assert_matches!( try_find_program_address(&mut invoke_context, exceeded_seeds, &address), - Result::Err(error) if error.downcast_ref::().unwrap() == &SyscallError::BadSeeds(PubkeyError::MaxSeedLengthExceeded), - )); + Result::Err(error) if error.downcast_ref::().unwrap() == &SyscallError::BadSeeds(PubkeyError::MaxSeedLengthExceeded) + ); - assert!(matches!( + assert_matches!( call_program_address_common( &mut invoke_context, seeds, @@ -4000,8 +4001,8 @@ mod tests { true, SyscallTryFindProgramAddress::call, ), - Result::Err(error) if error.downcast_ref::().unwrap() == &SyscallError::CopyOverlapping, - )); + Result::Err(error) if error.downcast_ref::().unwrap() == &SyscallError::CopyOverlapping + ); } #[test] @@ -4101,10 +4102,10 @@ mod tests { &mut result, ); - assert!(matches!( + assert_matches!( result, - ProgramResult::Err(error) if error.downcast_ref::().unwrap() == &SyscallError::InvalidLength, - )); + ProgramResult::Err(error) if error.downcast_ref::().unwrap() == &SyscallError::InvalidLength + ); } } diff --git a/programs/vote/Cargo.toml b/programs/vote/Cargo.toml index 130c7d71bd..4028c70cb2 100644 --- a/programs/vote/Cargo.toml +++ b/programs/vote/Cargo.toml @@ -25,6 +25,7 @@ solana-sdk = { workspace = true } thiserror = { workspace = true } [dev-dependencies] +assert_matches = { workspace = true } solana-logger = { workspace = true } test-case = { workspace = true } diff --git a/programs/vote/src/vote_state/mod.rs b/programs/vote/src/vote_state/mod.rs index fb63c7dc8a..53d9b912c3 100644 --- a/programs/vote/src/vote_state/mod.rs +++ b/programs/vote/src/vote_state/mod.rs @@ -1097,6 +1097,7 @@ mod tests { use { super::*, crate::vote_state, + assert_matches::assert_matches, solana_sdk::{ account::AccountSharedData, account_utils::StateMut, clock::DEFAULT_SLOTS_PER_EPOCH, hash::hash, transaction_context::InstructionAccount, @@ -1216,7 +1217,7 @@ mod tests { // Ensure that the vote state started out at 1_14_11 let vote_state_version = borrowed_account.get_state::().unwrap(); - assert!(matches!(vote_state_version, VoteStateVersions::V1_14_11(_))); + assert_matches!(vote_state_version, VoteStateVersions::V1_14_11(_)); // Convert the vote state to current as would occur during vote instructions let converted_vote_state = vote_state_version.convert_to_current(); @@ -1233,7 +1234,7 @@ mod tests { Ok(()) ); let vote_state_version = borrowed_account.get_state::().unwrap(); - assert!(matches!(vote_state_version, VoteStateVersions::V1_14_11(_))); + assert_matches!(vote_state_version, VoteStateVersions::V1_14_11(_)); // Convert the vote state to current as would occur during vote instructions let converted_vote_state = vote_state_version.convert_to_current(); @@ -1251,7 +1252,7 @@ mod tests { Ok(()) ); let vote_state_version = borrowed_account.get_state::().unwrap(); - assert!(matches!(vote_state_version, VoteStateVersions::V1_14_11(_))); + assert_matches!(vote_state_version, VoteStateVersions::V1_14_11(_)); // Convert the vote state to current as would occur during vote instructions let converted_vote_state = vote_state_version.convert_to_current(); @@ -1272,7 +1273,7 @@ mod tests { Ok(()) ); let vote_state_version = borrowed_account.get_state::().unwrap(); - assert!(matches!(vote_state_version, VoteStateVersions::Current(_))); + assert_matches!(vote_state_version, VoteStateVersions::Current(_)); // Convert the vote state to current as would occur during vote instructions let converted_vote_state = vote_state_version.convert_to_current(); diff --git a/remote-wallet/Cargo.toml b/remote-wallet/Cargo.toml index b5e20d18fa..21fecb564b 100644 --- a/remote-wallet/Cargo.toml +++ b/remote-wallet/Cargo.toml @@ -23,6 +23,9 @@ solana-sdk = { workspace = true } thiserror = { workspace = true } uriparse = { workspace = true } +[dev-dependencies] +assert_matches = { workspace = true } + [features] default = ["linux-static-hidraw", "hidapi"] linux-static-libusb = ["hidapi/linux-static-libusb"] diff --git a/remote-wallet/src/locator.rs b/remote-wallet/src/locator.rs index d460554be4..ca8e7d696c 100644 --- a/remote-wallet/src/locator.rs +++ b/remote-wallet/src/locator.rs @@ -164,7 +164,7 @@ impl Locator { #[cfg(test)] mod tests { - use super::*; + use {super::*, assert_matches::assert_matches}; #[test] fn test_manufacturer() { @@ -190,36 +190,36 @@ mod tests { manufacturer, pubkey: None, }; - assert!(matches!( + assert_matches!( Locator::new_from_parts(manufacturer, None::), - Ok(e) if e == expect, - )); - assert!(matches!( + Ok(e) if e == expect + ); + assert_matches!( Locator::new_from_parts(manufacturer_str, None::), - Ok(e) if e == expect, - )); + Ok(e) if e == expect + ); let expect = Locator { manufacturer, pubkey: Some(pubkey), }; - assert!(matches!( + assert_matches!( Locator::new_from_parts(manufacturer, Some(pubkey)), - Ok(e) if e == expect, - )); - assert!(matches!( + Ok(e) if e == expect + ); + assert_matches!( Locator::new_from_parts(manufacturer_str, Some(pubkey_str.as_str())), - Ok(e) if e == expect, - )); + Ok(e) if e == expect + ); - assert!(matches!( + assert_matches!( Locator::new_from_parts("bad-manufacturer", None::), - Err(LocatorError::ManufacturerError(e)) if e == ManufacturerError, - )); - assert!(matches!( + Err(LocatorError::ManufacturerError(e)) if e == ManufacturerError + ); + assert_matches!( Locator::new_from_parts(manufacturer, Some("bad-pubkey")), - Err(LocatorError::PubkeyError(e)) if e == ParsePubkeyError::Invalid, - )); + Err(LocatorError::PubkeyError(e)) if e == ParsePubkeyError::Invalid + ); } #[test] diff --git a/runtime/src/bank/serde_snapshot.rs b/runtime/src/bank/serde_snapshot.rs index a034517d30..338698407b 100644 --- a/runtime/src/bank/serde_snapshot.rs +++ b/runtime/src/bank/serde_snapshot.rs @@ -19,6 +19,7 @@ mod tests { }, status_cache::StatusCache, }, + assert_matches::assert_matches, solana_accounts_db::{ account_storage::{AccountStorageMap, AccountStorageReference}, accounts_db::{ @@ -419,7 +420,7 @@ mod tests { .get_epoch_reward_status_to_serialize() .unwrap_or(&EpochRewardStatus::Inactive); if let Some(rewards) = epoch_reward_status_active { - assert!(matches!(epoch_reward_status, EpochRewardStatus::Active(_))); + assert_matches!(epoch_reward_status, EpochRewardStatus::Active(_)); if let EpochRewardStatus::Active(StartBlockHeightAndRewards { start_block_height, ref stake_rewards_by_partition, @@ -431,7 +432,7 @@ mod tests { unreachable!("Epoch reward status should NOT be inactive."); } } else { - assert!(matches!(epoch_reward_status, EpochRewardStatus::Inactive)); + assert_matches!(epoch_reward_status, EpochRewardStatus::Inactive); } } } @@ -511,7 +512,7 @@ mod tests { .get_epoch_reward_status_to_serialize() .unwrap_or(&EpochRewardStatus::Inactive); if let Some(rewards) = epoch_reward_status_active { - assert!(matches!(epoch_reward_status, EpochRewardStatus::Active(_))); + assert_matches!(epoch_reward_status, EpochRewardStatus::Active(_)); if let EpochRewardStatus::Active(StartBlockHeightAndRewards { start_block_height, ref stake_rewards_by_partition, @@ -523,7 +524,7 @@ mod tests { unreachable!("Epoch reward status should NOT be inactive."); } } else { - assert!(matches!(epoch_reward_status, EpochRewardStatus::Inactive)); + assert_matches!(epoch_reward_status, EpochRewardStatus::Inactive); } } } @@ -602,7 +603,7 @@ mod tests { let epoch_reward_status = bank .get_epoch_reward_status_to_serialize() .unwrap_or(&EpochRewardStatus::Inactive); - assert!(matches!(epoch_reward_status, EpochRewardStatus::Inactive)); + assert_matches!(epoch_reward_status, EpochRewardStatus::Inactive); } #[cfg(RUSTC_WITH_SPECIALIZATION)] diff --git a/runtime/src/bank/tests.rs b/runtime/src/bank/tests.rs index cf461e330b..c3e1b61143 100644 --- a/runtime/src/bank/tests.rs +++ b/runtime/src/bank/tests.rs @@ -17,6 +17,7 @@ use { }, status_cache::MAX_CACHE_ENTRIES, }, + assert_matches::assert_matches, crossbeam_channel::{bounded, unbounded}, itertools::Itertools, rand::Rng, @@ -6043,16 +6044,16 @@ fn test_pre_post_transaction_balances() { // Failed transactions still produce balance sets // This is a TransactionError - not possible to charge fees - assert!(matches!( + assert_matches!( transaction_results.execution_results[1], - TransactionExecutionResult::NotExecuted(TransactionError::AccountNotFound), - )); + TransactionExecutionResult::NotExecuted(TransactionError::AccountNotFound) + ); assert_eq!(transaction_balances_set.pre_balances[1], vec![0, 0, 1]); assert_eq!(transaction_balances_set.post_balances[1], vec![0, 0, 1]); // Failed transactions still produce balance sets // This is an InstructionError - fees charged - assert!(matches!( + assert_matches!( transaction_results.execution_results[2], TransactionExecutionResult::Executed { details: TransactionExecutionDetails { @@ -6063,8 +6064,8 @@ fn test_pre_post_transaction_balances() { .. }, .. - }, - )); + } + ); assert_eq!( transaction_balances_set.pre_balances[2], vec![909_000, 0, 1] @@ -7230,7 +7231,7 @@ fn test_bank_load_program() { bank.store_account_and_update_capitalization(&key1, &program_account); bank.store_account_and_update_capitalization(&programdata_key, &programdata_account); let program = bank.load_program(&key1); - assert!(matches!(program.program, LoadedProgramType::LegacyV1(_))); + assert_matches!(program.program, LoadedProgramType::LegacyV1(_)); assert_eq!( program.account_size, program_account.data().len() + programdata_account.data().len() @@ -12691,10 +12692,10 @@ fn test_rewards_computation_and_partitioned_distribution_one_block() { if slot == num_slots_in_epoch { // This is the first block of epoch 1. Reward computation should happen in this block. // assert reward compute status activated at epoch boundary - assert!(matches!( + assert_matches!( curr_bank.get_reward_interval(), RewardInterval::InsideInterval - )); + ); // cap should increase because of new epoch rewards assert!(post_cap > pre_cap); @@ -12704,10 +12705,10 @@ fn test_rewards_computation_and_partitioned_distribution_one_block() { // rewards are transferred from epoch_rewards sysvar to stake accounts. The cap should stay the same. // 2. when curr_slot == num_slots_in_epoch+2, the 3rd block of epoch 1. reward distribution should have already completed. Therefore, // reward_status should stay inactive and cap should stay the same. - assert!(matches!( + assert_matches!( curr_bank.get_reward_interval(), RewardInterval::OutsideInterval - )); + ); assert_eq!(post_cap, pre_cap); } else { @@ -12804,20 +12805,20 @@ fn test_rewards_computation_and_partitioned_distribution_two_blocks() { if slot == num_slots_in_epoch { // This is the first block of epoch 1. Reward computation should happen in this block. // assert reward compute status activated at epoch boundary - assert!(matches!( + assert_matches!( curr_bank.get_reward_interval(), RewardInterval::InsideInterval - )); + ); // cap should increase because of new epoch rewards assert!(post_cap > pre_cap); } else if slot == num_slots_in_epoch + 1 { // When curr_slot == num_slots_in_epoch + 1, the 2nd block of epoch 1, reward distribution should happen in this block. // however, since rewards are transferred from epoch_rewards sysvar to stake accounts. The cap should stay the same. - assert!(matches!( + assert_matches!( curr_bank.get_reward_interval(), RewardInterval::InsideInterval - )); + ); assert_eq!(post_cap, pre_cap); } else if slot == num_slots_in_epoch + 2 || slot == num_slots_in_epoch + 3 { @@ -12826,10 +12827,10 @@ fn test_rewards_computation_and_partitioned_distribution_two_blocks() { // rewards are transferred from epoch_rewards sysvar to stake accounts. The cap should stay the same. // 2. when curr_slot == num_slots_in_epoch+2, the 3rd block of epoch 1. reward distribution should have already completed. Therefore, // reward_status should stay inactive and cap should stay the same. - assert!(matches!( + assert_matches!( curr_bank.get_reward_interval(), RewardInterval::OutsideInterval - )); + ); assert_eq!(post_cap, pre_cap); } else { diff --git a/runtime/src/bank_forks.rs b/runtime/src/bank_forks.rs index 8c8e6b54fd..8f59d54315 100644 --- a/runtime/src/bank_forks.rs +++ b/runtime/src/bank_forks.rs @@ -679,6 +679,7 @@ mod tests { create_genesis_config, create_genesis_config_with_leader, GenesisConfigInfo, }, }, + assert_matches::assert_matches, solana_accounts_db::epoch_accounts_hash::EpochAccountsHash, solana_sdk::{ clock::UnixTimestamp, @@ -1048,100 +1049,34 @@ mod tests { // | | // 10 12 - assert!(matches!( - bank_forks.relationship(0, 3), - BlockRelation::Ancestor - )); - assert!(matches!( - bank_forks.relationship(0, 10), - BlockRelation::Ancestor - )); - assert!(matches!( - bank_forks.relationship(0, 12), - BlockRelation::Ancestor - )); - assert!(matches!( - bank_forks.relationship(1, 3), - BlockRelation::Ancestor - )); - assert!(matches!( - bank_forks.relationship(2, 10), - BlockRelation::Ancestor - )); - assert!(matches!( - bank_forks.relationship(2, 12), - BlockRelation::Ancestor - )); - assert!(matches!( - bank_forks.relationship(4, 10), - BlockRelation::Ancestor - )); - assert!(matches!( - bank_forks.relationship(4, 12), - BlockRelation::Ancestor - )); - assert!(matches!( - bank_forks.relationship(6, 10), - BlockRelation::Unrelated - )); - assert!(matches!( - bank_forks.relationship(5, 12), - BlockRelation::Unrelated - )); - assert!(matches!( - bank_forks.relationship(6, 12), - BlockRelation::Ancestor - )); + assert_matches!(bank_forks.relationship(0, 3), BlockRelation::Ancestor); + assert_matches!(bank_forks.relationship(0, 10), BlockRelation::Ancestor); + assert_matches!(bank_forks.relationship(0, 12), BlockRelation::Ancestor); + assert_matches!(bank_forks.relationship(1, 3), BlockRelation::Ancestor); + assert_matches!(bank_forks.relationship(2, 10), BlockRelation::Ancestor); + assert_matches!(bank_forks.relationship(2, 12), BlockRelation::Ancestor); + assert_matches!(bank_forks.relationship(4, 10), BlockRelation::Ancestor); + assert_matches!(bank_forks.relationship(4, 12), BlockRelation::Ancestor); + assert_matches!(bank_forks.relationship(6, 10), BlockRelation::Unrelated); + assert_matches!(bank_forks.relationship(5, 12), BlockRelation::Unrelated); + assert_matches!(bank_forks.relationship(6, 12), BlockRelation::Ancestor); - assert!(matches!( - bank_forks.relationship(6, 2), - BlockRelation::Descendant - )); - assert!(matches!( - bank_forks.relationship(10, 2), - BlockRelation::Descendant - )); - assert!(matches!( - bank_forks.relationship(8, 3), - BlockRelation::Descendant - )); - assert!(matches!( - bank_forks.relationship(6, 3), - BlockRelation::Unrelated - )); - assert!(matches!( - bank_forks.relationship(12, 2), - BlockRelation::Descendant - )); - assert!(matches!( - bank_forks.relationship(12, 1), - BlockRelation::Unrelated - )); - assert!(matches!( - bank_forks.relationship(1, 2), - BlockRelation::Unrelated - )); + assert_matches!(bank_forks.relationship(6, 2), BlockRelation::Descendant); + assert_matches!(bank_forks.relationship(10, 2), BlockRelation::Descendant); + assert_matches!(bank_forks.relationship(8, 3), BlockRelation::Descendant); + assert_matches!(bank_forks.relationship(6, 3), BlockRelation::Unrelated); + assert_matches!(bank_forks.relationship(12, 2), BlockRelation::Descendant); + assert_matches!(bank_forks.relationship(12, 1), BlockRelation::Unrelated); + assert_matches!(bank_forks.relationship(1, 2), BlockRelation::Unrelated); - assert!(matches!( - bank_forks.relationship(1, 13), - BlockRelation::Unknown - )); - assert!(matches!( - bank_forks.relationship(13, 2), - BlockRelation::Unknown - )); + assert_matches!(bank_forks.relationship(1, 13), BlockRelation::Unknown); + assert_matches!(bank_forks.relationship(13, 2), BlockRelation::Unknown); bank_forks.set_root( 2, &AbsRequestSender::default(), Some(1), // highest confirmed root ); - assert!(matches!( - bank_forks.relationship(1, 2), - BlockRelation::Unknown - )); - assert!(matches!( - bank_forks.relationship(2, 0), - BlockRelation::Unknown - )); + assert_matches!(bank_forks.relationship(1, 2), BlockRelation::Unknown); + assert_matches!(bank_forks.relationship(2, 0), BlockRelation::Unknown); } } diff --git a/runtime/src/snapshot_utils.rs b/runtime/src/snapshot_utils.rs index 39d00d3682..9d8e802625 100644 --- a/runtime/src/snapshot_utils.rs +++ b/runtime/src/snapshot_utils.rs @@ -3115,9 +3115,9 @@ mod tests { accounts_hardlinks_dir, ); - assert!(matches!( + assert_matches!( ret, Err(GetSnapshotAccountsHardLinkDirError::GetAccountPath(_)) - )); + ); } } diff --git a/sdk/src/derivation_path.rs b/sdk/src/derivation_path.rs index 83d8dd208e..4e76ddf95d 100644 --- a/sdk/src/derivation_path.rs +++ b/sdk/src/derivation_path.rs @@ -268,7 +268,7 @@ impl Bip44 for Solana { #[cfg(test)] mod tests { - use {super::*, uriparse::URIReferenceBuilder}; + use {super::*, assert_matches::assert_matches, uriparse::URIReferenceBuilder}; struct TestCoin; impl Bip44 for TestCoin { @@ -481,10 +481,10 @@ mod tests { .try_query(Some("key=0/0/0")) .unwrap(); let uri = builder.build().unwrap(); - assert!(matches!( + assert_matches!( DerivationPath::from_uri(&uri, true), Err(DerivationPathError::InvalidDerivationPath(_)) - )); + ); // test://path?key=0/0&bad-key=0/0 let mut builder = URIReferenceBuilder::new(); @@ -498,10 +498,10 @@ mod tests { .try_query(Some("key=0/0&bad-key=0/0")) .unwrap(); let uri = builder.build().unwrap(); - assert!(matches!( + assert_matches!( DerivationPath::from_uri(&uri, true), Err(DerivationPathError::InvalidDerivationPath(_)) - )); + ); // test://path?bad-key=0/0 let mut builder = URIReferenceBuilder::new(); @@ -515,10 +515,10 @@ mod tests { .try_query(Some("bad-key=0/0")) .unwrap(); let uri = builder.build().unwrap(); - assert!(matches!( + assert_matches!( DerivationPath::from_uri(&uri, true), Err(DerivationPathError::InvalidDerivationPath(_)) - )); + ); // test://path?key=bad-value let mut builder = URIReferenceBuilder::new(); @@ -532,10 +532,10 @@ mod tests { .try_query(Some("key=bad-value")) .unwrap(); let uri = builder.build().unwrap(); - assert!(matches!( + assert_matches!( DerivationPath::from_uri(&uri, true), Err(DerivationPathError::InvalidDerivationPath(_)) - )); + ); // test://path?key= let mut builder = URIReferenceBuilder::new(); @@ -549,10 +549,10 @@ mod tests { .try_query(Some("key=")) .unwrap(); let uri = builder.build().unwrap(); - assert!(matches!( + assert_matches!( DerivationPath::from_uri(&uri, true), Err(DerivationPathError::InvalidDerivationPath(_)) - )); + ); // test://path?key let mut builder = URIReferenceBuilder::new(); @@ -566,10 +566,10 @@ mod tests { .try_query(Some("key")) .unwrap(); let uri = builder.build().unwrap(); - assert!(matches!( + assert_matches!( DerivationPath::from_uri(&uri, true), Err(DerivationPathError::InvalidDerivationPath(_)) - )); + ); } #[test] @@ -656,10 +656,10 @@ mod tests { .try_query(Some("full-path=m/44/999/1")) .unwrap(); let uri = builder.build().unwrap(); - assert!(matches!( + assert_matches!( DerivationPath::from_uri(&uri, true), Err(DerivationPathError::InvalidDerivationPath(_)) - )); + ); // test://path?key=0/0&full-path=m/44/999/1 let mut builder = URIReferenceBuilder::new(); @@ -673,10 +673,10 @@ mod tests { .try_query(Some("key=0/0&full-path=m/44/999/1")) .unwrap(); let uri = builder.build().unwrap(); - assert!(matches!( + assert_matches!( DerivationPath::from_uri(&uri, false), Err(DerivationPathError::InvalidDerivationPath(_)) - )); + ); // test://path?full-path=m/44/999/1&bad-key=0/0 let mut builder = URIReferenceBuilder::new(); @@ -690,10 +690,10 @@ mod tests { .try_query(Some("full-path=m/44/999/1&bad-key=0/0")) .unwrap(); let uri = builder.build().unwrap(); - assert!(matches!( + assert_matches!( DerivationPath::from_uri(&uri, false), Err(DerivationPathError::InvalidDerivationPath(_)) - )); + ); // test://path?full-path=bad-value let mut builder = URIReferenceBuilder::new(); @@ -707,10 +707,10 @@ mod tests { .try_query(Some("full-path=bad-value")) .unwrap(); let uri = builder.build().unwrap(); - assert!(matches!( + assert_matches!( DerivationPath::from_uri(&uri, false), Err(DerivationPathError::InvalidDerivationPath(_)) - )); + ); // test://path?full-path= let mut builder = URIReferenceBuilder::new(); @@ -724,10 +724,10 @@ mod tests { .try_query(Some("full-path=")) .unwrap(); let uri = builder.build().unwrap(); - assert!(matches!( + assert_matches!( DerivationPath::from_uri(&uri, false), Err(DerivationPathError::InvalidDerivationPath(_)) - )); + ); // test://path?full-path let mut builder = URIReferenceBuilder::new(); @@ -741,10 +741,10 @@ mod tests { .try_query(Some("full-path")) .unwrap(); let uri = builder.build().unwrap(); - assert!(matches!( + assert_matches!( DerivationPath::from_uri(&uri, false), Err(DerivationPathError::InvalidDerivationPath(_)) - )); + ); } #[test] diff --git a/streamer/Cargo.toml b/streamer/Cargo.toml index f85a2942d2..21ae96d11f 100644 --- a/streamer/Cargo.toml +++ b/streamer/Cargo.toml @@ -36,6 +36,7 @@ tokio = { workspace = true, features = ["full"] } x509-parser = { workspace = true } [dev-dependencies] +assert_matches = { workspace = true } solana-logger = { workspace = true } [lib] diff --git a/streamer/src/nonblocking/quic.rs b/streamer/src/nonblocking/quic.rs index 8e34657181..d238552abb 100644 --- a/streamer/src/nonblocking/quic.rs +++ b/streamer/src/nonblocking/quic.rs @@ -1096,6 +1096,7 @@ pub mod test { quic::{MAX_STAKED_CONNECTIONS, MAX_UNSTAKED_CONNECTIONS}, tls_certificates::new_self_signed_tls_certificate, }, + assert_matches::assert_matches, async_channel::unbounded as async_unbounded, crossbeam_channel::{unbounded, Receiver}, quinn::{ClientConfig, IdleTimeout, TransportConfig}, @@ -1260,8 +1261,7 @@ pub mod test { // It has been noticed if there is already connection open against the server, this open_uni can fail // with ApplicationClosed(ApplicationClose) error due to CONNECTION_CLOSE_CODE_TOO_MANY before writing to // the stream -- expect it. - let s2 = s2.err().unwrap(); - assert!(matches!(s2, quinn::ConnectionError::ApplicationClosed(_))); + assert_matches!(s2, Err(quinn::ConnectionError::ApplicationClosed(_))); } } diff --git a/streamer/src/nonblocking/sendmmsg.rs b/streamer/src/nonblocking/sendmmsg.rs index 3c8d608300..106e53d243 100644 --- a/streamer/src/nonblocking/sendmmsg.rs +++ b/streamer/src/nonblocking/sendmmsg.rs @@ -60,6 +60,7 @@ mod tests { packet::Packet, sendmmsg::SendPktsError, }, + assert_matches::assert_matches, solana_sdk::packet::PACKET_DATA_SIZE, std::{ io::ErrorKind, @@ -207,7 +208,7 @@ mod tests { if let Err(SendPktsError::IoError(ioerror, num_failed)) = batch_send(&sender, &packet_refs[..]).await { - assert!(matches!(ioerror.kind(), ErrorKind::PermissionDenied)); + assert_matches!(ioerror.kind(), ErrorKind::PermissionDenied); assert_eq!(num_failed, 2); } @@ -222,7 +223,7 @@ mod tests { if let Err(SendPktsError::IoError(ioerror, num_failed)) = batch_send(&sender, &packet_refs[..]).await { - assert!(matches!(ioerror.kind(), ErrorKind::PermissionDenied)); + assert_matches!(ioerror.kind(), ErrorKind::PermissionDenied); assert_eq!(num_failed, 3); } @@ -237,7 +238,7 @@ mod tests { if let Err(SendPktsError::IoError(ioerror, num_failed)) = batch_send(&sender, &packet_refs[..]).await { - assert!(matches!(ioerror.kind(), ErrorKind::PermissionDenied)); + assert_matches!(ioerror.kind(), ErrorKind::PermissionDenied); assert_eq!(num_failed, 2); } @@ -252,7 +253,7 @@ mod tests { if let Err(SendPktsError::IoError(ioerror, num_failed)) = multi_target_send(&sender, &packets[0], &dest_refs).await { - assert!(matches!(ioerror.kind(), ErrorKind::PermissionDenied)); + assert_matches!(ioerror.kind(), ErrorKind::PermissionDenied); assert_eq!(num_failed, 2); } @@ -267,7 +268,7 @@ mod tests { if let Err(SendPktsError::IoError(ioerror, num_failed)) = multi_target_send(&sender, &packets[0], &dest_refs).await { - assert!(matches!(ioerror.kind(), ErrorKind::PermissionDenied)); + assert_matches!(ioerror.kind(), ErrorKind::PermissionDenied); assert_eq!(num_failed, 3); } } diff --git a/streamer/src/sendmmsg.rs b/streamer/src/sendmmsg.rs index da82d6d756..3340b10e6f 100644 --- a/streamer/src/sendmmsg.rs +++ b/streamer/src/sendmmsg.rs @@ -166,6 +166,7 @@ mod tests { recvmmsg::recv_mmsg, sendmmsg::{batch_send, multi_target_send, SendPktsError}, }, + assert_matches::assert_matches, solana_sdk::packet::PACKET_DATA_SIZE, std::{ io::ErrorKind, @@ -309,7 +310,7 @@ mod tests { if let Err(SendPktsError::IoError(ioerror, num_failed)) = batch_send(&sender, &packet_refs[..]) { - assert!(matches!(ioerror.kind(), ErrorKind::PermissionDenied)); + assert_matches!(ioerror.kind(), ErrorKind::PermissionDenied); assert_eq!(num_failed, 2); } @@ -324,7 +325,7 @@ mod tests { if let Err(SendPktsError::IoError(ioerror, num_failed)) = batch_send(&sender, &packet_refs[..]) { - assert!(matches!(ioerror.kind(), ErrorKind::PermissionDenied)); + assert_matches!(ioerror.kind(), ErrorKind::PermissionDenied); assert_eq!(num_failed, 3); } @@ -339,7 +340,7 @@ mod tests { if let Err(SendPktsError::IoError(ioerror, num_failed)) = batch_send(&sender, &packet_refs[..]) { - assert!(matches!(ioerror.kind(), ErrorKind::PermissionDenied)); + assert_matches!(ioerror.kind(), ErrorKind::PermissionDenied); assert_eq!(num_failed, 2); } @@ -354,7 +355,7 @@ mod tests { if let Err(SendPktsError::IoError(ioerror, num_failed)) = multi_target_send(&sender, &packets[0], &dest_refs) { - assert!(matches!(ioerror.kind(), ErrorKind::PermissionDenied)); + assert_matches!(ioerror.kind(), ErrorKind::PermissionDenied); assert_eq!(num_failed, 2); } @@ -369,7 +370,7 @@ mod tests { if let Err(SendPktsError::IoError(ioerror, num_failed)) = multi_target_send(&sender, &packets[0], &dest_refs) { - assert!(matches!(ioerror.kind(), ErrorKind::PermissionDenied)); + assert_matches!(ioerror.kind(), ErrorKind::PermissionDenied); assert_eq!(num_failed, 3); } } diff --git a/tokens/Cargo.toml b/tokens/Cargo.toml index 7aa320d88f..37e675c521 100644 --- a/tokens/Cargo.toml +++ b/tokens/Cargo.toml @@ -34,6 +34,7 @@ tempfile = { workspace = true } thiserror = { workspace = true } [dev-dependencies] +assert_matches = { workspace = true } bincode = { workspace = true } solana-logger = { workspace = true } solana-streamer = { workspace = true } diff --git a/tokens/src/db.rs b/tokens/src/db.rs index cf699355d8..0d6ed67e0b 100644 --- a/tokens/src/db.rs +++ b/tokens/src/db.rs @@ -209,6 +209,7 @@ pub(crate) fn check_output_file(path: &str, db: &PickleDb) { mod tests { use { super::*, + assert_matches::assert_matches, csv::{ReaderBuilder, Trim}, solana_sdk::transaction::TransactionError, solana_transaction_status::TransactionConfirmationStatus, @@ -272,10 +273,10 @@ mod tests { let signature = Signature::default(); let transaction_info = TransactionInfo::default(); db.set(&signature.to_string(), &transaction_info).unwrap(); - assert!(matches!( - update_finalized_transaction(&mut db, &signature, None, 0, 0).unwrap(), - Some(0) - )); + assert_matches!( + update_finalized_transaction(&mut db, &signature, None, 0, 0), + Ok(Some(0)) + ); // Unchanged assert_eq!(