Skip to content

Commit

Permalink
tests: Move mock code to tests/common dir.
Browse files Browse the repository at this point in the history
  • Loading branch information
ceyhunsen committed Oct 3, 2024
1 parent e493986 commit 3d5c561
Show file tree
Hide file tree
Showing 21 changed files with 159 additions and 160 deletions.
2 changes: 1 addition & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
[workspace]
resolver = "2"
members = ["core", "mock"] # TODO: Add "circuits" back later
members = ["core"] # TODO: Add "circuits" back later

[workspace.dependencies]
bitcoin = "0.32.2"
Expand Down
3 changes: 0 additions & 3 deletions core/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -29,9 +29,6 @@ sqlx = { workspace = true, features = ["runtime-tokio", "postgres", "macros"] }
bitcoin-mock-rpc = { workspace = true }
musig2 = { workspace = true }

[dev-dependencies]
mock = { path = "../mock" }

[features]
default = []
mock_rpc = []
Expand Down
1 change: 0 additions & 1 deletion core/src/database/common.rs
Original file line number Diff line number Diff line change
Expand Up @@ -588,7 +588,6 @@ impl Database {
mod tests {
use super::Database;
use crate::{
mock::database::create_test_config_with_thread_name,
musig2::{nonce_pair, MuSigAggNonce, MuSigPubNonce, MuSigSecNonce},
ByteArray32, EVMAddress, UTXO,
};
Expand Down
5 changes: 1 addition & 4 deletions core/src/database/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -92,10 +92,7 @@ impl Database {

#[cfg(test)]
mod tests {
use crate::{
config::BridgeConfig, database::Database,
mock::database::create_test_config_with_thread_name,
};
use crate::{config::BridgeConfig, database::Database};

#[tokio::test]
async fn valid_database_connection() {
Expand Down
1 change: 0 additions & 1 deletion core/src/operator.rs
Original file line number Diff line number Diff line change
Expand Up @@ -702,7 +702,6 @@ where
#[cfg(test)]
mod tests {
use crate::{
create_extended_rpc, extended_rpc::ExtendedRpc, mock::database::create_test_config,
operator::Operator, servers::create_operator_server, traits::rpc::OperatorRpcClient, UTXO,
};
use bitcoin::{hashes::Hash, Amount, OutPoint, ScriptBuf, TxOut, Txid};
Expand Down
6 changes: 0 additions & 6 deletions core/src/servers.rs
Original file line number Diff line number Diff line change
Expand Up @@ -105,9 +105,3 @@ pub async fn create_aggregator_server(

Ok((client, handle, addr))
}

#[tracing::instrument(ret(level = tracing::Level::TRACE))]
fn is_test_env() -> bool {
// if thread name is not main then it is a test
thread::current().name().unwrap_or_default() != "main"
}
1 change: 0 additions & 1 deletion core/src/user.rs
Original file line number Diff line number Diff line change
Expand Up @@ -119,7 +119,6 @@ mod tests {
use crate::extended_rpc::ExtendedRpc;
use crate::user::User;
use crate::EVMAddress;
use crate::{create_extended_rpc, mock::database::create_test_config};
use secp256k1::{rand, SecretKey};

#[tokio::test]
Expand Down
2 changes: 0 additions & 2 deletions core/src/verifier.rs
Original file line number Diff line number Diff line change
Expand Up @@ -585,12 +585,10 @@ where
mod tests {
use crate::actor::Actor;
use crate::errors::BridgeError;
use crate::extended_rpc::ExtendedRpc;
use crate::musig2::nonce_pair;
use crate::user::User;
use crate::verifier::Verifier;
use crate::EVMAddress;
use crate::{create_extended_rpc, mock::database::create_test_config};
use secp256k1::rand;

#[tokio::test]
Expand Down
99 changes: 99 additions & 0 deletions core/tests/common/common.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,99 @@
//! # Common Test Utilities
//!
//! This file includes common functions/variables for tests.
use clementine_core::{config::BridgeConfig, errors::BridgeError};
use std::{env, net::TcpListener};

pub const ENV_CONF_FILE: &str = "TEST_CONFIG";

/// Returns configuration, read from configuration file which is specified from
/// either an environment variable or the function argument. Environment
/// variable is priotirized over the function argument `configuration_file`.
pub fn get_test_config(configuration_file: &str) -> Result<BridgeConfig, BridgeError> {
let env_config: Option<BridgeConfig> = if let Ok(config_file_path) = env::var(ENV_CONF_FILE) {
Some(BridgeConfig::try_parse_file(config_file_path.into())?)
} else {
None
};

// Read specified configuration file from `tests/data` directory.
let mut config = match BridgeConfig::try_parse_file(
format!(
"{}/tests/data/{}",
env!("CARGO_MANIFEST_DIR"),
configuration_file
)
.into(),
) {
Ok(c) => c,
Err(e) => return Err(e),
};

// Overwrite user's environment to test's hard coded data if environment
// file is specified.
if let Some(env_config) = env_config {
config.db_host = env_config.db_host;
config.db_port = env_config.db_port;
config.db_user = env_config.db_user;
config.db_password = env_config.db_password;
config.db_name = env_config.db_name;
};

#[cfg(test)]
{
config.port = 0;
}

Ok(config)
}

/// Finds consecutive idle ports starting from the given port, up to count num.
pub fn find_consecutive_idle_ports(port: u16, num: usize) -> Result<u16, BridgeError> {
let mut idle_ports = Vec::new();
let mut current_port = port;

while current_port < 65535 {
match TcpListener::bind(("0.0.0.0", current_port)) {
Ok(_) => {
idle_ports.push(current_port);
current_port += 1;
if idle_ports.len() == num + 1 {
break;
}
tracing::debug!(
"Ports {:?}-{:?} are available.",
current_port,
current_port + num as u16
);
}
Err(_e) => {
idle_ports.clear();
if current_port < port + num as u16 {
tracing::debug!(
"Ports {:?}-{:?} are not available. Searching for new ports...",
current_port,
current_port + num as u16
);
}
current_port += 1;
}
}
}

if idle_ports.len() == num + 1 {
Ok(idle_ports[0])
} else {
Err(BridgeError::PortError(
"No consecutive idle ports found".to_string(),
))
}
}

mod tests {
#[tokio::test]
async fn ports() {
let res = super::find_consecutive_idle_ports(0, 5).unwrap();
println!("{:?}", res);
}
}
21 changes: 15 additions & 6 deletions mock/src/database.rs → core/tests/common/database.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,10 @@
//!
//! This module provides mock database interfaces, for testing.
use clementine_core::{
config::BridgeConfig, database::Database, errors::BridgeError, utils::initialize_logger,
};

use super::common;
use std::thread;

Expand Down Expand Up @@ -113,10 +117,17 @@ async fn drop_database(config: &BridgeConfig) -> Result<(), BridgeError> {
Ok(())
}

#[cfg(test)]
mod tests {
use crate::common::{
common::get_test_config,
database::{self, create_database, drop_database},
};
use clementine_core::database::Database;

#[tokio::test]
async fn create_drop_database() {
let mut config = common::get_test_config("test_config.toml").unwrap();
let mut config = get_test_config("test_config.toml").unwrap();
config.db_name = "create_drop_database".to_string();

// Drop database (clear previous test run artifacts) and check that
Expand All @@ -135,8 +146,8 @@ mod tests {
}

#[tokio::test]
async fn test_initialize_database() {
let mut config = common::get_test_config("test_config.toml").unwrap();
async fn initialize_database() {
let mut config = get_test_config("test_config.toml").unwrap();
config.db_name = "initialize_database".to_string();

// Drop database (clear previous test run artifacts) and check that
Expand All @@ -145,9 +156,7 @@ mod tests {
assert!(Database::new(&config).await.is_err());

// It should be possible to initialize and connect to the new database.
crate::mock::database::initialize_database(&config)
.await
.unwrap();
database::initialize_database(&config).await.unwrap();
Database::new(&config).await.unwrap();

// Dropping database again should result connection to not be
Expand Down
7 changes: 5 additions & 2 deletions core/tests/common/deposit.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
//! # Deposit Related Utilities
use crate::common::mock::database::create_test_config_with_thread_name;
use crate::common::create_verifiers_and_operators;
use crate::common::database::create_test_config_with_thread_name;
use crate::create_extended_rpc;
use bitcoin::consensus::encode::deserialize_hex;
use bitcoin::Address;
Expand All @@ -11,7 +12,9 @@ use clementine_core::actor::Actor;
use clementine_core::config::BridgeConfig;
use clementine_core::errors::BridgeError;
use clementine_core::musig2::MuSigPartialSignature;
use clementine_core::servers::create_verifiers_and_operators;
use clementine_core::traits::rpc::AggregatorClient;
use clementine_core::traits::rpc::OperatorRpcClient;
use clementine_core::traits::rpc::VerifierRpcClient;
use clementine_core::user::User;
use clementine_core::EVMAddress;
use jsonrpsee::http_client::HttpClient;
Expand Down
File renamed without changes.
10 changes: 10 additions & 0 deletions core/tests/common/mod.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,15 @@
//! # Common Utilities for Integration Tests
mod common;
mod database;
mod deposit;
mod env;
mod rpc;
mod server;

pub use common::*;
pub use database::*;
pub use deposit::*;
pub use env::*;
pub use rpc::*;
pub use server::*;
4 changes: 2 additions & 2 deletions mock/src/rpc.rs → core/tests/common/rpc.rs
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ macro_rules! create_extended_rpc {

$config.bitcoin_rpc_url = handle.to_string();

ExtendedRpc::<bitcoin_mock_rpc::Client>::new(
clementine_core::extended_rpc::ExtendedRpc::<bitcoin_mock_rpc::Client>::new(
$config.bitcoin_rpc_url.clone(),
$config.bitcoin_rpc_user.clone(),
$config.bitcoin_rpc_password.clone(),
Expand All @@ -49,7 +49,7 @@ macro_rules! create_extended_rpc {
// Mutation for consistency with above defined macro
$config.bitcoin_rpc_url = $config.bitcoin_rpc_url.clone();

ExtendedRpc::<bitcoincore_rpc::Client>::new(
clementine_core::extended_rpc::ExtendedRpc::<bitcoincore_rpc::Client>::new(
$config.bitcoin_rpc_url.clone(),
$config.bitcoin_rpc_user.clone(),
$config.bitcoin_rpc_password.clone(),
Expand Down
Loading

0 comments on commit 3d5c561

Please sign in to comment.