Skip to content

Commit 05a6b68

Browse files
committed
lnwire: add new TestSerializedSize method
This uses all the interfaces and implementations added in the prior test.
1 parent b2f2478 commit 05a6b68

File tree

2 files changed

+70
-1
lines changed

2 files changed

+70
-1
lines changed

lnwire/pong.go

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -39,7 +39,8 @@ func NewPong(pongBytes []byte) *Pong {
3939
// A compile time check to ensure Pong implements the lnwire.Message interface.
4040
var _ Message = (*Pong)(nil)
4141

42-
// A compile time check to ensure Pong implements the lnwire.SizeableMessage interface.
42+
// A compile time check to ensure Pong implements the lnwire.SizeableMessage
43+
// interface.
4344
var _ SizeableMessage = (*Pong)(nil)
4445

4546
// Decode deserializes a serialized Pong message stored in the passed io.Reader

lnwire/serialized_size_test.go

Lines changed: 68 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,68 @@
1+
package lnwire
2+
3+
import (
4+
"bytes"
5+
"math"
6+
"testing"
7+
8+
"github.com/stretchr/testify/require"
9+
"pgregory.net/rapid"
10+
)
11+
12+
// TestSerializedSize uses property-based testing to verify that
13+
// SerializedSize returns the correct value for randomly generated messages.
14+
func TestSerializedSize(t *testing.T) {
15+
t.Parallel()
16+
17+
rapid.Check(t, func(t *rapid.T) {
18+
// Pick a random message type.
19+
msgType := rapid.Custom(func(t *rapid.T) MessageType {
20+
return MessageType(
21+
rapid.IntRange(
22+
0, int(math.MaxUint16),
23+
).Draw(t, "msgType"),
24+
)
25+
}).Draw(t, "msgType")
26+
27+
// Create an empty message of the given type.
28+
m, err := MakeEmptyMessage(msgType)
29+
30+
// An error means this isn't a valid message type, so we skip
31+
// it.
32+
if err != nil {
33+
return
34+
}
35+
36+
testMsg, ok := m.(TestMessage)
37+
require.True(
38+
t, ok, "message type %s does not "+
39+
"implement TestMessage", msgType,
40+
)
41+
42+
// Use the testMsg to make a new random message.
43+
msg := testMsg.RandTestMessage(t)
44+
45+
// Type assertion to ensure the message implements
46+
// SizeableMessage.
47+
sizeMsg, ok := msg.(SizeableMessage)
48+
require.True(
49+
t, ok, "message type %s does not "+
50+
"implement SizeableMessage", msgType,
51+
)
52+
53+
// Get the size using SerializedSize.
54+
size, err := sizeMsg.SerializedSize()
55+
require.NoError(t, err, "SerializedSize error")
56+
57+
// Get the size by actually serializing the message.
58+
var buf bytes.Buffer
59+
writtenBytes, err := WriteMessage(&buf, msg, 0)
60+
require.NoError(t, err, "WriteMessage error")
61+
62+
// The SerializedSize should match the number of bytes written.
63+
require.Equal(t, uint32(writtenBytes), size,
64+
"SerializedSize = %d, actual bytes "+
65+
"written = %d for message type %s (populated)",
66+
size, writtenBytes, msgType)
67+
})
68+
}

0 commit comments

Comments
 (0)