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

Function TestContextEncodedRequestWithCancel

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

Source from the content-addressed store, hash-verified

901}
902
903func TestContextEncodedRequestWithCancel(t *testing.T) {
904 s := RunDefaultServer()
905 defer s.Shutdown()
906
907 nc := NewDefaultConnection(t)
908 c, err := nats.NewEncodedConn(nc, nats.JSON_ENCODER)
909 if err != nil {
910 t.Fatalf("Unable to create encoded connection: %v", err)
911 }
912 defer c.Close()
913
914 ctx, cancelCB := context.WithCancel(context.Background())
915 defer cancelCB() // should always be called, not discarded, to prevent context leak
916
917 // timer which cancels the context though can also be arbitrarily extended
918 expirationTimer := time.AfterFunc(100*time.Millisecond, func() {
919 cancelCB()
920 })
921
922 type request struct {
923 Message string `json:"message"`
924 }
925 type response struct {
926 Code int `json:"code"`
927 }
928 c.Subscribe("slow", func(_, reply string, req *request) {
929 got := req.Message
930 expected := "Hello"
931 if got != expected {
932 t.Errorf("Expected to receive request with %q, got %q", got, expected)
933 }
934
935 // simulates latency into the client so that timeout is hit.
936 time.Sleep(40 * time.Millisecond)
937 c.Publish(reply, &response{Code: 200})
938 })
939 c.Subscribe("slower", func(_, reply string, req *request) {
940 got := req.Message
941 expected := "World"
942 if got != expected {
943 t.Errorf("Expected to receive request with %q, got %q", got, expected)
944 }
945
946 // we know this request will take longer so extend the timeout
947 expirationTimer.Reset(100 * time.Millisecond)
948
949 // slower reply which would have hit original timeout
950 time.Sleep(90 * time.Millisecond)
951 c.Publish(reply, &response{Code: 200})
952 })
953
954 for i := 0; i < 2; i++ {
955 req := &request{Message: "Hello"}
956 resp := &response{}
957 err := c.RequestWithContext(ctx, "slow", req, resp)
958 if err != nil {
959 t.Fatalf("Expected encoded request with context to not fail: %s", err)
960 }

Callers

nothing calls this directly

Calls 10

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

Tested by

no test coverage detected