(t *testing.T)
| 410 | } |
| 411 | |
| 412 | func 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 | |
| 467 | func TestContextSubNextMsgWithTimeoutCanceled(t *testing.T) { |
| 468 | s := RunDefaultServer() |
nothing calls this directly
no test coverage detected