MCPcopy
hub / github.com/nats-io/nats.go / TestCustomReconnectDelay

Function TestCustomReconnectDelay

test/nats_test.go:1017–1080  ·  view source on GitHub ↗
(t *testing.T)

Source from the content-addressed store, hash-verified

1015}
1016
1017func TestCustomReconnectDelay(t *testing.T) {
1018 s := RunServerOnPort(TEST_PORT)
1019 defer s.Shutdown()
1020
1021 expectedAttempt := 1
1022 errCh := make(chan error, 1)
1023 cCh := make(chan bool, 1)
1024 nc, err := nats.Connect(s.ClientURL(),
1025 nats.Timeout(100*time.Millisecond), // Need to lower for Windows tests
1026 nats.CustomReconnectDelay(func(n int) time.Duration {
1027 var err error
1028 var delay time.Duration
1029 if n != expectedAttempt {
1030 err = fmt.Errorf("Expected attempt to be %v, got %v", expectedAttempt, n)
1031 } else {
1032 expectedAttempt++
1033 if n <= 4 {
1034 delay = 100 * time.Millisecond
1035 }
1036 }
1037 if err != nil {
1038 select {
1039 case errCh <- err:
1040 default:
1041 }
1042 }
1043 return delay
1044 }),
1045 nats.MaxReconnects(4),
1046 nats.ClosedHandler(func(_ *nats.Conn) {
1047 cCh <- true
1048 }),
1049 )
1050 if err != nil {
1051 t.Fatalf("Error during connect: %v", err)
1052 }
1053 defer nc.Close()
1054
1055 // Cause disconnect
1056 s.Shutdown()
1057
1058 // We should be trying to reconnect 4 times
1059 start := time.Now()
1060
1061 // Wait on error or completion of test.
1062 select {
1063 case e := <-errCh:
1064 if e != nil {
1065 t.Fatal(e.Error())
1066 }
1067 case <-cCh:
1068 case <-time.After(2 * time.Second):
1069 t.Fatalf("No CB invoked")
1070 }
1071 // On Windows, a failed connect attempt will last as much as Timeout(),
1072 // so we need to take that into account.
1073 max := 500 * time.Millisecond
1074 if runtime.GOOS == "windows" {

Callers

nothing calls this directly

Calls 8

ConnectMethod · 0.80
ErrorfMethod · 0.80
ClosedHandlerMethod · 0.80
FatalfMethod · 0.80
RunServerOnPortFunction · 0.70
TimeoutMethod · 0.65
ErrorMethod · 0.65
CloseMethod · 0.45

Tested by

no test coverage detected