github.com/googleapis/api-linter@v1.65.2/rules/aip0231/response_resource_field_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 aip0231 16 17 import ( 18 "testing" 19 20 "github.com/googleapis/api-linter/rules/internal/testutils" 21 "github.com/jhump/protoreflect/desc" 22 ) 23 24 func TestResourceField(t *testing.T) { 25 // Set up the testing permutations. 26 tests := []struct { 27 testName string 28 src string 29 problems testutils.Problems 30 problemDesc func(m *desc.MessageDescriptor) desc.Descriptor 31 }{ 32 { 33 testName: "Valid", 34 src: ` 35 message BatchGetBooksResponse { 36 // Books requested. 37 repeated Book books = 1; 38 }`, 39 problems: testutils.Problems{}, 40 }, 41 { 42 testName: "ValidEs", 43 src: ` 44 message BatchGetMatchesResponse { 45 repeated Match matches = 1; 46 }`, 47 problems: testutils.Problems{}, 48 }, 49 { 50 testName: "FieldIsNotRepeated", 51 src: ` 52 message BatchGetBooksResponse { 53 // Book requested. 54 Book book = 1; 55 }`, 56 problems: testutils.Problems{{Message: "The \"Book\" type field on Batch Get Response message should be repeated"}}, 57 }, 58 { 59 testName: "MissingField", 60 src: ` 61 message BatchGetBooksResponse { 62 string response = 1; 63 }`, 64 problems: testutils.Problems{{Message: "Message \"BatchGetBooksResponse\" has no \"Book\" type field"}}, 65 problemDesc: func(m *desc.MessageDescriptor) desc.Descriptor { 66 return m 67 }, 68 }, 69 } 70 71 // Run each test individually. 72 for _, test := range tests { 73 t.Run(test.testName, func(t *testing.T) { 74 template := ` 75 {{.Src}} 76 message Book {} 77 message Match {} 78 ` 79 file := testutils.ParseProto3Tmpl(t, template, struct{ Src string }{test.src}) 80 81 m := file.GetMessageTypes()[0] 82 83 // Determine the descriptor that a failing test will attach to. 84 var problemDesc desc.Descriptor = m.GetFields()[0] 85 if test.problemDesc != nil { 86 problemDesc = test.problemDesc(m) 87 } 88 89 problems := resourceField.Lint(file) 90 if diff := test.problems.SetDescriptor(problemDesc).Diff(problems); diff != "" { 91 t.Errorf(diff) 92 } 93 }) 94 } 95 }