github.com/portworx/docker@v1.12.1/pkg/testutil/assert/assert.go (about)

     1  // Package assert contains functions for making assertions in unit tests
     2  package assert
     3  
     4  import (
     5  	"fmt"
     6  	"path/filepath"
     7  	"runtime"
     8  	"strings"
     9  )
    10  
    11  // TestingT is an interface which defines the methods of testing.T that are
    12  // required by this package
    13  type TestingT interface {
    14  	Fatalf(string, ...interface{})
    15  }
    16  
    17  // Equal compare the actual value to the expected value and fails the test if
    18  // they are not equal.
    19  func Equal(t TestingT, actual, expected interface{}) {
    20  	if expected != actual {
    21  		fatal(t, fmt.Sprintf("Expected '%v' (%T) got '%v' (%T)", expected, expected, actual, actual))
    22  	}
    23  }
    24  
    25  //EqualStringSlice compares two slices and fails the test if they do not contain
    26  // the same items.
    27  func EqualStringSlice(t TestingT, actual, expected []string) {
    28  	if len(actual) != len(expected) {
    29  		t.Fatalf("Expected (length %d): %q\nActual (length %d): %q",
    30  			len(expected), expected, len(actual), actual)
    31  	}
    32  	for i, item := range actual {
    33  		if item != expected[i] {
    34  			t.Fatalf("Slices differ at element %d, expected %q got %q",
    35  				i, expected[i], item)
    36  		}
    37  	}
    38  }
    39  
    40  // NilError asserts that the error is nil, otherwise it fails the test.
    41  func NilError(t TestingT, err error) {
    42  	if err != nil {
    43  		fatal(t, fmt.Sprintf("Expected no error, got: %s", err.Error()))
    44  	}
    45  }
    46  
    47  // Error asserts that error is not nil, and contains the expected text,
    48  // otherwise it fails the test.
    49  func Error(t TestingT, err error, contains string) {
    50  	if err == nil {
    51  		fatal(t, "Expected an error, but error was nil")
    52  	}
    53  
    54  	if !strings.Contains(err.Error(), contains) {
    55  		fatal(t, fmt.Sprintf("Expected error to contain '%s', got '%s'", contains, err.Error()))
    56  	}
    57  }
    58  
    59  // Contains asserts that the string contains a substring, otherwise it fails the
    60  // test.
    61  func Contains(t TestingT, actual, contains string) {
    62  	if !strings.Contains(actual, contains) {
    63  		fatal(t, fmt.Sprintf("Expected '%s' to contain '%s'", actual, contains))
    64  	}
    65  }
    66  
    67  func fatal(t TestingT, msg string) {
    68  	_, file, line, _ := runtime.Caller(2)
    69  	t.Fatalf("%s:%d: %s", filepath.Base(file), line, msg)
    70  }