(t *testing.T)
| 901 | } |
| 902 | |
| 903 | func 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 | } |
nothing calls this directly
no test coverage detected