Skip to content

Commit

Permalink
chore: add side-by-side tests with official proto.Marshal and Unmarshal
Browse files Browse the repository at this point in the history
This tests ensures that our encoding is compatible with official proto modules.

Closes #2

Signed-off-by: Dmitriy Matrenichev <dmitry.matrenichev@siderolabs.com>
  • Loading branch information
DmitriyMV committed Jul 26, 2022
1 parent 2519db3 commit f303808
Show file tree
Hide file tree
Showing 5 changed files with 862 additions and 1 deletion.
2 changes: 1 addition & 1 deletion marshal.go
Original file line number Diff line number Diff line change
Expand Up @@ -109,7 +109,7 @@ func (m *marshaller) encodeFields(val reflect.Value, fieldsData []FieldData) {
}

if noneEncoded {
panic("struct has no marshallable fields")
panic(fmt.Errorf("struct '%s' has no marshallable fields", val.Type().Name()))
}
}

Expand Down
73 changes: 73 additions & 0 deletions messages/helpers_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,73 @@
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/.

package messages_test

import (
"reflect"
"testing"

"github.com/google/go-cmp/cmp"
"github.com/google/go-cmp/cmp/cmpopts"
"github.com/stretchr/testify/require"
"google.golang.org/protobuf/proto"

"github.com/siderolabs/protoenc"
)

func shouldBeEqual[T any](t *testing.T, left, right T) {
t.Helper()

opts := makeOpts[T]()

if !cmp.Equal(left, right, opts...) {
t.Log(cmp.Diff(left, right, opts...))
t.FailNow()
}
}

func makeOpts[T any]() []cmp.Option {
var zero T

typ := reflect.TypeOf(zero)
for typ.Kind() == reflect.Ptr {
typ = typ.Elem()
}

if typ.Kind() == reflect.Struct {
return []cmp.Option{cmpopts.IgnoreUnexported(reflect.New(typ).Elem().Interface())}
}

return nil
}

type msg[T any] interface {
*T
proto.Message
}

func protoUnmarshal[T any, V msg[T]](t *testing.T, data []byte) V {
t.Helper()
var msg T
err := proto.Unmarshal(data, V(&msg))
require.NoError(t, err)
return V(&msg)
}

func ourUnmarshal[T any](t *testing.T, data []byte) T {
t.Helper()
var msg T
err := protoenc.Unmarshal(data, &msg)
require.NoError(t, err)
return msg
}

func must[T any](v T, err error) func(t *testing.T) T {
return func(t *testing.T) T {
t.Helper()
require.NoError(t, err)

return v
}
}
Loading

0 comments on commit f303808

Please sign in to comment.