(t *testing.T)
| 830 | } |
| 831 | |
| 832 | func TestContextEncodedRequestWithTimeoutCanceled(t *testing.T) { |
| 833 | s := RunDefaultServer() |
| 834 | defer s.Shutdown() |
| 835 | |
| 836 | nc := NewDefaultConnection(t) |
| 837 | c, err := nats.NewEncodedConn(nc, nats.JSON_ENCODER) |
| 838 | if err != nil { |
| 839 | t.Fatalf("Unable to create encoded connection: %v", err) |
| 840 | } |
| 841 | defer c.Close() |
| 842 | |
| 843 | ctx, cancelCB := context.WithTimeout(context.Background(), 100*time.Millisecond) |
| 844 | defer cancelCB() // should always be called, not discarded, to prevent context leak |
| 845 | |
| 846 | type request struct { |
| 847 | Message string `json:"message"` |
| 848 | } |
| 849 | type response struct { |
| 850 | Code int `json:"code"` |
| 851 | } |
| 852 | |
| 853 | c.Subscribe("fast", func(_, reply string, req *request) { |
| 854 | got := req.Message |
| 855 | expected := "Hello" |
| 856 | if got != expected { |
| 857 | t.Errorf("Expected to receive request with %q, got %q", got, expected) |
| 858 | } |
| 859 | |
| 860 | // simulates latency into the client so that timeout is hit. |
| 861 | time.Sleep(40 * time.Millisecond) |
| 862 | |
| 863 | c.Publish(reply, &response{Code: 200}) |
| 864 | }) |
| 865 | |
| 866 | // Fast request should not fail |
| 867 | req := &request{Message: "Hello"} |
| 868 | resp := &response{} |
| 869 | c.RequestWithContext(ctx, "fast", req, resp) |
| 870 | expectedCode := 200 |
| 871 | if resp.Code != expectedCode { |
| 872 | t.Errorf("Expected to receive %d, got: %d", expectedCode, resp.Code) |
| 873 | } |
| 874 | |
| 875 | // Cancel the context already so that rest of requests fail. |
| 876 | cancelCB() |
| 877 | |
| 878 | err = c.RequestWithContext(ctx, "fast", req, resp) |
| 879 | if err == nil { |
| 880 | t.Fatal("Expected request with timeout context to fail") |
| 881 | } |
| 882 | |
| 883 | // Reported error is "context canceled" from Context package, |
| 884 | // which is not a timeout error. |
| 885 | type timeoutError interface { |
| 886 | Timeout() bool |
| 887 | } |
| 888 | if _, ok := err.(timeoutError); ok { |
| 889 | t.Errorf("Expected to not have a timeout error") |
nothing calls this directly
no test coverage detected