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

Function TestContextSubNextMsgWithTimeout

test/context_test.go:412–465  ·  view source on GitHub ↗
(t *testing.T)

Source from the content-addressed store, hash-verified

410}
411
412func TestContextSubNextMsgWithTimeout(t *testing.T) {
413 s := RunDefaultServer()
414 defer s.Shutdown()
415
416 nc := NewDefaultConnection(t)
417 defer nc.Close()
418
419 ctx, cancelCB := context.WithTimeout(context.Background(), 100*time.Millisecond)
420 defer cancelCB() // should always be called, not discarded, to prevent context leak
421
422 sub, err := nc.SubscribeSync("slow")
423 if err != nil {
424 t.Fatalf("Expected to be able to subscribe: %s", err)
425 }
426
427 for i := 0; i < 2; i++ {
428 err := nc.Publish("slow", []byte("OK"))
429 if err != nil {
430 t.Fatalf("Expected publish to not fail: %s", err)
431 }
432 // Enough time to get a couple of messages
433 time.Sleep(40 * time.Millisecond)
434
435 msg, err := sub.NextMsgWithContext(ctx)
436 if err != nil {
437 t.Fatalf("Expected to receive message: %s", err)
438 }
439 got := string(msg.Data)
440 expected := "OK"
441 if got != expected {
442 t.Errorf("Expected to receive %s, got: %s", expected, got)
443 }
444 }
445
446 // Third message will fail because the context will be canceled by now
447 _, err = sub.NextMsgWithContext(ctx)
448 if err == nil {
449 t.Fatal("Expected to fail receiving a message")
450 }
451
452 // Reported error is "context deadline exceeded" from Context package,
453 // which implements net.Error Timeout interface.
454 type timeoutError interface {
455 Timeout() bool
456 }
457 timeoutErr, ok := err.(timeoutError)
458 if !ok || !timeoutErr.Timeout() {
459 t.Errorf("Expected to have a timeout error")
460 }
461 expected := `context deadline exceeded`
462 if !strings.Contains(err.Error(), expected) {
463 t.Errorf("Expected %q error, got: %q", expected, err.Error())
464 }
465}
466
467func TestContextSubNextMsgWithTimeoutCanceled(t *testing.T) {
468 s := RunDefaultServer()

Callers

nothing calls this directly

Calls 10

FatalfMethod · 0.80
NextMsgWithContextMethod · 0.80
ErrorfMethod · 0.80
RunDefaultServerFunction · 0.70
NewDefaultConnectionFunction · 0.70
SubscribeSyncMethod · 0.65
PublishMethod · 0.65
TimeoutMethod · 0.65
ErrorMethod · 0.65
CloseMethod · 0.45

Tested by

no test coverage detected