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

Function TestContextEncodedRequestWithDeadline

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

Source from the content-addressed store, hash-verified

1006}
1007
1008func TestContextEncodedRequestWithDeadline(t *testing.T) {
1009 s := RunDefaultServer()
1010 defer s.Shutdown()
1011
1012 nc := NewDefaultConnection(t)
1013 c, err := nats.NewEncodedConn(nc, nats.JSON_ENCODER)
1014 if err != nil {
1015 t.Fatalf("Unable to create encoded connection: %v", err)
1016 }
1017 defer c.Close()
1018
1019 deadline := time.Now().Add(100 * time.Millisecond)
1020 ctx, cancelCB := context.WithDeadline(context.Background(), deadline)
1021 defer cancelCB() // should always be called, not discarded, to prevent context leak
1022
1023 type request struct {
1024 Message string `json:"message"`
1025 }
1026 type response struct {
1027 Code int `json:"code"`
1028 }
1029 c.Subscribe("slow", func(_, reply string, req *request) {
1030 got := req.Message
1031 expected := "Hello"
1032 if got != expected {
1033 t.Errorf("Expected to receive request with %q, got %q", got, expected)
1034 }
1035
1036 // simulates latency into the client so that timeout is hit.
1037 time.Sleep(40 * time.Millisecond)
1038 c.Publish(reply, &response{Code: 200})
1039 })
1040
1041 for i := 0; i < 2; i++ {
1042 req := &request{Message: "Hello"}
1043 resp := &response{}
1044 err := c.RequestWithContext(ctx, "slow", req, resp)
1045 if err != nil {
1046 t.Fatalf("Expected encoded request with context to not fail: %s", err)
1047 }
1048 got := resp.Code
1049 expected := 200
1050 if got != expected {
1051 t.Errorf("Expected to receive %v, got: %v", expected, got)
1052 }
1053 }
1054
1055 // A third request with latency would make the context
1056 // reach the deadline.
1057 req := &request{Message: "Hello"}
1058 resp := &response{}
1059 err = c.RequestWithContext(ctx, "slow", req, resp)
1060 if err == nil {
1061 t.Fatal("Expected request with context to reach deadline")
1062 }
1063
1064 // Reported error is "context deadline exceeded" from Context package,
1065 // 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