|
| 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