package com.atlassian.stash.internal.process;

import com.atlassian.bitbucket.auth.AuthenticationContext;
import com.atlassian.bitbucket.user.ApplicationUser;
import com.atlassian.utils.process.ExternalProcessSettings;
import com.google.common.collect.Maps;
import org.hamcrest.collection.IsMapContaining;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.invocation.InvocationOnMock;
import org.mockito.runners.MockitoJUnitRunner;
import org.mockito.stubbing.Answer;

import java.util.Map;

import static org.hamcrest.Matchers.not;
import static org.hamcrest.collection.IsMapContaining.hasEntry;
import static org.junit.Assert.assertThat;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;

@RunWith(MockitoJUnitRunner.class)
public class RemoteUserExternalProcessConfigurerTest {

    @Mock
    private AuthenticationContext authContext;
    @Mock
    private ExternalProcessSettings settings;

    private Map<String, String> environmentSettings = Maps.newHashMap();

    private ApplicationUser currentUser;

    private RemoteUserExternalProcessConfigurer configurer;

    @Before
    public void setUp() throws Exception {
        when(authContext.getCurrentUser()).thenAnswer(new Answer<ApplicationUser>() {
            public ApplicationUser answer(InvocationOnMock invocationOnMock) throws Throwable {
                return currentUser;
            }
        });
        when(settings.getEnvironment()).thenReturn(environmentSettings);
        configurer = new RemoteUserExternalProcessConfigurer(authContext);
    }

    @Test
    public void testConfigure() throws Exception {
        currentUser = mock(ApplicationUser.class);
        when(currentUser.getName()).thenReturn("psy");
        configurer.configure(settings);
        assertThat(environmentSettings, hasEntry("REMOTE_USER", "psy"));
        currentUser = null;
        environmentSettings.clear();
        assertThat(environmentSettings, not(IsMapContaining.hasKey("REMOTE_USER")));
    }
}
