Skip to content

Commit 0715b2f

Browse files
authored
GH-662: Write tests for usages of 'panic_on_migration()' (#267)
* GH-662: Established a single function to test panic_on_migration * GH-662: Tested a frew more occurrences * GH-662: Finished last test * GH-662: Fixed all warning messages & formatting * GH-622: Decreased last_remapped duration for maybe_remap_handles_remapping_error * Revert "GH-622: Decreased last_remapped duration for maybe_remap_handles_remapping_error" This reverts commit 5d1e009. * GH-662: Amended Subjects name
1 parent 6a53bf9 commit 0715b2f

File tree

12 files changed

+294
-57
lines changed

12 files changed

+294
-57
lines changed

node/src/accountant/mod.rs

+19-2
Original file line numberDiff line numberDiff line change
@@ -1008,7 +1008,7 @@ mod tests {
10081008

10091009
use crate::accountant::dao_utils::from_time_t;
10101010
use crate::accountant::dao_utils::{to_time_t, CustomQuery};
1011-
use crate::accountant::payable_dao::{PayableAccount, PayableDaoError};
1011+
use crate::accountant::payable_dao::{PayableAccount, PayableDaoError, PayableDaoFactory};
10121012
use crate::accountant::pending_payable_dao::PendingPayableDaoError;
10131013
use crate::accountant::receivable_dao::ReceivableAccount;
10141014
use crate::accountant::scanners::{BeginScanError, NullScanner, ScannerMock};
@@ -1043,10 +1043,12 @@ mod tests {
10431043
use crate::test_utils::unshared_test_utils::notify_handlers::NotifyLaterHandleMock;
10441044
use crate::test_utils::unshared_test_utils::system_killer_actor::SystemKillerActor;
10451045
use crate::test_utils::unshared_test_utils::{
1046-
make_bc_with_defaults, prove_that_crash_request_handler_is_hooked_up, AssertionsMessage,
1046+
assert_on_initialization_with_panic_on_migration, make_bc_with_defaults,
1047+
prove_that_crash_request_handler_is_hooked_up, AssertionsMessage,
10471048
};
10481049
use crate::test_utils::{make_paying_wallet, make_wallet};
10491050
use masq_lib::messages::TopRecordsOrdering::{Age, Balance};
1051+
use masq_lib::test_utils::utils::ensure_node_home_directory_exists;
10501052
use masq_lib::ui_gateway::MessagePath::Conversation;
10511053
use web3::types::{TransactionReceipt, H256};
10521054

@@ -4338,4 +4340,19 @@ mod tests {
43384340
}
43394341
}
43404342
}
4343+
4344+
#[test]
4345+
fn make_dao_factory_uses_panic_on_migration() {
4346+
let data_dir = ensure_node_home_directory_exists(
4347+
"accountant",
4348+
"make_dao_factory_uses_panic_on_migration",
4349+
);
4350+
4351+
let act = |data_dir: &Path| {
4352+
let factory = Accountant::dao_factory(data_dir);
4353+
factory.make();
4354+
};
4355+
4356+
assert_on_initialization_with_panic_on_migration(&data_dir, &act);
4357+
}
43414358
}

node/src/actor_system_factory.rs

+35-5
Original file line numberDiff line numberDiff line change
@@ -49,6 +49,7 @@ use masq_lib::logger::Logger;
4949
use masq_lib::ui_gateway::{NodeFromUiMessage, NodeToUiMessage};
5050
use masq_lib::utils::{exit_process, AutomapProtocol};
5151
use std::net::{IpAddr, Ipv4Addr};
52+
use std::path::Path;
5253

5354
pub trait ActorSystemFactory {
5455
fn make_and_start_actors(
@@ -453,11 +454,7 @@ impl ActorFactory for ActorFactoryReal {
453454
let pending_payable_dao_factory = Box::new(Accountant::dao_factory(data_directory));
454455
let receivable_dao_factory = Box::new(Accountant::dao_factory(data_directory));
455456
let banned_dao_factory = Box::new(Accountant::dao_factory(data_directory));
456-
banned_cache_loader.load(connection_or_panic(
457-
db_initializer,
458-
data_directory,
459-
DbInitializationConfig::panic_on_migration(),
460-
));
457+
Self::load_banned_cache(db_initializer, banned_cache_loader, data_directory);
461458
let arbiter = Arbiter::builder().stop_system_on_panic(true);
462459
let addr: Addr<Accountant> = arbiter.start(move |_| {
463460
Accountant::new(
@@ -543,6 +540,20 @@ impl ActorFactory for ActorFactoryReal {
543540
}
544541
}
545542

543+
impl ActorFactoryReal {
544+
fn load_banned_cache(
545+
db_initializer: &dyn DbInitializer,
546+
banned_cache_loader: &dyn BannedCacheLoader,
547+
data_directory: &Path,
548+
) {
549+
banned_cache_loader.load(connection_or_panic(
550+
db_initializer,
551+
data_directory,
552+
DbInitializationConfig::panic_on_migration(),
553+
));
554+
}
555+
}
556+
546557
fn is_crashable(config: &BootstrapperConfig) -> bool {
547558
config.crash_point == CrashPoint::Message
548559
}
@@ -639,6 +650,7 @@ mod tests {
639650
};
640651
use crate::test_utils::recorder::{make_recorder, Recorder};
641652
use crate::test_utils::unshared_test_utils::arbitrary_id_stamp::ArbitraryIdStamp;
653+
use crate::test_utils::unshared_test_utils::assert_on_initialization_with_panic_on_migration;
642654
use crate::test_utils::unshared_test_utils::system_killer_actor::SystemKillerActor;
643655
use crate::test_utils::{alias_cryptde, rate_pack};
644656
use crate::test_utils::{main_cryptde, make_cryptde_pair};
@@ -2081,6 +2093,24 @@ mod tests {
20812093
assert_eq!(msg, &msg_of_irrelevant_choice);
20822094
}
20832095

2096+
#[test]
2097+
fn load_banned_cache_implements_panic_on_migration() {
2098+
let data_dir = ensure_node_home_directory_exists(
2099+
"actor_system_factory",
2100+
"load_banned_cache_implements_panic_on_migration",
2101+
);
2102+
2103+
let act = |data_dir: &Path| {
2104+
ActorFactoryReal::load_banned_cache(
2105+
&DbInitializerReal::default(),
2106+
&BannedCacheLoaderMock::default(),
2107+
&data_dir,
2108+
);
2109+
};
2110+
2111+
assert_on_initialization_with_panic_on_migration(&data_dir, &act);
2112+
}
2113+
20842114
fn public_key_for_dyn_cryptde_being_null(cryptde: &dyn CryptDE) -> &PublicKey {
20852115
let null_cryptde = <&CryptDENull>::from(cryptde);
20862116
null_cryptde.public_key()

node/src/blockchain/blockchain_bridge.rs

+27-9
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,7 @@ use crate::blockchain::blockchain_interface::{
1111
BlockchainInterfaceNonClandestine, BlockchainResult, BlockchainTxnInputs,
1212
};
1313
use crate::database::db_initializer::DbInitializationConfig;
14-
use crate::database::db_initializer::{DbInitializer, DATABASE_FILE};
14+
use crate::database::db_initializer::DbInitializer;
1515
use crate::db_config::config_dao::ConfigDaoReal;
1616
use crate::db_config::persistent_configuration::{
1717
PersistentConfiguration, PersistentConfigurationReal,
@@ -20,7 +20,7 @@ use crate::sub_lib::blockchain_bridge::{BlockchainBridgeSubs, RequestBalancesToP
2020
use crate::sub_lib::blockchain_bridge::{ConsumingWalletBalances, ReportAccountsPayable};
2121
use crate::sub_lib::peer_actors::BindMessage;
2222
use crate::sub_lib::set_consuming_wallet_message::SetConsumingWalletMessage;
23-
use crate::sub_lib::utils::handle_ui_crash_request;
23+
use crate::sub_lib::utils::{db_connection_launch_panic, handle_ui_crash_request};
2424
use crate::sub_lib::wallet::Wallet;
2525
use actix::Actor;
2626
use actix::Context;
@@ -230,12 +230,7 @@ impl BlockchainBridge {
230230
&data_directory,
231231
DbInitializationConfig::panic_on_migration(),
232232
)
233-
.unwrap_or_else(|_| {
234-
panic!(
235-
"Failed to connect to database at {:?}",
236-
&data_directory.join(DATABASE_FILE)
237-
)
238-
}),
233+
.unwrap_or_else(|err| db_connection_launch_panic(err, &data_directory)),
239234
));
240235
(
241236
blockchain_interface,
@@ -508,6 +503,7 @@ mod tests {
508503
use crate::blockchain::test_utils::BlockchainInterfaceMock;
509504
use crate::blockchain::tool_wrappers::SendTransactionToolsWrapperNull;
510505
use crate::database::db_initializer::test_utils::DbInitializerMock;
506+
use crate::database::db_initializer::DbInitializerReal;
511507
use crate::db_config::persistent_configuration::PersistentConfigError;
512508
use crate::match_every_type_id;
513509
use crate::node_test_utils::check_timestamp;
@@ -517,7 +513,8 @@ mod tests {
517513
use crate::test_utils::recorder_stop_conditions::StopCondition;
518514
use crate::test_utils::recorder_stop_conditions::StopConditions;
519515
use crate::test_utils::unshared_test_utils::{
520-
configure_default_persistent_config, prove_that_crash_request_handler_is_hooked_up, ZERO,
516+
assert_on_initialization_with_panic_on_migration, configure_default_persistent_config,
517+
prove_that_crash_request_handler_is_hooked_up, ZERO,
521518
};
522519
use crate::test_utils::{make_paying_wallet, make_wallet};
523520
use actix::System;
@@ -527,8 +524,10 @@ mod tests {
527524
use masq_lib::messages::ScanType;
528525
use masq_lib::test_utils::logging::init_test_logging;
529526
use masq_lib::test_utils::logging::TestLogHandler;
527+
use masq_lib::test_utils::utils::ensure_node_home_directory_exists;
530528
use rustc_hex::FromHex;
531529
use std::any::TypeId;
530+
use std::path::Path;
532531
use std::sync::{Arc, Mutex};
533532
use std::time::{Duration, SystemTime};
534533
use web3::types::{TransactionReceipt, H160, H256, U256};
@@ -1713,4 +1712,23 @@ mod tests {
17131712

17141713
prove_that_crash_request_handler_is_hooked_up(subject, CRASH_KEY);
17151714
}
1715+
1716+
#[test]
1717+
fn make_connections_implements_panic_on_migration() {
1718+
let data_dir = ensure_node_home_directory_exists(
1719+
"blockchain_bridge",
1720+
"make_connections_with_panic_on_migration",
1721+
);
1722+
1723+
let act = |data_dir: &Path| {
1724+
BlockchainBridge::make_connections(
1725+
Some("http://127.0.0.1".to_string()),
1726+
&DbInitializerReal::default(),
1727+
data_dir.to_path_buf(),
1728+
Chain::PolyMumbai,
1729+
);
1730+
};
1731+
1732+
assert_on_initialization_with_panic_on_migration(&data_dir, &act);
1733+
}
17161734
}

node/src/bootstrapper.rs

+62-13
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,7 @@ use crate::node_configurator::node_configurator_standard::{
2121
use crate::node_configurator::{initialize_database, DirsWrapper, NodeConfigurator};
2222
use crate::privilege_drop::{IdWrapper, IdWrapperReal};
2323
use crate::server_initializer::LoggerInitializerWrapper;
24+
use crate::stream_handler_pool::StreamHandlerPoolSubs;
2425
use crate::sub_lib::accountant;
2526
use crate::sub_lib::accountant::{PaymentThresholds, ScanIntervals};
2627
use crate::sub_lib::blockchain_bridge::BlockchainBridgeConfig;
@@ -32,6 +33,7 @@ use crate::sub_lib::neighborhood::{NeighborhoodConfig, NeighborhoodMode};
3233
use crate::sub_lib::node_addr::NodeAddr;
3334
use crate::sub_lib::socket_server::ConfiguredByPrivilege;
3435
use crate::sub_lib::ui_gateway::UiGatewayConfig;
36+
use crate::sub_lib::utils::db_connection_launch_panic;
3537
use crate::sub_lib::wallet::Wallet;
3638
use futures::try_ready;
3739
use itertools::Itertools;
@@ -515,15 +517,7 @@ impl ConfiguredByPrivilege for Bootstrapper {
515517
if node_addr.ip_addr() == Ipv4Addr::new(0, 0, 0, 0) => {} // node_addr still coming
516518
_ => Bootstrapper::report_local_descriptor(cryptdes.main, &self.config.node_descriptor), // here or not coming
517519
}
518-
let stream_handler_pool_subs = self.actor_system_factory.make_and_start_actors(
519-
self.config.clone(),
520-
Box::new(ActorFactoryReal {}),
521-
initialize_database(
522-
&self.config.data_directory,
523-
DbInitializationConfig::panic_on_migration(),
524-
),
525-
);
526-
520+
let stream_handler_pool_subs = self.start_actors_and_return_shp_subs();
527521
self.listener_handlers
528522
.iter_mut()
529523
.for_each(|f| f.bind_subs(stream_handler_pool_subs.add_sub.clone()));
@@ -612,6 +606,17 @@ impl Bootstrapper {
612606
}
613607
}
614608

609+
fn start_actors_and_return_shp_subs(&self) -> StreamHandlerPoolSubs {
610+
self.actor_system_factory.make_and_start_actors(
611+
self.config.clone(),
612+
Box::new(ActorFactoryReal {}),
613+
initialize_database(
614+
&self.config.data_directory,
615+
DbInitializationConfig::panic_on_migration(),
616+
),
617+
)
618+
}
619+
615620
pub fn report_local_descriptor(cryptde: &dyn CryptDE, descriptor: &NodeDescriptor) {
616621
let descriptor_msg = format!(
617622
"MASQ Node local descriptor: {}",
@@ -630,7 +635,9 @@ impl Bootstrapper {
630635
&self.config.data_directory,
631636
DbInitializationConfig::panic_on_migration(),
632637
)
633-
.expect("Cannot initialize database");
638+
.unwrap_or_else(|err| {
639+
db_connection_launch_panic(err, &self.config.data_directory)
640+
});
634641
let config_dao = ConfigDaoReal::new(conn);
635642
let mut persistent_config = PersistentConfigurationReal::new(Box::new(config_dao));
636643
let clandestine_port = self.establish_clandestine_port(&mut persistent_config);
@@ -728,7 +735,9 @@ mod tests {
728735
use crate::sub_lib::cryptde::PublicKey;
729736
use crate::sub_lib::cryptde::{CryptDE, PlainData};
730737
use crate::sub_lib::cryptde_null::CryptDENull;
731-
use crate::sub_lib::neighborhood::{NeighborhoodConfig, NeighborhoodMode, NodeDescriptor};
738+
use crate::sub_lib::neighborhood::{
739+
NeighborhoodConfig, NeighborhoodMode, NodeDescriptor, DEFAULT_RATE_PACK,
740+
};
732741
use crate::sub_lib::node_addr::NodeAddr;
733742
use crate::sub_lib::socket_server::ConfiguredByPrivilege;
734743
use crate::sub_lib::stream_connector::ConnectionInfo;
@@ -738,7 +747,9 @@ mod tests {
738747
use crate::test_utils::recorder::Recording;
739748
use crate::test_utils::tokio_wrapper_mocks::ReadHalfWrapperMock;
740749
use crate::test_utils::tokio_wrapper_mocks::WriteHalfWrapperMock;
741-
use crate::test_utils::unshared_test_utils::make_simplified_multi_config;
750+
use crate::test_utils::unshared_test_utils::{
751+
assert_on_initialization_with_panic_on_migration, make_simplified_multi_config,
752+
};
742753
use crate::test_utils::{assert_contains, rate_pack};
743754
use crate::test_utils::{main_cryptde, make_wallet};
744755
use actix::Recipient;
@@ -762,7 +773,7 @@ mod tests {
762773
use std::io::ErrorKind;
763774
use std::marker::Sync;
764775
use std::net::{IpAddr, SocketAddr};
765-
use std::path::PathBuf;
776+
use std::path::{Path, PathBuf};
766777
use std::str::FromStr;
767778
use std::sync::{Arc, Mutex};
768779
use std::thread;
@@ -1383,6 +1394,24 @@ mod tests {
13831394
assert_eq!(config.blockchain_bridge_config.gas_price, 11);
13841395
}
13851396

1397+
#[test]
1398+
fn initialize_as_unprivileged_implements_panic_on_migration_for_make_and_start_actors() {
1399+
let _lock = INITIALIZATION.lock();
1400+
let data_dir = ensure_node_home_directory_exists(
1401+
"bootstrapper",
1402+
"initialize_as_unprivileged_implements_panic_on_migration_for_make_and_start_actors",
1403+
);
1404+
1405+
let act = |data_dir: &Path| {
1406+
let mut config = BootstrapperConfig::new();
1407+
config.data_directory = data_dir.to_path_buf();
1408+
let subject = BootstrapperBuilder::new().config(config).build();
1409+
subject.start_actors_and_return_shp_subs();
1410+
};
1411+
1412+
assert_on_initialization_with_panic_on_migration(&data_dir, &act);
1413+
}
1414+
13861415
#[test]
13871416
fn initialize_with_clandestine_port_produces_expected_clandestine_discriminator_factories_vector(
13881417
) {
@@ -2022,6 +2051,26 @@ mod tests {
20222051
.is_none());
20232052
}
20242053

2054+
#[test]
2055+
fn set_up_clandestine_port_panics_on_migration() {
2056+
let data_dir = ensure_node_home_directory_exists(
2057+
"bootstrapper",
2058+
"set_up_clandestine_port_panics_on_migration",
2059+
);
2060+
2061+
let act = |data_dir: &Path| {
2062+
let mut config = BootstrapperConfig::new();
2063+
config.data_directory = data_dir.to_path_buf();
2064+
config.neighborhood_config = NeighborhoodConfig {
2065+
mode: NeighborhoodMode::Standard(NodeAddr::default(), vec![], DEFAULT_RATE_PACK),
2066+
};
2067+
let mut subject = BootstrapperBuilder::new().config(config).build();
2068+
subject.set_up_clandestine_port();
2069+
};
2070+
2071+
assert_on_initialization_with_panic_on_migration(&data_dir, &act);
2072+
}
2073+
20252074
#[test]
20262075
#[should_panic(
20272076
expected = "Database is corrupt: error setting clandestine port: TransactionError"

node/src/daemon/setup_reporter.rs

+3-1
Original file line numberDiff line numberDiff line change
@@ -470,7 +470,9 @@ impl SetupReporterReal {
470470
}
471471
Err(InitializationError::Nonexistent | InitializationError::SuppressedMigration) => {
472472
// When the Daemon runs for the first time, the database will not yet have been
473-
// created. If the database is old, it should not be used by the Daemon.
473+
// created. If the database is old, it should not be used by the Daemon (see more
474+
// information at ConfigDaoNull).
475+
474476
let parse_args_configuration = UnprivilegedParseArgsConfigurationDaoNull {};
475477
let mut persistent_config =
476478
PersistentConfigurationReal::new(Box::new(ConfigDaoNull::default()));

node/src/database/db_initializer.rs

+2-6
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@ use crate::database::db_migrations::db_migrator::{DbMigrator, DbMigratorReal};
55
use crate::db_config::secure_config_layer::EXAMPLE_ENCRYPTED;
66
use crate::sub_lib::accountant::{DEFAULT_PAYMENT_THRESHOLDS, DEFAULT_SCAN_INTERVALS};
77
use crate::sub_lib::neighborhood::DEFAULT_RATE_PACK;
8+
use crate::sub_lib::utils::db_connection_launch_panic;
89
use masq_lib::blockchains::chains::Chain;
910
use masq_lib::constants::{
1011
DEFAULT_GAS_PRICE, HIGHEST_RANDOM_CLANDESTINE_PORT, LOWEST_USABLE_INSECURE_PORT,
@@ -488,12 +489,7 @@ pub fn connection_or_panic(
488489
) -> Box<dyn ConnectionWrapper> {
489490
db_initializer
490491
.initialize(path, init_config)
491-
.unwrap_or_else(|_| {
492-
panic!(
493-
"Failed to connect to database at {:?}",
494-
path.join(DATABASE_FILE)
495-
)
496-
})
492+
.unwrap_or_else(|err| db_connection_launch_panic(err, path))
497493
}
498494

499495
#[derive(Clone)]

0 commit comments

Comments
 (0)