Search in sources :

Example 31 with InvocationOnMock

use of org.mockito.invocation.InvocationOnMock in project grpc-java by grpc.

the class ManagedChannelImplTest method informationPropagatedToNewStreamAndCallCredentials.

/**
   * Test that information such as the Call's context, MethodDescriptor, authority, executor are
   * propagated to newStream() and applyRequestMetadata().
   */
@Test
public void informationPropagatedToNewStreamAndCallCredentials() {
    ResolvedServerInfoGroup serverInfoGroup = ResolvedServerInfoGroup.builder().add(server).build();
    createChannel(new FakeNameResolverFactory(true), NO_INTERCEPTOR);
    CallOptions callOptions = CallOptions.DEFAULT.withCallCredentials(creds);
    final Context.Key<String> testKey = Context.key("testing");
    Context ctx = Context.current().withValue(testKey, "testValue");
    final LinkedList<Context> credsApplyContexts = new LinkedList<Context>();
    final LinkedList<Context> newStreamContexts = new LinkedList<Context>();
    doAnswer(new Answer<Void>() {

        @Override
        public Void answer(InvocationOnMock in) throws Throwable {
            credsApplyContexts.add(Context.current());
            return null;
        }
    }).when(creds).applyRequestMetadata(any(MethodDescriptor.class), any(Attributes.class), any(Executor.class), any(MetadataApplier.class));
    // First call will be on delayed transport.  Only newCall() is run within the expected context,
    // so that we can verify that the context is explicitly attached before calling newStream() and
    // applyRequestMetadata(), which happens after we detach the context from the thread.
    Context origCtx = ctx.attach();
    assertEquals("testValue", testKey.get());
    ClientCall<String, Integer> call = channel.newCall(method, callOptions);
    ctx.detach(origCtx);
    assertNull(testKey.get());
    call.start(mockCallListener, new Metadata());
    // Simulate name resolution results
    Subchannel subchannel = helper.createSubchannel(serverInfoGroup.toEquivalentAddressGroup(), Attributes.EMPTY);
    subchannel.requestConnection();
    verify(mockTransportFactory).newClientTransport(same(socketAddress), eq(authority), eq(userAgent));
    MockClientTransportInfo transportInfo = transports.poll();
    final ConnectionClientTransport transport = transportInfo.transport;
    when(transport.getAttributes()).thenReturn(Attributes.EMPTY);
    doAnswer(new Answer<ClientStream>() {

        @Override
        public ClientStream answer(InvocationOnMock in) throws Throwable {
            newStreamContexts.add(Context.current());
            return mock(ClientStream.class);
        }
    }).when(transport).newStream(any(MethodDescriptor.class), any(Metadata.class), any(CallOptions.class), any(StatsTraceContext.class));
    verify(creds, never()).applyRequestMetadata(any(MethodDescriptor.class), any(Attributes.class), any(Executor.class), any(MetadataApplier.class));
    // applyRequestMetadata() is called after the transport becomes ready.
    transportInfo.listener.transportReady();
    when(mockPicker.pickSubchannel(any(PickSubchannelArgs.class))).thenReturn(PickResult.withSubchannel(subchannel));
    helper.updatePicker(mockPicker);
    executor.runDueTasks();
    ArgumentCaptor<Attributes> attrsCaptor = ArgumentCaptor.forClass(Attributes.class);
    ArgumentCaptor<MetadataApplier> applierCaptor = ArgumentCaptor.forClass(MetadataApplier.class);
    verify(creds).applyRequestMetadata(same(method), attrsCaptor.capture(), same(executor.getScheduledExecutorService()), applierCaptor.capture());
    assertEquals("testValue", testKey.get(credsApplyContexts.poll()));
    assertEquals(authority, attrsCaptor.getValue().get(CallCredentials.ATTR_AUTHORITY));
    assertEquals(SecurityLevel.NONE, attrsCaptor.getValue().get(CallCredentials.ATTR_SECURITY_LEVEL));
    verify(transport, never()).newStream(any(MethodDescriptor.class), any(Metadata.class), any(CallOptions.class), any(StatsTraceContext.class));
    // newStream() is called after apply() is called
    applierCaptor.getValue().apply(new Metadata());
    verify(transport).newStream(same(method), any(Metadata.class), same(callOptions), any(StatsTraceContext.class));
    assertEquals("testValue", testKey.get(newStreamContexts.poll()));
    // The context should not live beyond the scope of newStream() and applyRequestMetadata()
    assertNull(testKey.get());
    // Second call will not be on delayed transport
    origCtx = ctx.attach();
    call = channel.newCall(method, callOptions);
    ctx.detach(origCtx);
    call.start(mockCallListener, new Metadata());
    verify(creds, times(2)).applyRequestMetadata(same(method), attrsCaptor.capture(), same(executor.getScheduledExecutorService()), applierCaptor.capture());
    assertEquals("testValue", testKey.get(credsApplyContexts.poll()));
    assertEquals(authority, attrsCaptor.getValue().get(CallCredentials.ATTR_AUTHORITY));
    assertEquals(SecurityLevel.NONE, attrsCaptor.getValue().get(CallCredentials.ATTR_SECURITY_LEVEL));
    // This is from the first call
    verify(transport).newStream(any(MethodDescriptor.class), any(Metadata.class), any(CallOptions.class), any(StatsTraceContext.class));
    // Still, newStream() is called after apply() is called
    applierCaptor.getValue().apply(new Metadata());
    verify(transport, times(2)).newStream(same(method), any(Metadata.class), same(callOptions), any(StatsTraceContext.class));
    assertEquals("testValue", testKey.get(newStreamContexts.poll()));
    assertNull(testKey.get());
}
Also used : Attributes(io.grpc.Attributes) Metadata(io.grpc.Metadata) ResolvedServerInfoGroup(io.grpc.ResolvedServerInfoGroup) CallOptions(io.grpc.CallOptions) Matchers.anyString(org.mockito.Matchers.anyString) Executor(java.util.concurrent.Executor) PickSubchannelArgs(io.grpc.LoadBalancer.PickSubchannelArgs) Context(io.grpc.Context) MetadataApplier(io.grpc.CallCredentials.MetadataApplier) MockClientTransportInfo(io.grpc.internal.TestUtils.MockClientTransportInfo) MethodDescriptor(io.grpc.MethodDescriptor) LinkedList(java.util.LinkedList) InvocationOnMock(org.mockito.invocation.InvocationOnMock) Subchannel(io.grpc.LoadBalancer.Subchannel) Test(org.junit.Test)

Example 32 with InvocationOnMock

use of org.mockito.invocation.InvocationOnMock in project grpc-java by grpc.

the class RoundRobinLoadBalancerTest method setUp.

@Before
public void setUp() {
    MockitoAnnotations.initMocks(this);
    for (int i = 0; i < 3; i++) {
        SocketAddress addr = new FakeSocketAddress("server" + i);
        EquivalentAddressGroup eag = new EquivalentAddressGroup(addr);
        servers.put(ResolvedServerInfoGroup.builder().add(new ResolvedServerInfo(addr)).build(), eag);
        subchannels.put(eag, mock(Subchannel.class));
    }
    when(mockHelper.createSubchannel(any(EquivalentAddressGroup.class), any(Attributes.class))).then(new Answer<Subchannel>() {

        @Override
        public Subchannel answer(InvocationOnMock invocation) throws Throwable {
            Object[] args = invocation.getArguments();
            Subchannel subchannel = subchannels.get(args[0]);
            when(subchannel.getAttributes()).thenReturn((Attributes) args[1]);
            return subchannel;
        }
    });
    loadBalancer = (RoundRobinLoadBalancer) RoundRobinLoadBalancerFactory.getInstance().newLoadBalancer(mockHelper);
}
Also used : EquivalentAddressGroup(io.grpc.EquivalentAddressGroup) Subchannel(io.grpc.LoadBalancer.Subchannel) InvocationOnMock(org.mockito.invocation.InvocationOnMock) Attributes(io.grpc.Attributes) ResolvedServerInfo(io.grpc.ResolvedServerInfo) SocketAddress(java.net.SocketAddress) Before(org.junit.Before)

Example 33 with InvocationOnMock

use of org.mockito.invocation.InvocationOnMock in project grpc-java by grpc.

the class NettyServerStreamTest method createStream.

@Override
protected NettyServerStream createStream() {
    when(handler.getWriteQueue()).thenReturn(writeQueue);
    doAnswer(new Answer<Object>() {

        @Override
        public Object answer(InvocationOnMock invocation) throws Throwable {
            if (future.isDone()) {
                ((ChannelPromise) invocation.getArguments()[1]).setSuccess();
            }
            return null;
        }
    }).when(writeQueue).enqueue(any(QueuedCommand.class), any(ChannelPromise.class), anyBoolean());
    when(writeQueue.enqueue(any(QueuedCommand.class), anyBoolean())).thenReturn(future);
    StatsTraceContext statsTraceCtx = StatsTraceContext.NOOP;
    NettyServerStream.TransportState state = new NettyServerStream.TransportState(handler, http2Stream, DEFAULT_MAX_MESSAGE_SIZE, statsTraceCtx);
    NettyServerStream stream = new NettyServerStream(channel, state, Attributes.EMPTY, "test-authority", statsTraceCtx);
    stream.transportState().setListener(serverListener);
    state.onStreamAllocated();
    verify(serverListener, atLeastOnce()).onReady();
    verifyNoMoreInteractions(serverListener);
    return stream;
}
Also used : StatsTraceContext(io.grpc.internal.StatsTraceContext) InvocationOnMock(org.mockito.invocation.InvocationOnMock) ChannelPromise(io.netty.channel.ChannelPromise) QueuedCommand(io.grpc.netty.WriteQueue.QueuedCommand)

Example 34 with InvocationOnMock

use of org.mockito.invocation.InvocationOnMock in project spring-security by spring-projects.

the class AbstractPreAuthenticatedProcessingFilterTests method getFilter.

private static ConcretePreAuthenticatedProcessingFilter getFilter(boolean grantAccess) throws Exception {
    ConcretePreAuthenticatedProcessingFilter filter = new ConcretePreAuthenticatedProcessingFilter();
    AuthenticationManager am = mock(AuthenticationManager.class);
    if (!grantAccess) {
        when(am.authenticate(any(Authentication.class))).thenThrow(new BadCredentialsException(""));
    } else {
        when(am.authenticate(any(Authentication.class))).thenAnswer(new Answer<Authentication>() {

            public Authentication answer(InvocationOnMock invocation) throws Throwable {
                return (Authentication) invocation.getArguments()[0];
            }
        });
    }
    filter.setAuthenticationManager(am);
    filter.afterPropertiesSet();
    return filter;
}
Also used : AuthenticationManager(org.springframework.security.authentication.AuthenticationManager) Authentication(org.springframework.security.core.Authentication) InvocationOnMock(org.mockito.invocation.InvocationOnMock) BadCredentialsException(org.springframework.security.authentication.BadCredentialsException)

Example 35 with InvocationOnMock

use of org.mockito.invocation.InvocationOnMock in project rest.li by linkedin.

the class TestRestLiFilterChain method testFilterInvocationResponseErrorOnError.

@SuppressWarnings("unchecked")
@Test
public void testFilterInvocationResponseErrorOnError() throws Exception {
    _restLiFilterChain = new RestLiFilterChain(Arrays.asList(_filters), _mockFilterChainCallback);
    _filters[1] = new CountFilterResponseErrorOnError();
    doAnswer(new Answer<Object>() {

        @Override
        public Object answer(InvocationOnMock invocation) throws Throwable {
            _restLiFilterChain.onResponse(_mockFilterRequestContext, _mockFilterResponseContext, _mockResponseAttachments);
            return null;
        }
    }).when(_mockFilterChainCallback).onRequestSuccess(eq(_mockRestLiRequestData), any(RestLiCallback.class));
    when(_mockFilterRequestContext.getRequestData()).thenReturn(_mockRestLiRequestData);
    when(_mockFilterResponseContext.getResponseData()).thenReturn(_mockRestLiResponseData);
    when(_responseHandler.buildExceptionResponseData(eq(_request), eq(_method), any(Object.class), anyMap(), anyList())).thenReturn(_mockRestLiResponseData);
    when(_mockFilterResponseContextFactory.fromThrowable(any(Throwable.class))).thenReturn(_mockFilterResponseContext);
    _restLiFilterChain.onRequest(_mockFilterRequestContext, _mockFilterResponseContextFactory);
    verifySecondFilterResponseException();
}
Also used : InvocationOnMock(org.mockito.invocation.InvocationOnMock) RestLiCallback(com.linkedin.restli.internal.server.RestLiCallback) CountFilterResponseErrorOnError(com.linkedin.restli.internal.server.filter.testfilters.CountFilterResponseErrorOnError) Test(org.testng.annotations.Test)

Aggregations

InvocationOnMock (org.mockito.invocation.InvocationOnMock)1088 Test (org.junit.Test)655 Answer (org.mockito.stubbing.Answer)287 Matchers.anyString (org.mockito.Matchers.anyString)145 HashMap (java.util.HashMap)124 PrepareForTest (org.powermock.core.classloader.annotations.PrepareForTest)113 Before (org.junit.Before)110 Mockito.doAnswer (org.mockito.Mockito.doAnswer)110 ArrayList (java.util.ArrayList)109 IOException (java.io.IOException)92 Context (android.content.Context)68 List (java.util.List)62 AtomicReference (java.util.concurrent.atomic.AtomicReference)61 CountDownLatch (java.util.concurrent.CountDownLatch)59 Test (org.testng.annotations.Test)59 File (java.io.File)55 UUID (java.util.UUID)46 Configuration (org.apache.hadoop.conf.Configuration)46 Activity (android.app.Activity)40 Semaphore (java.util.concurrent.Semaphore)38