package com.atlassian.stash.internal.backup.liquibase;

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

import javax.xml.stream.XMLStreamException;
import java.io.OutputStream;

import static org.hamcrest.Matchers.endsWith;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNotSame;
import static org.junit.Assert.assertSame;
import static org.junit.Assert.assertThat;
import static org.mockito.Matchers.same;
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.spy;

/**
 * Tests the operation of the {@link DefaultLiquibaseXmlWriterFactory} class.
 */
@RunWith(MockitoJUnitRunner.class)
public class DefaultLiquibaseXmlWriterFactoryTest {

    private static final String AUTHOR = "test.user";

    @Mock
    private OutputStream stream;

    private DefaultLiquibaseXmlWriterFactory factory;

    @Before
    public void setUp() throws Exception {
        factory = new DefaultLiquibaseXmlWriterFactory();
    }

    @Test
    public void testCreate() {
        DefaultLiquibaseXmlWriter liquibaseWriter = (DefaultLiquibaseXmlWriter) factory.create(stream, AUTHOR);

        assertNotNull(liquibaseWriter.getIdGenerator());
        assertEquals("test.user", liquibaseWriter.getChangeSetAuthor());
    }

    @Test
    public void testNewIdGeneratorForEveryNewWriter() throws Exception {

        DefaultLiquibaseXmlWriter liquibaseWriter1 = (DefaultLiquibaseXmlWriter) factory.create(stream, AUTHOR);
        DefaultLiquibaseXmlWriter liquibaseWriter2 = (DefaultLiquibaseXmlWriter) factory.create(stream, AUTHOR);

        assertNotSame(liquibaseWriter2.getIdGenerator(), liquibaseWriter1.getIdGenerator());

        assertThat(liquibaseWriter1.getIdGenerator().next("table"), endsWith("-1"));
        assertThat(liquibaseWriter2.getIdGenerator().next("table"), endsWith("-1"));
    }

    @Test(expected = LiquibaseDataAccessException.class)
    public void testCreateWithException() throws Exception {
        factory = spy(factory);
        doThrow(XMLStreamException.class).when(factory).newXmlWriter(same(stream));

        try {
            factory.create(stream, AUTHOR);
        } catch (LiquibaseDataAccessException e) {
            assertSame(XMLStreamException.class, e.getCause().getClass());
            throw e;
        }
    }
}
