/*
 * Copyright 2004-2014 the Seasar Foundation and the Others.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
 * either express or implied. See the License for the specific language
 * governing permissions and limitations under the License.
 */

package org.seasar.extension.dbcp.impl;

import java.sql.Connection;
import java.sql.SQLException;

import javax.sql.XAConnection;
import javax.transaction.xa.XAResource;
import javax.transaction.xa.Xid;

import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.seasar.extension.jta.xa.XidImpl;

/**
 * @author higa
 *
 */
public class DbXAResourceImplTest {

    /** XAConnection */
    private XAConnection xacon = null;
    /** Connection */
    private Connection con = null;
    /** XAResource */
    private XAResource xares = null;

    /**
     * setUp
     * @throws SQLException SQLException
     */
    @Before
    public void setUp() throws SQLException {
        final XADataSourceImpl xads2 = new XADataSourceImpl();
        xads2.setDriverClassName("org.postgresql.Driver");
        xads2.setURL("jdbc:postgresql://localhost:5432/test");
        xads2.setUser("postgres");
        xads2.setPassword("postgres");

        this.xacon = xads2.getXAConnection();
        this.con = this.xacon.getConnection();
        this.xares = new DbXAResourceImpl(this.con);
    }

    /**
     * tearDown
     * @throws Exception Exception
     */
    @After
    public void tearDown() throws Exception {
        this.xacon.close();
    }

    /**
     * @throws Exception Exception
     */
    @Test
    public void testDoBegin() throws Exception {
        this.xares.start(new XidImpl(), XAResource.TMNOFLAGS);
        Assert.assertFalse("1", this.con.getAutoCommit());
    }

    /**
     * @throws Exception Exception
     */
    @Test
    public void testDoCommit() throws Exception {
        final Xid xid = new XidImpl();
        this.xares.start(xid, XAResource.TMNOFLAGS);
        this.xares.end(xid, XAResource.TMSUCCESS);
        this.xares.commit(xid, true);
        Assert.assertTrue("1", this.con.getAutoCommit());
    }

    /**
     * @throws Exception Exception
     */
    @Test
    public void testDoRollback() throws Exception {
        final Xid xid = new XidImpl();
        this.xares.start(xid, XAResource.TMNOFLAGS);
        this.xares.end(xid, XAResource.TMFAIL);
        this.xares.rollback(xid);
        Assert.assertTrue("1", this.con.getAutoCommit());
    }
}
