Merge testutils crate into the main crate

This avoids having to keep the apis in sync between the macros and the
main project.
This commit is contained in:
LLFourn 2021-05-19 13:04:32 +10:00
parent fcae5adabd
commit d60c5003bf
No known key found for this signature in database
GPG Key ID: A27093B54DA11F65
11 changed files with 50 additions and 75 deletions

View File

@ -120,7 +120,7 @@ jobs:
- name: start ${{ matrix.blockchain.name }} - name: start ${{ matrix.blockchain.name }}
run: nohup ${{ matrix.blockchain.start }} & sleep 5 run: nohup ${{ matrix.blockchain.start }} & sleep 5
- name: Test - name: Test
run: $HOME/.cargo/bin/cargo test --features test-${{ matrix.blockchain.name }} --no-default-features ${{ matrix.blockchain.name }}::bdk_blockchain_tests run: $HOME/.cargo/bin/cargo test --features ${{ matrix.blockchain.name }},test-blockchains --no-default-features ${{ matrix.blockchain.name }}::bdk_blockchain_tests
check-wasm: check-wasm:
name: Check WASM name: Check WASM

View File

@ -32,6 +32,10 @@ socks = { version = "0.3", optional = true }
lazy_static = { version = "1.4", optional = true } lazy_static = { version = "1.4", optional = true }
tiny-bip39 = { version = "^0.8", optional = true } tiny-bip39 = { version = "^0.8", optional = true }
# Needed by bdk_blockchain_tests macro
bitcoincore-rpc = { version = "0.13", optional = true }
serial_test = { version = "0.4", optional = true }
# Platform-specific dependencies # Platform-specific dependencies
[target.'cfg(not(target_arch = "wasm32"))'.dependencies] [target.'cfg(not(target_arch = "wasm32"))'.dependencies]
tokio = { version = "1", features = ["rt"] } tokio = { version = "1", features = ["rt"] }
@ -54,17 +58,16 @@ all-keys = ["keys-bip39"]
keys-bip39 = ["tiny-bip39"] keys-bip39 = ["tiny-bip39"]
# Debug/Test features # Debug/Test features
test-electrum = ["electrum"] testutils = []
test-esplora = ["esplora"] test-blockchains = ["testutils", "bitcoincore-rpc", "electrum-client"]
test-md-docs = ["electrum"] test-md-docs = ["electrum"]
[dev-dependencies] [dev-dependencies]
bdk-testutils = { path = "./testutils" }
serial_test = "0.4"
lazy_static = "1.4" lazy_static = "1.4"
env_logger = "0.7" env_logger = "0.7"
base64 = "^0.11" base64 = "^0.11"
clap = "2.33" clap = "2.33"
serial_test = "0.4"
[[example]] [[example]]
name = "address_validator" name = "address_validator"
@ -78,10 +81,7 @@ path = "examples/compiler.rs"
required-features = ["compiler"] required-features = ["compiler"]
[workspace] [workspace]
members = ["macros", "testutils"] members = ["macros"]
# Generate docs with nightly to add the "features required" badge
# https://stackoverflow.com/questions/61417452/how-to-get-a-feature-requirement-tag-in-the-documentation-generated-by-cargo-do
[package.metadata.docs.rs] [package.metadata.docs.rs]
features = ["compiler", "electrum", "esplora", "compact_filters", "key-value-db", "all-keys"] features = ["compiler", "electrum", "esplora", "compact_filters", "key-value-db", "all-keys"]
# defines the configuration attribute `docsrs` # defines the configuration attribute `docsrs`

View File

@ -169,9 +169,8 @@ impl ConfigurableBlockchain for ElectrumBlockchain {
} }
} }
#[cfg(all(feature = "test-electrum", test))] #[cfg(feature = "test-blockchains")]
testutils::bdk_blockchain_tests! { crate::bdk_blockchain_tests! {
bdk => crate,
fn test_instance() -> ElectrumBlockchain { fn test_instance() -> ElectrumBlockchain {
ElectrumBlockchain::from(Client::new(&testutils::get_electrum_url()).unwrap()) ElectrumBlockchain::from(Client::new(&testutils::get_electrum_url()).unwrap())
} }

View File

@ -415,9 +415,8 @@ impl_error!(std::num::ParseIntError, Parsing, EsploraError);
impl_error!(consensus::encode::Error, BitcoinEncoding, EsploraError); impl_error!(consensus::encode::Error, BitcoinEncoding, EsploraError);
impl_error!(bitcoin::hashes::hex::Error, Hex, EsploraError); impl_error!(bitcoin::hashes::hex::Error, Hex, EsploraError);
#[cfg(all(feature = "test-esplora", test))] #[cfg(feature = "test-blockchains")]
testutils::bdk_blockchain_tests! { crate::bdk_blockchain_tests! {
bdk => crate,
fn test_instance() -> EsploraBlockchain { fn test_instance() -> EsploraBlockchain {
EsploraBlockchain::new(std::env::var("BDK_ESPLORA_URL").unwrap_or("127.0.0.1:3002".into()).as_str(), None) EsploraBlockchain::new(std::env::var("BDK_ESPLORA_URL").unwrap_or("127.0.0.1:3002".into()).as_str(), None)
} }

View File

@ -228,16 +228,12 @@ pub extern crate reqwest;
#[cfg(feature = "key-value-db")] #[cfg(feature = "key-value-db")]
pub extern crate sled; pub extern crate sled;
#[allow(unused_imports)]
#[cfg(test)]
#[macro_use]
extern crate testutils;
#[allow(unused_imports)] #[allow(unused_imports)]
#[cfg(test)] #[cfg(test)]
#[allow(unused_imports)] #[allow(unused_imports)]
#[cfg(test)] #[cfg(test)]
#[macro_use] #[macro_use]
extern crate serial_test; pub extern crate serial_test;
#[macro_use] #[macro_use]
pub(crate) mod error; pub(crate) mod error;
@ -265,3 +261,6 @@ pub use wallet::Wallet;
pub fn version() -> &'static str { pub fn version() -> &'static str {
env!("CARGO_PKG_VERSION", "unknown") env!("CARGO_PKG_VERSION", "unknown")
} }
#[cfg(any(feature = "testutils", test))]
pub mod testutils;

View File

@ -3,18 +3,19 @@
/// the setup required to run the tests yourself. /// the setup required to run the tests yourself.
#[macro_export] #[macro_export]
macro_rules! bdk_blockchain_tests { macro_rules! bdk_blockchain_tests {
(bdk => $bdk:ident, (
fn test_instance() -> $blockchain:ty $block:block) => { fn test_instance() -> $blockchain:ty $block:block) => {
#[cfg(test)]
mod bdk_blockchain_tests { mod bdk_blockchain_tests {
use $bdk::bitcoin::Network; use $crate::bitcoin::Network;
use $bdk::miniscript::Descriptor; use $crate::testutils::{TestClient};
use $crate::{TestClient, serial}; use $crate::blockchain::noop_progress;
use $bdk::blockchain::{Blockchain, noop_progress}; use $crate::database::MemoryDatabase;
use $bdk::descriptor::ExtendedDescriptor; use $crate::types::KeychainKind;
use $bdk::database::MemoryDatabase; use $crate::{Wallet, FeeRate};
use $bdk::types::KeychainKind; use $crate::wallet::AddressIndex::New;
use $bdk::{Wallet, TxBuilder, FeeRate}; use $crate::testutils;
use $bdk::wallet::AddressIndex::New; use $crate::serial_test::serial;
use super::*; use super::*;
@ -195,7 +196,7 @@ macro_rules! bdk_blockchain_tests {
// FIXME: I would like this to be cfg_attr(not(feature = "test-esplora"), ignore) but it // FIXME: I would like this to be cfg_attr(not(feature = "test-esplora"), ignore) but it
// doesn't work for some reason. // doesn't work for some reason.
#[cfg(not(feature = "test-esplora"))] #[cfg(not(feature = "esplora"))]
#[test] #[test]
#[serial] #[serial]
fn test_sync_reorg_block() { fn test_sync_reorg_block() {
@ -478,7 +479,7 @@ macro_rules! bdk_blockchain_tests {
#[test] #[test]
#[serial] #[serial]
fn test_sync_receive_coinbase() { fn test_sync_receive_coinbase() {
let (wallet, descriptors, mut test_client) = init_single_sig(); let (wallet, _, mut test_client) = init_single_sig();
let wallet_addr = wallet.get_address(New).unwrap(); let wallet_addr = wallet.get_address(New).unwrap();
wallet.sync(noop_progress(), None).unwrap(); wallet.sync(noop_progress(), None).unwrap();

View File

@ -8,12 +8,11 @@
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your option. // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your option.
// You may not use this file except in accordance with one or both of these // You may not use this file except in accordance with one or both of these
// licenses. // licenses.
#![allow(missing_docs)]
#[macro_use]
extern crate serde_json;
mod blockchain_tests; mod blockchain_tests;
pub use serial_test::serial; // pub use serial_test::serial;
use std::collections::HashMap; use std::collections::HashMap;
use std::env; use std::env;
@ -138,13 +137,14 @@ impl TranslateDescriptor for Descriptor<DescriptorPublicKey> {
} }
} }
#[doc(hidden)]
#[macro_export] #[macro_export]
macro_rules! testutils { macro_rules! testutils {
( @external $descriptors:expr, $child:expr ) => ({ ( @external $descriptors:expr, $child:expr ) => ({
use bitcoin::secp256k1::Secp256k1; use bitcoin::secp256k1::Secp256k1;
use miniscript::descriptor::{Descriptor, DescriptorPublicKey, DescriptorTrait}; use miniscript::descriptor::{Descriptor, DescriptorPublicKey, DescriptorTrait};
use $crate::TranslateDescriptor; use $crate::testutils::TranslateDescriptor;
let secp = Secp256k1::new(); let secp = Secp256k1::new();
@ -155,7 +155,7 @@ macro_rules! testutils {
use bitcoin::secp256k1::Secp256k1; use bitcoin::secp256k1::Secp256k1;
use miniscript::descriptor::{Descriptor, DescriptorPublicKey, DescriptorTrait}; use miniscript::descriptor::{Descriptor, DescriptorPublicKey, DescriptorTrait};
use $crate::TranslateDescriptor; use $crate::testutils::TranslateDescriptor;
let secp = Secp256k1::new(); let secp = Secp256k1::new();
@ -167,25 +167,27 @@ macro_rules! testutils {
( @tx ( $( ( $( $addr:tt )* ) => $amount:expr ),+ ) $( ( @locktime $locktime:expr ) )* $( ( @confirmations $confirmations:expr ) )* $( ( @replaceable $replaceable:expr ) )* ) => ({ ( @tx ( $( ( $( $addr:tt )* ) => $amount:expr ),+ ) $( ( @locktime $locktime:expr ) )* $( ( @confirmations $confirmations:expr ) )* $( ( @replaceable $replaceable:expr ) )* ) => ({
let mut outs = Vec::new(); let mut outs = Vec::new();
$( outs.push(testutils::TestIncomingOutput::new($amount, testutils!( $($addr)* ))); )+ $( outs.push($crate::testutils::TestIncomingOutput::new($amount, testutils!( $($addr)* ))); )+
#[allow(unused_mut)]
let mut locktime = None::<i64>; let mut locktime = None::<i64>;
$( locktime = Some($locktime); )* $( locktime = Some($locktime); )*
#[allow(unused_assignments, unused_mut)]
let mut min_confirmations = None::<u64>; let mut min_confirmations = None::<u64>;
$( min_confirmations = Some($confirmations); )* $( min_confirmations = Some($confirmations); )*
#[allow(unused_assignments, unused_mut)]
let mut replaceable = None::<bool>; let mut replaceable = None::<bool>;
$( replaceable = Some($replaceable); )* $( replaceable = Some($replaceable); )*
testutils::TestIncomingTx::new(outs, min_confirmations, locktime, replaceable) $crate::testutils::TestIncomingTx::new(outs, min_confirmations, locktime, replaceable)
}); });
( @literal $key:expr ) => ({ ( @literal $key:expr ) => ({
let key = $key.to_string(); let key = $key.to_string();
(key, None::<String>, None::<String>) (key, None::<String>, None::<String>)
}); });
( @generate_xprv $( $external_path:expr )* $( ,$internal_path:expr )* ) => ({ ( @generate_xprv $( $external_path:expr )? $( ,$internal_path:expr )? ) => ({
use rand::Rng; use rand::Rng;
let mut seed = [0u8; 32]; let mut seed = [0u8; 32];
@ -196,11 +198,13 @@ macro_rules! testutils {
&seed, &seed,
); );
#[allow(unused_assignments)]
let mut external_path = None::<String>; let mut external_path = None::<String>;
$( external_path = Some($external_path.to_string()); )* $( external_path = Some($external_path.to_string()); )?
#[allow(unused_assignments)]
let mut internal_path = None::<String>; let mut internal_path = None::<String>;
$( internal_path = Some($internal_path.to_string()); )* $( internal_path = Some($internal_path.to_string()); )?
(key.unwrap().to_string(), external_path, internal_path) (key.unwrap().to_string(), external_path, internal_path)
}); });
@ -230,11 +234,10 @@ macro_rules! testutils {
( @descriptors ( $external_descriptor:expr ) $( ( $internal_descriptor:expr ) )* $( ( @keys $( $keys:tt )* ) )* ) => ({ ( @descriptors ( $external_descriptor:expr ) $( ( $internal_descriptor:expr ) )* $( ( @keys $( $keys:tt )* ) )* ) => ({
use std::str::FromStr; use std::str::FromStr;
use std::collections::HashMap; use std::collections::HashMap;
use std::convert::TryInto; use miniscript::descriptor::Descriptor;
use miniscript::descriptor::{Descriptor, DescriptorPublicKey};
use miniscript::TranslatePk; use miniscript::TranslatePk;
#[allow(unused_assignments, unused_mut)]
let mut keys: HashMap<&'static str, (String, Option<String>, Option<String>)> = HashMap::new(); let mut keys: HashMap<&'static str, (String, Option<String>, Option<String>)> = HashMap::new();
$( $(
keys = testutils!{ @keys $( $keys )* }; keys = testutils!{ @keys $( $keys )* };
@ -257,6 +260,7 @@ macro_rules! testutils {
}); });
let external = external.to_string(); let external = external.to_string();
#[allow(unused_assignments, unused_mut)]
let mut internal = None::<String>; let mut internal = None::<String>;
$( $(
let string_internal: Descriptor<String> = FromStr::from_str($internal_descriptor).unwrap(); let string_internal: Descriptor<String> = FromStr::from_str($internal_descriptor).unwrap();

View File

@ -146,7 +146,7 @@ mod test {
let (mut wallet, descriptors, _) = get_funded_wallet(get_test_wpkh()); let (mut wallet, descriptors, _) = get_funded_wallet(get_test_wpkh());
wallet.add_address_validator(Arc::new(TestValidator)); wallet.add_address_validator(Arc::new(TestValidator));
let addr = testutils!(@external descriptors, 10); let addr = crate::testutils!(@external descriptors, 10);
let mut builder = wallet.build_tx(); let mut builder = wallet.build_tx();
builder.add_recipient(addr.script_pubkey(), 25_000); builder.add_recipient(addr.script_pubkey(), 25_000);
builder.finish().unwrap(); builder.finish().unwrap();

View File

@ -1515,6 +1515,7 @@ pub(crate) mod test {
use crate::types::KeychainKind; use crate::types::KeychainKind;
use super::*; use super::*;
use crate::testutils;
use crate::wallet::AddressIndex::{LastUnused, New, Peek, Reset}; use crate::wallet::AddressIndex::{LastUnused, New, Peek, Reset};
#[test] #[test]

View File

@ -1,2 +0,0 @@
target/
Cargo.lock

View File

@ -1,26 +0,0 @@
[package]
name = "bdk-testutils"
version = "0.4.0"
authors = ["Alekos Filini <alekos.filini@gmail.com>"]
edition = "2018"
homepage = "https://bitcoindevkit.org"
repository = "https://github.com/bitcoindevkit/bdk"
documentation = "https://docs.rs/bdk-testutils"
description = "Supporting testing utilities for `bdk`"
keywords = ["bdk"]
license = "MIT OR Apache-2.0"
[lib]
name = "testutils"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]
log = "0.4.8"
serde = { version = "1.0", features = ["derive"] }
serde_json = "1.0"
serial_test = "0.4"
bitcoin = "0.26"
bitcoincore-rpc = "0.13"
miniscript = "5.1"
electrum-client = "0.6.0"