package test.encoding.soapenc;

import javax.xml.parsers.*;  // JAXP interfaces
import org.w3c.dom.*;
import org.apache.soap.util.Bean;
import org.apache.soap.util.xml.Deserializer;
import java.io.ByteArrayInputStream;
import org.apache.soap.encoding.soapenc.DecimalDeserializer;
import java.math.BigDecimal;

import junit.framework.TestCase;

/**
 * This decimal deserializer test provides basic test
 * coverage for verifying that decimal numbers are
 * deserialized correctly.
 *
 * @author Sam Ruby (rubys@us.ibm.com)
 * @author Jim Stearns (Jim_Stearns@hp.com)
 */
public class DecimalDeserializerTest extends TestCase
{
    private Deserializer objectToTest;

    public DecimalDeserializerTest(String name)
    {
        super(name);
        objectToTest = new DecimalDeserializer();
    }

    private Node domFromXMLString(String str) throws Exception
    {
        DocumentBuilderFactory  factory = 
            DocumentBuilderFactory.newInstance();
        DocumentBuilder         builder;
        Document                document;
        builder = factory.newDocumentBuilder();

        ByteArrayInputStream bais = new ByteArrayInputStream(str.getBytes());
        document = builder.parse(bais);
        return document.getDocumentElement();
    }

    private Bean runUnmarshall(String value) throws Exception
    {
        Node myNode = domFromXMLString(
            "<value>" + value + "</value>");
        return objectToTest.unmarshall("dontCare", /* inScopeEncStyle */
                null,       /* QName: dontcare */
                myNode,
                null,       /* XMLJavaMappingRegistry: dontcare */
                null);      /* SOAPContext: dontcare */
    }

    public void testGoodPositiveDecimal() throws Exception
    {
        Bean bean = runUnmarshall("1.1");
        assertEquals(bean.value, new BigDecimal("1.1"));
    }

    public void testGoodZeroDecimal() throws Exception
    {
        Bean bean = runUnmarshall("0");
        assertEquals(bean.value, new BigDecimal("0"));
    }

    public void testGoodNegativeDecimal() throws Exception
    {
        Bean bean = runUnmarshall("-3.1");
        assertEquals(bean.value, new BigDecimal("-3.1"));
    }

    public void testBadDecimal() throws Exception
    {
        try {
            runUnmarshall("InvalidDecimal");
            fail("Didn't get expected NumberFormatException");
        } catch (NumberFormatException nfe) {
            return;
        }
    }

}
