<commit_before>/*******************************************************************************
 *                                                                              
 *  Copyright FUJITSU LIMITED 2016                                             
 *                                                                                                                                 
 *  Creation Date: 23.04.2012                                                      
 *                                                                              
 *******************************************************************************/

package org.oscm.ui.beans;

import static org.junit.Assert.*;
import static org.mockito.Matchers.any;
import static org.mockito.Matchers.anyBoolean;
import static org.mockito.Matchers.anyListOf;
import static org.mockito.Matchers.anyString;
import static org.mockito.Matchers.eq;
import static org.mockito.Matchers.isNull;
import static org.mockito.Mockito.*;

import java.util.*;

import javax.faces.application.FacesMessage;
import javax.security.auth.login.LoginException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.junit.Before;
import org.junit.Test;
import org.mockito.invocation.InvocationOnMock;
import org.mockito.stubbing.Answer;
import org.oscm.internal.intf.ConfigurationService;
import org.oscm.internal.intf.IdentityService;
import org.oscm.internal.intf.MarketplaceService;
import org.oscm.internal.intf.TenantService;
import org.oscm.internal.types.enumtypes.AuthenticationMode;
import org.oscm.internal.types.enumtypes.ConfigurationKey;
import org.oscm.internal.types.enumtypes.UserAccountStatus;
import org.oscm.internal.types.enumtypes.UserRoleType;
import org.oscm.internal.types.exception.*;
import org.oscm.internal.usergroupmgmt.UserGroupService;
import org.oscm.internal.vo.VOConfigurationSetting;
import org.oscm.internal.vo.VOTenant;
import org.oscm.internal.vo.VOUser;
import org.oscm.internal.vo.VOUserDetails;
import org.oscm.types.constants.Configuration;
import org.oscm.ui.common.Constants;
import org.oscm.ui.common.ServiceAccess;
import org.oscm.ui.common.UiDelegate;
import org.oscm.ui.dialog.common.saml2.AuthenticationHandler;
import org.oscm.ui.dialog.state.TableState;
import org.oscm.ui.filter.AuthenticationSettings;
import org.oscm.ui.model.User;
import org.oscm.ui.model.UserRole;
import org.oscm.ui.stubs.FacesContextStub;
import org.oscm.ui.stubs.UIViewRootStub;

/**
 * Unit tests for testing the UserBean.
 * 
 * @author weiser
 */
public class UserBeanTest {

    private UserBean userBean;
    private User user;
    private VOUserDetails loggedInUser;
    private final String OUTCOME_CANCEL = "cancel";
    private final String OUTCOME_SHOW_REGISTRATION = "showRegistration";
    private final String ERROR_COMPLETE_REGISTRATION = "error.complete.registration";
    private final String BASE_URL = "http://localhost:8180/oscm-portal";
    private final String SUBSCRIPTION_ADD_PAGE = "/marketplace/subscriptions/creation/add.jsf";

    private HttpServletRequest requestMock;
    private HttpServletResponse responseMock;

    private List<FacesMessage> facesMessages = new ArrayList<FacesMessage>();
    private TableState ts;
    private IdentityService idServiceMock;
    private ConfigurationService cfgMock;
    private ServiceAccess serviceAccessMock;
    private List<UserRole> roles;
    private ApplicationBean appBean;
    private AuthenticationSettings authSettingsMock;
    private AuthenticationHandler authHandlerMock;
    private HttpSession sessionMock;
    private UserGroupService userGroupService = mock(UserGroupService.class);
    private MarketplaceService marketplaceService = mock(MarketplaceService.class);
    private static final String ISSUER = "CT-MG";
    private static final String RECIPIENT = "http://www.bes-portal.de";
    private static final String IDP = "http://www.idp.de/openam/SSORedirect/request";
    private static final String KEYSTORE_PATH = "/openam/keystore.jks";
    private static final String KEYSTORE_PASSWORD = "<PASSWORD>";
    private static final String OUTCOME_SAMLSP_REDIRECT = "redirectToIdp";
    static final String OUTCOME_ADD_USER = "addUser";

    private String errorCodeValue = null;
    private TenantService tenantService;

    @Before
    public void setup() throws Exception {
        tenantService = mock(TenantService.class);
        FacesContextStub contextStub = new FacesContextStub(Locale.ENGLISH) {
            @Override
            public void addMessage(String arg0, FacesMessage arg1) {
                facesMessages.add(arg1);
            }
        };
        UIViewRootStub vrStub = new UIViewRootStub() {
            @Override
            public Locale getLocale() {
                return Locale.ENGLISH;
            };
        };
        contextStub.setViewRoot(vrStub);

        userBean = spy(new UserBean());

        // Create a user
        user = new User(new VOUserDetails());
        user.setUserId("myUserId");

        // Mock all necessary methods of userBean
        requestMock = mock(HttpServletRequest.class);
        doReturn("/oscm-portal").when(requestMock).getContextPath();
        doReturn(new StringBuffer("https://something.de")).when(requestMock)
                .getRequestURL();
        mockErrorAttribute(requestMock);
        doReturn(requestMock).when(userBean).getRequest();

        doReturn(user).when(userBean).getUserFromSession();
        doReturn("myUserId2").when(userBean).getMyUserId();
        doNothing().when(userBean).resetUIInputChildren();

        userBean.setSessionBean(new SessionBean());
        userBean.ui = mock(UiDelegate.class);

        ts = mock(TableState.class);
        when(userBean.ui.findBean(TableState.BEAN_NAME)).thenReturn(ts);

        UserRole role = new UserRole();
        role.setSelected(true);
        role.setUserRoleType(UserRoleType.MARKETPLACE_OWNER);
        roles = Arrays.asList(role);
        userBean.setUserRolesForNewUser(roles);
        userBean.setToken(userBean.getToken());
        userBean.getNewUser();

        idServiceMock = mock(IdentityService.class);
        doReturn(idServiceMock).when(userBean).getIdService();

        appBean = mock(ApplicationBean.class);
        when(userBean.ui.findBean(eq(UserBean.APPLICATION_BEAN))).thenReturn(
                appBean);
        loggedInUser = mock(VOUserDetails.class);
        doReturn(loggedInUser).when(userBean).getLoggedInUser();

        authSettingsMock = mock(AuthenticationSettings.class);

        authHandlerMock = mock(AuthenticationHandler.class);
        doReturn(OUTCOME_SAMLSP_REDIRECT).when(authHandlerMock)
                .handleAuthentication(true, sessionMock);

        responseMock = mock(HttpServletResponse.class);
        doReturn(responseMock).when(userBean).getResponse();
        sessionMock = mock(HttpSession.class);
        doReturn(sessionMock).when(userBean).getSession();

        doReturn("").when(userBean).getLoginRedirect(
                any(HttpServletRequest.class), any(HttpSession.class),
                anyBoolean());

        doReturn(sessionMock).when(requestMock).getSession();
        serviceAccessMock = mock(ServiceAccess.class);
        doReturn(serviceAccessMock).when(sessionMock).getAttribute(
                eq(ServiceAccess.SESS_ATTR_SERVICE_ACCESS));
        doReturn(idServiceMock).when(serviceAccessMock).getService(
                eq(IdentityService.class));

        doReturn(userGroupService).when(userBean).getUserGroupService();

        when(userBean.ui.findBean(eq(UserBean.APPLICATION_BEAN))).thenReturn(
            appBean);

        doReturn(marketplaceService).when(userBean).getMarketplaceService();
        doReturn(true).when(marketplaceService).doesOrganizationHaveAccessMarketplace(anyString(), anyString());
    }

    void mockErrorAttribute(HttpServletRequest requestMock) {
        doAnswer(new Answer<Void>() {
            @Override
            public Void answer(InvocationOnMock invocation) throws Throwable {
                errorCodeValue = (String) invocation.getArguments()[1];
                return null;
            }
        }).when(requestMock).setAttribute(eq(Constants.REQ_ATTR_ERROR_KEY),
                anyString());

        doAnswer(new Answer<String>() {
            @Override
            public String answer(InvocationOnMock invocation) throws Throwable {
                return errorCodeValue;
            }
        }).when(requestMock).getAttribute(eq(Constants.REQ_ATTR_ERROR_KEY));
    }

    @Test
    public void addUser() {
        assertEquals(UserBean.OUTCOME_ADD_USER, userBean.addUser());
    }

    @Test
    public void addUser_Ldap() {
        user.setRemoteLdapActive(true);

        assertEquals(UserBean.OUTCOME_IMPORT_USER, userBean.addUser());<commit_msg>Fixed unit tests<commit_after>/*******************************************************************************
 *                                                                              
 *  Copyright FUJITSU LIMITED 2016                                             
 *                                                                                                                                 
 *  Creation Date: 23.04.2012                                                      
 *                                                                              
 *******************************************************************************/

package org.oscm.ui.beans;

import static org.junit.Assert.*;
import static org.mockito.Matchers.any;
import static org.mockito.Matchers.anyBoolean;
import static org.mockito.Matchers.anyListOf;
import static org.mockito.Matchers.anyString;
import static org.mockito.Matchers.eq;
import static org.mockito.Matchers.isNull;
import static org.mockito.Mockito.*;

import java.util.*;

import javax.faces.application.FacesMessage;
import javax.security.auth.login.LoginException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.junit.Before;
import org.junit.Test;
import org.mockito.invocation.InvocationOnMock;
import org.mockito.stubbing.Answer;
import org.oscm.internal.intf.ConfigurationService;
import org.oscm.internal.intf.IdentityService;
import org.oscm.internal.intf.MarketplaceService;
import org.oscm.internal.intf.TenantService;
import org.oscm.internal.types.enumtypes.AuthenticationMode;
import org.oscm.internal.types.enumtypes.ConfigurationKey;
import org.oscm.internal.types.enumtypes.UserAccountStatus;
import org.oscm.internal.types.enumtypes.UserRoleType;
import org.oscm.internal.types.exception.*;
import org.oscm.internal.usergroupmgmt.UserGroupService;
import org.oscm.internal.vo.VOConfigurationSetting;
import org.oscm.internal.vo.VOTenant;
import org.oscm.internal.vo.VOUser;
import org.oscm.internal.vo.VOUserDetails;
import org.oscm.types.constants.Configuration;
import org.oscm.ui.common.Constants;
import org.oscm.ui.common.ServiceAccess;
import org.oscm.ui.common.UiDelegate;
import org.oscm.ui.dialog.common.saml2.AuthenticationHandler;
import org.oscm.ui.dialog.state.TableState;
import org.oscm.ui.filter.AuthenticationSettings;
import org.oscm.ui.model.User;
import org.oscm.ui.model.UserRole;
import org.oscm.ui.stubs.FacesContextStub;
import org.oscm.ui.stubs.UIViewRootStub;

/**
 * Unit tests for testing the UserBean.
 * 
 * @author weiser
 */
public class UserBeanTest {

    private UserBean userBean;
    private User user;
    private VOUserDetails loggedInUser;
    private final String OUTCOME_CANCEL = "cancel";
    private final String OUTCOME_SHOW_REGISTRATION = "showRegistration";
    private final String ERROR_COMPLETE_REGISTRATION = "error.complete.registration";
    private final String BASE_URL = "http://localhost:8180/oscm-portal";
    private final String SUBSCRIPTION_ADD_PAGE = "/marketplace/subscriptions/creation/add.jsf";

    private HttpServletRequest requestMock;
    private HttpServletResponse responseMock;

    private List<FacesMessage> facesMessages = new ArrayList<FacesMessage>();
    private TableState ts;
    private IdentityService idServiceMock;
    private ConfigurationService cfgMock;
    private ServiceAccess serviceAccessMock;
    private List<UserRole> roles;
    private ApplicationBean appBean;
    private AuthenticationSettings authSettingsMock;
    private AuthenticationHandler authHandlerMock;
    private HttpSession sessionMock;
    private UserGroupService userGroupService = mock(UserGroupService.class);
    private MarketplaceService marketplaceService = mock(MarketplaceService.class);
    private static final String ISSUER = "CT-MG";
    private static final String RECIPIENT = "http://www.bes-portal.de";
    private static final String IDP = "http://www.idp.de/openam/SSORedirect/request";
    private static final String KEYSTORE_PATH = "/openam/keystore.jks";
    private static final String KEYSTORE_PASSWORD = "<PASSWORD>";
    private static final String OUTCOME_SAMLSP_REDIRECT = "redirectToIdp";
    static final String OUTCOME_ADD_USER = "addUser";

    private String errorCodeValue = null;
    private TenantService tenantService;

    @Before
    public void setup() throws Exception {
        tenantService = mock(TenantService.class);
        FacesContextStub contextStub = new FacesContextStub(Locale.ENGLISH) {
            @Override
            public void addMessage(String arg0, FacesMessage arg1) {
                facesMessages.add(arg1);
            }
        };
        UIViewRootStub vrStub = new UIViewRootStub() {
            @Override
            public Locale getLocale() {
                return Locale.ENGLISH;
            };
        };
        contextStub.setViewRoot(vrStub);

        userBean = spy(new UserBean());

        // Create a user
        user = new User(new VOUserDetails());
        user.setUserId("myUserId");

        // Mock all necessary methods of userBean
        requestMock = mock(HttpServletRequest.class);
        doReturn("/oscm-portal").when(requestMock).getContextPath();
        doReturn(new StringBuffer("https://something.de")).when(requestMock)
                .getRequestURL();
        mockErrorAttribute(requestMock);
        doReturn(requestMock).when(userBean).getRequest();

        doReturn(user).when(userBean).getUserFromSession();
        doReturn("myUserId2").when(userBean).getMyUserId();
        doNothing().when(userBean).resetUIInputChildren();

        userBean.setSessionBean(new SessionBean());
        userBean.ui = mock(UiDelegate.class);

        ts = mock(TableState.class);
        when(userBean.ui.findBean(TableState.BEAN_NAME)).thenReturn(ts);

        UserRole role = new UserRole();
        role.setSelected(true);
        role.setUserRoleType(UserRoleType.MARKETPLACE_OWNER);
        roles = Arrays.asList(role);
        userBean.setUserRolesForNewUser(roles);
        userBean.setToken(userBean.getToken());
        userBean.getNewUser();

        idServiceMock = mock(IdentityService.class);
        doReturn(idServiceMock).when(userBean).getIdService();

        appBean = mock(ApplicationBean.class);
        when(userBean.ui.findBean(eq(UserBean.APPLICATION_BEAN))).thenReturn(
                appBean);
        loggedInUser = mock(VOUserDetails.class);
        doReturn(loggedInUser).when(userBean).getLoggedInUser();

        authSettingsMock = mock(AuthenticationSettings.class);

        authHandlerMock = mock(AuthenticationHandler.class);
        doReturn(OUTCOME_SAMLSP_REDIRECT).when(authHandlerMock)
                .handleAuthentication(true, sessionMock);

        responseMock = mock(HttpServletResponse.class);
        doReturn(responseMock).when(userBean).getResponse();
        sessionMock = mock(HttpSession.class);
        doReturn(sessionMock).when(userBean).getSession();

        doReturn("").when(userBean).getLoginRedirect(
                any(HttpServletRequest.class), any(HttpSession.class),
                anyBoolean());

        doReturn(sessionMock).when(requestMock).getSession();
        serviceAccessMock = mock(ServiceAccess.class);
        doReturn(serviceAccessMock).when(sessionMock).getAttribute(
                eq(ServiceAccess.SESS_ATTR_SERVICE_ACCESS));
        doReturn(idServiceMock).when(serviceAccessMock).getService(
                eq(IdentityService.class));

        doReturn(userGroupService).when(userBean).getUserGroupService();

        when(userBean.ui.findBean(eq(UserBean.APPLICATION_BEAN))).thenReturn(
            appBean);

        doReturn(marketplaceService).when(userBean).getMarketplaceService();
        doReturn(true).when(marketplaceService).doesOrganizationHaveAccessMarketplace(anyString(), anyString());
        userBean.getSessionBean().setTenantID("1");
    }

    void mockErrorAttribute(HttpServletRequest requestMock) {
        doAnswer(new Answer<Void>() {
            @Override
            public Void answer(InvocationOnMock invocation) throws Throwable {
                errorCodeValue = (String) invocation.getArguments()[1];
                return null;
            }
        }).when(requestMock).setAttribute(eq(Constants.REQ_ATTR_ERROR_KEY),
                anyString());

        doAnswer(new Answer<String>() {
            @Override
            public String answer(InvocationOnMock invocation) throws Throwable {
                return errorCodeValue;
            }
        }).when(requestMock).getAttribute(eq(Constants.REQ_ATTR_ERROR_KEY));
    }

    @Test
    public void addUser() {
        assertEquals(UserBean.OUTCOME_ADD_USER, userBean.addUser());
    }

    @Test
    public void addUser_Ldap() {
        user.setRemoteLdapActive(true);

        assertEquals(UserBean.OUTCOME_IMPORT_USER, userBean.addUser());
{'fraction_non_alphanumeric': 0.11322763180010084, 'fraction_numerical': 0.0025211496442377724, 'mean_word_length': 3.040289723856949, 'pattern_counts': {'":': 0, '<': 15, '<?xml version=': 0, '>': 15, 'https://': 2, 'lorem ipsum': 0, 'www.': 4, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 30, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '4044210', 'n_tokens_mistral': 4813, 'n_tokens_neox': 4710, 'n_words': 810}