github.com/opentelekomcloud/gophertelekomcloud@v0.9.3/testhelper/convenience.go (about)

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