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