package test.org.mule.routing.inbound;

import org.mule.api.ExceptionPayload;
import org.mule.api.MessagingException;
import org.mule.api.MuleMessage;
import org.mule.module.client.MuleClient;
import org.mule.transport.NullPayload;

import test.org.mule.tck.FunctionalTestCase;

public class SelectiveConsumerRouterTest extends FunctionalTestCase {

    static final String URL = "vm://SelectiveConsumerRouter";
    static final String ERROR_URL = "vm://error";

    static final long TIMEOUT = 3000;
    static final long SHORT_TIMEOUT = 500;

    protected String getConfigResources() {
        return "test/org/mule/routing/inbound/SelectiveConsumerRouterTest-config.xml";
    }

    public void testSend_OK() throws Exception {
        MuleClient client = new MuleClient();
        MuleMessage message = client.send(URL, "abc", null);
        assertEquals("abc", message.getPayload());
        assertNull(client.request(ERROR_URL, SHORT_TIMEOUT));
    }

    public void testSend_FailureAtInbound() throws Exception {
        MuleClient client = new MuleClient();
        MuleMessage message = client.send(URL, "failure@inbound", null);
        assertEquals(NullPayload.getInstance(), message.getPayload());
        MuleMessage error = client.request(ERROR_URL, TIMEOUT);
        assertEquals("failure@inbound", error.getPayload());
    }

    public void testSend_FailureAtComponent() throws Exception {
        MuleClient client = new MuleClient();
        MuleMessage message = client.send(URL, "failure@component", null);
        assertEquals("FAILURE!! (@component)", message.getPayload());
        assertNull(client.request(ERROR_URL, SHORT_TIMEOUT));
    }

    public void testSend_ExceptionAtComponent() throws Exception {
        MuleClient client = new MuleClient();
        MuleMessage message = client.send(URL, "exception@component", null);
        assertEquals(NullPayload.getInstance(), message.getPayload());
        ExceptionPayload ep = message.getExceptionPayload();
        MessagingException me = (MessagingException) ep.getException();
        RuntimeException re = (RuntimeException) me.getCause();
        assertEquals("EXCEPTION!! (@component)", re.getMessage());
        assertNull(client.request(ERROR_URL, SHORT_TIMEOUT));
    }

}
