-
Notifications
You must be signed in to change notification settings - Fork 43
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Expose test helpers #484
Merged
+326
−427
Merged
Expose test helpers #484
Changes from 1 commit
Commits
Show all changes
5 commits
Select commit
Hold shift + click to select a range
424af98
Expose payjoin-test-utils as a standalone crate
spacebear21 d2e9f35
Consume test_utils in integration/e2e tests
spacebear21 505d5e7
Ignore unused test, don't just TODO it
DanGould 4c6e920
Introduce TestServices helper
spacebear21 9a017bc
Add http_agent to TestServices and fetch ohttp keys
spacebear21 File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,25 @@ | ||
[package] | ||
name = "payjoin-test-utils" | ||
version = "0.1.0" | ||
edition = "2021" | ||
authors = ["Dan Gould <[email protected]>"] | ||
rust-version = "1.63" | ||
license = "MIT" | ||
|
||
[dependencies] | ||
bitcoin = { version = "0.32.5", features = ["base64"] } | ||
bitcoincore-rpc = "0.19.0" | ||
bitcoind = { version = "0.36.0", features = ["0_21_2"] } | ||
http = "1" | ||
log = "0.4.7" | ||
ohttp-relay = { version = "0.0.9", features = ["_test-util"] } | ||
once_cell = "1" | ||
payjoin-directory = { path = "../payjoin-directory", features = ["_danger-local-https"] } | ||
rcgen = "0.11" | ||
reqwest = { version = "0.12", default-features = false, features = ["rustls-tls"] } | ||
testcontainers = "0.15.0" | ||
testcontainers-modules = { version = "0.1.3", features = ["redis"] } | ||
tokio = { version = "1.12.0", features = ["full"] } | ||
tracing = "0.1.40" | ||
tracing-subscriber = { version = "0.3.17", features = ["env-filter"] } | ||
url = "2.2.2" |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,116 @@ | ||
use std::env; | ||
use std::sync::Arc; | ||
use std::time::Duration; | ||
|
||
use bitcoin::Amount; | ||
use bitcoind::bitcoincore_rpc::json::AddressType; | ||
use bitcoind::bitcoincore_rpc::{self, RpcApi}; | ||
use http::StatusCode; | ||
use log::{log_enabled, Level}; | ||
use once_cell::sync::OnceCell; | ||
use reqwest::{Client, ClientBuilder}; | ||
use tracing_subscriber::{EnvFilter, FmtSubscriber}; | ||
use url::Url; | ||
|
||
pub type BoxError = Box<dyn std::error::Error + 'static>; | ||
pub type BoxSendSyncError = Box<dyn std::error::Error + Send + Sync>; | ||
|
||
static INIT_TRACING: OnceCell<()> = OnceCell::new(); | ||
|
||
pub fn init_tracing() { | ||
INIT_TRACING.get_or_init(|| { | ||
let subscriber = FmtSubscriber::builder() | ||
.with_env_filter(EnvFilter::from_default_env()) | ||
.with_test_writer() | ||
.finish(); | ||
|
||
tracing::subscriber::set_global_default(subscriber) | ||
.expect("failed to set global default subscriber"); | ||
}); | ||
} | ||
|
||
pub async fn init_directory( | ||
db_host: String, | ||
local_cert_key: (Vec<u8>, Vec<u8>), | ||
) -> std::result::Result< | ||
(u16, tokio::task::JoinHandle<std::result::Result<(), BoxSendSyncError>>), | ||
BoxSendSyncError, | ||
> { | ||
println!("Database running on {}", db_host); | ||
let timeout = Duration::from_secs(2); | ||
payjoin_directory::listen_tcp_with_tls_on_free_port(db_host, timeout, local_cert_key).await | ||
} | ||
|
||
// generates or gets a DER encoded localhost cert and key. | ||
pub fn local_cert_key() -> (Vec<u8>, Vec<u8>) { | ||
let cert = | ||
rcgen::generate_simple_self_signed(vec!["0.0.0.0".to_string(), "localhost".to_string()]) | ||
.expect("Failed to generate cert"); | ||
let cert_der = cert.serialize_der().expect("Failed to serialize cert"); | ||
let key_der = cert.serialize_private_key_der(); | ||
(cert_der, key_der) | ||
} | ||
|
||
pub fn init_bitcoind_sender_receiver( | ||
sender_address_type: Option<AddressType>, | ||
receiver_address_type: Option<AddressType>, | ||
) -> Result<(bitcoind::BitcoinD, bitcoincore_rpc::Client, bitcoincore_rpc::Client), BoxError> { | ||
let bitcoind_exe = | ||
env::var("BITCOIND_EXE").ok().or_else(|| bitcoind::downloaded_exe_path().ok()).unwrap(); | ||
let mut conf = bitcoind::Conf::default(); | ||
conf.view_stdout = log_enabled!(Level::Debug); | ||
let bitcoind = bitcoind::BitcoinD::with_conf(bitcoind_exe, &conf)?; | ||
let receiver = bitcoind.create_wallet("receiver")?; | ||
let receiver_address = receiver.get_new_address(None, receiver_address_type)?.assume_checked(); | ||
let sender = bitcoind.create_wallet("sender")?; | ||
let sender_address = sender.get_new_address(None, sender_address_type)?.assume_checked(); | ||
bitcoind.client.generate_to_address(1, &receiver_address)?; | ||
bitcoind.client.generate_to_address(101, &sender_address)?; | ||
|
||
assert_eq!( | ||
Amount::from_btc(50.0)?, | ||
receiver.get_balances()?.mine.trusted, | ||
"receiver doesn't own bitcoin" | ||
); | ||
|
||
assert_eq!( | ||
Amount::from_btc(50.0)?, | ||
sender.get_balances()?.mine.trusted, | ||
"sender doesn't own bitcoin" | ||
); | ||
Ok((bitcoind, sender, receiver)) | ||
} | ||
|
||
pub fn http_agent(cert_der: Vec<u8>) -> Result<Client, BoxError> { | ||
Ok(http_agent_builder(cert_der)?.build()?) | ||
} | ||
|
||
fn http_agent_builder(cert_der: Vec<u8>) -> Result<ClientBuilder, BoxError> { | ||
Ok(ClientBuilder::new() | ||
.danger_accept_invalid_certs(true) | ||
.use_rustls_tls() | ||
.add_root_certificate(reqwest::tls::Certificate::from_der(cert_der.as_slice()).unwrap())) | ||
} | ||
|
||
const TESTS_TIMEOUT: Duration = Duration::from_secs(20); | ||
const WAIT_SERVICE_INTERVAL: Duration = Duration::from_secs(3); | ||
|
||
pub async fn wait_for_service_ready( | ||
service_url: Url, | ||
agent: Arc<Client>, | ||
) -> Result<(), &'static str> { | ||
let health_url = service_url.join("/health").map_err(|_| "Invalid URL")?; | ||
let start = std::time::Instant::now(); | ||
|
||
while start.elapsed() < TESTS_TIMEOUT { | ||
let request_result = | ||
agent.get(health_url.as_str()).send().await.map_err(|_| "Bad request")?; | ||
match request_result.status() { | ||
StatusCode::OK => return Ok(()), | ||
StatusCode::NOT_FOUND => return Err("Endpoint not found"), | ||
_ => std::thread::sleep(WAIT_SERVICE_INTERVAL), | ||
} | ||
} | ||
|
||
Err("Timeout waiting for service to be ready") | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
You didn't introduce it but this should be a docstring with
///
prefix