panic.go 1.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. // Copyright (c) 2015 Arista Networks, Inc.
  2. // Use of this source code is governed by the Apache License 2.0
  3. // that can be found in the COPYING file.
  4. package test
  5. import (
  6. "fmt"
  7. "runtime"
  8. "testing"
  9. )
  10. // ShouldPanic will test is a function is panicking
  11. func ShouldPanic(t *testing.T, fn func()) {
  12. t.Helper()
  13. defer func() {
  14. t.Helper()
  15. if r := recover(); r == nil {
  16. t.Errorf("%sThe function %p should have panicked",
  17. getCallerInfo(), fn)
  18. }
  19. }()
  20. fn()
  21. }
  22. // ShouldPanicWith will test is a function is panicking with a specific message
  23. func ShouldPanicWith(t *testing.T, msg interface{}, fn func()) {
  24. t.Helper()
  25. defer func() {
  26. t.Helper()
  27. if r := recover(); r == nil {
  28. t.Errorf("%sThe function %p should have panicked with %#v",
  29. getCallerInfo(), fn, msg)
  30. } else if d := Diff(msg, r); len(d) != 0 {
  31. t.Errorf("%sThe function %p panicked with the wrong message.\n"+
  32. "Expected: %#v\nReceived: %#v\nDiff:%s",
  33. getCallerInfo(), fn, msg, r, d)
  34. }
  35. }()
  36. fn()
  37. }
  38. func getCallerInfo() string {
  39. _, file, line, ok := runtime.Caller(4)
  40. if !ok {
  41. return ""
  42. }
  43. return fmt.Sprintf("%s:%d\n", file, line)
  44. }