assertions.go 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. // ⚡️ Fiber is an Express inspired web framework written in Go with ☕️
  2. // 🤖 Github Repository: https://github.com/gofiber/fiber
  3. // 📌 API Documentation: https://docs.gofiber.io
  4. package utils
  5. import (
  6. "bytes"
  7. "fmt"
  8. "log"
  9. "path/filepath"
  10. "reflect"
  11. "runtime"
  12. "testing"
  13. "text/tabwriter"
  14. )
  15. // AssertEqual checks if values are equal
  16. func AssertEqual(tb testing.TB, expected, actual interface{}, description ...string) { //nolint:thelper // TODO: Verify if tb can be nil
  17. if tb != nil {
  18. tb.Helper()
  19. }
  20. if reflect.DeepEqual(expected, actual) {
  21. return
  22. }
  23. aType := "<nil>"
  24. bType := "<nil>"
  25. if expected != nil {
  26. aType = reflect.TypeOf(expected).String()
  27. }
  28. if actual != nil {
  29. bType = reflect.TypeOf(actual).String()
  30. }
  31. testName := "AssertEqual"
  32. if tb != nil {
  33. testName = tb.Name()
  34. }
  35. _, file, line, _ := runtime.Caller(1)
  36. var buf bytes.Buffer
  37. const pad = 5
  38. w := tabwriter.NewWriter(&buf, 0, 0, pad, ' ', 0)
  39. _, _ = fmt.Fprintf(w, "\nTest:\t%s", testName)
  40. _, _ = fmt.Fprintf(w, "\nTrace:\t%s:%d", filepath.Base(file), line)
  41. if len(description) > 0 {
  42. _, _ = fmt.Fprintf(w, "\nDescription:\t%s", description[0])
  43. }
  44. _, _ = fmt.Fprintf(w, "\nExpect:\t%v\t(%s)", expected, aType)
  45. _, _ = fmt.Fprintf(w, "\nResult:\t%v\t(%s)", actual, bType)
  46. var result string
  47. if err := w.Flush(); err != nil {
  48. result = err.Error()
  49. } else {
  50. result = buf.String()
  51. }
  52. if tb != nil {
  53. tb.Fatal(result)
  54. } else {
  55. log.Fatal(result) //nolint:revive // tb might be nil, so we need a fallback
  56. }
  57. }