errors_test.go 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. package dtls
  2. import (
  3. "errors"
  4. "fmt"
  5. "net"
  6. "testing"
  7. "golang.org/x/xerrors"
  8. )
  9. var errExample = errors.New("an example error")
  10. func TestErrorUnwrap(t *testing.T) {
  11. cases := []struct {
  12. err error
  13. errUnwrapped []error
  14. }{
  15. {
  16. &FatalError{Err: errExample},
  17. []error{errExample},
  18. },
  19. {
  20. &TemporaryError{Err: errExample},
  21. []error{errExample},
  22. },
  23. {
  24. &InternalError{Err: errExample},
  25. []error{errExample},
  26. },
  27. {
  28. &TimeoutError{Err: errExample},
  29. []error{errExample},
  30. },
  31. {
  32. &HandshakeError{Err: errExample},
  33. []error{errExample},
  34. },
  35. }
  36. for _, c := range cases {
  37. c := c
  38. t.Run(fmt.Sprintf("%T", c.err), func(t *testing.T) {
  39. err := c.err
  40. for _, unwrapped := range c.errUnwrapped {
  41. e := xerrors.Unwrap(err)
  42. if !errors.Is(e, unwrapped) {
  43. t.Errorf("Unwrapped error is expected to be '%v', got '%v'", unwrapped, e)
  44. }
  45. }
  46. })
  47. }
  48. }
  49. func TestErrorNetError(t *testing.T) {
  50. cases := []struct {
  51. err error
  52. str string
  53. timeout, temporary bool
  54. }{
  55. {&FatalError{Err: errExample}, "dtls fatal: an example error", false, false},
  56. {&TemporaryError{Err: errExample}, "dtls temporary: an example error", false, true},
  57. {&InternalError{Err: errExample}, "dtls internal: an example error", false, false},
  58. {&TimeoutError{Err: errExample}, "dtls timeout: an example error", true, true},
  59. {&HandshakeError{Err: errExample}, "handshake error: an example error", false, false},
  60. {&HandshakeError{Err: &TimeoutError{Err: errExample}}, "handshake error: dtls timeout: an example error", true, true},
  61. }
  62. for _, c := range cases {
  63. c := c
  64. t.Run(fmt.Sprintf("%T", c.err), func(t *testing.T) {
  65. ne, ok := c.err.(net.Error)
  66. if !ok {
  67. t.Fatalf("%T doesn't implement net.Error", c.err)
  68. }
  69. if ne.Timeout() != c.timeout {
  70. t.Errorf("%T.Timeout() should be %v", c.err, c.timeout)
  71. }
  72. if ne.Temporary() != c.temporary {
  73. t.Errorf("%T.Temporary() should be %v", c.err, c.temporary)
  74. }
  75. if ne.Error() != c.str {
  76. t.Errorf("%T.Error() should be %v", c.err, c.str)
  77. }
  78. })
  79. }
  80. }