<commit_before>/**
 * Copyright (C) 2012-2014 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package ninja.servlet;

import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.CoreMatchers.nullValue;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.assertTrue;
import static org.mockito.Matchers.anyString;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;

import java.util.Map;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import ninja.*;
import ninja.bodyparser.BodyParserEngine;
import ninja.bodyparser.BodyParserEngineManager;
import ninja.session.FlashScope;
import ninja.session.Session;

import ninja.utils.NinjaConstant;
import ninja.utils.ResultHandler;
import ninja.validation.Validation;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.ArgumentCaptor;
import org.mockito.Matchers;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;

import com.google.common.collect.Maps;
import ninja.utils.NinjaProperties;

@RunWith(MockitoJUnitRunner.class)
public class ContextImplTest {

    @Mock
    private Session sessionCookie;

    @Mock
    private FlashScope flashCookie;

    @Mock
    private BodyParserEngineManager bodyParserEngineManager;

    @Mock
    private ServletContext servletContext;

    @Mock
    private HttpServletRequest httpServletRequest;

    @Mock
    private HttpServletResponse httpServletResponse;

    @Mock
    private Route route;

    @Mock
    private ResultHandler resultHandler;

    @Mock
    private Validation validation;

    @Mock
    private BodyParserEngine bodyParserEngine;
    
    @Mock
    private NinjaProperties ninjaProperties;

    private ContextImpl context;

    @Before
    public void setUp() {
        //default setup for httpServlet request.
        //According to servlet spec the following will be returned:
        when(httpServletRequest.getContextPath()).thenReturn("");
        when(httpServletRequest.getRequestURI()).thenReturn("/");


        context = new ContextImpl(
                bodyParserEngineManager, 
                flashCookie, 
                ninjaProperties,
                resultHandler, 
                sessionCookie,
                validation);
    }

    @Test
    public void testGetRequestUri() {

        //say the httpServletRequest to return a certain value:
        when(httpServletRequest.getRequestURI()).thenReturn("/index");

        //init the context from a (mocked) servlet
        context.init(servletContext, httpServletRequest, httpServletResponse);

        //make sure this is correct
        assertEquals("/index", context.getRequestUri());
    }

    @Test
    public void testGetHostname() {

        //say the httpServletRequest to return a certain value:
        when(httpServletRequest.getHeader("host")).thenReturn("test.com");

        //init the context from a (mocked) servlet
        context.init(servletContext, httpServletRequest, httpServletResponse);

        //make sure this is correct
        assertEquals("test.com", context.getHostname());
    }

    @Test
    public void testGetRemoteAddrReturnsDefaultRemoteAddr() {

        //say the httpServletRequest to return a certain value:
        when(httpServletRequest.getRemoteAddr()).thenReturn("mockedRemoteAddr");
        when(httpServletRequest.getHeader(Context.X_FORWARD_HEADER)).thenReturn("x-forwarded-for-mockedRemoteAddr");

        //init the context from a (mocked) servlet
        context.init(httpServletRequest, httpServletResponse);

        //make sure this is correct
        assertEquals("mockedRemoteAddr", context.getRemoteAddr());
    }
    
    @Test
    public void testGetRemoteAddrParsesXForwardedForIfSetInApplicationConf() {

        //say the httpServletRequest to return a certain value:
        when(httpServletRequest.getRemoteAddr()).thenReturn("mockedRemoteAddr");
        when(httpServletRequest.getHeader(Context.X_FORWARD_HEADER)).thenReturn("192.168.1.44");

        when(ninjaProperties.getBooleanWithDefault(Context.NINJA_PROPERTIES_X_FORWARDED_FOR, false))
                .thenReturn(Boolean.TRUE);

        //init the context from a (mocked) servlet
        context.init(httpServletRequest, httpServletResponse);

        //make sure this is correct
        assertEquals("192.168.1.44", context.getRemoteAddr());
    }
    
    @Test
    public void testGetRemoteAddrParsesXForwardedForIfMoreThanOneHostPresent() {

        //say the httpServletRequest to return a certain value:
        when(httpServletRequest.getRemoteAddr()).thenReturn("mockedRemoteAddr");
        when(httpServletRequest.getHeader(Context.X_FORWARD_HEADER)).thenReturn("192.168.1.1, 192.168.1.2, 192.168.1.3");

        when(ninjaProperties.getBooleanWithDefault(Context.NINJA_PROPERTIES_X_FORWARDED_FOR, false))
                .thenReturn(Boolean.TRUE);

        //init the context from a (mocked) servlet
        context.init(httpServletRequest, httpServletResponse);

        //make sure this is correct
        assertEquals("192.168.1.1", context.getRemoteAddr());
    }
    
    @Test
    public void testGetRemoteAddrUsesFallbackIfXForwardedForIsNotValidInetAddr() {

        //say the httpServletRequest to return a certain value:
        when(httpServletRequest.getRemoteAddr()).thenReturn("mockedRemoteAddr");
        when(httpServletRequest.getHeader(Context.X_FORWARD_HEADER)).thenReturn("I_AM_NOT_A_VALID_ADDRESS");

        when(ninjaProperties.getBooleanWithDefault(Context.NINJA_PROPERTIES_X_FORWARDED_FOR, false))
                .thenReturn(Boolean.TRUE);

        //init the context from a (mocked) servlet
        context.init(servletContext, httpServletRequest, httpServletResponse);

        //make sure this is correct
        assertEquals("mockedRemoteAddr", context.getRemoteAddr());
    }

    @Test
    public void testAddCookieViaResult() {
        Cookie cookie = Cookie.builder("cookie", "yum").setDomain("domain").build();
        context.init(servletContext, httpServletRequest, httpServletResponse);
        //context.addCookie(cookie);

        //generate an arbitrary result:
        Result result = Results.html();
        result.addCookie(cookie);<commit_msg>Added a tiny fix to make the testcase work again.<commit_after>/**
 * Copyright (C) 2012-2014 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package ninja.servlet;

import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.CoreMatchers.nullValue;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.assertTrue;
import static org.mockito.Matchers.anyString;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;

import java.util.Map;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import ninja.*;
import ninja.bodyparser.BodyParserEngine;
import ninja.bodyparser.BodyParserEngineManager;
import ninja.session.FlashScope;
import ninja.session.Session;

import ninja.utils.NinjaConstant;
import ninja.utils.ResultHandler;
import ninja.validation.Validation;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.ArgumentCaptor;
import org.mockito.Matchers;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;

import com.google.common.collect.Maps;
import ninja.utils.NinjaProperties;

@RunWith(MockitoJUnitRunner.class)
public class ContextImplTest {

    @Mock
    private Session sessionCookie;

    @Mock
    private FlashScope flashCookie;

    @Mock
    private BodyParserEngineManager bodyParserEngineManager;

    @Mock
    private ServletContext servletContext;

    @Mock
    private HttpServletRequest httpServletRequest;

    @Mock
    private HttpServletResponse httpServletResponse;

    @Mock
    private Route route;

    @Mock
    private ResultHandler resultHandler;

    @Mock
    private Validation validation;

    @Mock
    private BodyParserEngine bodyParserEngine;
    
    @Mock
    private NinjaProperties ninjaProperties;

    private ContextImpl context;

    @Before
    public void setUp() {
        //default setup for httpServlet request.
        //According to servlet spec the following will be returned:
        when(httpServletRequest.getContextPath()).thenReturn("");
        when(httpServletRequest.getRequestURI()).thenReturn("/");


        context = new ContextImpl(
                bodyParserEngineManager, 
                flashCookie, 
                ninjaProperties,
                resultHandler, 
                sessionCookie,
                validation);
    }

    @Test
    public void testGetRequestUri() {

        //say the httpServletRequest to return a certain value:
        when(httpServletRequest.getRequestURI()).thenReturn("/index");

        //init the context from a (mocked) servlet
        context.init(servletContext, httpServletRequest, httpServletResponse);

        //make sure this is correct
        assertEquals("/index", context.getRequestUri());
    }

    @Test
    public void testGetHostname() {

        //say the httpServletRequest to return a certain value:
        when(httpServletRequest.getHeader("host")).thenReturn("test.com");

        //init the context from a (mocked) servlet
        context.init(servletContext, httpServletRequest, httpServletResponse);

        //make sure this is correct
        assertEquals("test.com", context.getHostname());
    }

    @Test
    public void testGetRemoteAddrReturnsDefaultRemoteAddr() {

        //say the httpServletRequest to return a certain value:
        when(httpServletRequest.getRemoteAddr()).thenReturn("mockedRemoteAddr");
        when(httpServletRequest.getHeader(Context.X_FORWARD_HEADER)).thenReturn("x-forwarded-for-mockedRemoteAddr");

        //init the context from a (mocked) servlet
        context.init(servletContext, httpServletRequest, httpServletResponse);

        //make sure this is correct
        assertEquals("mockedRemoteAddr", context.getRemoteAddr());
    }
    
    @Test
    public void testGetRemoteAddrParsesXForwardedForIfSetInApplicationConf() {

        //say the httpServletRequest to return a certain value:
        when(httpServletRequest.getRemoteAddr()).thenReturn("mockedRemoteAddr");
        when(httpServletRequest.getHeader(Context.X_FORWARD_HEADER)).thenReturn("192.168.1.44");

        when(ninjaProperties.getBooleanWithDefault(Context.NINJA_PROPERTIES_X_FORWARDED_FOR, false))
                .thenReturn(Boolean.TRUE);

        //init the context from a (mocked) servlet
        context.init(servletContext, httpServletRequest, httpServletResponse);

        //make sure this is correct
        assertEquals("192.168.1.44", context.getRemoteAddr());
    }
    
    @Test
    public void testGetRemoteAddrParsesXForwardedForIfMoreThanOneHostPresent() {

        //say the httpServletRequest to return a certain value:
        when(httpServletRequest.getRemoteAddr()).thenReturn("mockedRemoteAddr");
        when(httpServletRequest.getHeader(Context.X_FORWARD_HEADER)).thenReturn("192.168.1.1, 192.168.1.2, 192.168.1.3");

        when(ninjaProperties.getBooleanWithDefault(Context.NINJA_PROPERTIES_X_FORWARDED_FOR, false))
                .thenReturn(Boolean.TRUE);

        //init the context from a (mocked) servlet
        context.init(servletContext, httpServletRequest, httpServletResponse);

        //make sure this is correct
        assertEquals("192.168.1.1", context.getRemoteAddr());
    }
    
    @Test
    public void testGetRemoteAddrUsesFallbackIfXForwardedForIsNotValidInetAddr() {

        //say the httpServletRequest to return a certain value:
        when(httpServletRequest.getRemoteAddr()).thenReturn("mockedRemoteAddr");
        when(httpServletRequest.getHeader(Context.X_FORWARD_HEADER)).thenReturn("I_AM_NOT_A_VALID_ADDRESS");

        when(ninjaProperties.getBooleanWithDefault(Context.NINJA_PROPERTIES_X_FORWARDED_FOR, false))
                .thenReturn(Boolean.TRUE);

        //init the context from a (mocked) servlet
        context.init(servletContext, httpServletRequest, httpServletResponse);

        //make sure this is correct
        assertEquals("mockedRemoteAddr", context.getRemoteAddr());
    }

    @Test
    public void testAddCookieViaResult() {
        Cookie cookie = Cookie.builder("cookie", "yum").setDomain("domain").build();
        context.init(servletContext, httpServletRequest, httpServletResponse);
        //context.addCookie(cookie);

        //generate an arbitrary result:
        Result result = Results.html();
        result.addCookie(cookie);
{'fraction_non_alphanumeric': 0.08921775898520085, 'fraction_numerical': 0.008738548273431995, 'mean_word_length': 3.5136768447837152, 'pattern_counts': {'":': 0, '<': 3, '<?xml version=': 0, '>': 3, 'https://': 0, 'lorem ipsum': 0, 'www.': 2, 'xml': 0}, 'pii_count': 12, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '1217151', 'n_tokens_mistral': 3920, 'n_tokens_neox': 3719, 'n_words': 923}