
package com.clicktravel.cheddar.application.continuation;

import static org.junit.Assert.assertEquals;

import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

import org.junit.Test;

public class ContinuationHandlerTest {

    @Test(timeout = 1000)
    public void shouldReturnMethodResult_whenWaitAndPut() throws Exception {
        // Given
        final Object simpleResult = new Object();
        final ContinuationHandler continuationHandler = new ContinuationHandler();
        continuationHandler.createContinuation();
        final String continuationId = continuationHandler.getContinuationId();
        final Runnable runnable = new Runnable() {
            @Override
            public void run() {
                continuationHandler.setSimpleMethodResult(continuationId, simpleResult);
                continuationHandler.offerMethodResult();
            }
        };
        Executors.newSingleThreadScheduledExecutor().schedule(runnable, 200, TimeUnit.MILLISECONDS);

        // When
        final Object actualResult = continuationHandler.pollForMethodReturnValue();

        // Then
        assertEquals(simpleResult, actualResult);
    }

    @Test(timeout = 1000)
    public void shouldReturnException_whenWaitAndPut() throws Exception {
        // Given
        final Exception exceptionResult = new Exception();
        final ContinuationHandler continuationHandler = new ContinuationHandler();
        continuationHandler.createContinuation();
        final String continuationId = continuationHandler.getContinuationId();
        final Runnable runnable = new Runnable() {
            @Override
            public void run() {
                continuationHandler.setExceptionMethodResult(continuationId, exceptionResult);
                continuationHandler.offerMethodResult();
            }
        };
        Executors.newSingleThreadScheduledExecutor().schedule(runnable, 200, TimeUnit.MILLISECONDS);

        // When
        Exception thrownException = null;
        try {
            continuationHandler.pollForMethodReturnValue();
        } catch (final Exception e) {
            thrownException = e;
        }

        // Then
        assertEquals(exceptionResult, thrownException);
    }
}
