-
Notifications
You must be signed in to change notification settings - Fork 279
/
testutil.go
34 lines (29 loc) · 1.05 KB
/
testutil.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
// Package testutil contains helper functions for unit tests.
package testutil
import (
"encoding/json"
"reflect"
"testing"
"github.com/golang/protobuf/proto"
"github.com/stretchr/testify/assert"
"google.golang.org/protobuf/encoding/protojson"
)
// AssertProtoJSONEqual asserts that a protobuf message matches the given JSON. The protoMsg can also be a slice
// of protobuf messages.
func AssertProtoJSONEqual(t *testing.T, expected string, protoMsg interface{}, msgAndArgs ...interface{}) bool {
protoMsgVal := reflect.ValueOf(protoMsg)
if protoMsgVal.Kind() == reflect.Slice {
var protoMsgs []json.RawMessage
for i := 0; i < protoMsgVal.Len(); i++ {
protoMsgs = append(protoMsgs, toProtoJSON(protoMsgVal.Index(i).Interface()))
}
bs, _ := json.Marshal(protoMsgs)
return assert.JSONEq(t, expected, string(bs), msgAndArgs...)
}
return assert.JSONEq(t, expected, string(toProtoJSON(protoMsg)), msgAndArgs...)
}
func toProtoJSON(protoMsg interface{}) json.RawMessage {
v2 := proto.MessageV2(protoMsg)
bs, _ := protojson.Marshal(v2)
return bs
}