github.com/ali-iotechsys/cli@v20.10.0+incompatible/internal/test/output/output.go (about)

     1  package output
     2  
     3  import (
     4  	"strings"
     5  	"testing"
     6  
     7  	"github.com/pkg/errors"
     8  )
     9  
    10  // Assert checks output lines at specified locations
    11  func Assert(t *testing.T, actual string, expectedLines map[int]func(string) error) {
    12  	t.Helper()
    13  	for i, line := range strings.Split(actual, "\n") {
    14  		cmp, ok := expectedLines[i]
    15  		if !ok {
    16  			continue
    17  		}
    18  		if err := cmp(line); err != nil {
    19  			t.Errorf("line %d: %s", i, err)
    20  		}
    21  	}
    22  	if t.Failed() {
    23  		t.Log(actual)
    24  	}
    25  }
    26  
    27  // Prefix returns whether the line has the specified string as prefix
    28  func Prefix(expected string) func(string) error {
    29  	return func(actual string) error {
    30  		if strings.HasPrefix(actual, expected) {
    31  			return nil
    32  		}
    33  		return errors.Errorf("expected %q to start with %q", actual, expected)
    34  	}
    35  }
    36  
    37  // Suffix returns whether the line has the specified string as suffix
    38  func Suffix(expected string) func(string) error {
    39  	return func(actual string) error {
    40  		if strings.HasSuffix(actual, expected) {
    41  			return nil
    42  		}
    43  		return errors.Errorf("expected %q to end with %q", actual, expected)
    44  	}
    45  }
    46  
    47  // Contains returns whether the line contains the specified string
    48  func Contains(expected string) func(string) error {
    49  	return func(actual string) error {
    50  		if strings.Contains(actual, expected) {
    51  			return nil
    52  		}
    53  		return errors.Errorf("expected %q to contain %q", actual, expected)
    54  	}
    55  }
    56  
    57  // Equals returns whether the line is the same as the specified string
    58  func Equals(expected string) func(string) error {
    59  	return func(actual string) error {
    60  		if expected == actual {
    61  			return nil
    62  		}
    63  		return errors.Errorf("got %q, expected %q", actual, expected)
    64  	}
    65  }