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

Function TestContextEncodedRequestWithTimeout

test/enc_test.go:761–830  ·  view source on GitHub ↗
(t *testing.T)

Source from the content-addressed store, hash-verified

759}
760
761func TestContextEncodedRequestWithTimeout(t *testing.T) {
762 s := RunDefaultServer()
763 defer s.Shutdown()
764
765 nc := NewDefaultConnection(t)
766 c, err := nats.NewEncodedConn(nc, nats.JSON_ENCODER)
767 if err != nil {
768 t.Fatalf("Unable to create encoded connection: %v", err)
769 }
770 defer c.Close()
771
772 deadline := time.Now().Add(100 * time.Millisecond)
773 ctx, cancelCB := context.WithDeadline(context.Background(), deadline)
774 defer cancelCB() // should always be called, not discarded, to prevent context leak
775
776 type request struct {
777 Message string `json:"message"`
778 }
779 type response struct {
780 Code int `json:"code"`
781 }
782 c.Subscribe("slow", func(_, reply string, req *request) {
783 got := req.Message
784 expected := "Hello"
785 if got != expected {
786 t.Errorf("Expected to receive request with %q, got %q", got, expected)
787 }
788
789 // simulates latency into the client so that timeout is hit.
790 time.Sleep(40 * time.Millisecond)
791 c.Publish(reply, &response{Code: 200})
792 })
793
794 for i := 0; i < 2; i++ {
795 req := &request{Message: "Hello"}
796 resp := &response{}
797 err := c.RequestWithContext(ctx, "slow", req, resp)
798 if err != nil {
799 t.Fatalf("Expected encoded request with context to not fail: %s", err)
800 }
801 got := resp.Code
802 expected := 200
803 if got != expected {
804 t.Errorf("Expected to receive %v, got: %v", expected, got)
805 }
806 }
807
808 // A third request with latency would make the context
809 // reach the deadline.
810 req := &request{Message: "Hello"}
811 resp := &response{}
812 err = c.RequestWithContext(ctx, "slow", req, resp)
813 if err == nil {
814 t.Fatal("Expected request with context to reach deadline")
815 }
816
817 // Reported error is "context deadline exceeded" from Context package,
818 // which implements net.Error Timeout interface.

Callers

nothing calls this directly

Calls 11

CloseMethod · 0.95
SubscribeMethod · 0.95
PublishMethod · 0.95
RequestWithContextMethod · 0.95
FatalfMethod · 0.80
ErrorfMethod · 0.80
RunDefaultServerFunction · 0.70
NewDefaultConnectionFunction · 0.70
AddMethod · 0.65
TimeoutMethod · 0.65
ErrorMethod · 0.65

Tested by

no test coverage detected