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

Function TestContextSubNextMsgWithCancel

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

Source from the content-addressed store, hash-verified

521}
522
523func TestContextSubNextMsgWithCancel(t *testing.T) {
524 s := RunDefaultServer()
525 defer s.Shutdown()
526
527 nc := NewDefaultConnection(t)
528 defer nc.Close()
529
530 ctx, cancelCB := context.WithCancel(context.Background())
531 defer cancelCB() // should always be called, not discarded, to prevent context leak
532
533 // timer which cancels the context though can also be arbitrarily extended
534 time.AfterFunc(100*time.Millisecond, func() {
535 cancelCB()
536 })
537
538 sub1, err := nc.SubscribeSync("foo")
539 if err != nil {
540 t.Fatalf("Expected to be able to subscribe: %s", err)
541 }
542 sub2, err := nc.SubscribeSync("bar")
543 if err != nil {
544 t.Fatalf("Expected to be able to subscribe: %s", err)
545 }
546
547 for i := 0; i < 2; i++ {
548 err := nc.Publish("foo", []byte("OK"))
549 if err != nil {
550 t.Fatalf("Expected publish to not fail: %s", err)
551 }
552 resp, err := sub1.NextMsgWithContext(ctx)
553 if err != nil {
554 t.Fatalf("Expected request with context to not fail: %s", err)
555 }
556 got := string(resp.Data)
557 expected := "OK"
558 if got != expected {
559 t.Errorf("Expected to receive %s, got: %s", expected, got)
560 }
561 }
562 err = nc.Publish("bar", []byte("Also OK"))
563 if err != nil {
564 t.Fatalf("Expected publish to not fail: %s", err)
565 }
566
567 resp, err := sub2.NextMsgWithContext(ctx)
568 if err != nil {
569 t.Fatalf("Expected request with context to not fail: %s", err)
570 }
571 got := string(resp.Data)
572 expected := "Also OK"
573 if got != expected {
574 t.Errorf("Expected to receive %s, got: %s", expected, got)
575 }
576
577 // We do not have another message pending so timer will
578 // cancel the context.
579 _, err = sub2.NextMsgWithContext(ctx)
580 if err == nil {

Callers

nothing calls this directly

Calls 9

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

Tested by

no test coverage detected