ecode_test.go 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. package ecode
  2. import (
  3. "testing"
  4. )
  5. func TestNew(t *testing.T) {
  6. defer func() {
  7. errStr := recover()
  8. if errStr != "ecode: 1 already exist" {
  9. t.Logf("New duplicate ecode should cause panic")
  10. t.FailNow()
  11. }
  12. }()
  13. var _ error = New(1)
  14. var _ error = New(2)
  15. var _ error = New(1)
  16. }
  17. func TestErrMessage(t *testing.T) {
  18. e1 := New(3)
  19. if e1.Error() != "3" {
  20. t.Logf("ecode message should be `3`")
  21. t.FailNow()
  22. }
  23. if e1.Message() != "3" {
  24. t.Logf("unregistered ecode message should be ecode number")
  25. t.FailNow()
  26. }
  27. Register(map[int]string{3: "testErr"})
  28. if e1.Message() != "testErr" {
  29. t.Logf("registered ecode message should be `testErr`")
  30. t.FailNow()
  31. }
  32. }
  33. func TestCause(t *testing.T) {
  34. e1 := New(4)
  35. var err error = e1
  36. e2 := Cause(err)
  37. if e2.Code() != 4 {
  38. t.Logf("parsed error code should be 4")
  39. t.FailNow()
  40. }
  41. }
  42. func TestInt(t *testing.T) {
  43. e1 := Int(1)
  44. if e1.Code() != 1 {
  45. t.Logf("int parsed error code should be 1")
  46. t.FailNow()
  47. }
  48. if e1.Error() != "1" || e1.Message() != "1" {
  49. t.Logf("int parsed error string should be `1`")
  50. t.FailNow()
  51. }
  52. }
  53. func TestString(t *testing.T) {
  54. eStr := String("123")
  55. if eStr.Code() != 123 {
  56. t.Logf("string parsed error code should be 123")
  57. t.FailNow()
  58. }
  59. if eStr.Error() != "123" || eStr.Message() != "123" {
  60. t.Logf("string parsed error string should be `123`")
  61. t.FailNow()
  62. }
  63. eStr = String("test")
  64. if eStr.Code() != -500 {
  65. t.Logf("invalid string parsed error code should be -500")
  66. t.FailNow()
  67. }
  68. if eStr.Error() != "-500" || eStr.Message() != "-500" {
  69. t.Logf("invalid string parsed error string should be `-500`")
  70. t.FailNow()
  71. }
  72. }