Skip to content

Commit 57ae9bf

Browse files
authored
Merge pull request #13 from buffrr/testutil
Create test harness
2 parents 2051713 + c9db1a6 commit 57ae9bf

File tree

13 files changed

+608
-172
lines changed

13 files changed

+608
-172
lines changed

Cargo.lock

Lines changed: 12 additions & 3 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

Cargo.toml

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
11
[workspace]
22

33
resolver = "2"
4-
members = [ "node", "protocol", "wallet"]
4+
members = [ "node", "protocol", "testutil", "wallet"]

node/Cargo.toml

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -39,5 +39,5 @@ threadpool = "1.8.1"
3939

4040
[dev-dependencies]
4141
assert_cmd = "2.0.16"
42-
bitcoind = { version = "0.36.0", features = ["26_0"] }
4342
predicates = "3.1.2"
43+
testutil = { path = "../testutil" }

node/src/lib.rs

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,9 @@
11
extern crate core;
22

3+
// needed for testutil
4+
pub extern crate jsonrpsee;
5+
pub extern crate log;
6+
37
pub mod config;
48
pub mod node;
59
pub mod rpc;

node/src/rpc.rs

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -52,7 +52,7 @@ pub(crate) type Responder<T> = oneshot::Sender<T>;
5252
#[derive(Debug, Clone, Serialize, Deserialize)]
5353
pub struct ServerInfo {
5454
pub chain: ExtendedNetwork,
55-
tip: ChainAnchor,
55+
pub tip: ChainAnchor,
5656
}
5757

5858
pub enum ChainStateCommand {
@@ -380,13 +380,14 @@ impl WalletManager {
380380

381381
// Use testnet in the wallet if regtest is specified to work around
382382
// a bug in bdk comparing regtest descriptors
383+
// TODO: might have been fixed already?
383384
ExtendedNetwork::Regtest => {
384385
genesis_hash = Some(
385386
bdk::bitcoin::constants::genesis_block(Regtest)
386387
.header
387388
.block_hash(),
388389
);
389-
Network::Testnet
390+
Network::Regtest
390391
}
391392
ExtendedNetwork::Signet => {
392393
genesis_hash = Some(

node/src/wallets.rs

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -94,16 +94,16 @@ pub enum AddressKind {
9494

9595
#[derive(Debug, Clone, Serialize, Deserialize)]
9696
pub struct ConfirmedBalance {
97-
total: Amount,
98-
spendable: Amount,
99-
immature: Amount,
100-
locked: Amount,
97+
pub total: Amount,
98+
pub spendable: Amount,
99+
pub immature: Amount,
100+
pub locked: Amount,
101101
}
102102

103103
#[derive(Debug, Clone, Serialize, Deserialize)]
104104
pub struct UnconfirmedBalance {
105-
total: Amount,
106-
locked: Amount,
105+
pub total: Amount,
106+
pub locked: Amount,
107107
}
108108

109109
#[derive(Debug, Clone, Serialize, Deserialize)]

node/tests/fetcher_tests.rs

Lines changed: 49 additions & 60 deletions
Original file line numberDiff line numberDiff line change
@@ -1,71 +1,60 @@
1-
pub mod utils;
1+
use std::{
2+
sync::mpsc::TryRecvError,
3+
time::{Duration, Instant},
4+
};
25

3-
#[cfg(test)]
4-
mod tests {
5-
use std::{
6-
sync::mpsc::TryRecvError,
7-
time::{Duration, Instant},
8-
};
6+
use anyhow::Result;
7+
use protocol::{bitcoin::BlockHash, constants::ChainAnchor};
8+
use reqwest::blocking::Client;
9+
use spaced::source::{BitcoinRpc, BitcoinRpcAuth, BlockEvent, BlockFetcher};
10+
use testutil::TestRig;
911

10-
use crate::utils::SpaceD;
11-
use anyhow::Result;
12-
use bitcoind::bitcoincore_rpc::RpcApi;
13-
use protocol::constants::ChainAnchor;
14-
use reqwest::blocking::Client;
15-
use spaced::source::{BitcoinRpc, BitcoinRpcAuth, BlockEvent, BlockFetcher};
16-
use wallet::bitcoin::Network;
12+
async fn setup(blocks: u64) -> Result<(TestRig, u64, BlockHash)> {
13+
let rig = TestRig::new().await?;
14+
rig.mine_blocks(blocks as _, None).await?;
15+
let height = 0;
16+
let hash = rig.get_block_hash(height).await?;
17+
Ok((rig, height, hash))
18+
}
1719

18-
#[test]
19-
fn test_block_fetching_from_bitcoin_rpc() -> Result<()> {
20-
let spaced = SpaceD::new()?;
21-
let fetcher_rpc = BitcoinRpc::new(
22-
&spaced.bitcoind.rpc_url(),
23-
BitcoinRpcAuth::UserPass("user".to_string(), "password".to_string()),
24-
);
25-
let miner_addr = spaced
26-
.bitcoind
27-
.client
28-
.get_new_address(None, None)?
29-
.require_network(Network::Regtest)?;
30-
const GENERATED_BLOCKS: u32 = 10;
31-
spaced
32-
.bitcoind
33-
.client
34-
.generate_to_address(GENERATED_BLOCKS as u64, &miner_addr)?;
20+
#[test]
21+
fn test_block_fetching_from_bitcoin_rpc() -> Result<()> {
22+
const GENERATED_BLOCKS: u64 = 10;
3523

36-
let client = Client::new();
37-
let (fetcher, receiver) = BlockFetcher::new(fetcher_rpc.clone(), client.clone(), 8);
38-
fetcher.start(ChainAnchor {
39-
hash: fetcher_rpc.send_json_blocking(&client, &fetcher_rpc.get_block_hash(0))?,
40-
height: 0,
41-
});
24+
let (rig, mut height, hash) = tokio::runtime::Runtime::new()?
25+
.block_on(setup(GENERATED_BLOCKS))?;
26+
let fetcher_rpc = BitcoinRpc::new(
27+
&rig.bitcoind.rpc_url(),
28+
BitcoinRpcAuth::UserPass("user".to_string(), "password".to_string()),
29+
);
4230

43-
let mut start_block = 0;
44-
let timeout = Duration::from_secs(5);
45-
let start_time = Instant::now();
31+
let client = Client::new();
32+
let (fetcher, receiver) = BlockFetcher::new(fetcher_rpc.clone(), client.clone(), 8);
4633

47-
loop {
48-
if start_time.elapsed() > timeout {
49-
panic!("Test timed out after {:?}", timeout);
50-
}
51-
match receiver.try_recv() {
52-
Ok(BlockEvent::Block(id, _)) => {
53-
start_block += 1;
54-
if id.height == GENERATED_BLOCKS {
55-
break;
56-
}
57-
}
58-
Ok(BlockEvent::Error(e)) => panic!("Unexpected error: {}", e),
59-
Err(TryRecvError::Empty) => {
60-
std::thread::sleep(Duration::from_millis(10));
34+
fetcher.start(ChainAnchor { hash, height: 0 });
35+
36+
let timeout = Duration::from_secs(5);
37+
let start_time = Instant::now();
38+
39+
loop {
40+
if start_time.elapsed() > timeout {
41+
panic!("Test timed out after {:?}", timeout);
42+
}
43+
match receiver.try_recv() {
44+
Ok(BlockEvent::Block(id, _)) => {
45+
height += 1;
46+
if id.height == GENERATED_BLOCKS as u32 {
47+
break;
6148
}
62-
Err(TryRecvError::Disconnected) => panic!("Disconnected unexpectedly"),
6349
}
50+
Ok(BlockEvent::Error(e)) => panic!("Unexpected error: {}", e),
51+
Err(TryRecvError::Empty) => {
52+
std::thread::sleep(Duration::from_millis(10));
53+
}
54+
Err(TryRecvError::Disconnected) => panic!("Disconnected unexpectedly"),
6455
}
65-
assert_eq!(
66-
start_block, GENERATED_BLOCKS,
67-
"Not all blocks were received"
68-
);
69-
Ok(())
7056
}
57+
58+
assert_eq!(height, GENERATED_BLOCKS, "Not all blocks were received");
59+
Ok(())
7160
}

node/tests/space_cli_tests.rs

Lines changed: 24 additions & 29 deletions
Original file line numberDiff line numberDiff line change
@@ -1,34 +1,29 @@
1-
pub mod utils;
1+
use std::process::Command;
22

3-
#[cfg(test)]
4-
mod tests {
5-
use crate::utils::SpaceD;
6-
use anyhow::Result;
7-
use assert_cmd::prelude::*;
8-
use predicates::prelude::*;
9-
use serde_json::from_str;
10-
use spaced::config::ExtendedNetwork;
11-
use spaced::rpc::ServerInfo;
12-
use std::process::Command;
3+
use anyhow::Result;
4+
use assert_cmd::prelude::*;
5+
use predicates::prelude::*;
6+
use serde_json::from_str;
7+
use spaced::{config::ExtendedNetwork, rpc::ServerInfo};
8+
use testutil::TestRig;
139

14-
#[tokio::test]
15-
async fn test_get_server_info() -> Result<()> {
16-
env_logger::init();
17-
let spaced = SpaceD::new()?;
10+
#[tokio::test]
11+
async fn test_get_server_info() -> Result<()> {
12+
env_logger::init();
13+
let rig = TestRig::new().await?;
1814

19-
Command::cargo_bin("space-cli")?
20-
.arg("--chain")
21-
.arg("regtest")
22-
.arg("--spaced-rpc-url")
23-
.arg(spaced.spaced_rpc_url())
24-
.arg("getserverinfo")
25-
.assert()
26-
.success()
27-
.stdout(predicate::function(|x: &str| {
28-
let info: ServerInfo = from_str(x).unwrap();
29-
return info.chain == ExtendedNetwork::Regtest;
30-
}));
15+
Command::cargo_bin("space-cli")?
16+
.arg("--chain")
17+
.arg("regtest")
18+
.arg("--spaced-rpc-url")
19+
.arg(rig.spaced.rpc_url())
20+
.arg("getserverinfo")
21+
.assert()
22+
.success()
23+
.stdout(predicate::function(|x: &str| {
24+
let info: ServerInfo = from_str(x).unwrap();
25+
return info.chain == ExtendedNetwork::Regtest;
26+
}));
3127

32-
Ok(())
33-
}
28+
Ok(())
3429
}

node/tests/utils.rs

Lines changed: 0 additions & 70 deletions
This file was deleted.

0 commit comments

Comments
 (0)