github.com/prysmaticlabs/prysm@v1.4.4/beacon-chain/sync/decode_pubsub_test.go (about) 1 package sync 2 3 import ( 4 "bytes" 5 "reflect" 6 "testing" 7 8 "github.com/d4l3k/messagediff" 9 pubsub "github.com/libp2p/go-libp2p-pubsub" 10 pb "github.com/libp2p/go-libp2p-pubsub/pb" 11 "github.com/prysmaticlabs/prysm/beacon-chain/p2p" 12 p2ptesting "github.com/prysmaticlabs/prysm/beacon-chain/p2p/testing" 13 ethpb "github.com/prysmaticlabs/prysm/proto/eth/v1alpha1" 14 "github.com/prysmaticlabs/prysm/shared/testutil" 15 "google.golang.org/protobuf/proto" 16 ) 17 18 func TestService_decodePubsubMessage(t *testing.T) { 19 tests := []struct { 20 name string 21 topic string 22 input *pubsub.Message 23 want proto.Message 24 wantErr error 25 }{ 26 { 27 name: "Nil message", 28 input: nil, 29 wantErr: errNilPubsubMessage, 30 }, 31 { 32 name: "nil topic", 33 input: &pubsub.Message{ 34 Message: &pb.Message{ 35 Topic: nil, 36 }, 37 }, 38 wantErr: errNilPubsubMessage, 39 }, 40 { 41 name: "invalid topic format", 42 topic: "foo", 43 wantErr: errInvalidTopic, 44 }, 45 { 46 name: "topic not mapped to any message type", 47 topic: "/eth2/abcdef/foo", 48 wantErr: p2p.ErrMessageNotMapped, 49 }, 50 { 51 name: "valid message -- beacon block", 52 topic: p2p.GossipTypeMapping[reflect.TypeOf(ðpb.SignedBeaconBlock{})], 53 input: &pubsub.Message{ 54 Message: &pb.Message{ 55 Data: func() []byte { 56 buf := new(bytes.Buffer) 57 if _, err := p2ptesting.NewTestP2P(t).Encoding().EncodeGossip(buf, testutil.NewBeaconBlock()); err != nil { 58 t.Fatal(err) 59 } 60 return buf.Bytes() 61 }(), 62 }, 63 }, 64 wantErr: nil, 65 want: testutil.NewBeaconBlock(), 66 }, 67 } 68 for _, tt := range tests { 69 t.Run(tt.name, func(t *testing.T) { 70 s := &Service{ 71 cfg: &Config{P2P: p2ptesting.NewTestP2P(t)}, 72 } 73 if tt.topic != "" { 74 if tt.input == nil { 75 tt.input = &pubsub.Message{Message: &pb.Message{}} 76 } else if tt.input.Message == nil { 77 tt.input.Message = &pb.Message{} 78 } 79 tt.input.Message.Topic = &tt.topic 80 } 81 got, err := s.decodePubsubMessage(tt.input) 82 if err != tt.wantErr { 83 t.Errorf("decodePubsubMessage() error = %v, wantErr %v", err, tt.wantErr) 84 return 85 } 86 if !reflect.DeepEqual(got, tt.want) { 87 diff, _ := messagediff.PrettyDiff(got, tt.want) 88 t.Log(diff) 89 t.Errorf("decodePubsubMessage() got = %v, want %v", got, tt.want) 90 } 91 }) 92 } 93 }