error_1_13_test.go 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. // +build go1.13
  2. package errors
  3. import (
  4. "io"
  5. "testing"
  6. )
  7. // This test should work only for go 1.13 and latter
  8. func TestIs113(t *testing.T) {
  9. custErr := errorWithCustomIs{
  10. Key: "TestForFun",
  11. Err: io.EOF,
  12. }
  13. shouldMatch := errorWithCustomIs{
  14. Key: "TestForFun",
  15. }
  16. shouldNotMatch := errorWithCustomIs{Key: "notOk"}
  17. if !Is(custErr, shouldMatch) {
  18. t.Errorf("custErr is not a TestForFun customError")
  19. }
  20. if Is(custErr, shouldNotMatch) {
  21. t.Errorf("custErr is a notOk customError")
  22. }
  23. if !Is(custErr, New(shouldMatch)) {
  24. t.Errorf("custErr is not a New(TestForFun customError)")
  25. }
  26. if Is(custErr, New(shouldNotMatch)) {
  27. t.Errorf("custErr is a New(notOk customError)")
  28. }
  29. if !Is(New(custErr), shouldMatch) {
  30. t.Errorf("New(custErr) is not a TestForFun customError")
  31. }
  32. if Is(New(custErr), shouldNotMatch) {
  33. t.Errorf("New(custErr) is a notOk customError")
  34. }
  35. if !Is(New(custErr), New(shouldMatch)) {
  36. t.Errorf("New(custErr) is not a New(TestForFun customError)")
  37. }
  38. if Is(New(custErr), New(shouldNotMatch)) {
  39. t.Errorf("New(custErr) is a New(notOk customError)")
  40. }
  41. }
  42. type errorWithCustomIs struct {
  43. Key string
  44. Err error
  45. }
  46. func (ewci errorWithCustomIs) Error() string {
  47. return "["+ewci.Key+"]: " + ewci.Err.Error()
  48. }
  49. func (ewci errorWithCustomIs) Is(target error) bool {
  50. matched, ok := target.(errorWithCustomIs)
  51. return ok && matched.Key == ewci.Key
  52. }