Skip to content

Commit 56832fb

Browse files
committed
f Use a LeakChecker instead of just a single Weak
1 parent b6f0726 commit 56832fb

File tree

2 files changed

+31
-9
lines changed

2 files changed

+31
-9
lines changed

src/lib.rs

Lines changed: 24 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -110,6 +110,8 @@ use std::default::Default;
110110
use std::net::ToSocketAddrs;
111111
use std::sync::{Arc, Mutex, RwLock};
112112
use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH};
113+
#[cfg(cycle_tests)]
114+
use std::{any::Any, sync::Weak};
113115

114116
pub use balance::{BalanceDetails, LightningBalance, PendingSweepBalance};
115117
use bitcoin::secp256k1::PublicKey;
@@ -1763,15 +1765,31 @@ impl Node {
17631765
}
17641766

17651767
#[cfg(cycle_tests)]
1766-
/// Fetch a reference to the inner NetworkGraph, for Arc cycle detection
1767-
pub fn fetch_ref(&self) -> std::sync::Weak<Graph> {
1768-
Arc::downgrade(&self.network_graph)
1768+
/// Fetch a [`LeakChecker`] which can be used to ensure that the inner fields of this object
1769+
/// are released.
1770+
///
1771+
/// Call [`LeakChecker::assert_no_leaks`] after this [`Node`] has been `drop`ped (otherwise it
1772+
/// will assume that all fields have leaked).
1773+
pub fn leak_checker(&self) -> LeakChecker {
1774+
let graph = Arc::downgrade(&self.network_graph) as Weak<dyn Any>;
1775+
LeakChecker(vec![graph])
17691776
}
17701777
}
17711778

1772-
impl Drop for Node {
1773-
fn drop(&mut self) {
1774-
let _ = self.stop();
1779+
#[cfg(cycle_tests)]
1780+
/// A list of [`Weak`]s which can be used to check that a [`Node`]'s inner fields are being
1781+
/// properly released after the [`Node`] is dropped.
1782+
pub struct LeakChecker(Vec<Weak<dyn Any>>);
1783+
1784+
#[cfg(cycle_tests)]
1785+
impl LeakChecker {
1786+
/// Asserts that all the stored [`Weak`]s point to contents which have been freed.
1787+
///
1788+
/// This will (obviously) panic if the [`Node`] has not yet been dropped.
1789+
pub fn assert_no_leaks(&self) {
1790+
for weak in self.0.iter() {
1791+
assert_eq!(weak.strong_count(), 0);
1792+
}
17751793
}
17761794
}
17771795

tests/common/mod.rs

Lines changed: 7 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -301,9 +301,13 @@ impl Deref for TestNode {
301301
impl Drop for TestNode {
302302
fn drop(&mut self) {
303303
if !std::thread::panicking() {
304-
let graph_ref = (**self).fetch_ref();
305-
self.inner.take();
306-
assert_eq!(graph_ref.strong_count(), 0);
304+
let leak_checks = (**self).leak_checker();
305+
match self.inner.take().unwrap().stop() {
306+
Ok(()) => {},
307+
Err(e) if e == NodeError::NotRunning => {},
308+
Err(e) => panic!("{e:?}"),
309+
}
310+
leak_checks.assert_no_leaks();
307311
}
308312
}
309313
}

0 commit comments

Comments
 (0)