package com.atlassian.stash.internal.scm.git.protocol.http;

import com.atlassian.stash.internal.scm.git.GitWriteTracker;
import com.atlassian.bitbucket.request.RequestContext;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InOrder;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;

import static org.mockito.Mockito.inOrder;
import static org.mockito.Mockito.when;

@RunWith(MockitoJUnitRunner.class)
public class GitSmartWriteRequestTest extends GitSmartRequestTestBase {
    @Mock
    private GitWriteTracker writeTracker;

    @Test
    public void testShouldIncrementAndDecrementWriteOperationCounterForWriteOperations() throws Exception {
        smartRequest = createGitSmartRequest();
        stubCommandBuilder();

        smartRequest.handleRequest();

        InOrder inOrder = inOrder(writeTracker);
        inOrder.verify(writeTracker).onWriteStart();
        inOrder.verify(writeTracker).onWriteEnd();
    }

    @Test
    public void testShouldDecrementWriteOperationCounterIfOperationThrowsException() throws Exception {
        smartRequest = createGitSmartRequest();
        stubCommandBuilder();
        when(command.call()).thenThrow(new RuntimeException("boom!"));

        try {
            smartRequest.handleRequest();
        } catch (RuntimeException e) {
            // stop the exception we throw from halting the test
        }

        InOrder inOrder = inOrder(writeTracker);
        inOrder.verify(writeTracker).onWriteStart();
        inOrder.verify(writeTracker).onWriteEnd();
    }

    @Override
    protected GitSmartRequest createGitSmartRequest() {
        return new GitSmartWriteRequest(repository, builderFactory, config, eventPublisher, i18nService,
                request, response, servletContext, writeTracker, requestContext) {

            @Override
            protected void addLabels(RequestContext requestContext) {
                // No-op
            }

            @Override
            protected void onSuccess() {
                // No-op
            }

            protected boolean isOperationComplete() {
                throw new UnsupportedOperationException();
            }
        };
    }
}
