forked from TrueCloudLab/frostfs-sdk-go
60 lines
1.1 KiB
Go
60 lines
1.1 KiB
Go
package tree
|
|
|
|
import (
|
|
"context"
|
|
"errors"
|
|
"testing"
|
|
"time"
|
|
|
|
"github.com/stretchr/testify/require"
|
|
)
|
|
|
|
type (
|
|
testDialer struct {
|
|
err error
|
|
addr string
|
|
}
|
|
)
|
|
|
|
func (d *testDialer) dial(_ context.Context) error {
|
|
return d.err
|
|
}
|
|
|
|
func (d *testDialer) endpoint() string {
|
|
return d.addr
|
|
}
|
|
|
|
func TestCircuitBreaker(t *testing.T) {
|
|
ctx := context.Background()
|
|
remoteErr := errors.New("service is being synchronized")
|
|
d := &testDialer{
|
|
err: remoteErr,
|
|
addr: "addr",
|
|
}
|
|
|
|
// Hit threshold
|
|
cb := NewCircuitBreaker(1*time.Second, 10)
|
|
for i := 0; i < 10; i++ {
|
|
err := cb.Dial(ctx, d)
|
|
require.ErrorIs(t, err, remoteErr)
|
|
}
|
|
|
|
// Immediate request should return circuit breaker error
|
|
d.err = nil
|
|
require.ErrorIs(t, cb.Dial(ctx, d), ErrCBClosed)
|
|
|
|
// Request after breakDuration should be ok
|
|
time.Sleep(1 * time.Second)
|
|
require.NoError(t, cb.Dial(ctx, d))
|
|
|
|
// Then hit threshold once again
|
|
d.err = remoteErr
|
|
for i := 0; i < 10; i++ {
|
|
err := cb.Dial(ctx, d)
|
|
require.ErrorIs(t, err, remoteErr)
|
|
}
|
|
|
|
// Immediate request should return circuit breaker error
|
|
d.err = nil
|
|
require.ErrorIs(t, cb.Dial(ctx, d), ErrCBClosed)
|
|
}
|