/*
 * Copyright 2018 Scytl Secure Electronic Voting SA
 *
 * All rights reserved
 *
 * See our extended copyright notice in *file 'Copyright.txt' which is part of this source code package
 */
package com.scytl.products.ov.commons.util;

import static org.junit.Assert.assertEquals;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;

import javax.servlet.http.HttpServletRequest;

import org.junit.Before;
import org.junit.Test;

/**
 * Tests of {@link HttpRequestService}.
 */
public class HttpRequestServiceTest {
    private static final String X_FORWARDED_FOR = "X-Forwarded-For";

    private static final String ADDRESS = "address";

    private HttpServletRequest request;

    private HttpRequestService service;

    @Before
    public void setUp() {
        request = mock(HttpServletRequest.class);
        service = new HttpRequestService();
    }

    @Test
    public void testGetIpServer() {
        when(request.getLocalAddr()).thenReturn(ADDRESS);
        assertEquals(ADDRESS, service.getIpServer(request));
    }

    @Test
    public void testGetIpClientAddressNoProxy() {
        when(request.getRemoteAddr()).thenReturn("remoteAddress");
        when(request.getHeader(X_FORWARDED_FOR)).thenReturn(ADDRESS);
        assertEquals(ADDRESS, service.getIpClientAddress(request));
    }

    @Test
    public void testGetIpClientAddressProxy() {
        when(request.getRemoteAddr()).thenReturn("remoteAddress");
        when(request.getHeader(X_FORWARDED_FOR)).thenReturn(ADDRESS + ",proxyAddress");
        assertEquals(ADDRESS, service.getIpClientAddress(request));
    }

    @Test
    public void testGetIpClientAddressNoXForwardedFor() {
        HttpServletRequest request = mock(HttpServletRequest.class);
        when(request.getRemoteAddr()).thenReturn(ADDRESS);
        when(request.getHeader(X_FORWARDED_FOR)).thenReturn(null);
        assertEquals(ADDRESS, service.getIpClientAddress(request));
    }

    @Test
    public void testGetIpClientAddressEmptyXForwardedFor() {
        HttpServletRequest request = mock(HttpServletRequest.class);
        when(request.getRemoteAddr()).thenReturn(ADDRESS);
        when(request.getHeader(X_FORWARDED_FOR)).thenReturn("");
        assertEquals(ADDRESS, service.getIpClientAddress(request));
    }
}
