istio.io/istio@v0.0.0-20240520182934-d79c90f27776/pkg/test/framework/components/echo/match/matcher.go (about)

     1  // Copyright Istio Authors
     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  //     http://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 match
    16  
    17  import (
    18  	"errors"
    19  
    20  	"istio.io/istio/pkg/test"
    21  	"istio.io/istio/pkg/test/framework/components/echo"
    22  )
    23  
    24  // Matcher is used to filter matching instances
    25  type Matcher func(echo.Instance) bool
    26  
    27  // GetMatches returns the subset of echo.Instances that match this Matcher.
    28  func (m Matcher) GetMatches(i echo.Instances) echo.Instances {
    29  	out := make(echo.Instances, 0)
    30  	for _, i := range i {
    31  		if m(i) {
    32  			out = append(out, i)
    33  		}
    34  	}
    35  	return out
    36  }
    37  
    38  // GetServiceMatches returns the subset of echo.Services that match this Matcher.
    39  func (m Matcher) GetServiceMatches(services echo.Services) echo.Services {
    40  	out := make(echo.Services, 0)
    41  	for _, s := range services {
    42  		if len(s) > 0 && m(s[0]) {
    43  			out = append(out, s)
    44  		}
    45  	}
    46  	return out
    47  }
    48  
    49  // First finds the first Instance that matches the Matcher.
    50  func (m Matcher) First(i echo.Instances) (echo.Instance, error) {
    51  	for _, i := range i {
    52  		if m(i) {
    53  			return i, nil
    54  		}
    55  	}
    56  
    57  	return nil, errors.New("found 0 matching echo instances")
    58  }
    59  
    60  // FirstOrFail calls First and then fails the test if an error occurs.
    61  func (m Matcher) FirstOrFail(t test.Failer, i echo.Instances) echo.Instance {
    62  	res, err := m.First(i)
    63  	if err != nil {
    64  		t.Fatal(err)
    65  	}
    66  	return res
    67  }
    68  
    69  // Any indicates whether any echo.Instance matches this matcher.
    70  func (m Matcher) Any(i echo.Instances) bool {
    71  	for _, i := range i {
    72  		if m(i) {
    73  			return true
    74  		}
    75  	}
    76  	return false
    77  }
    78  
    79  func (m Matcher) All(i echo.Instances) bool {
    80  	for _, i := range i {
    81  		if !m(i) {
    82  			return false
    83  		}
    84  	}
    85  
    86  	return true
    87  }