@@ -34,6 +34,7 @@ package jsonpb
34
34
import (
35
35
"bytes"
36
36
"encoding/json"
37
+ "errors"
37
38
"io"
38
39
"math"
39
40
"reflect"
@@ -533,6 +534,26 @@ func TestMarshalAnyJSONPBMarshaler(t *testing.T) {
533
534
}
534
535
}
535
536
537
+ func TestMarshalWithCustomValidation (t * testing.T ) {
538
+ msg := dynamicMessage {rawJson : `{ "foo": "bar", "baz": [0, 1, 2, 3] }` , dummy1 : & dynamicMessage {}}
539
+
540
+ js , err := new (Marshaler ).MarshalToString (& msg )
541
+ if err != nil {
542
+ t .Errorf ("an unexpected error occurred when marshalling to json: %v" , err )
543
+ }
544
+ err = Unmarshal (strings .NewReader (js ), & msg )
545
+ if err != nil {
546
+ t .Errorf ("an unexpected error occurred when unmarshalling from json: %v" , err )
547
+ }
548
+
549
+ // tickle an error in custom validation
550
+ msg .dummy2 = int32 (len (msg .rawJson ) + 1 )
551
+ _ , err = new (Marshaler ).MarshalToString (& msg )
552
+ if err == nil {
553
+ t .Errorf ("marshalling to json should have generated validation error but did not" )
554
+ }
555
+ }
556
+
536
557
// Test marshaling message containing unset required fields should produce error.
537
558
func TestMarshalUnsetRequiredFields (t * testing.T ) {
538
559
msgExt := & pb.Real {}
@@ -1004,6 +1025,13 @@ func (s *stringField) UnmarshalJSONPB(jum *Unmarshaler, js []byte) error {
1004
1025
// It provides implementations of JSONPBMarshaler and JSONPBUnmarshaler for JSON support.
1005
1026
type dynamicMessage struct {
1006
1027
rawJson string `protobuf:"bytes,1,opt,name=rawJson"`
1028
+
1029
+ // an unexported nested message is present just to ensure that it
1030
+ // won't result in a panic (see issue #509)
1031
+ dummy1 * dynamicMessage `protobuf:"bytes,2,opt,name=dummy1"`
1032
+
1033
+ // this is used to implement a custom validation rule
1034
+ dummy2 int32 `protobuf:"varint,3,opt,name=dummy2"`
1007
1035
}
1008
1036
1009
1037
func (m * dynamicMessage ) Reset () {
@@ -1026,6 +1054,13 @@ func (m *dynamicMessage) UnmarshalJSONPB(jum *Unmarshaler, js []byte) error {
1026
1054
return nil
1027
1055
}
1028
1056
1057
+ func (m * dynamicMessage ) ValidateRecursive () error {
1058
+ if int (m .dummy2 ) > len (m .rawJson ) {
1059
+ return errors .New ("dummy2 should be <= rawJson length" )
1060
+ }
1061
+ return nil
1062
+ }
1063
+
1029
1064
// Test unmarshaling message containing unset required fields should produce error.
1030
1065
func TestUnmarshalUnsetRequiredFields (t * testing.T ) {
1031
1066
tests := []struct {
0 commit comments