github.com/googleapis/api-linter@v1.65.2/rules/internal/testutils/problems.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 testutils 16 17 import ( 18 "strings" 19 20 "github.com/google/go-cmp/cmp" 21 "github.com/googleapis/api-linter/lint" 22 "github.com/jhump/protoreflect/desc" 23 ) 24 25 // Problems is a slice of individual Problem objects. 26 type Problems []lint.Problem 27 28 // Diff determines whether a Problem is sufficiently similar to another 29 // to be considered equivalent, and returns a diff otherwise. 30 // 31 // This is intended for unit tests and is intentially generous on what 32 // constitutes equality. 33 func (problems Problems) Diff(other []lint.Problem) string { 34 // If the problems differ in length, they are by definition unequal. 35 if len(problems) != len(other) { 36 return cmp.Diff(problems, other) 37 } 38 39 // Iterate over the individual problems and determine whether they are 40 // sufficiently equivalent. 41 for i := range problems { 42 x, y := problems[i], other[i] 43 44 // The descriptors must exactly match, otherwise the problems are unequal. 45 if x.Descriptor != y.Descriptor { 46 return cmp.Diff(problems, other) 47 } 48 49 // The suggestions, if present, must exactly match. 50 if x.Suggestion != y.Suggestion { 51 return cmp.Diff(problems, other) 52 } 53 54 // When comparing messages, we want to know if the test string is a 55 // substring of the actual one. 56 if !strings.Contains(y.Message, x.Message) { 57 return cmp.Diff(problems, other) 58 } 59 } 60 61 // These sets of problems are sufficiently equal. 62 return "" 63 } 64 65 // SetDescriptor sets the given descriptor to every Problem in the slice and 66 // returns the slice back. 67 // 68 // This is intended primarily for use in unit tests. 69 func (problems Problems) SetDescriptor(d desc.Descriptor) Problems { 70 for i := range problems { 71 problems[i].Descriptor = d 72 } 73 return problems 74 }