Skip to content

Commit

Permalink
Validate optional fields correctly
Browse files Browse the repository at this point in the history
  • Loading branch information
felipeparaujo committed Sep 26, 2023
1 parent d1496ba commit 8d2e889
Show file tree
Hide file tree
Showing 4 changed files with 56 additions and 25 deletions.
7 changes: 5 additions & 2 deletions fieldbehavior/fieldbehavior.go
Original file line number Diff line number Diff line change
Expand Up @@ -62,13 +62,16 @@ func CopyFields(dst, src proto.Message, behaviorsToCopy ...annotations.FieldBeha
}

func isMessageFieldPresent(m protoreflect.Message, f protoreflect.FieldDescriptor) bool {
return isPresent(m.Get(f), f)
return isPresent(m.Get(f), f, m.Has(f))
}

func isPresent(v protoreflect.Value, f protoreflect.FieldDescriptor) bool {
func isPresent(v protoreflect.Value, f protoreflect.FieldDescriptor, populated bool) bool {
if !v.IsValid() {
return false
}
if f.HasOptionalKeyword() && populated {
return true
}
if f.IsList() {
return v.List().Len() > 0
}
Expand Down
11 changes: 11 additions & 0 deletions fieldbehavior/fieldbehavior_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -100,6 +100,17 @@ func TestValidateRequiredFieldsWithMask(t *testing.T) {
"missing required field: shipment.origin_site",
)
})
t.Run("missing optional field annotated with required", func(t *testing.T) {
t.Parallel()
assert.Error(
t,
ValidateRequiredFieldsWithMask(
&examplefreightv1.Site{},
&fieldmaskpb.FieldMask{Paths: []string{"personnel_count"}},
),
"missing required field: personnel_count",
)
})
t.Run("missing nested not in mask", func(t *testing.T) {
t.Parallel()
assert.NilError(
Expand Down
2 changes: 2 additions & 0 deletions proto/einride/example/freight/v1/site.proto
Original file line number Diff line number Diff line change
Expand Up @@ -30,4 +30,6 @@ message Site {
string display_name = 5 [(google.api.field_behavior) = REQUIRED];
// The geographic location of the site.
google.type.LatLng lat_lng = 6;
// Personnel count on site.
optional int64 personnel_count = 7 [(google.api.field_behavior) = REQUIRED];
}
61 changes: 38 additions & 23 deletions proto/gen/einride/example/freight/v1/site.pb.go

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

0 comments on commit 8d2e889

Please sign in to comment.