Skip to content

Commit

Permalink
BPAAS-1054: Add structured logger to tests
Browse files Browse the repository at this point in the history
  • Loading branch information
boecklim committed Oct 13, 2023
1 parent a5d3b26 commit 416b26f
Show file tree
Hide file tree
Showing 7 changed files with 52 additions and 73 deletions.
35 changes: 26 additions & 9 deletions PeerManager_Mock.go
Original file line number Diff line number Diff line change
@@ -1,17 +1,34 @@
package p2p

import "github.com/libsv/go-p2p/chaincfg/chainhash"
import (
"context"
"log/slog"

type TestLogger struct{}
"github.com/libsv/go-p2p/chaincfg/chainhash"
)

func (l TestLogger) LogLevel() int {
return 0
type mockHandler struct {
}

func (h *mockHandler) Enabled(_ context.Context, _ slog.Level) bool {
return false
}

func (h *mockHandler) Handle(_ context.Context, _ slog.Record) error {
return nil
}

func (h *mockHandler) WithAttrs(_ []slog.Attr) slog.Handler {
return &mockHandler{}
}

func (h *mockHandler) WithGroup(_ string) slog.Handler {
return &mockHandler{}
}

func (h *mockHandler) Handler() slog.Handler {
return &mockHandler{}
}
func (l TestLogger) Debugf(format string, args ...interface{}) {}
func (l TestLogger) Infof(format string, args ...interface{}) {}
func (l TestLogger) Warnf(format string, args ...interface{}) {}
func (l TestLogger) Errorf(format string, args ...interface{}) {}
func (l TestLogger) Fatalf(format string, args ...interface{}) {}

type PeerManagerMock struct {
Peers []PeerI
Expand Down
8 changes: 6 additions & 2 deletions PeerManager_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package p2p

import (
"fmt"
"log/slog"
"testing"
"time"

Expand All @@ -14,10 +15,12 @@ import (
var (
tx1 = "b042f298deabcebbf15355aa3a13c7d7cfe96c44ac4f492735f936f8e50d06f6"
tx1Hash, _ = chainhash.NewHashFromStr(tx1)
logger = TestLogger{}
)

func TestNewPeerManager(t *testing.T) {

logger := slog.New(&mockHandler{})

t.Run("nil peers no error", func(t *testing.T) {
pm := NewPeerManager(logger, wire.TestNet)
require.NotNil(t, pm)
Expand Down Expand Up @@ -61,7 +64,7 @@ func TestNewPeerManager(t *testing.T) {

func TestAnnounceNewTransaction(t *testing.T) {
t.Run("announce tx", func(t *testing.T) {

logger := slog.New(&mockHandler{})
pm := NewPeerManager(logger, wire.TestNet, WithBatchDuration(1*time.Millisecond))
require.NotNil(t, pm)

Expand All @@ -82,6 +85,7 @@ func TestAnnounceNewTransaction(t *testing.T) {
})

t.Run("announce tx - multiple peers", func(t *testing.T) {
logger := slog.New(&mockHandler{})
pm := NewPeerManager(logger, wire.TestNet, WithBatchDuration(1*time.Millisecond))
require.NotNil(t, pm)

Expand Down
8 changes: 5 additions & 3 deletions Peer_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package p2p
import (
"bytes"
"encoding/binary"
"log/slog"
"net"
"testing"
"time"
Expand Down Expand Up @@ -250,9 +251,9 @@ func newTestPeer(t *testing.T) (net.Conn, *Peer, *MockPeerHandler) {
peerConn, myConn := connutil.AsyncPipe()

peerHandler := NewMockPeerHandler()

logger := slog.New(&mockHandler{})
p, err := NewPeer(
&TestLogger{},
logger,
"MockPeerHandler:0000",
peerHandler,
wire.MainNet,
Expand Down Expand Up @@ -283,8 +284,9 @@ func newTestPeer(t *testing.T) (net.Conn, *Peer, *MockPeerHandler) {
func newIncomingTestPeer(t *testing.T) (net.Conn, *Peer, *MockPeerHandler) {
peerConn, myConn := connutil.AsyncPipe()
peerHandler := NewMockPeerHandler()
logger := slog.New(&mockHandler{})
p, err := NewPeer(
&TestLogger{},
logger,
"MockPeerHandler:0000",
peerHandler,
wire.MainNet,
Expand Down
19 changes: 10 additions & 9 deletions examples/simple/handler.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,49 +3,50 @@ package main
import (
"fmt"

"log/slog"

"github.com/libsv/go-p2p"
"github.com/libsv/go-p2p/wire"
"github.com/ordishs/go-utils"
)

// SimplePeerHandler is a simple implementation of the PeerHandler interface.
// This is how you can customize the behaviour of the peer.
type SimplePeerHandler struct {
logger utils.Logger
logger *slog.Logger
}

func (s *SimplePeerHandler) HandleTransactionGet(msg *wire.InvVect, peer p2p.PeerI) ([]byte, error) {
s.logger.Infof("Peer %s requested transaction %s", peer.String(), msg.Hash.String())
s.logger.Info("Peer requested transaction", slog.String("hash", msg.Hash.String()), slog.String("peer", peer.String()))
// You should implement a store and return the transaction bytes here.
return nil, fmt.Errorf("transaction not found")
}

func (s *SimplePeerHandler) HandleTransactionSent(msg *wire.MsgTx, peer p2p.PeerI) error {
s.logger.Infof("Sent transaction %s to peer %s", msg.TxHash().String(), peer.String())
s.logger.Info("Sent transaction to peer", slog.String("hash", msg.TxHash().String()), slog.String("peer", peer.String()))
// This is called when a transaction is sent to a peer. You could save this to your store here.
return nil
}

func (s *SimplePeerHandler) HandleTransactionAnnouncement(msg *wire.InvVect, peer p2p.PeerI) error {
s.logger.Infof("Peer %s announced transaction %s", peer.String(), msg.Hash.String())
s.logger.Info("Peer announced transaction", slog.String("hash", msg.Hash.String()), slog.String("peer", peer.String()))
// This is called when a transaction is announced by a peer. Handle this as you wish.
return nil
}

func (s *SimplePeerHandler) HandleTransactionRejection(rejMsg *wire.MsgReject, peer p2p.PeerI) error {
s.logger.Infof("Peer %s rejected transaction %s", peer.String(), rejMsg.Hash.String())
s.logger.Info("Peer rejected transaction", slog.String("hash", rejMsg.Hash.String()), slog.String("peer", peer.String()))
// This is called when a transaction is rejected by a peer. Handle this as you wish.
return nil
}

func (s *SimplePeerHandler) HandleTransaction(msg *wire.MsgTx, peer p2p.PeerI) error {
s.logger.Infof("Received transaction %s from peer %s", msg.TxHash().String(), peer.String())
s.logger.Info("Received transaction from peer", slog.String("hash", msg.TxHash().String()), slog.String("peer", peer.String()))
// This is called when a transaction is received from a peer. Handle this as you wish.
return nil
}

func (s *SimplePeerHandler) HandleBlockAnnouncement(msg *wire.InvVect, peer p2p.PeerI) error {
s.logger.Infof("Peer %s announced block %s", peer.String(), msg.Hash.String())
s.logger.Info("Peer announced block", slog.String("hash", msg.Hash.String()), slog.String("peer", peer.String()))
// This is called when a block is announced by a peer. Handle this as you wish.
return nil
}
Expand All @@ -56,7 +57,7 @@ func (s *SimplePeerHandler) HandleBlock(msg wire.Message, peer p2p.PeerI) error
return fmt.Errorf("failed to cast message to block message")
}

s.logger.Infof("Received block %s from peer %s", blockMsg.Header.BlockHash().String(), peer.String())
s.logger.Info("Received block from peer", slog.String("hash", blockMsg.Header.BlockHash().String()), slog.String("peer", peer.String()))
// This is called when a block is received from a peer. Handle this as you wish.
// note: the block message is a custom BlockMessage and not a wire.MsgBlock
return nil
Expand Down
8 changes: 4 additions & 4 deletions examples/simple/main.go
Original file line number Diff line number Diff line change
@@ -1,16 +1,16 @@
package main

import (
"log/slog"
"os"
"os/signal"

"github.com/libsv/go-p2p"
"github.com/libsv/go-p2p/wire"
"github.com/ordishs/gocore"
)

func main() {
logger := gocore.Log("simple-p2p-test")
logger := slog.New(slog.NewJSONHandler(os.Stdout, &slog.HandlerOptions{Level: slog.LevelInfo}))

// Make sure to use the correct network here.
// For mainnet use wire.MainNet
Expand All @@ -26,11 +26,11 @@ func main() {

peer, err := p2p.NewPeer(logger, "localhost:58333", peerHandler, network)
if err != nil {
logger.Fatalf("failed to create peer: %s", err)
logger.Error("failed to create peer", slog.String("err", err.Error()))
}

if err = peerManager.AddPeer(peer); err != nil {
logger.Fatalf("failed to add peer: %s", err)
logger.Error("failed to add peer", slog.String("err", err.Error()))
}

// setup signal catching
Expand Down
8 changes: 1 addition & 7 deletions go.mod
Original file line number Diff line number Diff line change
@@ -1,21 +1,15 @@
module github.com/libsv/go-p2p

go 1.21
go 1.21.3

require (
github.com/cbeuw/connutil v0.0.0-20200411215123-966bfaa51ee3
github.com/davecgh/go-spew v1.1.1
github.com/ordishs/go-utils v1.0.24
github.com/ordishs/gocore v1.0.33
github.com/stretchr/testify v1.8.1
)

require (
github.com/mattn/go-colorable v0.1.13 // indirect
github.com/mattn/go-isatty v0.0.16 // indirect
github.com/mgutz/ansi v0.0.0-20170206155736-9520e82c474b // indirect
github.com/pmezard/go-difflib v1.0.0 // indirect
golang.org/x/sys v0.3.0 // indirect
golang.org/x/text v0.6.0 // indirect
gopkg.in/yaml.v3 v3.0.1 // indirect
)
39 changes: 0 additions & 39 deletions go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -3,18 +3,8 @@ github.com/cbeuw/connutil v0.0.0-20200411215123-966bfaa51ee3/go.mod h1:6jR2SzckG
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/mattn/go-colorable v0.1.2/go.mod h1:U0ppj6V5qS13XJ6of8GYAs25YV2eR4EVcfRqFIhoBtE=
github.com/mattn/go-colorable v0.1.13 h1:fFA4WZxdEF4tXPZVKMLwD8oUnCTTo08duU7wxecdEvA=
github.com/mattn/go-colorable v0.1.13/go.mod h1:7S9/ev0klgBDR4GtXTXX8a3vIGJpMovkB8vQcUbaXHg=
github.com/mattn/go-isatty v0.0.8/go.mod h1:Iq45c/XA43vh69/j3iqttzPXn0bhXyGjM0Hdxcsrc5s=
github.com/mattn/go-isatty v0.0.16 h1:bq3VjFmv/sOjHtdEhmkEV4x1AJtvUvOJ2PFAZ5+peKQ=
github.com/mattn/go-isatty v0.0.16/go.mod h1:kYGgaQfpe5nmfYZH+SKPsOc2e4SrIfOl2e/yFXSvRLM=
github.com/mgutz/ansi v0.0.0-20170206155736-9520e82c474b h1:j7+1HpAFS1zy5+Q4qx1fWh90gTKwiN4QCGoY9TWyyO4=
github.com/mgutz/ansi v0.0.0-20170206155736-9520e82c474b/go.mod h1:01TrycV0kFyexm33Z7vhZRXopbI8J3TDReVlkTgMUxE=
github.com/ordishs/go-utils v1.0.24 h1:QIVYaaN4LE5SnCRbLii7OOrkC2Qqvg4FVKe9zzA3Yd8=
github.com/ordishs/go-utils v1.0.24/go.mod h1:k9G7Bbv2GwoOn9fwZx70yM5jwwIymkv+90FUKLudtyc=
github.com/ordishs/gocore v1.0.33 h1:pJbrmi9OMNu73RtUpuzJK/4uvwgYmvuPlb6WxwYPW1g=
github.com/ordishs/gocore v1.0.33/go.mod h1:Nm48yxIUBuKvVXwLC8bB8aQDNUsBpaoVRTtcmjKlhrQ=
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
Expand All @@ -24,35 +14,6 @@ github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/
github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU=
github.com/stretchr/testify v1.8.1 h1:w7B6lhMri9wdJUVmEZPGGhZzrYTPvgJArz7wNPgYKsk=
github.com/stretchr/testify v1.8.1/go.mod h1:w2LPCIKwWwSfY2zedu0+kehJoqGctiVI29o6fzry7u4=
github.com/yuin/goldmark v1.4.13/go.mod h1:6yULJ656Px+3vBD8DxQVa3kxgyrAnzto9xy5taEt/CY=
golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
golang.org/x/crypto v0.0.0-20210921155107-089bfa567519/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc=
golang.org/x/mod v0.6.0-dev.0.20220419223038-86c51ed26bb4/go.mod h1:jJ57K6gSWd91VN4djpZkiMVwK6gcyfeH4XE8wZrZaV4=
golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=
golang.org/x/net v0.0.0-20210226172049-e18ecbb05110/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg=
golang.org/x/net v0.0.0-20220722155237-a158d28d115b/go.mod h1:XRhObCWvk6IyKnWLug+ECip1KBveYUHfp+8e9klMJ9c=
golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sync v0.0.0-20220722155255-886fb9371eb4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
golang.org/x/sys v0.0.0-20190222072716-a9d3bda3a223/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20210615035016-665e8c7367d1/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.0.0-20220520151302-bc2c85ada10a/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.0.0-20220722155257-8c9f86f7a55f/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.0.0-20220811171246-fbc7d0a398ab/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.3.0 h1:w8ZOecv6NaNa/zC8944JTU3vz4u6Lagfk4RPQxv92NQ=
golang.org/x/sys v0.3.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo=
golang.org/x/term v0.0.0-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8=
golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
golang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ=
golang.org/x/text v0.6.0 h1:3XmdazWV+ubf7QgHSTWeykHOci5oeekaGJBLkrkaw4k=
golang.org/x/text v0.6.0/go.mod h1:mrYo+phRRbMaCq/xk9113O4dZlRixOauAjOtrjsXDZ8=
golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo=
golang.org/x/tools v0.1.12/go.mod h1:hNGJHUnrk76NpqgfD5Aqm5Crs+Hm0VOH/i9J2+nxYbc=
golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
Expand Down

0 comments on commit 416b26f

Please sign in to comment.