(t *testing.T)
| 521 | } |
| 522 | |
| 523 | func 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 { |
nothing calls this directly
no test coverage detected