package com.atlassian.stash.internal.scm.git.pull;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InOrder;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;

import java.util.Arrays;

import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertSame;
import static org.mockito.Mockito.*;

@RunWith(MockitoJUnitRunner.class)
public class CompositePullRequestAutoMergeStrategyTest {

    @Mock
    private PullRequestAutoMergeStrategy first;
    @Mock
    private PullRequestMerge merge;
    @Mock
    private PullRequestRefs refs;
    @Mock
    private PullRequestAutoMergeRequest request;
    @Mock
    private PullRequestAutoMergeStrategy second;

    @Test
    public void testMerge() {
        when(second.merge(same(request), same(refs))).thenReturn(merge);

        assertSame(merge, runMerge());

        InOrder ordered = inOrder(first, second);
        ordered.verify(first).merge(same(request), same(refs));
        ordered.verify(second).merge(same(request), same(refs));
    }

    @Test
    public void testMergeReturnsFirstSuccessfulMerge() {
        when(first.merge(same(request), same(refs))).thenReturn(merge);

        assertSame(merge, runMerge());

        verify(first).merge(same(request), same(refs));
        verifyZeroInteractions(second);
    }

    @Test
    public void testMergeWhenAllStrategiesFail() {
        assertNull(runMerge());
    }

    private PullRequestMerge runMerge() {
        return new CompositePullRequestAutoMergeStrategy(Arrays.asList(first, second)).merge(request, refs);
    }
}
