DS-Lab / src / test / java / dslab / rmi / dmtp / DmtpClientStubTest.java
DmtpClientStubTest.java
Raw
package dslab.rmi.dmtp;

import dslab.ComponentFactory;
import dslab.TestObjects;
import dslab.protocol.dmtp.Dmtp;
import dslab.protocol.dmtp.InvalidMessageException;
import dslab.protocol.dmtp.NoOpenMessageException;
import dslab.rmi.channel.SocketChannel;
import dslab.routing.AddressResolutionException;
import dslab.util.ComponentId;
import org.junit.Test;

import java.nio.channels.ClosedChannelException;
import java.util.List;

import static dslab.TestObjects.*;
import static org.junit.Assert.assertEquals;
import static org.mockito.Mockito.*;

public class DmtpClientStubTest {

    @Test
    public void shouldSerializeCalls() throws ClosedChannelException, NoOpenMessageException {

        var socketChannel = mock(SocketChannel.class);
        when(socketChannel.readLinesWhileReady()).thenReturn("ok DMTP2.0").getMock();
        Dmtp dmtp = transferServerComponentFactory().newDmtpInstance(socketChannel);

        dmtp.subject("greetings");

        verify(socketChannel).write("subject greetings");
    }

    @Test
    public void shouldReturnDeserializedServerResponses()
            throws ClosedChannelException, AddressResolutionException, NoOpenMessageException {

        var socketChannel = mock(SocketChannel.class);
        when(socketChannel.readLinesWhileReady()).thenReturn("ok DMTP2.0", "ok 2");
        Dmtp dmtp = transferServerComponentFactory().newDmtpInstance(socketChannel);

        var result = dmtp.to(List.of(arthurAtEarthPlanet, zaphodAtUniverZe));

        assertEquals(2, result);
    }

    @Test(expected = NoOpenMessageException.class)
    public void shouldThrowDeserializedErrors() throws ClosedChannelException, NoOpenMessageException, InvalidMessageException {

        var socketChannel = mock(SocketChannel.class);

        when(socketChannel.readLinesWhileReady()).thenReturn(
                "ok DMTP2.0",
                "error " + NoOpenMessageException.class.getSimpleName() + " " +
                        new NoOpenMessageException().getMessage());

        transferServerComponentFactory().newDmtpInstance(socketChannel).send();
    }
}