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

Function testContextRequestWithDeadline

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

Source from the content-addressed store, hash-verified

342}
343
344func testContextRequestWithDeadline(t *testing.T, nc *nats.Conn) {
345 deadline := time.Now().Add(100 * time.Millisecond)
346 ctx, cancelCB := context.WithDeadline(context.Background(), deadline)
347 defer cancelCB() // should always be called, not discarded, to prevent context leak
348
349 nc.Subscribe("slow", func(m *nats.Msg) {
350 // simulates latency into the client so that timeout is hit.
351 time.Sleep(40 * time.Millisecond)
352 nc.Publish(m.Reply, []byte("OK"))
353 })
354
355 for i := 0; i < 2; i++ {
356 resp, err := nc.RequestWithContext(ctx, "slow", []byte(""))
357 if err != nil {
358 t.Fatalf("Expected request with context to not fail: %s", err)
359 }
360 got := string(resp.Data)
361 expected := "OK"
362 if got != expected {
363 t.Errorf("Expected to receive %s, got: %s", expected, got)
364 }
365 }
366
367 // A third request with latency would make the context
368 // reach the deadline.
369 _, err := nc.RequestWithContext(ctx, "slow", []byte(""))
370 if err == nil {
371 t.Fatal("Expected request with context to reach deadline")
372 }
373
374 // Reported error is "context deadline exceeded" from Context package,
375 // which implements net.Error Timeout interface.
376 type timeoutError interface {
377 Timeout() bool
378 }
379 timeoutErr, ok := err.(timeoutError)
380 if !ok || !timeoutErr.Timeout() {
381 t.Errorf("Expected to have a timeout error")
382 }
383 expected := `context deadline exceeded`
384 if !strings.Contains(err.Error(), expected) {
385 t.Errorf("Expected %q error, got: %q", expected, err.Error())
386 }
387}
388
389func TestContextRequestWithDeadline(t *testing.T) {
390 s := RunDefaultServer()

Calls 8

FatalfMethod · 0.80
ErrorfMethod · 0.80
AddMethod · 0.65
SubscribeMethod · 0.65
PublishMethod · 0.65
TimeoutMethod · 0.65
ErrorMethod · 0.65
RequestWithContextMethod · 0.45

Tested by

no test coverage detected