github.com/gophercloud/gophercloud@v1.11.0/testhelper/convenience.go (about)

     1  package testhelper
     2  
     3  import (
     4  	"bytes"
     5  	"encoding/json"
     6  	"errors"
     7  	"fmt"
     8  	"path/filepath"
     9  	"reflect"
    10  	"runtime"
    11  	"strings"
    12  	"testing"
    13  )
    14  
    15  const (
    16  	logBodyFmt = "\033[1;31m%s %s\033[0m"
    17  	greenCode  = "\033[0m\033[1;32m"
    18  	yellowCode = "\033[0m\033[1;33m"
    19  	resetCode  = "\033[0m\033[1;31m"
    20  )
    21  
    22  func prefix(depth int) string {
    23  	_, file, line, _ := runtime.Caller(depth)
    24  	return fmt.Sprintf("Failure in %s, line %d:", filepath.Base(file), line)
    25  }
    26  
    27  func green(str interface{}) string {
    28  	return fmt.Sprintf("%s%#v%s", greenCode, str, resetCode)
    29  }
    30  
    31  func yellow(str interface{}) string {
    32  	return fmt.Sprintf("%s%#v%s", yellowCode, str, resetCode)
    33  }
    34  
    35  func logFatal(t *testing.T, str string) {
    36  	t.Fatalf(logBodyFmt, prefix(3), str)
    37  }
    38  
    39  func logError(t *testing.T, str string) {
    40  	t.Errorf(logBodyFmt, prefix(3), str)
    41  }
    42  
    43  type diffLogger func([]string, interface{}, interface{})
    44  
    45  type visit struct {
    46  	a1  uintptr
    47  	a2  uintptr
    48  	typ reflect.Type
    49  }
    50  
    51  // Recursively visits the structures of "expected" and "actual". The diffLogger function will be
    52  // invoked with each different value encountered, including the reference path that was followed
    53  // to get there.
    54  func deepDiffEqual(expected, actual reflect.Value, visited map[visit]bool, path []string, logDifference diffLogger) {
    55  	defer func() {
    56  		// Fall back to the regular reflect.DeepEquals function.
    57  		if r := recover(); r != nil {
    58  			var e, a interface{}
    59  			if expected.IsValid() {
    60  				e = expected.Interface()
    61  			}
    62  			if actual.IsValid() {
    63  				a = actual.Interface()
    64  			}
    65  
    66  			if !reflect.DeepEqual(e, a) {
    67  				logDifference(path, e, a)
    68  			}
    69  		}
    70  	}()
    71  
    72  	if !expected.IsValid() && actual.IsValid() {
    73  		logDifference(path, nil, actual.Interface())
    74  		return
    75  	}
    76  	if expected.IsValid() && !actual.IsValid() {
    77  		logDifference(path, expected.Interface(), nil)
    78  		return
    79  	}
    80  	if !expected.IsValid() && !actual.IsValid() {
    81  		return
    82  	}
    83  
    84  	hard := func(k reflect.Kind) bool {
    85  		switch k {
    86  		case reflect.Array, reflect.Map, reflect.Slice, reflect.Struct:
    87  			return true
    88  		}
    89  		return false
    90  	}
    91  
    92  	if expected.CanAddr() && actual.CanAddr() && hard(expected.Kind()) {
    93  		addr1 := expected.UnsafeAddr()
    94  		addr2 := actual.UnsafeAddr()
    95  
    96  		if addr1 > addr2 {
    97  			addr1, addr2 = addr2, addr1
    98  		}
    99  
   100  		if addr1 == addr2 {
   101  			// References are identical. We can short-circuit
   102  			return
   103  		}
   104  
   105  		typ := expected.Type()
   106  		v := visit{addr1, addr2, typ}
   107  		if visited[v] {
   108  			// Already visited.
   109  			return
   110  		}
   111  
   112  		// Remember this visit for later.
   113  		visited[v] = true
   114  	}
   115  
   116  	switch expected.Kind() {
   117  	case reflect.Array:
   118  		for i := 0; i < expected.Len(); i++ {
   119  			hop := append(path, fmt.Sprintf("[%d]", i))
   120  			deepDiffEqual(expected.Index(i), actual.Index(i), visited, hop, logDifference)
   121  		}
   122  		return
   123  	case reflect.Slice:
   124  		if expected.IsNil() != actual.IsNil() {
   125  			logDifference(path, expected.Interface(), actual.Interface())
   126  			return
   127  		}
   128  		if expected.Len() == actual.Len() && expected.Pointer() == actual.Pointer() {
   129  			return
   130  		}
   131  		for i := 0; i < expected.Len(); i++ {
   132  			hop := append(path, fmt.Sprintf("[%d]", i))
   133  			deepDiffEqual(expected.Index(i), actual.Index(i), visited, hop, logDifference)
   134  		}
   135  		return
   136  	case reflect.Interface:
   137  		if expected.IsNil() != actual.IsNil() {
   138  			logDifference(path, expected.Interface(), actual.Interface())
   139  			return
   140  		}
   141  		deepDiffEqual(expected.Elem(), actual.Elem(), visited, path, logDifference)
   142  		return
   143  	case reflect.Ptr:
   144  		deepDiffEqual(expected.Elem(), actual.Elem(), visited, path, logDifference)
   145  		return
   146  	case reflect.Struct:
   147  		for i, n := 0, expected.NumField(); i < n; i++ {
   148  			field := expected.Type().Field(i)
   149  			hop := append(path, "."+field.Name)
   150  			deepDiffEqual(expected.Field(i), actual.Field(i), visited, hop, logDifference)
   151  		}
   152  		return
   153  	case reflect.Map:
   154  		if expected.IsNil() != actual.IsNil() {
   155  			logDifference(path, expected.Interface(), actual.Interface())
   156  			return
   157  		}
   158  		if expected.Len() == actual.Len() && expected.Pointer() == actual.Pointer() {
   159  			return
   160  		}
   161  
   162  		var keys []reflect.Value
   163  		if expected.Len() >= actual.Len() {
   164  			keys = expected.MapKeys()
   165  		} else {
   166  			keys = actual.MapKeys()
   167  		}
   168  
   169  		for _, k := range keys {
   170  			expectedValue := expected.MapIndex(k)
   171  			actualValue := actual.MapIndex(k)
   172  
   173  			if !expectedValue.IsValid() {
   174  				logDifference(path, nil, actual.Interface())
   175  				return
   176  			}
   177  			if !actualValue.IsValid() {
   178  				logDifference(path, expected.Interface(), nil)
   179  				return
   180  			}
   181  
   182  			hop := append(path, fmt.Sprintf("[%v]", k))
   183  			deepDiffEqual(expectedValue, actualValue, visited, hop, logDifference)
   184  		}
   185  		return
   186  	case reflect.Func:
   187  		if expected.IsNil() != actual.IsNil() {
   188  			logDifference(path, expected.Interface(), actual.Interface())
   189  		}
   190  		return
   191  	default:
   192  		if expected.Interface() != actual.Interface() {
   193  			logDifference(path, expected.Interface(), actual.Interface())
   194  		}
   195  	}
   196  }
   197  
   198  func deepDiff(expected, actual interface{}, logDifference diffLogger) {
   199  	if expected == nil || actual == nil {
   200  		logDifference([]string{}, expected, actual)
   201  		return
   202  	}
   203  
   204  	expectedValue := reflect.ValueOf(expected)
   205  	actualValue := reflect.ValueOf(actual)
   206  
   207  	if expectedValue.Type() != actualValue.Type() {
   208  		logDifference([]string{}, expected, actual)
   209  		return
   210  	}
   211  	deepDiffEqual(expectedValue, actualValue, map[visit]bool{}, []string{}, logDifference)
   212  }
   213  
   214  // AssertEquals compares two arbitrary values and performs a comparison. If the
   215  // comparison fails, a fatal error is raised that will fail the test
   216  func AssertEquals(t *testing.T, expected, actual interface{}) {
   217  	if expected != actual {
   218  		logFatal(t, fmt.Sprintf("expected %s but got %s", green(expected), yellow(actual)))
   219  	}
   220  }
   221  
   222  // CheckEquals is similar to AssertEquals, except with a non-fatal error
   223  func CheckEquals(t *testing.T, expected, actual interface{}) {
   224  	if expected != actual {
   225  		logError(t, fmt.Sprintf("expected %s but got %s", green(expected), yellow(actual)))
   226  	}
   227  }
   228  
   229  // AssertDeepEquals - like Equals - performs a comparison - but on more complex
   230  // structures that requires deeper inspection
   231  func AssertDeepEquals(t *testing.T, expected, actual interface{}) {
   232  	pre := prefix(2)
   233  
   234  	differed := false
   235  	deepDiff(expected, actual, func(path []string, expected, actual interface{}) {
   236  		differed = true
   237  		t.Errorf("\033[1;31m%sat %s expected %s, but got %s\033[0m",
   238  			pre,
   239  			strings.Join(path, ""),
   240  			green(expected),
   241  			yellow(actual))
   242  	})
   243  	if differed {
   244  		logFatal(t, "The structures were different.")
   245  	}
   246  }
   247  
   248  // CheckDeepEquals is similar to AssertDeepEquals, except with a non-fatal error
   249  func CheckDeepEquals(t *testing.T, expected, actual interface{}) {
   250  	pre := prefix(2)
   251  
   252  	deepDiff(expected, actual, func(path []string, expected, actual interface{}) {
   253  		t.Errorf("\033[1;31m%s at %s expected %s, but got %s\033[0m",
   254  			pre,
   255  			strings.Join(path, ""),
   256  			green(expected),
   257  			yellow(actual))
   258  	})
   259  }
   260  
   261  func isByteArrayEquals(t *testing.T, expectedBytes []byte, actualBytes []byte) bool {
   262  	return bytes.Equal(expectedBytes, actualBytes)
   263  }
   264  
   265  // AssertByteArrayEquals a convenience function for checking whether two byte arrays are equal
   266  func AssertByteArrayEquals(t *testing.T, expectedBytes []byte, actualBytes []byte) {
   267  	if !isByteArrayEquals(t, expectedBytes, actualBytes) {
   268  		logFatal(t, "The bytes differed.")
   269  	}
   270  }
   271  
   272  // CheckByteArrayEquals a convenience function for silent checking whether two byte arrays are equal
   273  func CheckByteArrayEquals(t *testing.T, expectedBytes []byte, actualBytes []byte) {
   274  	if !isByteArrayEquals(t, expectedBytes, actualBytes) {
   275  		logError(t, "The bytes differed.")
   276  	}
   277  }
   278  
   279  // isJSONEquals is a utility function that implements JSON comparison for AssertJSONEquals and
   280  // CheckJSONEquals.
   281  func isJSONEquals(t *testing.T, expectedJSON string, actual interface{}) bool {
   282  	var parsedExpected, parsedActual interface{}
   283  	err := json.Unmarshal([]byte(expectedJSON), &parsedExpected)
   284  	if err != nil {
   285  		t.Errorf("Unable to parse expected value as JSON: %v", err)
   286  		return false
   287  	}
   288  
   289  	jsonActual, err := json.Marshal(actual)
   290  	AssertNoErr(t, err)
   291  	err = json.Unmarshal(jsonActual, &parsedActual)
   292  	AssertNoErr(t, err)
   293  
   294  	if !reflect.DeepEqual(parsedExpected, parsedActual) {
   295  		prettyExpected, err := json.MarshalIndent(parsedExpected, "", "  ")
   296  		if err != nil {
   297  			t.Logf("Unable to pretty-print expected JSON: %v\n%s", err, expectedJSON)
   298  		} else {
   299  			// We can't use green() here because %#v prints prettyExpected as a byte array literal, which
   300  			// is... unhelpful. Converting it to a string first leaves "\n" uninterpreted for some reason.
   301  			t.Logf("Expected JSON:\n%s%s%s", greenCode, prettyExpected, resetCode)
   302  		}
   303  
   304  		prettyActual, err := json.MarshalIndent(actual, "", "  ")
   305  		if err != nil {
   306  			t.Logf("Unable to pretty-print actual JSON: %v\n%#v", err, actual)
   307  		} else {
   308  			// We can't use yellow() for the same reason.
   309  			t.Logf("Actual JSON:\n%s%s%s", yellowCode, prettyActual, resetCode)
   310  		}
   311  
   312  		return false
   313  	}
   314  	return true
   315  }
   316  
   317  // AssertJSONEquals serializes a value as JSON, parses an expected string as JSON, and ensures that
   318  // both are consistent. If they aren't, the expected and actual structures are pretty-printed and
   319  // shown for comparison.
   320  //
   321  // This is useful for comparing structures that are built as nested map[string]interface{} values,
   322  // which are a pain to construct as literals.
   323  func AssertJSONEquals(t *testing.T, expectedJSON string, actual interface{}) {
   324  	if !isJSONEquals(t, expectedJSON, actual) {
   325  		logFatal(t, "The generated JSON structure differed.")
   326  	}
   327  }
   328  
   329  // CheckJSONEquals is similar to AssertJSONEquals, but nonfatal.
   330  func CheckJSONEquals(t *testing.T, expectedJSON string, actual interface{}) {
   331  	if !isJSONEquals(t, expectedJSON, actual) {
   332  		logError(t, "The generated JSON structure differed.")
   333  	}
   334  }
   335  
   336  // AssertNoErr is a convenience function for checking whether an error value is
   337  // an actual error
   338  func AssertNoErr(t *testing.T, e error) {
   339  	if e != nil {
   340  		logFatal(t, fmt.Sprintf("unexpected error %s", yellow(e.Error())))
   341  	}
   342  }
   343  
   344  // AssertErr is a convenience function for checking whether an error value is
   345  // nil
   346  func AssertErr(t *testing.T, e error) {
   347  	if e == nil {
   348  		logFatal(t, fmt.Sprintf("expected error, got nil"))
   349  	}
   350  }
   351  
   352  // CheckNoErr is similar to AssertNoErr, except with a non-fatal error
   353  func CheckNoErr(t *testing.T, e error) {
   354  	if e != nil {
   355  		logError(t, fmt.Sprintf("unexpected error %s", yellow(e.Error())))
   356  	}
   357  }
   358  
   359  // CheckErr is similar to AssertErr, except with a non-fatal error. If expected
   360  // errors are passed, this function also checks that an error in e's tree is
   361  // assignable to one of them. The tree consists of e itself, followed by the
   362  // errors obtained by repeatedly calling Unwrap.
   363  //
   364  // CheckErr panics if expected contains anything other than non-nil pointers to
   365  // either a type that implements error, or to any interface type.
   366  func CheckErr(t *testing.T, e error, expected ...interface{}) {
   367  	if e == nil {
   368  		logError(t, "expected error, got nil")
   369  		return
   370  	}
   371  
   372  	if len(expected) > 0 {
   373  		for _, expectedError := range expected {
   374  			if errors.As(e, expectedError) {
   375  				return
   376  			}
   377  		}
   378  		logError(t, fmt.Sprintf("unexpected error %s", yellow(e.Error())))
   379  	}
   380  }
   381  
   382  // AssertIntLesserOrEqual verifies that first value is lesser or equal than second values
   383  func AssertIntLesserOrEqual(t *testing.T, v1 int, v2 int) {
   384  	if !(v1 <= v2) {
   385  		logFatal(t, fmt.Sprintf("The first value \"%v\" is greater than the second value \"%v\"", v1, v2))
   386  	}
   387  }
   388  
   389  // AssertIntGreaterOrEqual verifies that first value is greater or equal than second values
   390  func AssertIntGreaterOrEqual(t *testing.T, v1 int, v2 int) {
   391  	if !(v1 >= v2) {
   392  		logFatal(t, fmt.Sprintf("The first value \"%v\" is lesser than the second value \"%v\"", v1, v2))
   393  	}
   394  }