MCPcopy
hub / github.com/redis/go-redis / TestCircuitBreaker

Function TestCircuitBreaker

maintnotifications/circuit_breaker_test.go:9–226  ·  view source on GitHub ↗
(t *testing.T)

Source from the content-addressed store, hash-verified

7)
8
9func TestCircuitBreaker(t *testing.T) {
10 config := &Config{
11 CircuitBreakerFailureThreshold: 5,
12 CircuitBreakerResetTimeout: 60 * time.Second,
13 CircuitBreakerMaxRequests: 3,
14 }
15
16 t.Run("InitialState", func(t *testing.T) {
17 cb := newCircuitBreaker("test-endpoint:6379", config)
18
19 if cb.IsOpen() {
20 t.Error("Circuit breaker should start in closed state")
21 }
22
23 if cb.GetState() != CircuitBreakerClosed {
24 t.Errorf("Expected state %v, got %v", CircuitBreakerClosed, cb.GetState())
25 }
26 })
27
28 t.Run("SuccessfulExecution", func(t *testing.T) {
29 cb := newCircuitBreaker("test-endpoint:6379", config)
30
31 err := cb.Execute(func() error {
32 return nil // Success
33 })
34
35 if err != nil {
36 t.Errorf("Expected no error, got %v", err)
37 }
38
39 if cb.GetState() != CircuitBreakerClosed {
40 t.Errorf("Expected state %v, got %v", CircuitBreakerClosed, cb.GetState())
41 }
42 })
43
44 t.Run("FailureThreshold", func(t *testing.T) {
45 cb := newCircuitBreaker("test-endpoint:6379", config)
46 testError := errors.New("test error")
47
48 // Fail 4 times (below threshold of 5)
49 for i := 0; i < 4; i++ {
50 err := cb.Execute(func() error {
51 return testError
52 })
53 if err != testError {
54 t.Errorf("Expected test error, got %v", err)
55 }
56 if cb.GetState() != CircuitBreakerClosed {
57 t.Errorf("Circuit should still be closed after %d failures", i+1)
58 }
59 }
60
61 // 5th failure should open the circuit
62 err := cb.Execute(func() error {
63 return testError
64 })
65 if err != testError {
66 t.Errorf("Expected test error, got %v", err)

Callers

nothing calls this directly

Calls 7

newCircuitBreakerFunction · 0.85
IsOpenMethod · 0.80
ExecuteMethod · 0.80
RunMethod · 0.45
ErrorMethod · 0.45
GetStateMethod · 0.45
GetStatsMethod · 0.45

Tested by

no test coverage detected