github.com/gophercloud/gophercloud@v1.14.1/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.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, interface{}, interface{}) 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 interface{} 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 interface{}, 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 interface{}) { 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 interface{}) { 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 AssertDeepEquals(t *testing.T, expected, actual interface{}) { 238 t.Helper() 239 240 pre := prefix(2) 241 242 differed := false 243 deepDiff(expected, actual, func(path []string, expected, actual interface{}) { 244 differed = true 245 t.Errorf("\033[1;31m%sat %s expected %s, but got %s\033[0m", 246 pre, 247 strings.Join(path, ""), 248 green(expected), 249 yellow(actual)) 250 }) 251 if differed { 252 logFatal(t, "The structures were different.") 253 } 254 } 255 256 // CheckDeepEquals is similar to AssertDeepEquals, except with a non-fatal error 257 func CheckDeepEquals(t *testing.T, expected, actual interface{}) { 258 t.Helper() 259 260 pre := prefix(2) 261 262 deepDiff(expected, actual, func(path []string, expected, actual interface{}) { 263 t.Errorf("\033[1;31m%s at %s expected %s, but got %s\033[0m", 264 pre, 265 strings.Join(path, ""), 266 green(expected), 267 yellow(actual)) 268 }) 269 } 270 271 func isByteArrayEquals(t *testing.T, expectedBytes []byte, actualBytes []byte) bool { 272 return bytes.Equal(expectedBytes, actualBytes) 273 } 274 275 // AssertByteArrayEquals a convenience function for checking whether two byte arrays are equal 276 func AssertByteArrayEquals(t *testing.T, expectedBytes []byte, actualBytes []byte) { 277 t.Helper() 278 279 if !isByteArrayEquals(t, expectedBytes, actualBytes) { 280 logFatal(t, "The bytes differed.") 281 } 282 } 283 284 // CheckByteArrayEquals a convenience function for silent checking whether two byte arrays are equal 285 func CheckByteArrayEquals(t *testing.T, expectedBytes []byte, actualBytes []byte) { 286 t.Helper() 287 288 if !isByteArrayEquals(t, expectedBytes, actualBytes) { 289 logError(t, "The bytes differed.") 290 } 291 } 292 293 // isJSONEquals is a utility function that implements JSON comparison for AssertJSONEquals and 294 // CheckJSONEquals. 295 func isJSONEquals(t *testing.T, expectedJSON string, actual interface{}) bool { 296 var parsedExpected, parsedActual interface{} 297 err := json.Unmarshal([]byte(expectedJSON), &parsedExpected) 298 if err != nil { 299 t.Errorf("Unable to parse expected value as JSON: %v", err) 300 return false 301 } 302 303 jsonActual, err := json.Marshal(actual) 304 AssertNoErr(t, err) 305 err = json.Unmarshal(jsonActual, &parsedActual) 306 AssertNoErr(t, err) 307 308 if !reflect.DeepEqual(parsedExpected, parsedActual) { 309 prettyExpected, err := json.MarshalIndent(parsedExpected, "", " ") 310 if err != nil { 311 t.Logf("Unable to pretty-print expected JSON: %v\n%s", err, expectedJSON) 312 } else { 313 // We can't use green() here because %#v prints prettyExpected as a byte array literal, which 314 // is... unhelpful. Converting it to a string first leaves "\n" uninterpreted for some reason. 315 t.Logf("Expected JSON:\n%s%s%s", greenCode, prettyExpected, resetCode) 316 } 317 318 prettyActual, err := json.MarshalIndent(actual, "", " ") 319 if err != nil { 320 t.Logf("Unable to pretty-print actual JSON: %v\n%#v", err, actual) 321 } else { 322 // We can't use yellow() for the same reason. 323 t.Logf("Actual JSON:\n%s%s%s", yellowCode, prettyActual, resetCode) 324 } 325 326 return false 327 } 328 return true 329 } 330 331 // AssertJSONEquals serializes a value as JSON, parses an expected string as JSON, and ensures that 332 // both are consistent. If they aren't, the expected and actual structures are pretty-printed and 333 // shown for comparison. 334 // 335 // This is useful for comparing structures that are built as nested map[string]interface{} values, 336 // which are a pain to construct as literals. 337 func AssertJSONEquals(t *testing.T, expectedJSON string, actual interface{}) { 338 t.Helper() 339 340 if !isJSONEquals(t, expectedJSON, actual) { 341 logFatal(t, "The generated JSON structure differed.") 342 } 343 } 344 345 // CheckJSONEquals is similar to AssertJSONEquals, but nonfatal. 346 func CheckJSONEquals(t *testing.T, expectedJSON string, actual interface{}) { 347 t.Helper() 348 349 if !isJSONEquals(t, expectedJSON, actual) { 350 logError(t, "The generated JSON structure differed.") 351 } 352 } 353 354 // AssertNoErr is a convenience function for checking whether an error value is 355 // an actual error 356 func AssertNoErr(t *testing.T, e error) { 357 t.Helper() 358 359 if e != nil { 360 logFatal(t, fmt.Sprintf("unexpected error %s", yellow(e.Error()))) 361 } 362 } 363 364 // AssertErr is a convenience function for checking whether an error value is 365 // nil 366 func AssertErr(t *testing.T, e error) { 367 t.Helper() 368 369 if e == nil { 370 logFatal(t, fmt.Sprintf("expected error, got nil")) 371 } 372 } 373 374 // CheckNoErr is similar to AssertNoErr, except with a non-fatal error 375 func CheckNoErr(t *testing.T, e error) { 376 t.Helper() 377 378 if e != nil { 379 logError(t, fmt.Sprintf("unexpected error %s", yellow(e.Error()))) 380 } 381 } 382 383 // CheckErr is similar to AssertErr, except with a non-fatal error. If expected 384 // errors are passed, this function also checks that an error in e's tree is 385 // assignable to one of them. The tree consists of e itself, followed by the 386 // errors obtained by repeatedly calling Unwrap. 387 // 388 // CheckErr panics if expected contains anything other than non-nil pointers to 389 // either a type that implements error, or to any interface type. 390 func CheckErr(t *testing.T, e error, expected ...interface{}) { 391 t.Helper() 392 393 if e == nil { 394 logError(t, "expected error, got nil") 395 return 396 } 397 398 if len(expected) > 0 { 399 for _, expectedError := range expected { 400 if errors.As(e, expectedError) { 401 return 402 } 403 } 404 logError(t, fmt.Sprintf("unexpected error %s", yellow(e.Error()))) 405 } 406 } 407 408 // AssertIntLesserOrEqual verifies that first value is lesser or equal than second values 409 func AssertIntLesserOrEqual(t *testing.T, v1 int, v2 int) { 410 t.Helper() 411 412 if !(v1 <= v2) { 413 logFatal(t, fmt.Sprintf("The first value \"%v\" is greater than the second value \"%v\"", v1, v2)) 414 } 415 } 416 417 // AssertIntGreaterOrEqual verifies that first value is greater or equal than second values 418 func AssertIntGreaterOrEqual(t *testing.T, v1 int, v2 int) { 419 t.Helper() 420 421 if !(v1 >= v2) { 422 logFatal(t, fmt.Sprintf("The first value \"%v\" is lesser than the second value \"%v\"", v1, v2)) 423 } 424 }