

package org.apache.servicecomb.transport.rest.vertx.accesslog.element.impl;

import static org.junit.Assert.assertEquals;

import org.apache.servicecomb.transport.rest.vertx.accesslog.AccessLogParam;
import org.junit.Test;
import org.mockito.Mockito;

import io.vertx.core.http.HttpServerRequest;
import io.vertx.core.net.SocketAddress;
import io.vertx.ext.web.RoutingContext;

public class LocalPortItemTest {

  @Test
  public void getFormattedElement() {
    AccessLogParam<RoutingContext> param = new AccessLogParam<>();
    RoutingContext context = Mockito.mock(RoutingContext.class);
    HttpServerRequest request = Mockito.mock(HttpServerRequest.class);
    SocketAddress localAddress = Mockito.mock(SocketAddress.class);

    param.setContextData(context);
    Mockito.when(context.request()).thenReturn(request);
    Mockito.when(request.localAddress()).thenReturn(localAddress);
    Mockito.when(localAddress.port()).thenReturn(8080);

    String result = new LocalPortItem().getFormattedItem(param);

    assertEquals("8080", result);
  }

  @Test
  public void getFormattedElementOnRequestIsNull() {
    AccessLogParam<RoutingContext> param = new AccessLogParam<>();
    RoutingContext context = Mockito.mock(RoutingContext.class);

    param.setContextData(context);
    Mockito.when(context.request()).thenReturn(null);

    String result = new LocalPortItem().getFormattedItem(param);

    assertEquals("-", result);
  }

  @Test
  public void getFormattedElementOnLocalAddressIsNull() {
    AccessLogParam<RoutingContext> param = new AccessLogParam<>();
    RoutingContext context = Mockito.mock(RoutingContext.class);
    HttpServerRequest request = Mockito.mock(HttpServerRequest.class);

    param.setContextData(context);
    Mockito.when(context.request()).thenReturn(request);
    Mockito.when(request.localAddress()).thenReturn(null);

    String result = new LocalPortItem().getFormattedItem(param);

    assertEquals("-", result);
  }
}
