github.com/googleapis/api-linter@v1.65.2/locations/field_locations_test.go (about) 1 // Copyright 2019 Google LLC 2 // 3 // Licensed under the Apache License, Version 2.0 (the "License"); 4 // you may not use this file except in compliance with the License. 5 // You may obtain a copy of the License at 6 // 7 // https://www.apache.org/licenses/LICENSE-2.0 8 // 9 // Unless required by applicable law or agreed to in writing, software 10 // distributed under the License is distributed on an "AS IS" BASIS, 11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 // See the License for the specific language governing permissions and 13 // limitations under the License. 14 15 package locations 16 17 import ( 18 "testing" 19 20 "github.com/google/go-cmp/cmp" 21 "github.com/jhump/protoreflect/desc" 22 apb "google.golang.org/genproto/googleapis/api/annotations" 23 ) 24 25 func TestFieldLocations(t *testing.T) { 26 f := parse(t, ` 27 message Book { 28 string name = 1; 29 Author author = 2; 30 } 31 message Author {} 32 `) 33 tests := []struct { 34 name string 35 field *desc.FieldDescriptor 36 span []int32 37 }{ 38 {"Primitive", f.GetMessageTypes()[0].GetFields()[0], []int32{3, 2, 8}}, 39 {"Composite", f.GetMessageTypes()[0].GetFields()[1], []int32{4, 2, 8}}, 40 } 41 for _, test := range tests { 42 t.Run(test.name, func(t *testing.T) { 43 l := FieldType(test.field) 44 if diff := cmp.Diff(l.GetSpan(), test.span); diff != "" { 45 t.Errorf(diff) 46 } 47 }) 48 } 49 } 50 51 func TestFieldLabel(t *testing.T) { 52 f := parse(t, ` 53 message Book { 54 string name = 1; 55 optional string author = 2; 56 } 57 `) 58 for _, test := range []struct { 59 name string 60 field *desc.FieldDescriptor 61 span []int32 62 }{ 63 {"Present", f.GetMessageTypes()[0].GetFields()[1], []int32{4, 8, 16}}, 64 {"Absent", f.GetMessageTypes()[0].GetFields()[0], nil}, 65 } { 66 t.Run(test.name, func(t *testing.T) { 67 l := FieldLabel(test.field) 68 if diff := cmp.Diff(l.GetSpan(), test.span); diff != "" { 69 t.Errorf(diff) 70 } 71 }) 72 } 73 } 74 75 func TestFieldResourceReference(t *testing.T) { 76 f := parse(t, ` 77 import "google/api/resource.proto"; 78 message GetBookRequest { 79 string name = 1 [(google.api.resource_reference) = { 80 type: "library.googleapis.com/Book" 81 }]; 82 } 83 `) 84 loc := FieldResourceReference(f.GetMessageTypes()[0].GetFields()[0]) 85 // resource_reference annotation location is roughly line 4, column 19. 86 if diff := cmp.Diff(loc.GetSpan(), []int32{4, 19, 6, 3}); diff != "" { 87 t.Errorf(diff) 88 } 89 } 90 91 func TestFieldOption(t *testing.T) { 92 f := parse(t, ` 93 import "google/api/resource.proto"; 94 message GetBookRequest { 95 string name = 1 [(google.api.resource_reference) = { 96 type: "library.googleapis.com/Book" 97 }]; 98 } 99 `) 100 loc := FieldOption(f.GetMessageTypes()[0].GetFields()[0], apb.E_ResourceReference) 101 if diff := cmp.Diff(loc.GetSpan(), []int32{4, 19, 6, 3}); diff != "" { 102 t.Errorf(diff) 103 } 104 }