breaker_test.go 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100
  1. package breaker
  2. import (
  3. "errors"
  4. "testing"
  5. "time"
  6. xtime "go-common/library/time"
  7. )
  8. func TestGroup(t *testing.T) {
  9. g1 := NewGroup(nil)
  10. g2 := NewGroup(_conf)
  11. if g1.conf != g2.conf {
  12. t.FailNow()
  13. }
  14. brk := g2.Get("key")
  15. brk1 := g2.Get("key1")
  16. if brk == brk1 {
  17. t.FailNow()
  18. }
  19. brk2 := g2.Get("key")
  20. if brk != brk2 {
  21. t.FailNow()
  22. }
  23. g := NewGroup(_conf)
  24. c := &Config{
  25. Window: xtime.Duration(1 * time.Second),
  26. Sleep: xtime.Duration(100 * time.Millisecond),
  27. Bucket: 10,
  28. Ratio: 0.5,
  29. Request: 100,
  30. SwitchOff: !_conf.SwitchOff,
  31. }
  32. g.Reload(c)
  33. if g.conf.SwitchOff == _conf.SwitchOff {
  34. t.FailNow()
  35. }
  36. }
  37. func TestInit(t *testing.T) {
  38. switchOff := _conf.SwitchOff
  39. c := &Config{
  40. Window: xtime.Duration(3 * time.Second),
  41. Sleep: xtime.Duration(100 * time.Millisecond),
  42. Bucket: 10,
  43. Ratio: 0.5,
  44. Request: 100,
  45. SwitchOff: !switchOff,
  46. }
  47. Init(c)
  48. if _conf.SwitchOff == switchOff {
  49. t.FailNow()
  50. }
  51. }
  52. func TestGo(t *testing.T) {
  53. if err := Go("test_run", func() error {
  54. t.Log("breaker allow,callback run()")
  55. return nil
  56. }, func() error {
  57. t.Log("breaker not allow,callback fallback()")
  58. return errors.New("breaker not allow")
  59. }); err != nil {
  60. t.Error(err)
  61. }
  62. _group.Reload(&Config{
  63. Window: xtime.Duration(3 * time.Second),
  64. Sleep: xtime.Duration(100 * time.Millisecond),
  65. Bucket: 10,
  66. Ratio: 0.5,
  67. Request: 100,
  68. SwitchOff: true,
  69. })
  70. if err := Go("test_fallback", func() error {
  71. t.Log("breaker allow,callback run()")
  72. return nil
  73. }, func() error {
  74. t.Log("breaker not allow,callback fallback()")
  75. return nil
  76. }); err != nil {
  77. t.Error(err)
  78. }
  79. }
  80. func markSuccess(b Breaker, count int) {
  81. for i := 0; i < count; i++ {
  82. b.MarkSuccess()
  83. }
  84. }
  85. func markFailed(b Breaker, count int) {
  86. for i := 0; i < count; i++ {
  87. b.MarkFailed()
  88. }
  89. }