mirror of
https://github.com/protocolbuffers/protobuf-go.git
synced 2024-12-28 00:19:55 +00:00
b0c26f1868
This adds a experimental function to the internal/impl package which validates a wire-format message against a message type. The validator reports whether the message can be successfully unmarshaled, and whether the result is initialized (all required fields are set). In some cases, the validator returns ambiguous results when full validation would be expensive. The validator is unused outside of tests. In the future, it may be used to permit lazy unmarshaling of some data. It is being added now for testing; in particular, the wire fuzzer now checks the validator output for consistency with the unmarshaler. The validator adds a small amount of unused per-MessageType state. If this becomes a concern, we could conditionalize it with a build tag. Change-Id: I4216ef81d6a9ed975302eed189b02d08608858b4 Reviewed-on: https://go-review.googlesource.com/c/protobuf/+/212302 Reviewed-by: Joe Tsai <thebrokentoaster@gmail.com>
56 lines
1.7 KiB
Go
56 lines
1.7 KiB
Go
// Copyright 2019 The Go Authors. All rights reserved.
|
|
// Use of this source code is governed by a BSD-style.
|
|
// license that can be found in the LICENSE file.
|
|
|
|
package proto_test
|
|
|
|
import (
|
|
"fmt"
|
|
"testing"
|
|
|
|
"google.golang.org/protobuf/internal/impl"
|
|
"google.golang.org/protobuf/reflect/protoregistry"
|
|
piface "google.golang.org/protobuf/runtime/protoiface"
|
|
)
|
|
|
|
// TestValidate tests the internal message validator.
|
|
//
|
|
// Despite being more properly associated with the internal/impl package,
|
|
// it is located here to take advantage of the test wire encoder/decoder inputs.
|
|
|
|
func TestValidateValid(t *testing.T) {
|
|
for _, test := range testValidMessages {
|
|
for _, m := range test.decodeTo {
|
|
t.Run(fmt.Sprintf("%s (%T)", test.desc, m), func(t *testing.T) {
|
|
mt := m.ProtoReflect().Type()
|
|
want := impl.ValidationValidInitialized
|
|
if test.validationStatus != 0 {
|
|
want = test.validationStatus
|
|
} else if test.partial {
|
|
want = impl.ValidationValidMaybeUninitalized
|
|
}
|
|
var opts piface.UnmarshalOptions
|
|
opts.Resolver = protoregistry.GlobalTypes
|
|
if got, want := impl.Validate(test.wire, mt, opts), want; got != want {
|
|
t.Errorf("Validate(%x) = %v, want %v", test.wire, got, want)
|
|
}
|
|
})
|
|
}
|
|
}
|
|
}
|
|
|
|
func TestValidateInvalid(t *testing.T) {
|
|
for _, test := range testInvalidMessages {
|
|
for _, m := range test.decodeTo {
|
|
t.Run(fmt.Sprintf("%s (%T)", test.desc, m), func(t *testing.T) {
|
|
mt := m.ProtoReflect().Type()
|
|
var opts piface.UnmarshalOptions
|
|
opts.Resolver = protoregistry.GlobalTypes
|
|
if got, want := impl.Validate(test.wire, mt, opts), impl.ValidationInvalid; got != want {
|
|
t.Errorf("Validate(%x) = %v, want %v", test.wire, got, want)
|
|
}
|
|
})
|
|
}
|
|
}
|
|
}
|