package com.atlassian.bitbucket.mesh.request;

import com.atlassian.bitbucket.mesh.rpc.v1.RpcGetCommitRequest;
import com.google.protobuf.ByteString;
import io.grpc.ServerCall;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnitRunner;

import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.ArgumentMatchers.same;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoMoreInteractions;

@RunWith(MockitoJUnitRunner.class)
public class RequestServerCallListenerTest {

    @Mock
    private ServerCall.Listener<Object> delegate;
    @Mock
    private GrpcRequestDescriptor descriptor;
    @InjectMocks
    private RequestServerCallListener<Object> listener;

    @Test
    public void testOnMessage() {
        RpcGetCommitRequest response = RpcGetCommitRequest.newBuilder()
                .setCommitish(ByteString.copyFromUtf8("ba34d26579a1074902b0ef1029d3348fcbf7019a"))
                .build();

        listener.onMessage(response);

        verify(delegate).onMessage(same(response));
        verify(descriptor).onMessageReceived();
        verify(descriptor).onBytesReceived(eq((long) response.getSerializedSize()));
        verifyNoMoreInteractions(delegate, descriptor);
    }

    @Test
    public void testOnMessageHandlesNonMessages() {
        listener.onMessage("Test");

        verify(delegate).onMessage(eq("Test"));
        verify(descriptor).onMessageReceived();
        verifyNoMoreInteractions(delegate, descriptor);
    }
}
