routing: use T.TempDir to create temporary test directory

Signed-off-by: Eng Zer Jun <engzerjun@gmail.com>
This commit is contained in:
Eng Zer Jun committed 2022-08-24 09:03:05 +08:00
1 parent 71185d46fb
commit b5a626be78
8 files changed
+117 -197

No files matched your search

+46 -83
View File
@@ -3,9 +3,7 @@ package chainview
import ( import (
"bytes" "bytes"
"fmt" "fmt"
"io/ioutil"
"net" "net"
"os"
"os/exec" "os/exec"
"path/filepath" "path/filepath"
"runtime" "runtime"
@@ -504,15 +502,10 @@ func testFilterBlockDisconnected(node *rpctest.Harness,
require.NoError(t, err, "error getting best block") require.NoError(t, err, "error getting best block")
// Init a chain view that has this node as its block source. // Init a chain view that has this node as its block source.
cleanUpFunc, reorgView, err := chainViewInit( reorgView, err := chainViewInit(
reorgNode.RPCConfig(), reorgNode.P2PAddress(), bestHeight, t, reorgNode.RPCConfig(), reorgNode.P2PAddress(), bestHeight,
) )
require.NoError(t, err, "unable to create chain view") require.NoError(t, err, "unable to create chain view")
defer func() {
if cleanUpFunc != nil {
cleanUpFunc()
}
}()
if err = reorgView.Start(); err != nil { if err = reorgView.Start(); err != nil {
t.Fatalf("unable to start btcd chain view: %v", err) t.Fatalf("unable to start btcd chain view: %v", err)
@@ -681,8 +674,8 @@ func testFilterBlockDisconnected(node *rpctest.Harness,
time.Sleep(time.Millisecond * 500) time.Sleep(time.Millisecond * 500)
} }
type chainViewInitFunc func(rpcInfo rpcclient.ConnConfig, type chainViewInitFunc func(t *testing.T, rpcInfo rpcclient.ConnConfig,
p2pAddr string, bestHeight int32) (func(), FilteredChainView, error) p2pAddr string, bestHeight int32) (FilteredChainView, error)
type testCase struct { type testCase struct {
name string name string
@@ -715,20 +708,14 @@ var interfaceImpls = []struct {
}{ }{
{ {
name: "bitcoind_zmq", name: "bitcoind_zmq",
chainViewInit: func(_ rpcclient.ConnConfig, chainViewInit: func(t *testing.T, _ rpcclient.ConnConfig,
p2pAddr string, bestHeight int32) (func(), p2pAddr string, bestHeight int32) (FilteredChainView, error) {
FilteredChainView, error) {
// Start a bitcoind instance. // Start a bitcoind instance.
tempBitcoindDir, err := ioutil.TempDir("", "bitcoind") tempBitcoindDir := t.TempDir()
if err != nil {
return nil, nil, err
}
zmqBlockHost := "ipc:///" + tempBitcoindDir + "/blocks.socket" zmqBlockHost := "ipc:///" + tempBitcoindDir + "/blocks.socket"
zmqTxHost := "ipc:///" + tempBitcoindDir + "/tx.socket" zmqTxHost := "ipc:///" + tempBitcoindDir + "/tx.socket"
cleanUp1 := func() {
os.RemoveAll(tempBitcoindDir)
}
rpcPort := getFreePort() rpcPort := getFreePort()
bitcoind := exec.Command( bitcoind := exec.Command(
"bitcoind", "bitcoind",
@@ -744,25 +731,22 @@ var interfaceImpls = []struct {
"-zmqpubrawblock="+zmqBlockHost, "-zmqpubrawblock="+zmqBlockHost,
"-zmqpubrawtx="+zmqTxHost, "-zmqpubrawtx="+zmqTxHost,
) )
err = bitcoind.Start() err := bitcoind.Start()
if err != nil { if err != nil {
cleanUp1() return nil, err
return nil, nil, err
} }
// Sanity check to ensure that the process did in fact // Sanity check to ensure that the process did in fact
// start. // start.
if bitcoind.Process == nil { if bitcoind.Process == nil {
cleanUp1() return nil, fmt.Errorf("bitcoind cmd " +
return nil, nil, fmt.Errorf("bitcoind cmd " +
"Process is not set after Start") "Process is not set after Start")
} }
cleanUp2 := func() { t.Cleanup(func() {
_ = bitcoind.Process.Kill() _ = bitcoind.Process.Kill()
_ = bitcoind.Wait() _ = bitcoind.Wait()
cleanUp1() })
}
host := fmt.Sprintf("127.0.0.1:%d", rpcPort) host := fmt.Sprintf("127.0.0.1:%d", rpcPort)
cfg := &chain.BitcoindConfig{ cfg := &chain.BitcoindConfig{
@@ -806,14 +790,13 @@ var interfaceImpls = []struct {
return nil return nil
}, 10*time.Second) }, 10*time.Second)
if err != nil { if err != nil {
return cleanUp2, nil, fmt.Errorf("unable to "+ return nil, fmt.Errorf("unable to "+
"establish connection to bitcoind: %v", "establish connection to bitcoind: %v",
err) err)
} }
cleanUp3 := func() { t.Cleanup(func() {
chainConn.Stop() chainConn.Stop()
cleanUp2() })
}
blockCache := blockcache.NewBlockCache(10000) blockCache := blockcache.NewBlockCache(10000)
@@ -821,23 +804,17 @@ var interfaceImpls = []struct {
chainConn, blockCache, chainConn, blockCache,
) )
return cleanUp3, chainView, nil return chainView, nil
}, },
}, },
{ {
name: "bitcoind_polling", name: "bitcoind_polling",
chainViewInit: func(_ rpcclient.ConnConfig, chainViewInit: func(t *testing.T, _ rpcclient.ConnConfig,
p2pAddr string, bestHeight int32) (func(), p2pAddr string, bestHeight int32) (FilteredChainView, error) {
FilteredChainView, error) {
// Start a bitcoind instance. // Start a bitcoind instance.
tempBitcoindDir, err := ioutil.TempDir("", "bitcoind") tempBitcoindDir := t.TempDir()
if err != nil {
return nil, nil, err
}
cleanUp1 := func() {
os.RemoveAll(tempBitcoindDir)
}
rpcPort := getFreePort() rpcPort := getFreePort()
bitcoind := exec.Command( bitcoind := exec.Command(
"bitcoind", "bitcoind",
@@ -851,25 +828,22 @@ var interfaceImpls = []struct {
fmt.Sprintf("-rpcport=%d", rpcPort), fmt.Sprintf("-rpcport=%d", rpcPort),
"-disablewallet", "-disablewallet",
) )
err = bitcoind.Start() err := bitcoind.Start()
if err != nil { if err != nil {
cleanUp1() return nil, err
return nil, nil, err
} }
// Sanity check to ensure that the process did in fact // Sanity check to ensure that the process did in fact
// start. // start.
if bitcoind.Process == nil { if bitcoind.Process == nil {
cleanUp1() return nil, fmt.Errorf("bitcoind cmd " +
return nil, nil, fmt.Errorf("bitcoind cmd " +
"Process is not set after Start") "Process is not set after Start")
} }
cleanUp2 := func() { t.Cleanup(func() {
_ = bitcoind.Process.Kill() _ = bitcoind.Process.Kill()
_ = bitcoind.Wait() _ = bitcoind.Wait()
cleanUp1() })
}
host := fmt.Sprintf("127.0.0.1:%d", rpcPort) host := fmt.Sprintf("127.0.0.1:%d", rpcPort)
cfg := &chain.BitcoindConfig{ cfg := &chain.BitcoindConfig{
@@ -913,14 +887,13 @@ var interfaceImpls = []struct {
return nil return nil
}, 10*time.Second) }, 10*time.Second)
if err != nil { if err != nil {
return cleanUp2, nil, fmt.Errorf("unable to "+ return nil, fmt.Errorf("unable to "+
"establish connection to bitcoind: %v", "establish connection to bitcoind: %v",
err) err)
} }
cleanUp3 := func() { t.Cleanup(func() {
chainConn.Stop() chainConn.Stop()
cleanUp2() })
}
blockCache := blockcache.NewBlockCache(10000) blockCache := blockcache.NewBlockCache(10000)
@@ -928,26 +901,22 @@ var interfaceImpls = []struct {
chainConn, blockCache, chainConn, blockCache,
) )
return cleanUp3, chainView, nil return chainView, nil
}, },
}, },
{ {
name: "p2p_neutrino", name: "p2p_neutrino",
chainViewInit: func(_ rpcclient.ConnConfig, chainViewInit: func(t *testing.T, _ rpcclient.ConnConfig,
p2pAddr string, bestHeight int32) (func(), p2pAddr string, bestHeight int32) (FilteredChainView, error) {
FilteredChainView, error) {
spvDir, err := ioutil.TempDir("", "neutrino") spvDir := t.TempDir()
if err != nil {
return nil, nil, err
}
dbName := filepath.Join(spvDir, "neutrino.db") dbName := filepath.Join(spvDir, "neutrino.db")
spvDatabase, err := walletdb.Create( spvDatabase, err := walletdb.Create(
"bdb", dbName, true, kvdb.DefaultDBTimeout, "bdb", dbName, true, kvdb.DefaultDBTimeout,
) )
if err != nil { if err != nil {
return nil, nil, err return nil, err
} }
spvConfig := neutrino.Config{ spvConfig := neutrino.Config{
@@ -959,7 +928,7 @@ var interfaceImpls = []struct {
spvNode, err := neutrino.NewChainService(spvConfig) spvNode, err := neutrino.NewChainService(spvConfig)
if err != nil { if err != nil {
return nil, nil, err return nil, err
} }
// Wait until the node has fully synced up to the local // Wait until the node has fully synced up to the local
@@ -982,16 +951,15 @@ var interfaceImpls = []struct {
return nil return nil
}, 10*time.Second) }, 10*time.Second)
if err != nil { if err != nil {
return nil, nil, fmt.Errorf("unable to "+ return nil, fmt.Errorf("unable to "+
"establish connection to bitcoind: %v", "establish connection to bitcoind: %v",
err) err)
} }
cleanUp := func() { t.Cleanup(func() {
spvDatabase.Close() spvDatabase.Close()
spvNode.Stop() spvNode.Stop()
os.RemoveAll(spvDir) })
}
blockCache := blockcache.NewBlockCache(10000) blockCache := blockcache.NewBlockCache(10000)
@@ -999,27 +967,26 @@ var interfaceImpls = []struct {
spvNode, blockCache, spvNode, blockCache,
) )
if err != nil { if err != nil {
return nil, nil, err return nil, err
} }
return cleanUp, chainView, nil return chainView, nil
}, },
}, },
{ {
name: "btcd_websockets", name: "btcd_websockets",
chainViewInit: func(config rpcclient.ConnConfig, chainViewInit: func(_ *testing.T, config rpcclient.ConnConfig,
p2pAddr string, bestHeight int32) (func(), p2pAddr string, bestHeight int32) (FilteredChainView, error) {
FilteredChainView, error) {
blockCache := blockcache.NewBlockCache(10000) blockCache := blockcache.NewBlockCache(10000)
chainView, err := NewBtcdFilteredChainView( chainView, err := NewBtcdFilteredChainView(
config, blockCache, config, blockCache,
) )
if err != nil { if err != nil {
return nil, nil, err return nil, err
} }
return nil, chainView, err return chainView, err
}, },
}, },
} }
@@ -1048,8 +1015,8 @@ func TestFilteredChainView(t *testing.T) {
t.Fatalf("error getting best block: %v", err) t.Fatalf("error getting best block: %v", err)
} }
cleanUpFunc, chainView, err := chainViewImpl.chainViewInit( chainView, err := chainViewImpl.chainViewInit(
rpcConfig, p2pAddr, bestHeight, t, rpcConfig, p2pAddr, bestHeight,
) )
if err != nil { if err != nil {
t.Fatalf("unable to make chain view: %v", err) t.Fatalf("unable to make chain view: %v", err)
@@ -1075,9 +1042,5 @@ func TestFilteredChainView(t *testing.T) {
if err := chainView.Stop(); err != nil { if err := chainView.Stop(); err != nil {
t.Fatalf("unable to stop chain view: %v", err) t.Fatalf("unable to stop chain view: %v", err)
} }
if cleanUpFunc != nil {
cleanUpFunc()
}
} }
} }
+5 -11
View File
@@ -5,7 +5,6 @@ import (
"crypto/sha256" "crypto/sha256"
"fmt" "fmt"
"io" "io"
"io/ioutil"
"reflect" "reflect"
"testing" "testing"
"time" "time"
@@ -48,7 +47,7 @@ var (
func TestControlTowerSubscribeUnknown(t *testing.T) { func TestControlTowerSubscribeUnknown(t *testing.T) {
t.Parallel() t.Parallel()
db, err := initDB(false) db, err := initDB(t, false)
require.NoError(t, err, "unable to init db") require.NoError(t, err, "unable to init db")
pControl := NewControlTower(channeldb.NewPaymentControl(db)) pControl := NewControlTower(channeldb.NewPaymentControl(db))
@@ -65,7 +64,7 @@ func TestControlTowerSubscribeUnknown(t *testing.T) {
func TestControlTowerSubscribeSuccess(t *testing.T) { func TestControlTowerSubscribeSuccess(t *testing.T) {
t.Parallel() t.Parallel()
db, err := initDB(false) db, err := initDB(t, false)
require.NoError(t, err, "unable to init db") require.NoError(t, err, "unable to init db")
pControl := NewControlTower(channeldb.NewPaymentControl(db)) pControl := NewControlTower(channeldb.NewPaymentControl(db))
@@ -182,7 +181,7 @@ func TestPaymentControlSubscribeFail(t *testing.T) {
func testPaymentControlSubscribeFail(t *testing.T, registerAttempt, func testPaymentControlSubscribeFail(t *testing.T, registerAttempt,
keepFailedPaymentAttempts bool) { keepFailedPaymentAttempts bool) {
db, err := initDB(keepFailedPaymentAttempts) db, err := initDB(t, keepFailedPaymentAttempts)
require.NoError(t, err, "unable to init db") require.NoError(t, err, "unable to init db")
pControl := NewControlTower(channeldb.NewPaymentControl(db)) pControl := NewControlTower(channeldb.NewPaymentControl(db))
@@ -294,14 +293,9 @@ func testPaymentControlSubscribeFail(t *testing.T, registerAttempt,
} }
} }
func initDB(keepFailedPaymentAttempts bool) (*channeldb.DB, error) { func initDB(t *testing.T, keepFailedPaymentAttempts bool) (*channeldb.DB, error) {
tempPath, err := ioutil.TempDir("", "routingdb")
if err != nil {
return nil, err
}
db, err := channeldb.Open( db, err := channeldb.Open(
tempPath, channeldb.OptionKeepFailedPaymentAttempts( t.TempDir(), channeldb.OptionKeepFailedPaymentAttempts(
keepFailedPaymentAttempts, keepFailedPaymentAttempts,
), ),
) )
+14 -4
View File
@@ -2,7 +2,6 @@ package routing
import ( import (
"fmt" "fmt"
"io/ioutil"
"math" "math"
"os" "os"
"testing" "testing"
@@ -122,13 +121,20 @@ func (c *integratedRoutingContext) testPayment(maxParts uint32,
) )
// Create temporary database for mission control. // Create temporary database for mission control.
file, err := ioutil.TempFile("", "*.db") file, err := os.CreateTemp("", "*.db")
if err != nil { if err != nil {
c.t.Fatal(err) c.t.Fatal(err)
} }
dbPath := file.Name() dbPath := file.Name()
defer os.Remove(dbPath) c.t.Cleanup(func() {
if err := file.Close(); err != nil {
c.t.Fatal(err)
}
if err := os.Remove(dbPath); err != nil {
c.t.Fatal(err)
}
})
db, err := kvdb.Open( db, err := kvdb.Open(
kvdb.BoltBackendName, dbPath, true, kvdb.DefaultDBTimeout, kvdb.BoltBackendName, dbPath, true, kvdb.DefaultDBTimeout,
@@ -136,7 +142,11 @@ func (c *integratedRoutingContext) testPayment(maxParts uint32,
if err != nil { if err != nil {
c.t.Fatal(err) c.t.Fatal(err)
} }
defer db.Close() c.t.Cleanup(func() {
if err := db.Close(); err != nil {
c.t.Fatal(err)
}
})
// Instantiate a new mission control with the current configuration // Instantiate a new mission control with the current configuration
// values. // values.
+8 -4
View File
@@ -1,7 +1,6 @@
package routing package routing
import ( import (
"io/ioutil"
"os" "os"
"reflect" "reflect"
"testing" "testing"
@@ -24,12 +23,16 @@ func TestMissionControlStore(t *testing.T) {
// Set time zone explicitly to keep test deterministic. // Set time zone explicitly to keep test deterministic.
time.Local = time.UTC time.Local = time.UTC
file, err := ioutil.TempFile("", "*.db") file, err := os.CreateTemp("", "*.db")
if err != nil { if err != nil {
t.Fatal(err) t.Fatal(err)
} }
dbPath := file.Name() dbPath := file.Name()
t.Cleanup(func() {
require.NoError(t, file.Close())
require.NoError(t, os.Remove(dbPath))
})
db, err := kvdb.Create( db, err := kvdb.Create(
kvdb.BoltBackendName, dbPath, true, kvdb.DefaultDBTimeout, kvdb.BoltBackendName, dbPath, true, kvdb.DefaultDBTimeout,
@@ -37,8 +40,9 @@ func TestMissionControlStore(t *testing.T) {
if err != nil { if err != nil {
t.Fatal(err) t.Fatal(err)
} }
defer db.Close() t.Cleanup(func() {
defer os.Remove(dbPath) require.NoError(t, db.Close())
})
store, err := newMissionControlStore(db, testMaxRecords, time.Second) store, err := newMissionControlStore(db, testMaxRecords, time.Second)
if err != nil { if err != nil {
+8 -9
View File
@@ -1,7 +1,6 @@
package routing package routing
import ( import (
"io/ioutil"
"os" "os"
"testing" "testing"
"time" "time"
@@ -57,10 +56,14 @@ func createMcTestContext(t *testing.T) *mcTestContext {
now: mcTestTime, now: mcTestTime,
} }
file, err := ioutil.TempFile("", "*.db") file, err := os.CreateTemp("", "*.db")
if err != nil { if err != nil {
t.Fatal(err) t.Fatal(err)
} }
t.Cleanup(func() {
require.NoError(t, file.Close())
require.NoError(t, os.Remove(file.Name()))
})
ctx.dbPath = file.Name() ctx.dbPath = file.Name()
@@ -70,6 +73,9 @@ func createMcTestContext(t *testing.T) *mcTestContext {
if err != nil { if err != nil {
t.Fatal(err) t.Fatal(err)
} }
t.Cleanup(func() {
require.NoError(t, ctx.db.Close())
})
ctx.restartMc() ctx.restartMc()
@@ -102,12 +108,6 @@ func (ctx *mcTestContext) restartMc() {
ctx.mc = mc ctx.mc = mc
} }
// cleanup closes the database and removes the temp file.
func (ctx *mcTestContext) cleanup() {
ctx.db.Close()
os.Remove(ctx.dbPath)
}
// Assert that mission control returns a probability for an edge. // Assert that mission control returns a probability for an edge.
func (ctx *mcTestContext) expectP(amt lnwire.MilliSatoshi, expected float64) { func (ctx *mcTestContext) expectP(amt lnwire.MilliSatoshi, expected float64) {
ctx.t.Helper() ctx.t.Helper()
@@ -143,7 +143,6 @@ func (ctx *mcTestContext) reportSuccess() {
// TestMissionControl tests mission control probability estimation. // TestMissionControl tests mission control probability estimation.
func TestMissionControl(t *testing.T) { func TestMissionControl(t *testing.T) {
ctx := createMcTestContext(t) ctx := createMcTestContext(t)
defer ctx.cleanup()
ctx.now = testTime ctx.now = testTime
+24 -64
View File
@@ -11,7 +11,6 @@ import (
"io/ioutil" "io/ioutil"
"math" "math"
"net" "net"
"os"
"reflect" "reflect"
"strings" "strings"
"testing" "testing"
@@ -150,28 +149,17 @@ type testChan struct {
} }
// makeTestGraph creates a new instance of a channeldb.ChannelGraph for testing // makeTestGraph creates a new instance of a channeldb.ChannelGraph for testing
// purposes. A callback which cleans up the created temporary directories is // purposes.
// also returned and intended to be executed after the test completes. func makeTestGraph(t *testing.T, useCache bool) (*channeldb.ChannelGraph,
func makeTestGraph(useCache bool) (*channeldb.ChannelGraph, kvdb.Backend, kvdb.Backend, error) {
func(), error) {
// First, create a temporary directory to be used for the duration of // Create channelgraph for the first time.
// this test. backend, backendCleanup, err := kvdb.GetTestBackend(t.TempDir(), "cgr")
tempDirName, err := ioutil.TempDir("", "channeldb")
if err != nil { if err != nil {
return nil, nil, nil, err return nil, nil, err
} }
// Next, create channelgraph for the first time. t.Cleanup(backendCleanup)
backend, backendCleanup, err := kvdb.GetTestBackend(tempDirName, "cgr")
if err != nil {
return nil, nil, nil, err
}
cleanUp := func() {
backendCleanup()
_ = os.RemoveAll(tempDirName)
}
opts := channeldb.DefaultOptions() opts := channeldb.DefaultOptions()
graph, err := channeldb.NewChannelGraph( graph, err := channeldb.NewChannelGraph(
@@ -180,16 +168,17 @@ func makeTestGraph(useCache bool) (*channeldb.ChannelGraph, kvdb.Backend,
useCache, false, useCache, false,
) )
if err != nil { if err != nil {
cleanUp() return nil, nil, err
return nil, nil, nil, err
} }
return graph, backend, cleanUp, nil return graph, backend, nil
} }
// parseTestGraph returns a fully populated ChannelGraph given a path to a JSON // parseTestGraph returns a fully populated ChannelGraph given a path to a JSON
// file which encodes a test graph. // file which encodes a test graph.
func parseTestGraph(useCache bool, path string) (*testGraphInstance, error) { func parseTestGraph(t *testing.T, useCache bool, path string) (
*testGraphInstance, error) {
graphJSON, err := ioutil.ReadFile(path) graphJSON, err := ioutil.ReadFile(path)
if err != nil { if err != nil {
return nil, err return nil, err
@@ -214,7 +203,7 @@ func parseTestGraph(useCache bool, path string) (*testGraphInstance, error) {
testAddrs = append(testAddrs, testAddr) testAddrs = append(testAddrs, testAddr)
// Next, create a temporary graph database for usage within the test. // Next, create a temporary graph database for usage within the test.
graph, graphBackend, cleanUp, err := makeTestGraph(useCache) graph, graphBackend, err := makeTestGraph(t, useCache)
if err != nil { if err != nil {
return nil, err return nil, err
} }
@@ -429,7 +418,6 @@ func parseTestGraph(useCache bool, path string) (*testGraphInstance, error) {
return &testGraphInstance{ return &testGraphInstance{
graph: graph, graph: graph,
graphBackend: graphBackend, graphBackend: graphBackend,
cleanUp: cleanUp,
aliasMap: aliasMap, aliasMap: aliasMap,
privKeyMap: privKeyMap, privKeyMap: privKeyMap,
channelIDs: channelIDs, channelIDs: channelIDs,
@@ -497,7 +485,6 @@ type testChannel struct {
type testGraphInstance struct { type testGraphInstance struct {
graph *channeldb.ChannelGraph graph *channeldb.ChannelGraph
graphBackend kvdb.Backend graphBackend kvdb.Backend
cleanUp func()
// aliasMap is a map from a node's alias to its public key. This type is // aliasMap is a map from a node's alias to its public key. This type is
// provided in order to allow easily look up from the human memorable alias // provided in order to allow easily look up from the human memorable alias
@@ -533,8 +520,8 @@ func (g *testGraphInstance) getLink(chanID lnwire.ShortChannelID) (
// a deterministical way and added to the channel graph. A list of nodes is // a deterministical way and added to the channel graph. A list of nodes is
// not required and derived from the channel data. The goal is to keep // not required and derived from the channel data. The goal is to keep
// instantiating a test channel graph as light weight as possible. // instantiating a test channel graph as light weight as possible.
func createTestGraphFromChannels(useCache bool, testChannels []*testChannel, func createTestGraphFromChannels(t *testing.T, useCache bool,
source string) (*testGraphInstance, error) { testChannels []*testChannel, source string) (*testGraphInstance, error) {
// We'll use this fake address for the IP address of all the nodes in // We'll use this fake address for the IP address of all the nodes in
// our tests. This value isn't needed for path finding so it doesn't // our tests. This value isn't needed for path finding so it doesn't
@@ -547,7 +534,7 @@ func createTestGraphFromChannels(useCache bool, testChannels []*testChannel,
testAddrs = append(testAddrs, testAddr) testAddrs = append(testAddrs, testAddr)
// Next, create a temporary graph database for usage within the test. // Next, create a temporary graph database for usage within the test.
graph, graphBackend, cleanUp, err := makeTestGraph(useCache) graph, graphBackend, err := makeTestGraph(t, useCache)
if err != nil { if err != nil {
return nil, err return nil, err
} }
@@ -765,7 +752,6 @@ func createTestGraphFromChannels(useCache bool, testChannels []*testChannel,
return &testGraphInstance{ return &testGraphInstance{
graph: graph, graph: graph,
graphBackend: graphBackend, graphBackend: graphBackend,
cleanUp: cleanUp,
aliasMap: aliasMap, aliasMap: aliasMap,
privKeyMap: privKeyMap, privKeyMap: privKeyMap,
links: links, links: links,
@@ -883,7 +869,6 @@ func runFindPathWithMetadata(t *testing.T, useCache bool) {
} }
ctx := newPathFindingTestContext(t, useCache, testChannels, "alice") ctx := newPathFindingTestContext(t, useCache, testChannels, "alice")
defer ctx.cleanup()
paymentAmt := lnwire.NewMSatFromSatoshis(100) paymentAmt := lnwire.NewMSatFromSatoshis(100)
target := ctx.keyFromAlias("bob") target := ctx.keyFromAlias("bob")
@@ -952,7 +937,6 @@ func runFindLowestFeePath(t *testing.T, useCache bool) {
} }
ctx := newPathFindingTestContext(t, useCache, testChannels, "roasbeef") ctx := newPathFindingTestContext(t, useCache, testChannels, "roasbeef")
defer ctx.cleanup()
const ( const (
startingHeight = 100 startingHeight = 100
@@ -1053,9 +1037,8 @@ var basicGraphPathFindingTests = []basicGraphPathFindingTestCase{
}} }}
func runBasicGraphPathFinding(t *testing.T, useCache bool) { func runBasicGraphPathFinding(t *testing.T, useCache bool) {
testGraphInstance, err := parseTestGraph(useCache, basicGraphFilePath) testGraphInstance, err := parseTestGraph(t, useCache, basicGraphFilePath)
require.NoError(t, err, "unable to create graph") require.NoError(t, err, "unable to create graph")
defer testGraphInstance.cleanUp()
// With the test graph loaded, we'll test some basic path finding using // With the test graph loaded, we'll test some basic path finding using
// the pre-generated graph. Consult the testdata/basic_graph.json file // the pre-generated graph. Consult the testdata/basic_graph.json file
@@ -1218,9 +1201,8 @@ func testBasicGraphPathFindingCase(t *testing.T, graphInstance *testGraphInstanc
// the path can support custom TLV records for the receiver under the // the path can support custom TLV records for the receiver under the
// appropriate circumstances. // appropriate circumstances.
func runPathFindingWithAdditionalEdges(t *testing.T, useCache bool) { func runPathFindingWithAdditionalEdges(t *testing.T, useCache bool) {
graph, err := parseTestGraph(useCache, basicGraphFilePath) graph, err := parseTestGraph(t, useCache, basicGraphFilePath)
require.NoError(t, err, "unable to create graph") require.NoError(t, err, "unable to create graph")
defer graph.cleanUp()
sourceNode, err := graph.graph.SourceNode() sourceNode, err := graph.graph.SourceNode()
require.NoError(t, err, "unable to fetch source node") require.NoError(t, err, "unable to fetch source node")
@@ -1641,7 +1623,6 @@ func runNewRoutePathTooLong(t *testing.T, useCache bool) {
} }
ctx := newPathFindingTestContext(t, useCache, testChannels, "start") ctx := newPathFindingTestContext(t, useCache, testChannels, "start")
defer ctx.cleanup()
// Assert that we can find 20 hop routes. // Assert that we can find 20 hop routes.
node20 := ctx.keyFromAlias("node-20") node20 := ctx.keyFromAlias("node-20")
@@ -1669,9 +1650,8 @@ func runNewRoutePathTooLong(t *testing.T, useCache bool) {
} }
func runPathNotAvailable(t *testing.T, useCache bool) { func runPathNotAvailable(t *testing.T, useCache bool) {
graph, err := parseTestGraph(useCache, basicGraphFilePath) graph, err := parseTestGraph(t, useCache, basicGraphFilePath)
require.NoError(t, err, "unable to create graph") require.NoError(t, err, "unable to create graph")
defer graph.cleanUp()
sourceNode, err := graph.graph.SourceNode() sourceNode, err := graph.graph.SourceNode()
require.NoError(t, err, "unable to fetch source node") require.NoError(t, err, "unable to fetch source node")
@@ -1728,7 +1708,6 @@ func runDestTLVGraphFallback(t *testing.T, useCache bool) {
} }
ctx := newPathFindingTestContext(t, useCache, testChannels, "roasbeef") ctx := newPathFindingTestContext(t, useCache, testChannels, "roasbeef")
defer ctx.cleanup()
sourceNode, err := ctx.graph.SourceNode() sourceNode, err := ctx.graph.SourceNode()
require.NoError(t, err, "unable to fetch source node") require.NoError(t, err, "unable to fetch source node")
@@ -1826,7 +1805,6 @@ func runMissingFeatureDep(t *testing.T, useCache bool) {
} }
ctx := newPathFindingTestContext(t, useCache, testChannels, "roasbeef") ctx := newPathFindingTestContext(t, useCache, testChannels, "roasbeef")
defer ctx.cleanup()
// Conner's node in the graph has a broken feature vector, since it // Conner's node in the graph has a broken feature vector, since it
// signals payment addresses without signaling tlv onions. Pathfinding // signals payment addresses without signaling tlv onions. Pathfinding
@@ -1899,7 +1877,6 @@ func runUnknownRequiredFeatures(t *testing.T, useCache bool) {
} }
ctx := newPathFindingTestContext(t, useCache, testChannels, "roasbeef") ctx := newPathFindingTestContext(t, useCache, testChannels, "roasbeef")
defer ctx.cleanup()
conner := ctx.keyFromAlias("conner") conner := ctx.keyFromAlias("conner")
joost := ctx.keyFromAlias("joost") joost := ctx.keyFromAlias("joost")
@@ -1941,7 +1918,6 @@ func runDestPaymentAddr(t *testing.T, useCache bool) {
} }
ctx := newPathFindingTestContext(t, useCache, testChannels, "roasbeef") ctx := newPathFindingTestContext(t, useCache, testChannels, "roasbeef")
defer ctx.cleanup()
luoji := ctx.keyFromAlias("luoji") luoji := ctx.keyFromAlias("luoji")
@@ -1967,9 +1943,8 @@ func runDestPaymentAddr(t *testing.T, useCache bool) {
} }
func runPathInsufficientCapacity(t *testing.T, useCache bool) { func runPathInsufficientCapacity(t *testing.T, useCache bool) {
graph, err := parseTestGraph(useCache, basicGraphFilePath) graph, err := parseTestGraph(t, useCache, basicGraphFilePath)
require.NoError(t, err, "unable to create graph") require.NoError(t, err, "unable to create graph")
defer graph.cleanUp()
sourceNode, err := graph.graph.SourceNode() sourceNode, err := graph.graph.SourceNode()
require.NoError(t, err, "unable to fetch source node") require.NoError(t, err, "unable to fetch source node")
@@ -1998,9 +1973,8 @@ func runPathInsufficientCapacity(t *testing.T, useCache bool) {
// runRouteFailMinHTLC tests that if we attempt to route an HTLC which is // runRouteFailMinHTLC tests that if we attempt to route an HTLC which is
// smaller than the advertised minHTLC of an edge, then path finding fails. // smaller than the advertised minHTLC of an edge, then path finding fails.
func runRouteFailMinHTLC(t *testing.T, useCache bool) { func runRouteFailMinHTLC(t *testing.T, useCache bool) {
graph, err := parseTestGraph(useCache, basicGraphFilePath) graph, err := parseTestGraph(t, useCache, basicGraphFilePath)
require.NoError(t, err, "unable to create graph") require.NoError(t, err, "unable to create graph")
defer graph.cleanUp()
sourceNode, err := graph.graph.SourceNode() sourceNode, err := graph.graph.SourceNode()
require.NoError(t, err, "unable to fetch source node") require.NoError(t, err, "unable to fetch source node")
@@ -2050,7 +2024,6 @@ func runRouteFailMaxHTLC(t *testing.T, useCache bool) {
} }
ctx := newPathFindingTestContext(t, useCache, testChannels, "roasbeef") ctx := newPathFindingTestContext(t, useCache, testChannels, "roasbeef")
defer ctx.cleanup()
// First, attempt to send a payment greater than the max HTLC we are // First, attempt to send a payment greater than the max HTLC we are
// about to set, which should succeed. // about to set, which should succeed.
@@ -2084,9 +2057,8 @@ func runRouteFailMaxHTLC(t *testing.T, useCache bool) {
// ignore the disable flags, with the assumption that the correct bandwidth is // ignore the disable flags, with the assumption that the correct bandwidth is
// found among the bandwidth hints. // found among the bandwidth hints.
func runRouteFailDisabledEdge(t *testing.T, useCache bool) { func runRouteFailDisabledEdge(t *testing.T, useCache bool) {
graph, err := parseTestGraph(useCache, basicGraphFilePath) graph, err := parseTestGraph(t, useCache, basicGraphFilePath)
require.NoError(t, err, "unable to create graph") require.NoError(t, err, "unable to create graph")
defer graph.cleanUp()
sourceNode, err := graph.graph.SourceNode() sourceNode, err := graph.graph.SourceNode()
require.NoError(t, err, "unable to fetch source node") require.NoError(t, err, "unable to fetch source node")
@@ -2150,9 +2122,8 @@ func runRouteFailDisabledEdge(t *testing.T, useCache bool) {
// bandwidth hints is used by the path finding algorithm to consider whether to // bandwidth hints is used by the path finding algorithm to consider whether to
// use a local channel. // use a local channel.
func runPathSourceEdgesBandwidth(t *testing.T, useCache bool) { func runPathSourceEdgesBandwidth(t *testing.T, useCache bool) {
graph, err := parseTestGraph(useCache, basicGraphFilePath) graph, err := parseTestGraph(t, useCache, basicGraphFilePath)
require.NoError(t, err, "unable to create graph") require.NoError(t, err, "unable to create graph")
defer graph.cleanUp()
sourceNode, err := graph.graph.SourceNode() sourceNode, err := graph.graph.SourceNode()
require.NoError(t, err, "unable to fetch source node") require.NoError(t, err, "unable to fetch source node")
@@ -2462,7 +2433,6 @@ func runRestrictOutgoingChannel(t *testing.T, useCache bool) {
} }
ctx := newPathFindingTestContext(t, useCache, testChannels, "roasbeef") ctx := newPathFindingTestContext(t, useCache, testChannels, "roasbeef")
defer ctx.cleanup()
const ( const (
startingHeight = 100 startingHeight = 100
@@ -2523,7 +2493,6 @@ func runRestrictLastHop(t *testing.T, useCache bool) {
} }
ctx := newPathFindingTestContext(t, useCache, testChannels, "source") ctx := newPathFindingTestContext(t, useCache, testChannels, "source")
defer ctx.cleanup()
paymentAmt := lnwire.NewMSatFromSatoshis(100) paymentAmt := lnwire.NewMSatFromSatoshis(100)
target := ctx.keyFromAlias("target") target := ctx.keyFromAlias("target")
@@ -2592,7 +2561,6 @@ func testCltvLimit(t *testing.T, useCache bool, limit uint32,
} }
ctx := newPathFindingTestContext(t, useCache, testChannels, "roasbeef") ctx := newPathFindingTestContext(t, useCache, testChannels, "roasbeef")
defer ctx.cleanup()
paymentAmt := lnwire.NewMSatFromSatoshis(100) paymentAmt := lnwire.NewMSatFromSatoshis(100)
target := ctx.keyFromAlias("target") target := ctx.keyFromAlias("target")
@@ -2770,7 +2738,6 @@ func testProbabilityRouting(t *testing.T, useCache bool,
} }
ctx := newPathFindingTestContext(t, useCache, testChannels, "roasbeef") ctx := newPathFindingTestContext(t, useCache, testChannels, "roasbeef")
defer ctx.cleanup()
alias := ctx.testGraphInstance.aliasMap alias := ctx.testGraphInstance.aliasMap
@@ -2853,7 +2820,6 @@ func runEqualCostRouteSelection(t *testing.T, useCache bool) {
} }
ctx := newPathFindingTestContext(t, useCache, testChannels, "source") ctx := newPathFindingTestContext(t, useCache, testChannels, "source")
defer ctx.cleanup()
alias := ctx.testGraphInstance.aliasMap alias := ctx.testGraphInstance.aliasMap
@@ -2922,7 +2888,6 @@ func runNoCycle(t *testing.T, useCache bool) {
} }
ctx := newPathFindingTestContext(t, useCache, testChannels, "source") ctx := newPathFindingTestContext(t, useCache, testChannels, "source")
defer ctx.cleanup()
const ( const (
startingHeight = 100 startingHeight = 100
@@ -2975,7 +2940,6 @@ func runRouteToSelf(t *testing.T, useCache bool) {
} }
ctx := newPathFindingTestContext(t, useCache, testChannels, "source") ctx := newPathFindingTestContext(t, useCache, testChannels, "source")
defer ctx.cleanup()
paymentAmt := lnwire.NewMSatFromSatoshis(100) paymentAmt := lnwire.NewMSatFromSatoshis(100)
target := ctx.source target := ctx.source
@@ -3013,7 +2977,7 @@ func newPathFindingTestContext(t *testing.T, useCache bool,
testChannels []*testChannel, source string) *pathFindingTestContext { testChannels []*testChannel, source string) *pathFindingTestContext {
testGraphInstance, err := createTestGraphFromChannels( testGraphInstance, err := createTestGraphFromChannels(
useCache, testChannels, source, t, useCache, testChannels, source,
) )
require.NoError(t, err, "unable to create graph") require.NoError(t, err, "unable to create graph")
@@ -3046,10 +3010,6 @@ func (c *pathFindingTestContext) aliasFromKey(pubKey route.Vertex) string {
return "" return ""
} }
func (c *pathFindingTestContext) cleanup() {
c.testGraphInstance.cleanUp()
}
func (c *pathFindingTestContext) findPath(target route.Vertex, func (c *pathFindingTestContext) findPath(target route.Vertex,
amt lnwire.MilliSatoshi) ([]*channeldb.CachedEdgePolicy, amt lnwire.MilliSatoshi) ([]*channeldb.CachedEdgePolicy,
error) { error) {
+1 -2
View File
@@ -180,9 +180,8 @@ func TestRouterPaymentStateMachine(t *testing.T) {
}, 2), }, 2),
} }
testGraph, err := createTestGraphFromChannels(true, testChannels, "a") testGraph, err := createTestGraphFromChannels(t, true, testChannels, "a")
require.NoError(t, err, "unable to create graph") require.NoError(t, err, "unable to create graph")
defer testGraph.cleanUp()
paymentAmt := lnwire.NewMSatFromSatoshis(1000) paymentAmt := lnwire.NewMSatFromSatoshis(1000)
+11 -20
View File
@@ -196,7 +196,7 @@ func createTestCtxFromGraphInstanceAssumeValid(t *testing.T,
func createTestCtxSingleNode(t *testing.T, func createTestCtxSingleNode(t *testing.T,
startingHeight uint32) (*testCtx, func()) { startingHeight uint32) (*testCtx, func()) {
graph, graphBackend, cleanup, err := makeTestGraph(true) graph, graphBackend, err := makeTestGraph(t, true)
require.NoError(t, err, "failed to make test graph") require.NoError(t, err, "failed to make test graph")
sourceNode, err := createTestNode() sourceNode, err := createTestNode()
@@ -209,7 +209,6 @@ func createTestCtxSingleNode(t *testing.T,
graphInstance := &testGraphInstance{ graphInstance := &testGraphInstance{
graph: graph, graph: graph,
graphBackend: graphBackend, graphBackend: graphBackend,
cleanUp: cleanup,
} }
return createTestCtxFromGraphInstance( return createTestCtxFromGraphInstance(
@@ -222,7 +221,7 @@ func createTestCtxFromFile(t *testing.T,
// We'll attempt to locate and parse out the file // We'll attempt to locate and parse out the file
// that encodes the graph that our tests should be run against. // that encodes the graph that our tests should be run against.
graphInstance, err := parseTestGraph(true, testGraph) graphInstance, err := parseTestGraph(t, true, testGraph)
require.NoError(t, err, "unable to create test graph") require.NoError(t, err, "unable to create test graph")
return createTestCtxFromGraphInstance( return createTestCtxFromGraphInstance(
@@ -392,9 +391,8 @@ func TestChannelUpdateValidation(t *testing.T) {
}, 2), }, 2),
} }
testGraph, err := createTestGraphFromChannels(true, testChannels, "a") testGraph, err := createTestGraphFromChannels(t, true, testChannels, "a")
require.NoError(t, err, "unable to create graph") require.NoError(t, err, "unable to create graph")
defer testGraph.cleanUp()
const startingBlockHeight = 101 const startingBlockHeight = 101
ctx, cleanUp := createTestCtxFromGraphInstance( ctx, cleanUp := createTestCtxFromGraphInstance(
@@ -1247,10 +1245,9 @@ func TestIgnoreChannelEdgePolicyForUnknownChannel(t *testing.T) {
// Setup an initially empty network. // Setup an initially empty network.
testChannels := []*testChannel{} testChannels := []*testChannel{}
testGraph, err := createTestGraphFromChannels( testGraph, err := createTestGraphFromChannels(
true, testChannels, "roasbeef", t, true, testChannels, "roasbeef",
) )
require.NoError(t, err, "unable to create graph") require.NoError(t, err, "unable to create graph")
defer testGraph.cleanUp()
ctx, cleanUp := createTestCtxFromGraphInstance( ctx, cleanUp := createTestCtxFromGraphInstance(
t, startingBlockHeight, testGraph, false, t, startingBlockHeight, testGraph, false,
@@ -2220,12 +2217,11 @@ func TestPruneChannelGraphStaleEdges(t *testing.T) {
// We'll create our test graph and router backed with these test // We'll create our test graph and router backed with these test
// channels we've created. // channels we've created.
testGraph, err := createTestGraphFromChannels( testGraph, err := createTestGraphFromChannels(
true, testChannels, "a", t, true, testChannels, "a",
) )
if err != nil { if err != nil {
t.Fatalf("unable to create test graph: %v", err) t.Fatalf("unable to create test graph: %v", err)
} }
defer testGraph.cleanUp()
const startingHeight = 100 const startingHeight = 100
ctx, cleanUp := createTestCtxFromGraphInstance( ctx, cleanUp := createTestCtxFromGraphInstance(
@@ -2352,10 +2348,9 @@ func testPruneChannelGraphDoubleDisabled(t *testing.T, assumeValid bool) {
// We'll create our test graph and router backed with these test // We'll create our test graph and router backed with these test
// channels we've created. // channels we've created.
testGraph, err := createTestGraphFromChannels( testGraph, err := createTestGraphFromChannels(
true, testChannels, "self", t, true, testChannels, "self",
) )
require.NoError(t, err, "unable to create test graph") require.NoError(t, err, "unable to create test graph")
defer testGraph.cleanUp()
const startingHeight = 100 const startingHeight = 100
ctx, cleanUp := createTestCtxFromGraphInstanceAssumeValid( ctx, cleanUp := createTestCtxFromGraphInstanceAssumeValid(
@@ -2711,8 +2706,7 @@ func TestUnknownErrorSource(t *testing.T) {
}, 4), }, 4),
} }
testGraph, err := createTestGraphFromChannels(true, testChannels, "a") testGraph, err := createTestGraphFromChannels(t, true, testChannels, "a")
defer testGraph.cleanUp()
require.NoError(t, err, "unable to create graph") require.NoError(t, err, "unable to create graph")
const startingBlockHeight = 101 const startingBlockHeight = 101
@@ -2843,9 +2837,8 @@ func TestSendToRouteStructuredError(t *testing.T) {
}, 2), }, 2),
} }
testGraph, err := createTestGraphFromChannels(true, testChannels, "a") testGraph, err := createTestGraphFromChannels(t, true, testChannels, "a")
require.NoError(t, err, "unable to create graph") require.NoError(t, err, "unable to create graph")
defer testGraph.cleanUp()
const startingBlockHeight = 101 const startingBlockHeight = 101
ctx, cleanUp := createTestCtxFromGraphInstance( ctx, cleanUp := createTestCtxFromGraphInstance(
@@ -2959,9 +2952,8 @@ func TestSendToRouteMaxHops(t *testing.T) {
}, 1), }, 1),
} }
testGraph, err := createTestGraphFromChannels(true, testChannels, "a") testGraph, err := createTestGraphFromChannels(t, true, testChannels, "a")
require.NoError(t, err, "unable to create graph") require.NoError(t, err, "unable to create graph")
defer testGraph.cleanUp()
const startingBlockHeight = 101 const startingBlockHeight = 101
@@ -3066,9 +3058,8 @@ func TestBuildRoute(t *testing.T) {
}, 4), }, 4),
} }
testGraph, err := createTestGraphFromChannels(true, testChannels, "a") testGraph, err := createTestGraphFromChannels(t, true, testChannels, "a")
require.NoError(t, err, "unable to create graph") require.NoError(t, err, "unable to create graph")
defer testGraph.cleanUp()
const startingBlockHeight = 101 const startingBlockHeight = 101
@@ -3304,7 +3295,7 @@ func createDummyTestGraph(t *testing.T) *testGraphInstance {
}, 2), }, 2),
} }
testGraph, err := createTestGraphFromChannels(true, testChannels, "a") testGraph, err := createTestGraphFromChannels(t, true, testChannels, "a")
require.NoError(t, err, "failed to create graph") require.NoError(t, err, "failed to create graph")
return testGraph return testGraph
} }