(t *testing.T)
| 596 | } |
| 597 | |
| 598 | func TestContextSubNextMsgWithDeadline(t *testing.T) { |
| 599 | s := RunDefaultServer() |
| 600 | defer s.Shutdown() |
| 601 | |
| 602 | nc := NewDefaultConnection(t) |
| 603 | defer nc.Close() |
| 604 | |
| 605 | deadline := time.Now().Add(100 * time.Millisecond) |
| 606 | ctx, cancelCB := context.WithDeadline(context.Background(), deadline) |
| 607 | defer cancelCB() // should always be called, not discarded, to prevent context leak |
| 608 | |
| 609 | sub, err := nc.SubscribeSync("slow") |
| 610 | if err != nil { |
| 611 | t.Fatalf("Expected to be able to subscribe: %s", err) |
| 612 | } |
| 613 | |
| 614 | for i := 0; i < 2; i++ { |
| 615 | err := nc.Publish("slow", []byte("OK")) |
| 616 | if err != nil { |
| 617 | t.Fatalf("Expected publish to not fail: %s", err) |
| 618 | } |
| 619 | // Enough time to get a couple of messages |
| 620 | time.Sleep(40 * time.Millisecond) |
| 621 | |
| 622 | msg, err := sub.NextMsgWithContext(ctx) |
| 623 | if err != nil { |
| 624 | t.Fatalf("Expected to receive message: %s", err) |
| 625 | } |
| 626 | got := string(msg.Data) |
| 627 | expected := "OK" |
| 628 | if got != expected { |
| 629 | t.Errorf("Expected to receive %s, got: %s", expected, got) |
| 630 | } |
| 631 | } |
| 632 | |
| 633 | // Third message will fail because the context will be canceled by now |
| 634 | _, err = sub.NextMsgWithContext(ctx) |
| 635 | if err == nil { |
| 636 | t.Fatal("Expected to fail receiving a message") |
| 637 | } |
| 638 | |
| 639 | // Reported error is "context deadline exceeded" from Context package, |
| 640 | // which implements net.Error Timeout interface. |
| 641 | type timeoutError interface { |
| 642 | Timeout() bool |
| 643 | } |
| 644 | timeoutErr, ok := err.(timeoutError) |
| 645 | if !ok || !timeoutErr.Timeout() { |
| 646 | t.Errorf("Expected to have a timeout error") |
| 647 | } |
| 648 | expected := `context deadline exceeded` |
| 649 | if !strings.Contains(err.Error(), expected) { |
| 650 | t.Errorf("Expected %q error, got: %q", expected, err.Error()) |
| 651 | } |
| 652 | } |
| 653 | |
| 654 | func TestContextRequestConnClosed(t *testing.T) { |
| 655 | s := RunDefaultServer() |
nothing calls this directly
no test coverage detected