forked from hashicorp/consul
-
Notifications
You must be signed in to change notification settings - Fork 0
/
testing.go
79 lines (70 loc) · 2.25 KB
/
testing.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
// Copyright (c) HashiCorp, Inc.
// SPDX-License-Identifier: MPL-2.0
package structs
import (
"bytes"
"reflect"
"testing"
"github.com/hashicorp/consul-net-rpc/go-msgpack/codec"
"github.com/stretchr/testify/require"
)
// TestingOldPre1dot7MsgpackHandle is the common configuration pre-1.7.0
var TestingOldPre1dot7MsgpackHandle = &codec.MsgpackHandle{}
// TestMsgpackEncodeDecode is a test helper to easily write a test to verify
// msgpack encoding and decoding using two handles is identical.
func TestMsgpackEncodeDecode(t *testing.T, in interface{}, requireEncoderEquality bool) {
t.Helper()
var (
// This is the common configuration pre-1.7.0
handle1 = TestingOldPre1dot7MsgpackHandle
// This is the common configuration post-1.7.0
handle2 = MsgpackHandle
)
// Verify the 3 interface{} args are all pointers to the same kind of type.
inType := reflect.TypeOf(in)
require.Equal(t, reflect.Ptr, inType.Kind())
// Encode using both handles.
var b1 []byte
{
var buf bytes.Buffer
enc := codec.NewEncoder(&buf, handle1)
require.NoError(t, enc.Encode(in))
b1 = buf.Bytes()
}
var b2 []byte
{
var buf bytes.Buffer
enc := codec.NewEncoder(&buf, handle2)
require.NoError(t, enc.Encode(in))
b2 = buf.Bytes()
}
if requireEncoderEquality {
// The resulting bytes should be identical.
require.Equal(t, b1, b2)
}
// Decode both outputs using both handles.
t.Run("old encoder and old decoder", func(t *testing.T) {
out1 := reflect.New(inType.Elem()).Interface()
dec := codec.NewDecoderBytes(b1, handle1)
require.NoError(t, dec.Decode(out1))
require.Equal(t, in, out1)
})
t.Run("old encoder and new decoder", func(t *testing.T) {
out1 := reflect.New(inType.Elem()).Interface()
dec := codec.NewDecoderBytes(b1, handle2)
require.NoError(t, dec.Decode(out1))
require.Equal(t, in, out1)
})
t.Run("new encoder and old decoder", func(t *testing.T) {
out2 := reflect.New(inType.Elem()).Interface()
dec := codec.NewDecoderBytes(b2, handle1)
require.NoError(t, dec.Decode(out2))
require.Equal(t, in, out2)
})
t.Run("new encoder and new decoder", func(t *testing.T) {
out2 := reflect.New(inType.Elem()).Interface()
dec := codec.NewDecoderBytes(b2, handle2)
require.NoError(t, dec.Decode(out2))
require.Equal(t, in, out2)
})
}