istio.io/istio@v0.0.0-20240520182934-d79c90f27776/istioctl/pkg/util/testutil/util.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 testutil
    16  
    17  import (
    18  	"bytes"
    19  	"regexp"
    20  	"strings"
    21  	"testing"
    22  
    23  	"github.com/spf13/cobra"
    24  
    25  	"istio.io/istio/pilot/test/util"
    26  )
    27  
    28  type TestCase struct {
    29  	Args []string
    30  
    31  	// Typically use one of the three
    32  	ExpectedOutput string         // Expected constant output
    33  	ExpectedRegexp *regexp.Regexp // Expected regexp output
    34  	GoldenFilename string         // Expected output stored in golden file
    35  
    36  	WantException bool
    37  }
    38  
    39  func VerifyOutput(t *testing.T, cmd *cobra.Command, c TestCase) {
    40  	t.Helper()
    41  
    42  	cmd.SetArgs(c.Args)
    43  
    44  	var out bytes.Buffer
    45  	cmd.SetOut(&out)
    46  	cmd.SetErr(&out)
    47  	cmd.SilenceUsage = true
    48  
    49  	fErr := cmd.Execute()
    50  	output := out.String()
    51  
    52  	if c.ExpectedOutput != "" && c.ExpectedOutput != output {
    53  		t.Fatalf("Unexpected output for '%s %s'\n got: %q\nwant: %q", cmd.Name(),
    54  			strings.Join(c.Args, " "), output, c.ExpectedOutput)
    55  	}
    56  
    57  	if c.ExpectedRegexp != nil && !c.ExpectedRegexp.MatchString(output) {
    58  		t.Fatalf("Output didn't match for '%s %s'\n got %v\nwant: %v", cmd.Name(),
    59  			strings.Join(c.Args, " "), output, c.ExpectedRegexp)
    60  	}
    61  
    62  	if c.GoldenFilename != "" {
    63  		util.CompareContent(t, []byte(output), c.GoldenFilename)
    64  	}
    65  
    66  	if c.WantException {
    67  		if fErr == nil {
    68  			t.Fatalf("Wanted an exception for 'istioctl %s', didn't get one, output was %q",
    69  				strings.Join(c.Args, " "), output)
    70  		}
    71  	} else {
    72  		if fErr != nil {
    73  			t.Fatalf("Unwanted exception for 'istioctl %s': %v", strings.Join(c.Args, " "), fErr)
    74  		}
    75  	}
    76  }