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

Function testContextRequestWithTimeout

test/context_test.go:41–115  ·  view source on GitHub ↗
(t *testing.T, nc *nats.Conn)

Source from the content-addressed store, hash-verified

39}
40
41func testContextRequestWithTimeout(t *testing.T, nc *nats.Conn) {
42 nc.Subscribe("slow", func(m *nats.Msg) {
43 // Simulates latency into the client so that timeout is hit.
44 time.Sleep(200 * time.Millisecond)
45 nc.Publish(m.Reply, []byte("NG"))
46 })
47 nc.Subscribe("fast", func(m *nats.Msg) {
48 nc.Publish(m.Reply, []byte("OK"))
49 })
50 nc.Subscribe("hdrs", func(m *nats.Msg) {
51 if m.Header.Get("Hdr-Test") != "1" {
52 m.Respond([]byte("-ERR"))
53 }
54
55 r := nats.NewMsg(m.Reply)
56 r.Header = m.Header
57 r.Data = []byte("+OK")
58 m.RespondMsg(r)
59 })
60
61 ctx, cancelCB := context.WithTimeout(context.Background(), 100*time.Millisecond)
62 defer cancelCB() // should always be called, not discarded, to prevent context leak
63
64 // Fast request should not fail at this point.
65 resp, err := nc.RequestWithContext(ctx, "fast", []byte(""))
66 if err != nil {
67 t.Fatalf("Expected request with context to not fail on fast response: %s", err)
68 }
69 got := string(resp.Data)
70 expected := "OK"
71 if got != expected {
72 t.Errorf("Expected to receive %s, got: %s", expected, got)
73 }
74
75 // Slow request hits timeout so expected to fail.
76 _, err = nc.RequestWithContext(ctx, "slow", []byte("world"))
77 if err == nil {
78 t.Fatal("Expected request with timeout context to fail")
79 }
80
81 // Reported error is "context deadline exceeded" from Context package,
82 // which implements net.Error interface.
83 type timeoutError interface {
84 Timeout() bool
85 }
86 timeoutErr, ok := err.(timeoutError)
87 if !ok || !timeoutErr.Timeout() {
88 t.Error("Expected to have a timeout error")
89 }
90 expected = `context deadline exceeded`
91 if !strings.Contains(err.Error(), expected) {
92 t.Errorf("Expected %q error, got: %q", expected, err.Error())
93 }
94
95 // 2nd request should fail again even if they would be fast because context
96 // has already timed out.
97 _, err = nc.RequestWithContext(ctx, "fast", []byte("world"))
98 if err == nil {

Callers 2

Calls 12

RespondMsgMethod · 0.80
FatalfMethod · 0.80
ErrorfMethod · 0.80
RequestMsgWithContextMethod · 0.80
SubscribeMethod · 0.65
PublishMethod · 0.65
GetMethod · 0.65
RespondMethod · 0.65
TimeoutMethod · 0.65
ErrorMethod · 0.65
AddMethod · 0.65
RequestWithContextMethod · 0.45

Tested by

no test coverage detected