package com.atlassian.bitbucket.scm.ssh;

import com.atlassian.bitbucket.i18n.SimpleI18nService;
import com.atlassian.utils.process.ProcessTimeoutException;
import org.junit.Test;

import java.io.ByteArrayOutputStream;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;

public class SshCommandExitHandlerTest {

    @Test
    public void testOnNormalExit() throws Exception {
        ByteArrayOutputStream stream = new ByteArrayOutputStream();
        SshCommandExitHandler handler = new SshCommandExitHandler(new SimpleI18nService(), stream);

        handler.onExit("git-upload-pack '/data/repositories/1'", 0, "", null);
        assertEquals(stream.toString(), "");
        assertEquals(handler.getExitCode().intValue(), 0);
    }

    @Test
    public void testOnExitWithError() throws Exception {
        ByteArrayOutputStream stream = new ByteArrayOutputStream();
        SshCommandExitHandler handler = new SshCommandExitHandler(new SimpleI18nService(), stream);

        handler.onExit("git-receive-pack '/data/repositories/1'", 1, "", new RuntimeException("Testing"));
        assertEquals(stream.toString(), "");
        assertEquals(handler.getExitCode().intValue(), 1);
    }

    @Test
    public void testOnExitWithTimeout() throws Exception {
        ByteArrayOutputStream stream = new ByteArrayOutputStream();
        SshCommandExitHandler handler = new SshCommandExitHandler(new SimpleI18nService(), stream);

        handler.onExit("hg -R qa/test serve --stdio", 2, "", new ProcessTimeoutException("Testing"));
        assertTrue(stream.toString().contains("bitbucket.scm.ssh.process.timeout"));
        assertEquals(handler.getExitCode().intValue(), 2);
    }
}
