package com.atlassian.stash.internal.johnson.handler.bean;

import com.atlassian.stash.internal.johnson.handler.EventDetails;
import liquibase.exception.LockException;
import org.junit.Test;
import org.springframework.beans.factory.BeanCreationException;

import java.sql.SQLException;

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

public class LiquibaseFailureHandlerTest {

    private final LiquibaseFailureHandler handler = new LiquibaseFailureHandler();

    @Test
    public void testHandleLockException() throws Exception {
        LockException lockException = new LockException("can-not-acquire-lock");
        testHandle(new BeanCreationException("can-not-create-bean", lockException), "schema-locked", lockException);
    }

    @Test
    public void testHandleLockExceptionCausedByMYSQLBinaryLogging() throws Exception {
        LockException lockException = new LockException("can-not-acquire-lock", new SQLException("Binary logging not possible. Message: Transaction level 'FOO' in InnoDB is not safe for binlog mode 'BAR'"));
        testHandle(new BeanCreationException("can-not-create-bean", lockException), "database-mysql-binary-log", lockException);
    }

    @Test
    public void testHandleUnknownError() throws Exception {
        RuntimeException exception = new RuntimeException();
        testHandle(new BeanCreationException("can-not-create-bean", exception), "schema-update-failed", exception);
    }

    private void testHandle(BeanCreationException e, String eventType, Throwable eventThrowable) {
        EventDetails event = handler.handle(e);
        assertNotNull(event);
        assertEquals(eventType, event.getEventType());
        assertEquals(eventThrowable, event.getThrowable());
    }

}
