(t *testing.T, nc *nats.Conn)
| 342 | } |
| 343 | |
| 344 | func testContextRequestWithDeadline(t *testing.T, nc *nats.Conn) { |
| 345 | deadline := time.Now().Add(100 * time.Millisecond) |
| 346 | ctx, cancelCB := context.WithDeadline(context.Background(), deadline) |
| 347 | defer cancelCB() // should always be called, not discarded, to prevent context leak |
| 348 | |
| 349 | nc.Subscribe("slow", func(m *nats.Msg) { |
| 350 | // simulates latency into the client so that timeout is hit. |
| 351 | time.Sleep(40 * time.Millisecond) |
| 352 | nc.Publish(m.Reply, []byte("OK")) |
| 353 | }) |
| 354 | |
| 355 | for i := 0; i < 2; i++ { |
| 356 | resp, err := nc.RequestWithContext(ctx, "slow", []byte("")) |
| 357 | if err != nil { |
| 358 | t.Fatalf("Expected request with context to not fail: %s", err) |
| 359 | } |
| 360 | got := string(resp.Data) |
| 361 | expected := "OK" |
| 362 | if got != expected { |
| 363 | t.Errorf("Expected to receive %s, got: %s", expected, got) |
| 364 | } |
| 365 | } |
| 366 | |
| 367 | // A third request with latency would make the context |
| 368 | // reach the deadline. |
| 369 | _, err := nc.RequestWithContext(ctx, "slow", []byte("")) |
| 370 | if err == nil { |
| 371 | t.Fatal("Expected request with context to reach deadline") |
| 372 | } |
| 373 | |
| 374 | // Reported error is "context deadline exceeded" from Context package, |
| 375 | // which implements net.Error Timeout interface. |
| 376 | type timeoutError interface { |
| 377 | Timeout() bool |
| 378 | } |
| 379 | timeoutErr, ok := err.(timeoutError) |
| 380 | if !ok || !timeoutErr.Timeout() { |
| 381 | t.Errorf("Expected to have a timeout error") |
| 382 | } |
| 383 | expected := `context deadline exceeded` |
| 384 | if !strings.Contains(err.Error(), expected) { |
| 385 | t.Errorf("Expected %q error, got: %q", expected, err.Error()) |
| 386 | } |
| 387 | } |
| 388 | |
| 389 | func TestContextRequestWithDeadline(t *testing.T) { |
| 390 | s := RunDefaultServer() |
no test coverage detected