// Copyright 2008-2012 severally by the contributors
//
// 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 net.sf.practicalxml;

import javax.xml.XMLConstants;

import org.w3c.dom.Element;


public class TestXsiUtil
extends AbstractTestCase
{
    public void testSetXsiNil() throws Exception
    {
        Element root = DomUtil.newDocument("root");
        Element child1 = DomUtil.appendChild(root, "child1");
        Element child2 = DomUtil.appendChild(root, "child2");

        XsiUtil.setXsiNil(child1, true);
        assertEquals("true", child1.getAttributeNS(XMLConstants.W3C_XML_SCHEMA_INSTANCE_NS_URI, "nil"));

        // setting a value of "false" doesn't affect an element without the attribute
        XsiUtil.setXsiNil(child2, false);
        assertEquals("", child2.getAttributeNS(XMLConstants.W3C_XML_SCHEMA_INSTANCE_NS_URI, "nil"));

        // and will remove the attribute from an element that already has it
        XsiUtil.setXsiNil(child1, false);
        assertEquals("", child1.getAttributeNS(XMLConstants.W3C_XML_SCHEMA_INSTANCE_NS_URI, "nil"));
    }


    public void testGetXsiNil() throws Exception
    {
        Element root = DomUtil.newDocument("root");

        // this attribute is defined using the "xsd:boolean" type, so can be "true" or "1"

        Element child1 = DomUtil.appendChild(root, "child1");
        child1.setAttributeNS(XMLConstants.W3C_XML_SCHEMA_INSTANCE_NS_URI, "nil", "true");
        assertTrue(XsiUtil.getXsiNil(child1));

        Element child2 = DomUtil.appendChild(root, "child2");
        child2.setAttributeNS(XMLConstants.W3C_XML_SCHEMA_INSTANCE_NS_URI, "nil", "1");
        assertTrue(XsiUtil.getXsiNil(child2));

        // the spec doesn't say anything about case-sensitivity, but I'll accept uppercase

        Element child3 = DomUtil.appendChild(root, "child3");
        child3.setAttributeNS(XMLConstants.W3C_XML_SCHEMA_INSTANCE_NS_URI, "nil", "TRUE");
        assertTrue(XsiUtil.getXsiNil(child3));

        // the "nil" attribute without a namespace is invalid

        Element child4 = DomUtil.appendChild(root, "child4");
        child4.setAttribute("nil", "true");
        assertFalse(XsiUtil.getXsiNil(child4));

        // missing the attribute entirely is also false (and shouldn't blow up)

        Element child5 = DomUtil.appendChild(root, "child5");
        assertFalse(XsiUtil.getXsiNil(child5));
    }
}
