48 lines
981 B
Go
48 lines
981 B
Go
package connection
|
|
|
|
import (
|
|
"context"
|
|
"errors"
|
|
"testing"
|
|
)
|
|
|
|
func TestReconnectorRetriesAfterDisconnect(t *testing.T) {
|
|
failures := 0
|
|
reconnector := Reconnector{
|
|
MaxAttempts: 3,
|
|
Dial: func(context.Context) error {
|
|
failures++
|
|
if failures < 2 {
|
|
return errors.New("simulated disconnect")
|
|
}
|
|
return nil
|
|
},
|
|
}
|
|
|
|
attempts, err := reconnector.Connect(context.Background())
|
|
if err != nil {
|
|
t.Fatalf("connect after retry: %v", err)
|
|
}
|
|
if attempts != 2 {
|
|
t.Fatalf("expected success on second attempt, got %d", attempts)
|
|
}
|
|
}
|
|
|
|
func TestReconnectorReturnsLastError(t *testing.T) {
|
|
expected := errors.New("still disconnected")
|
|
reconnector := Reconnector{
|
|
MaxAttempts: 2,
|
|
Dial: func(context.Context) error {
|
|
return expected
|
|
},
|
|
}
|
|
|
|
attempts, err := reconnector.Connect(context.Background())
|
|
if !errors.Is(err, expected) {
|
|
t.Fatalf("expected last error, got %v", err)
|
|
}
|
|
if attempts != 2 {
|
|
t.Fatalf("expected two attempts, got %d", attempts)
|
|
}
|
|
}
|