private void writeStatusToTrailers(Status status) { stashedTrailers.removeAll(Status.CODE_KEY); stashedTrailers.removeAll(Status.MESSAGE_KEY); stashedTrailers.put(Status.CODE_KEY, status); if (status.getDescription() != null) { stashedTrailers.put(Status.MESSAGE_KEY, status.getDescription()); } }
@Test public void cancelInOnMessageShouldInvokeStreamCancel() throws Exception { final ClientCallImpl<Void, Void> call = new ClientCallImpl<Void, Void>( DESCRIPTOR, MoreExecutors.directExecutor(), CallOptions.DEFAULT, provider, deadlineCancellationExecutor); final Exception cause = new Exception(); ClientCall.Listener<Void> callListener = new ClientCall.Listener<Void>() { @Override public void onMessage(Void message) { call.cancel("foo", cause); } }; call.start(callListener, new Metadata()); call.halfClose(); call.request(1); verify(stream).start(listenerArgumentCaptor.capture()); ClientStreamListener streamListener = listenerArgumentCaptor.getValue(); streamListener.onReady(); streamListener.headersRead(new Metadata()); streamListener.messageRead(new ByteArrayInputStream(new byte[0])); verify(stream).cancel(statusCaptor.capture()); Status status = statusCaptor.getValue(); assertEquals(Status.CANCELLED.getCode(), status.getCode()); assertEquals("foo", status.getDescription()); assertSame(cause, status.getCause()); }
@Test public void statusFromCancelled_returnStatusAsSetOnCtx() { Context.CancellableContext cancellableContext = Context.current().withCancellation(); cancellableContext.cancel(Status.DEADLINE_EXCEEDED.withDescription("foo bar").asException()); Status status = statusFromCancelled(cancellableContext); assertNotNull(status); assertEquals(Status.Code.DEADLINE_EXCEEDED, status.getCode()); assertEquals("foo bar", status.getDescription()); }
@Test public void statusFromCancelled_TimeoutExceptionShouldMapToDeadlineExceeded() { FakeClock fakeClock = new FakeClock(); Context.CancellableContext cancellableContext = Context.current() .withDeadlineAfter(100, TimeUnit.MILLISECONDS, fakeClock.scheduledExecutorService); fakeClock.forwardTime(System.nanoTime(), TimeUnit.NANOSECONDS); fakeClock.forwardMillis(100); assertTrue(cancellableContext.isCancelled()); assertThat(cancellableContext.cancellationCause(), instanceOf(TimeoutException.class)); Status status = statusFromCancelled(cancellableContext); assertNotNull(status); assertEquals(Status.Code.DEADLINE_EXCEEDED, status.getCode()); assertEquals("context timed out", status.getDescription()); }