sre_breaker_test.go 1.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. package breaker
  2. import (
  3. "testing"
  4. "time"
  5. xtime "go-common/library/time"
  6. "github.com/stretchr/testify/assert"
  7. )
  8. func getSRE() Breaker {
  9. return NewGroup(&Config{
  10. Window: xtime.Duration(1 * time.Second),
  11. Bucket: 10,
  12. Request: 100,
  13. K: 2,
  14. }).Get("")
  15. }
  16. func testSREClose(t *testing.T, b Breaker) {
  17. markSuccess(b, 80)
  18. assert.Equal(t, b.Allow(), nil)
  19. markSuccess(b, 120)
  20. assert.Equal(t, b.Allow(), nil)
  21. }
  22. func testSREOpen(t *testing.T, b Breaker) {
  23. markSuccess(b, 100)
  24. assert.Equal(t, b.Allow(), nil)
  25. markFailed(b, 10000000)
  26. assert.NotEqual(t, b.Allow(), nil)
  27. }
  28. func testSREHalfOpen(t *testing.T, b Breaker) {
  29. // failback
  30. assert.Equal(t, b.Allow(), nil)
  31. t.Run("allow single failed", func(t *testing.T) {
  32. markFailed(b, 10000000)
  33. assert.NotEqual(t, b.Allow(), nil)
  34. })
  35. time.Sleep(2 * time.Second)
  36. t.Run("allow single succeed", func(t *testing.T) {
  37. assert.Equal(t, b.Allow(), nil)
  38. markSuccess(b, 10000000)
  39. assert.Equal(t, b.Allow(), nil)
  40. })
  41. }
  42. func TestSRE(t *testing.T) {
  43. b := getSRE()
  44. testSREClose(t, b)
  45. b = getSRE()
  46. testSREOpen(t, b)
  47. b = getSRE()
  48. testSREHalfOpen(t, b)
  49. }