MCPcopy Create free account
hub / github.com/CPChain/chain / TestClientReconnect

Function TestClientReconnect

api/rpc/client_test.go:422–486  ·  view source on GitHub ↗
(t *testing.T)

Source from the content-addressed store, hash-verified

420}
421
422func TestClientReconnect(t *testing.T) {
423 startServer := func(addr string) (*Server, net.Listener) {
424 srv := newTestServer("service", new(Service))
425 l, err := net.Listen("tcp", addr)
426 if err != nil {
427 t.Fatal(err)
428 }
429 go http.Serve(l, srv.WebsocketHandler([]string{"*"}))
430 return srv, l
431 }
432
433 ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
434 defer cancel()
435
436 // Start a server and corresponding client.
437 s1, l1 := startServer("127.0.0.1:0")
438 client, err := DialContext(ctx, "ws://"+l1.Addr().String())
439 if err != nil {
440 t.Fatal("can't dial", err)
441 }
442
443 // Perform a call. This should work because the server is up.
444 var resp Result
445 if err := client.CallContext(ctx, &resp, "service_echo", "", 1, nil); err != nil {
446 t.Fatal(err)
447 }
448
449 // Shut down the server and try calling again. It shouldn't work.
450 l1.Close()
451 s1.Stop()
452 if err := client.CallContext(ctx, &resp, "service_echo", "", 2, nil); err == nil {
453 t.Error("successful call while the server is down")
454 t.Logf("resp: %#v", resp)
455 }
456
457 // Allow for some cool down time so we can listen on the same address again.
458 time.Sleep(2 * time.Second)
459
460 // Start it up again and call again. The connection should be reestablished.
461 // We spawn multiple calls here to check whether this hangs somehow.
462 s2, l2 := startServer(l1.Addr().String())
463 defer l2.Close()
464 defer s2.Stop()
465
466 start := make(chan struct{})
467 errors := make(chan error, 20)
468 for i := 0; i < cap(errors); i++ {
469 go func() {
470 <-start
471 var resp Result
472 errors <- client.CallContext(ctx, &resp, "service_echo", "", 3, nil)
473 }()
474 }
475 close(start)
476 errcount := 0
477 for i := 0; i < cap(errors); i++ {
478 if err = <-errors; err != nil {
479 errcount++

Callers

nothing calls this directly

Calls 10

newTestServerFunction · 0.85
WebsocketHandlerMethod · 0.80
CallContextMethod · 0.80
SleepMethod · 0.80
DialContextFunction · 0.70
FatalMethod · 0.65
CloseMethod · 0.65
StopMethod · 0.65
ErrorMethod · 0.65
StringMethod · 0.45

Tested by

no test coverage detected