github.com/googleapis/api-linter@v1.65.2/rules/aip0133/request_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 aip0133 16 17 import ( 18 "testing" 19 20 "github.com/googleapis/api-linter/rules/internal/testutils" 21 "github.com/jhump/protoreflect/desc" 22 "github.com/jhump/protoreflect/desc/builder" 23 ) 24 25 func TestResourceField(t *testing.T) { 26 // Set up the testing permutations. 27 tests := []struct { 28 testName string 29 messageName string 30 messageField *field 31 descriptor func(*desc.MessageDescriptor) desc.Descriptor 32 problems testutils.Problems 33 }{ 34 { 35 "Valid", 36 "CreateBookRequest", 37 &field{"book", builder.FieldTypeMessage(builder.NewMessage("Book"))}, 38 nil, 39 testutils.Problems{}, 40 }, 41 { 42 "MissingField", 43 "CreateBookRequest", 44 nil, 45 nil, 46 testutils.Problems{{Message: "Message \"CreateBookRequest\" has no \"Book\" type field"}}, 47 }, 48 { 49 "WrongName", 50 "CreateBookRequest", 51 &field{"payload", builder.FieldTypeMessage(builder.NewMessage("Book"))}, 52 func(m *desc.MessageDescriptor) desc.Descriptor { 53 return m.GetFields()[0] 54 }, 55 testutils.Problems{{Suggestion: "book"}}, 56 }, 57 } 58 59 // Run each test individually. 60 for _, test := range tests { 61 t.Run(test.testName, func(t *testing.T) { 62 // Create an appropriate message descriptor. 63 messageBuilder := builder.NewMessage(test.messageName) 64 65 if test.messageField != nil { 66 messageBuilder.AddField( 67 builder.NewField(test.messageField.fieldName, test.messageField.fieldType), 68 ) 69 } 70 71 message, err := messageBuilder.Build() 72 if err != nil { 73 t.Fatalf("Could not build %s message.", test.messageName) 74 } 75 76 var d desc.Descriptor = message 77 if test.descriptor != nil { 78 d = test.descriptor(message) 79 } 80 81 // Run the lint rule, and establish that it returns the correct problems. 82 problems := resourceField.Lint(message.GetFile()) 83 if diff := test.problems.SetDescriptor(d).Diff(problems); diff != "" { 84 t.Errorf(diff) 85 } 86 }) 87 } 88 }