package eu.dnetlib.enabling.is.registry.schema;

import static org.junit.Assert.assertNotNull;
import static org.mockito.Matchers.anyString;
import static org.mockito.Mockito.when;

import javax.xml.XMLConstants;
import javax.xml.transform.stream.StreamSource;
import javax.xml.validation.Schema;
import javax.xml.validation.SchemaFactory;

import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnitRunner;
import org.xml.sax.SAXException;

import eu.dnetlib.enabling.tools.StreamOpaqueResource;

/**
 * test schema validator.
 *
 * @author marko
 *
 */
@RunWith(MockitoJUnitRunner.class)
public class OpaqueResourceValidatorImplTest {

	/**
	 * instance under test.
	 */
	private transient OpaqueResourceValidatorImpl validator;

	/**
	 * resource schema dao mock.
	 */
	@Mock
	private transient ResourceSchemaDAO schemaDao;

	/**
	 * prepare tests.
	 *
	 * @throws SAXException
	 *             schema related
	 */
	@Before
	public void setUp() throws SAXException {
		final SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
		final Schema schema = schemaFactory.newSchema(new StreamSource(getClass().getResourceAsStream("schema.xsd")));

		when(schemaDao.getResourceSchema(anyString())).thenReturn(schema);

		validator = new OpaqueResourceValidatorImpl();
		validator.setSchemaDao(schemaDao);
	}

	/**
	 * test profile validation.
	 *
	 * @throws Exception
	 *             could happen
	 */
	@Test
	public void testValid() throws Exception { // NOPMD
		validator.validate(new StreamOpaqueResource(getClass().getResourceAsStream("valid-profile.xml")));
		assertNotNull("dummy", validator);
	}

	/**
	 * test profile validation.
	 *
	 * @throws Exception
	 *             could happen
	 */
	@Test(expected = ValidationException.class)
	public void testInvalid() throws Exception { // NOPMD
		validator.validate(new StreamOpaqueResource(getClass().getResourceAsStream("invalid-profile.xml")));
	}

	/**
	 * Validate a profile which has an optional "any" element, possible non-standard behavior in java validator.
	 *
	 * @throws Exception could happen
	 */
	@Test
	public void testValidAnyOptional() throws Exception { // NOPMD
		final SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
		final Schema schema = schemaFactory.newSchema(new StreamSource(getClass().getResourceAsStream("any-schema.xsd")));

		when(schemaDao.getResourceSchema(anyString())).thenReturn(schema);

		validator.validate(new StreamOpaqueResource(getClass().getResourceAsStream("valid-any-optional.xml")));
	}

}
