dhulipudi / webextest

test
0 stars 0 forks source link

test coverage #6

Open dhulipudi opened 7 months ago

dhulipudi commented 7 months ago

import java.io.IOException; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map;

import javax.jcr.Session; import javax.servlet.Servlet; import javax.servlet.ServletException;

import org.apache.jackrabbit.api.security.user.User; import org.apache.sling.api.SlingHttpServletRequest; import org.apache.sling.api.SlingHttpServletResponse; import org.apache.sling.api.resource.ResourceResolver; import org.apache.sling.api.servlets.HttpConstants; import org.apache.sling.api.servlets.SlingAllMethodsServlet; import org.osgi.framework.Constants; import org.osgi.service.component.annotations.Component; import org.osgi.service.component.annotations.Reference; import org.slf4j.Logger; import org.slf4j.LoggerFactory;

import com.wellsfargo.bc.core.services.user.BCUserConstants; import com.wellsfargo.bc.core.services.user.BCUserInfo; import com.wellsfargo.bc.core.services.user.BCUserManager; /**

@Component(service = Servlet.class, property = { Constants.SERVICE_DESCRIPTION + "=Brand Central User Create Service", "sling.servlet.methods=" + HttpConstants.METHOD_GET, "sling.servlet.paths=" + "/bin/content/usermanager", }) public class UserManagerServlet extends SlingAllMethodsServlet {

private static final long serialVersionUID = 1L;
private static final Logger LOG = LoggerFactory.getLogger(UserManagerServlet.class);

@Reference
BCUserManager bcUserManager;

@Override
protected void doPost(final SlingHttpServletRequest request,
        final SlingHttpServletResponse resp) throws ServletException, IOException {
    process(request, resp);
}

@Override
protected void doGet(final SlingHttpServletRequest request,
        final SlingHttpServletResponse resp) throws ServletException, IOException {
    process(request, resp);
}

private void process(final SlingHttpServletRequest request,
        final SlingHttpServletResponse resp) throws ServletException, IOException {
    try (ResourceResolver resourceResolver =  request.getResourceResolver()){
        final Session session = resourceResolver.adaptTo(Session.class);
        final String loggedInuser = session.getUserID();
        LOG.info("Logged in User:{}", loggedInuser );
        final User user = bcUserManager.getUser(resourceResolver,loggedInuser);
        resp.setContentType("application/json");
        Map<String, String[]> parameters = request.getParameterMap();

        final String action = request.getParameter(BCUserConstants.REQ_ACTION);
        final String userID = request.getParameter(BCUserConstants.REQ_USERID);
        BCUserInfo bcUserInfo = new BCUserInfo();
        LOG.info("Action:{} UserID:{}", action, userID );

        //Reset the password with random password
        if ( action != null && action.equalsIgnoreCase(BCUserConstants.REQ_ACTION_PASSWORD_RESET)) {
            bcUserInfo = bcUserManager.resetPassword(userID, null);
            LOG.info("User Password Reset:{}",bcUserInfo );
        }else if ( action != null && action.equalsIgnoreCase(BCUserConstants.REQ_ACTION_USER_CREATE_UPDATE)) {              
            //Handle User roles association and remove from the parameters 
            final String roles = request.getParameter(BCUserConstants.REQ_ROLES);
            List<String> rolesList = null;
            if(roles != null) {
                rolesList = roles != null ? Arrays.asList(roles.split(",", -1)) : null;
            }
            if (bcUserManager.isMember(resourceResolver, user, BCUserConstants.BCAdmin)) {
                LOG.info("Create User Starts!" );
                bcUserInfo = bcUserManager.createOrUpdateUser(parameters,rolesList,request.getResourceResolver());
            }
        }else if ( action != null && action.equalsIgnoreCase(BCUserConstants.REQ_ACTION_USER_FOLDER)) {
            LOG.info("User Folder Assocation!" );
            final String folder = request.getParameter(BCUserConstants.REQ_FOLDER);
            bcUserManager.addFolderToUser(userID, folder, resourceResolver);
        }else if ( action != null && action.equalsIgnoreCase(BCUserConstants.REQ_ACTION_PASSWORD_UPDATE)) {
            final String password = request.getParameter(BCUserConstants.REQ_PASSWORD);
            bcUserInfo = bcUserManager.resetPassword(userID, password);
            LOG.info("User Password Reset:{}",bcUserInfo );             
        }

        resp.getWriter().write("User successfully created with ID : " + bcUserInfo);

    }catch(Exception e) {
        LOG.error("Error in Create User:{}", e.getMessage());
    }

}

}

dhulipudi commented 7 months ago

import org.apache.sling.api.resource.ResourceResolver; import org.apache.sling.api.resource.ResourceResolverFactory; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.MockitoAnnotations;

import javax.jcr.Session; import javax.servlet.ServletException; import java.io.IOException;

import static org.mockito.Mockito.*;

public class UserManagerServletTest {

@InjectMocks
private UserManagerServlet userManagerServlet;

@Mock
private ResourceResolverFactory resourceResolverFactory;

@Mock
private ResourceResolver resourceResolver;

@Mock
private Session session;

@BeforeEach
public void setup() throws Exception {
    MockitoAnnotations.initMocks(this);

    when(resourceResolverFactory.getResourceResolver(anyMap())).thenReturn(resourceResolver);
    when(resourceResolver.adaptTo(Session.class)).thenReturn(session);
}

@Test
public void testDoGet() throws ServletException, IOException {
    // Your test code here
}

// More tests...

}

==========

import org.apache.sling.api.resource.ResourceResolver; import org.apache.sling.api.resource.ResourceResolverFactory; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.MockitoAnnotations;

import javax.jcr.Session; import javax.servlet.ServletException; import java.io.IOException;

import static org.mockito.Mockito.*;

public class UserManagerServletTest {

@InjectMocks
private UserManagerServlet userManagerServlet;

@Mock
private ResourceResolverFactory resourceResolverFactory;

@Mock
private ResourceResolver resourceResolver;

@Mock
private Session session;

@BeforeEach
public void setup() throws Exception {
    MockitoAnnotations.initMocks(this);

    when(resourceResolverFactory.getResourceResolver(anyMap())).thenReturn(resourceResolver);
    when(resourceResolver.adaptTo(Session.class)).thenReturn(session);
}

@Test
public void testDoGet() throws ServletException, IOException {
    // Your test code here
}

// More tests...

}

======

=================

import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.MockitoAnnotations; import org.springframework.mock.web.MockHttpServletRequest; import org.springframework.mock.web.MockHttpServletResponse;

import javax.servlet.ServletException; import java.io.IOException;

import static org.mockito.Mockito.*;

public class UserManagerServletTest {

@InjectMocks
private UserManagerServlet userManagerServlet;

@Mock
private BCUserManager bcUserManager;

private MockHttpServletRequest request;
private MockHttpServletResponse response;

@BeforeEach
public void setup() {
    MockitoAnnotations.initMocks(this);

    request = new MockHttpServletRequest();
    response = new MockHttpServletResponse();
}

@Test
public void testDoGet() throws ServletException, IOException {
    userManagerServlet.doGet(request, response);

    // Your verification code here
}

// More tests...

}

=========================

import org.apache.sling.api.resource.ResourceResolverFactory; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.MockitoAnnotations;

import javax.servlet.ServletException; import java.io.IOException;

import static org.mockito.Mockito.*;

public class UserManagerServletTest {

@InjectMocks
private UserManagerServlet userManagerServlet;

@Mock
private ResourceResolverFactory resourceResolverFactory;

@BeforeEach
public void setup() {
    MockitoAnnotations.initMocks(this);
}

@Test
public void testDoGet() throws ServletException, IOException {
    // Your test code here
}

// More tests...

}

=============

import org.apache.sling.api.resource.ResourceResolver; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.MockitoAnnotations;

import javax.jcr.Session; import javax.servlet.ServletException; import java.io.IOException;

import static org.mockito.Mockito.*;

public class UserManagerServletTest {

@InjectMocks
private UserManagerServlet userManagerServlet;

@Mock
private ResourceResolver resourceResolver;

@Mock
private Session session;

@BeforeEach
public void setup() {
    MockitoAnnotations.initMocks(this);

    when(resourceResolver.adaptTo(Session.class)).thenReturn(session);
}

@Test
public void testDoGet() throws ServletException, IOException {
    // Your test code here
}

// More tests...

}

========

===============

import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.MockitoAnnotations;

import javax.servlet.ServletException; import java.io.IOException;

import static org.mockito.Mockito.*;

public class UserManagerServletTest {

@InjectMocks
private UserManagerServlet userManagerServlet;

@Mock
private BCUserManager bcUserManager;

@BeforeEach
public void setup() {
    MockitoAnnotations.initMocks(this);
}

@Test
public void testDoGet() throws ServletException, IOException {
    // Your test code here
}

// More tests...

}

============

dhulipudi commented 7 months ago

package com.wellsfargo.bc.core.servlets;

import static org.junit.jupiter.api.Assertions.assertEquals; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when;

import java.io.IOException; import java.io.PrintWriter; import java.util.Arrays; import java.util.List; import java.util.Map;

import javax.jcr.Session; import javax.servlet.ServletException;

import io.wcm.testing.mock.aem.junit5.AemContext; import io.wcm.testing.mock.aem.junit5.AemContextExtension;

import org.apache.sling.api.resource.ResourceResolver; import org.apache.sling.testing.mock.sling.ResourceResolverType; import org.apache.sling.testing.mock.sling.servlet.MockSlingHttpServletRequest; import org.apache.sling.testing.mock.sling.servlet.MockSlingHttpServletResponse; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.Mock; import org.mockito.Mockito; import org.mockito.MockitoAnnotations; import org.slf4j.Logger; import org.slf4j.LoggerFactory;

import com.fasterxml.jackson.databind.Module.SetupContext; import com.wellsfargo.bc.core.services.user.BCUserConstants; import com.wellsfargo.bc.core.services.user.BCUserInfo; import com.wellsfargo.bc.core.services.user.BCUserManager;

@ExtendWith(AemContextExtension.class) public class UserManagerServletTest {

private final Logger LOG = LoggerFactory.getLogger(this.getClass());

// Create a mock object of BCUserManager @Mock private BCUserManager bcUserManager;

@Mock
private Session session;

@Mock
private ResourceResolver resourceResolver;

private AutoCloseable closeable;

private UserManagerServlet userManagerServlet = new UserManagerServlet();

private AemContext aemContext;
private MockSlingHttpServletRequest request;
private MockSlingHttpServletResponse response;
private Session mockSession;
@BeforeEach
void setup() {
     aemContext = new AemContext(ResourceResolverType.JCR_MOCK);
     request = new MockSlingHttpServletRequest(aemContext.resourceResolver(), aemContext.bundleContext());
     response = aemContext.response();

    closeable = MockitoAnnotations.openMocks(this);
    when(resourceResolver.adaptTo(Session.class)).thenReturn(session);
    when(session.getUserID()).thenReturn("testUser");

}

@Test
void doGet() throws ServletException, IOException {
     userManagerServlet.doGet(request, response);
}

@Test
void doPost(AemContext context) throws ServletException, IOException {
    // Similar to testDoGet() but for doPost()
    userManagerServlet.doPost(request, response);
}

@Test
void process() throws ServletException, IOException {
    userManagerServlet.bcUserManager = mock(BCUserManager.class);

    aemContext.registerService(BCUserManager.class, userManagerServlet.bcUserManager);
    request.setAttribute("userID", "testUser");
    request.setAttribute("password", "password");
    request.setAttribute("givenName", "password");
    request.setAttribute("familyName", "password");
    request.setAttribute("email", "test.user@wellsfargo.com");
    Map<String, String[]> parameters = request.getParameterMap();

    request.setAttribute("roles", "advanced-design-user-candidate");
    final String roles = request.getParameter(BCUserConstants.REQ_ROLES);
    List<String> rolesList = null;
    if(roles != null) {
        rolesList = roles != null ? Arrays.asList(roles.split(",", -1)) : null;
    }

    when(userManagerServlet.bcUserManager.isMember(aemContext.resourceResolver(), null, BCUserConstants.BCAdmin)).thenReturn(true);
    when(userManagerServlet.bcUserManager.createOrUpdateUser(parameters, rolesList, aemContext.resourceResolver())).thenReturn(new BCUserInfo());
}

@AfterEach
void closeMocks() throws Exception {
    closeable.close();
}

@Test
public void testGetUserID() {
    String loggedInUser = session.getUserID();
    assertEquals("testUser", loggedInUser);
}

}

dhulipudi commented 7 months ago

@Test void process_UserIsMember() throws ServletException, IOException { // Arrange userManagerServlet.bcUserManager = mock(BCUserManager.class); aemContext.registerService(BCUserManager.class, userManagerServlet.bcUserManager); request.setAttribute("userID", "testUser"); request.setAttribute("password", "password"); request.setAttribute("givenName", "password"); request.setAttribute("familyName", "password"); request.setAttribute("email", "test.user@wellsfargo.com"); request.setAttribute("roles", "advanced-design-user-candidate"); final String roles = request.getParameter(BCUserConstants.REQ_ROLES); List rolesList = roles != null ? Arrays.asList(roles.split(",", -1)) : null; Map<String, String[]> parameters = request.getParameterMap();

when(userManagerServlet.bcUserManager.isMember(aemContext.resourceResolver(), null, BCUserConstants.BCAdmin)).thenReturn(true);
when(userManagerServlet.bcUserManager.createOrUpdateUser(parameters, rolesList, aemContext.resourceResolver())).thenReturn(new BCUserInfo());

// Act
userManagerServlet.process(request, response);

// Assert
verify(userManagerServlet.bcUserManager).isMember(aemContext.resourceResolver(), null, BCUserConstants.BCAdmin);
verify(userManagerServlet.bcUserManager).createOrUpdateUser(parameters, rolesList, aemContext.resourceResolver());

}

@Test void process_UserIsNotMember() throws ServletException, IOException { // Arrange userManagerServlet.bcUserManager = mock(BCUserManager.class); aemContext.registerService(BCUserManager.class, userManagerServlet.bcUserManager); request.setAttribute("userID", "testUser"); request.setAttribute("password", "password"); request.setAttribute("givenName", "password"); request.setAttribute("familyName", "password"); request.setAttribute("email", "test.user@wellsfargo.com"); request.setAttribute("roles", "advanced-design-user-candidate"); final String roles = request.getParameter(BCUserConstants.REQ_ROLES); List rolesList = roles != null ? Arrays.asList(roles.split(",", -1)) : null; Map<String, String[]> parameters = request.getParameterMap();

when(userManagerServlet.bcUserManager.isMember(aemContext.resourceResolver(), null, BCUserConstants.BCAdmin)).thenReturn(false);
when(userManagerServlet.bcUserManager.createOrUpdateUser(parameters, rolesList, aemContext.resourceResolver())).thenReturn(new BCUserInfo());

// Act
userManagerServlet.process(request, response);

// Assert
verify(userManagerServlet.bcUserManager).isMember(aemContext.resourceResolver(), null, BCUserConstants.BCAdmin);
verify(userManagerServlet.bcUserManager, never()).createOrUpdateUser(parameters, rolesList, aemContext.resourceResolver());

}

dhulipudi commented 7 months ago

package com.wellsfargo.bc.core.servlets;

import com.wellsfargo.bc.core.services.user.BCUserConstants; import com.wellsfargo.bc.core.services.user.BCUserManager; import org.apache.jackrabbit.api.security.user.User; import org.apache.sling.api.SlingHttpServletRequest; import org.apache.sling.api.SlingHttpServletResponse; import org.apache.sling.api.resource.ResourceResolver; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.MockitoAnnotations; import static org.mockito.Mockito.times;

import javax.jcr.Session;

import java.util.HashMap;

import static org.mockito.Mockito.when;

import static org.mockito.Mockito.verify;

public class UserManagerServletTest {

@Mock
private SlingHttpServletRequest request;

@Mock
private SlingHttpServletResponse response;
@Mock
private ResourceResolver resourceResolver;
@Mock
private Session session;
@Mock
private User user;

@InjectMocks
private UserManagerServlet userManagerServlet;
@Mock
private BCUserManager bcUserManager;

@BeforeEach
public void setup() {
    MockitoAnnotations.openMocks(this);
}

@Test
public void testDoPost() throws Exception {
    userManagerServlet.doPost(request, response);
    verify(request).getResourceResolver();
}
@Test
public void testProcess() throws Exception {
    // Mock the necessary objects and methods
    when(request.getResourceResolver()).thenReturn(resourceResolver);
    when(resourceResolver.adaptTo(Session.class)).thenReturn(session);
    when(session.getUserID()).thenReturn("testUser");
    when(bcUserManager.getUser(resourceResolver, "testUser")).thenReturn(user);
    when(request.getParameterMap()).thenReturn(new HashMap<>());
    when(request.getParameter(BCUserConstants.REQ_ACTION)).thenReturn(BCUserConstants.REQ_ACTION_PASSWORD_RESET);
    when(request.getParameter(BCUserConstants.REQ_USERID)).thenReturn("testUser");

    // Call the method under test
    userManagerServlet.process(request, response);

    // Verify the interactions with the mocked objects
    verify(request, times(1)).getResourceResolver();
    verify(resourceResolver).adaptTo(Session.class);
    verify(session).getUserID();
    verify(bcUserManager).getUser(resourceResolver, "testUser");
    verify(request).getParameterMap();
    verify(request, times(1)).getParameter(BCUserConstants.REQ_ACTION);
    verify(request).getParameter(BCUserConstants.REQ_USERID);
}

}

dhulipudi commented 7 months ago

=====2 == package com.wellsfargo.bc.core.servlets;

import java.io.IOException; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map;

import javax.jcr.Session; import javax.servlet.Servlet; import javax.servlet.ServletException;

import org.apache.jackrabbit.api.security.user.User; import org.apache.sling.api.SlingHttpServletRequest; import org.apache.sling.api.SlingHttpServletResponse; import org.apache.sling.api.resource.ResourceResolver; import org.apache.sling.api.servlets.HttpConstants; import org.apache.sling.api.servlets.SlingAllMethodsServlet; import org.osgi.framework.Constants; import org.osgi.service.component.annotations.Component; import org.osgi.service.component.annotations.Reference; import org.slf4j.Logger; import org.slf4j.LoggerFactory;

import com.wellsfargo.bc.core.services.user.BCUserConstants; import com.wellsfargo.bc.core.services.user.BCUserInfo; import com.wellsfargo.bc.core.services.user.BCUserManager; /**

@Component(service = Servlet.class, property = { Constants.SERVICE_DESCRIPTION + "=Brand Central User Create Service", "sling.servlet.methods=" + HttpConstants.METHOD_GET, "sling.servlet.paths=" + "/bin/content/usermanager", }) public class UserManagerServlet extends SlingAllMethodsServlet {

private static final long serialVersionUID = 1L;
private static final Logger LOG = LoggerFactory.getLogger(UserManagerServlet.class);

@Reference
BCUserManager bcUserManager;

@Override
protected void doPost(final SlingHttpServletRequest request,
        final SlingHttpServletResponse resp) throws ServletException, IOException {
    process(request, resp);
}

@Override
protected void doGet(final SlingHttpServletRequest request,
        final SlingHttpServletResponse resp) throws ServletException, IOException {
    process(request, resp);
}

public void process(final SlingHttpServletRequest request,
                    final SlingHttpServletResponse resp) throws ServletException, IOException {
    try (ResourceResolver resourceResolver =  request.getResourceResolver()){
        final Session session = resourceResolver.adaptTo(Session.class);
        final String loggedInuser = session.getUserID();
        LOG.info("Logged in User:{}", loggedInuser );
        final User user = bcUserManager.getUser(resourceResolver,loggedInuser);
        resp.setContentType("application/json");
        Map<String, String[]> parameters = request.getParameterMap();

        final String action = request.getParameter(BCUserConstants.REQ_ACTION);
        final String userID = request.getParameter(BCUserConstants.REQ_USERID);
        BCUserInfo bcUserInfo = new BCUserInfo();
        LOG.info("Action:{} UserID:{}", action, userID );

        //Reset the password with random password
        if ( action != null && action.equalsIgnoreCase(BCUserConstants.REQ_ACTION_PASSWORD_RESET)) {
            bcUserInfo = bcUserManager.resetPassword(userID, null);
            LOG.info("User Password Reset:{}",bcUserInfo );
        }else if ( action != null && action.equalsIgnoreCase(BCUserConstants.REQ_ACTION_USER_CREATE_UPDATE)) {              
            //Handle User roles association and remove from the parameters 
            final String roles = request.getParameter(BCUserConstants.REQ_ROLES);
            List<String> rolesList = null;
            if(roles != null) {
                rolesList = roles != null ? Arrays.asList(roles.split(",", -1)) : null;
            }
            if (bcUserManager.isMember(resourceResolver, user, BCUserConstants.BCAdmin)) {
                LOG.info("Create User Starts!" );
                bcUserInfo = bcUserManager.createOrUpdateUser(parameters,rolesList,request.getResourceResolver());
            }
        }else if ( action != null && action.equalsIgnoreCase(BCUserConstants.REQ_ACTION_USER_FOLDER)) {
            LOG.info("User Folder Assocation!" );
            final String folder = request.getParameter(BCUserConstants.REQ_FOLDER);
            bcUserManager.addFolderToUser(userID, folder, resourceResolver);
        }else if ( action != null && action.equalsIgnoreCase(BCUserConstants.REQ_ACTION_PASSWORD_UPDATE)) {
            final String password = request.getParameter(BCUserConstants.REQ_PASSWORD);
            bcUserInfo = bcUserManager.resetPassword(userID, password);
            LOG.info("User Password Reset:{}",bcUserInfo );             
        }

        resp.getWriter().write("User successfully created with ID : " + bcUserInfo);

    }catch(Exception e) {
        LOG.error("Error in Create User:{}", e.getMessage());
    }

}

}

dhulipudi commented 7 months ago

===ppp

package com.wellsfargo.bc.core.servlets;

import com.wellsfargo.bc.core.services.user.BCUserConstants; import com.wellsfargo.bc.core.services.user.BCUserManager; import org.apache.jackrabbit.api.security.user.User; import org.apache.sling.api.SlingHttpServletRequest; import org.apache.sling.api.SlingHttpServletResponse; import org.apache.sling.api.resource.ResourceResolver; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.MockitoAnnotations; import com.wellsfargo.bc.core.services.user.BCUserInfo;

import static org.mockito.ArgumentMatchers.*; import static org.mockito.Mockito.times;

import javax.jcr.Session;

import java.util.HashMap;

import static org.mockito.Mockito.when;

import static org.mockito.Mockito.verify;

public class UserManagerServletTest {

@Mock
private SlingHttpServletRequest request;

@Mock
private SlingHttpServletResponse response;
@Mock
private ResourceResolver resourceResolver;
@Mock
private Session session;
@Mock
private User user;

@InjectMocks
private UserManagerServlet userManagerServlet;
@Mock
private BCUserManager bcUserManager;

@BeforeEach
public void setup() {
    MockitoAnnotations.openMocks(this);
}

@Test
public void testDoPost() throws Exception {
    userManagerServlet.doPost(request, response);
    verify(request).getResourceResolver();
}
@Test
public void testProcess() throws Exception {
    // Mock the necessary objects and methods
    when(request.getResourceResolver()).thenReturn(resourceResolver);
    when(resourceResolver.adaptTo(Session.class)).thenReturn(session);
    when(session.getUserID()).thenReturn("testUser");
    when(bcUserManager.getUser(resourceResolver, "testUser")).thenReturn(user);
    when(request.getParameterMap()).thenReturn(new HashMap<>());
    when(request.getParameter(BCUserConstants.REQ_ACTION)).thenReturn(BCUserConstants.REQ_ACTION_PASSWORD_RESET);
    when(request.getParameter(BCUserConstants.REQ_USERID)).thenReturn("testUser");

    // Call the method under test
    userManagerServlet.process(request, response);

    // Verify the interactions with the mocked objects
    verify(request, times(1)).getResourceResolver();
    verify(resourceResolver).adaptTo(Session.class);
    verify(session).getUserID();
    verify(bcUserManager).getUser(resourceResolver, "testUser");
    verify(request).getParameterMap();
    verify(request, times(1)).getParameter(BCUserConstants.REQ_ACTION);
    verify(request).getParameter(BCUserConstants.REQ_USERID);
}
@Test
public void testProcessWithNullAction() throws Exception {
    // Set up the mocks
    when(request.getParameter(BCUserConstants.REQ_ACTION)).thenReturn(null);

    // Call the method under test
    userManagerServlet.process(request, response);

    // Verify the interactions with the mocked objects
    verify(request, times(0)).getParameter(BCUserConstants.REQ_ACTION);
}

@Test
public void testProcessWithUnknownAction() throws Exception {
    // Set up the mocks
    when(request.getParameter(BCUserConstants.REQ_ACTION)).thenReturn("unknownAction");

    // Call the method under test
    userManagerServlet.process(request, response);

    // Verify the interactions with the mocked objects
    verify(request, times(0)).getParameter(BCUserConstants.REQ_ACTION);
}

@Test
public void testProcessWithPasswordResetAction() throws Exception {
    // Set up the mocks
    when(request.getParameter(BCUserConstants.REQ_ACTION)).thenReturn(BCUserConstants.REQ_ACTION_PASSWORD_RESET);
    when(request.getParameter(BCUserConstants.REQ_USERID)).thenReturn("testUser");
    when(bcUserManager.resetPassword(anyString(), any())).thenReturn(new BCUserInfo());

    // Call the method under test
    userManagerServlet.process(request, response);

    // Verify the interactions with the mocked objects
    verify(request, times(0)).getParameter(BCUserConstants.REQ_ACTION);
    verify(request, times(0)).getParameter(BCUserConstants.REQ_USERID);
    verify(bcUserManager, times(0)).resetPassword(anyString(), any());
}

@Test
public void testProcessWithUserCreateUpdateAction() throws Exception {
    // Set up the mocks
    when(request.getParameter(BCUserConstants.REQ_ACTION)).thenReturn(BCUserConstants.REQ_ACTION_USER_CREATE_UPDATE);
    when(request.getParameter(BCUserConstants.REQ_ROLES)).thenReturn("role1,role2");
    when(bcUserManager.isMember(any(), any(), anyString())).thenReturn(true);
    when(bcUserManager.createOrUpdateUser(any(), anyList(), any())).thenReturn(new BCUserInfo());

    // Call the method under test
    userManagerServlet.process(request, response);

    // Verify the interactions with the mocked objects
    verify(request, times(0)).getParameter(BCUserConstants.REQ_ACTION);
    verify(request, times(0)).getParameter(BCUserConstants.REQ_ROLES);
    verify(bcUserManager, times(0)).isMember(any(), any(), anyString());
    verify(bcUserManager, times(0)).createOrUpdateUser(any(), anyList(), any());
}

@Test
public void testProcessWithUserFolderAction() throws Exception {
    // Set up the mocks
    when(request.getParameter(BCUserConstants.REQ_ACTION)).thenReturn(BCUserConstants.REQ_ACTION_USER_FOLDER);
    when(request.getParameter(BCUserConstants.REQ_USERID)).thenReturn("testUser");
    when(request.getParameter(BCUserConstants.REQ_FOLDER)).thenReturn("/content/dam/we-retail/en/stores");

    // Call the method under test
    userManagerServlet.process(request, response);

    // Verify the interactions with the mocked objects
    verify(request, times(0)).getParameter(BCUserConstants.REQ_ACTION);
    verify(request, times(0)).getParameter(BCUserConstants.REQ_USERID);
    verify(request, times(0)).getParameter(BCUserConstants.REQ_FOLDER);
    verify(bcUserManager, times(0)).addFolderToUser(anyString(), anyString(), any());
}

@Test
public void testProcessWithPasswordUpdateAction() throws Exception {
    // Set up the mocks
    when(request.getParameter(BCUserConstants.REQ_ACTION)).thenReturn(BCUserConstants.REQ_ACTION_PASSWORD_UPDATE);
    when(request.getParameter(BCUserConstants.REQ_USERID)).thenReturn("testUser");
    when(request.getParameter(BCUserConstants.REQ_PASSWORD)).thenReturn("newPassword");
    when(bcUserManager.resetPassword(anyString(), any())).thenReturn(new BCUserInfo());

    // Call the method under test
    userManagerServlet.process(request, response);

    // Verify the interactions with the mocked objects
    verify(request, times(0)).getParameter(BCUserConstants.REQ_ACTION);
    verify(request, times(0)).getParameter(BCUserConstants.REQ_USERID);
    verify(request, times(0)).getParameter(BCUserConstants.REQ_PASSWORD);
    verify(bcUserManager, times(0)).resetPassword(anyString(), any());
}

}

dhulipudi commented 7 months ago

package com.wellsfargo.bc.core.servlets;

import static org.junit.jupiter.api.Assertions.assertEquals; import static org.mockito.Mockito.*;

import java.io.PrintWriter; import java.io.StringWriter;

import javax.servlet.ServletException;

import org.apache.sling.api.SlingHttpServletRequest; import org.apache.sling.api.SlingHttpServletResponse; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.MockitoAnnotations;

import com.wellsfargo.bc.core.services.lms.LMSService;

public class LMSUserStatusServletTest {

@InjectMocks
private LMSUserStatusServlet servlet;

@Mock
private LMSService lmsService;

@Mock
private SlingHttpServletRequest request;

@Mock
private SlingHttpServletResponse response;

@BeforeEach
public void setup() {
    MockitoAnnotations.openMocks(this);
}

@Test
public void testProcess() throws Exception {
    when(request.getParameter("userID")).thenReturn("testUser");
    when(request.getParameter("status")).thenReturn("certified");
    when(lmsService.updateLMSUserStatus("testUser", "certified")).thenReturn(true);

    StringWriter stringWriter = new StringWriter();
    PrintWriter writer = new PrintWriter(stringWriter);
    when(response.getWriter()).thenReturn(writer);

    servlet.doGet(request, response);

    String result = stringWriter.getBuffer().toString().trim();
    assertEquals("User status successfully updated for the ID : testUser", result);
}

}

dhulipudi commented 7 months ago

package com.wellsfargo.bc.core.services.lms.impl;

import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.mockito.Mockito.*;

import javax.jcr.PropertyType; import javax.jcr.Session; import javax.jcr.Value; import javax.jcr.ValueFactory;

import org.apache.commons.lang.StringUtils; import org.apache.sling.api.resource.ResourceResolver; import org.apache.sling.api.resource.ResourceResolverFactory; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.MockitoAnnotations;

import com.wellsfargo.bc.core.services.lms.LMSConfiguration; import com.wellsfargo.bc.core.services.user.BCUserConstants; import com.wellsfargo.bc.core.services.user.BCUserInfo; import com.wellsfargo.bc.core.services.user.BCUserManager; import org.apache.jackrabbit.api.security.user.UserManager; import org.apache.jackrabbit.api.security.user.Authorizable; import javax.jcr.RepositoryException; import javax.security.auth.login.LoginException;

public class LMSServiceImplTest {

@InjectMocks
private LMSServiceImpl lmsService;

@Mock
private BCUserManager bcUserManager;

@Mock
private ResourceResolverFactory resourceResolverFactory;

@Mock
private ResourceResolver resourceResolver;

@Mock
private Session session;

@Mock
private ValueFactory valueFactory;

@Mock
private Value value;

@Mock
private LMSConfiguration lmsConfiguration;

@BeforeEach
public void setup() {
    MockitoAnnotations.openMocks(this);
}

@Test
public void testCheckLMSUserCertificateStatus() throws Exception {
    BCUserInfo userInfo = new BCUserInfo();
    userInfo.setStatus(BCUserConstants.CERTIFIED);
    when(bcUserManager.getUser("testUser")).thenReturn(userInfo);

    boolean result = lmsService.checkLMSUserCertificateStatus("testUser");

    assertEquals(true, result);
}

@Test
public void testUpdateLMSUserStatus() throws Exception {
    when(resourceResolverFactory.getServiceResourceResolver(anyMap())).thenReturn(resourceResolver);
    when(resourceResolver.adaptTo(Session.class)).thenReturn(session);
    when(session.getValueFactory()).thenReturn(valueFactory);
    when(valueFactory.createValue(anyString(), eq(PropertyType.STRING))).thenReturn(value);

    UserManager userManager = mock(UserManager.class);
    when(resourceResolver.adaptTo(UserManager.class)).thenReturn(userManager);

    Authorizable authorizable = mock(Authorizable.class);
    when(userManager.getAuthorizable(anyString())).thenReturn(authorizable);

    boolean result = lmsService.updateLMSUserStatus("testUser", BCUserConstants.CERTIFIED);

    assertEquals(false, result);
}

@Test
public void testCheckLMSUserCertificateStatusWithNullUserID() throws Exception {
    boolean result = lmsService.checkLMSUserCertificateStatus(null);
    assertEquals(false, result);
}

@Test
public void testCheckLMSUserCertificateStatusWithNonNullUserID() throws Exception {
    when(bcUserManager.getUser(anyString())).thenReturn(new BCUserInfo());
    boolean result = lmsService.checkLMSUserCertificateStatus("testUser");
    assertEquals(false, result);
}

@Test
public void testGetLMSUrlWithNullUserID() throws Exception {
    String result = lmsService.getLMSUrl(null);
    assertEquals(StringUtils.EMPTY, result);
}

@Test
public void testGetLMSUrlWithNonNullUserID() throws Exception {
    String result = lmsService.getLMSUrl("testUser");
    assertNotNull(result);
}

@Test
public void testUpdateLMSUserStatusWithNullAuthorizable() throws Exception {
    UserManager userManager = mock(UserManager.class);
    when(userManager.getAuthorizable(anyString())).thenReturn(null);
    boolean result = lmsService.updateLMSUserStatus("testUser", BCUserConstants.CERTIFIED);
    assertEquals(false, result);
}

@Test
public void testUpdateLMSUserStatusWithExceptionFromGetAuthorizable() throws Exception {
    UserManager userManager = mock(UserManager.class);
    when(userManager.getAuthorizable(anyString())).thenThrow(new RepositoryException());
    boolean result = lmsService.updateLMSUserStatus("testUser", BCUserConstants.CERTIFIED);
    assertEquals(false, result);
}

@Test
public void testUpdateLMSUserStatusWithExceptionFromGetServiceResourceResolver() throws Exception {
    when(resourceResolverFactory.getServiceResourceResolver(anyMap())).thenThrow(new LoginException());
    boolean result = lmsService.updateLMSUserStatus("testUser", BCUserConstants.CERTIFIED);
    assertEquals(false, result);
}

}

dhulipudi commented 7 months ago

package com.wellsfargo.bc.core.services.lms.impl;

import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Map;

import javax.jcr.PropertyType; import javax.jcr.RepositoryException; import javax.jcr.Session; import javax.jcr.Value; import javax.jcr.ValueFactory;

import org.apache.commons.lang3.StringUtils; import org.apache.http.Consts; import org.apache.http.HttpEntity; import org.apache.http.NameValuePair; import org.apache.http.client.entity.UrlEncodedFormEntity; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpPost; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; import org.apache.http.message.BasicNameValuePair; import org.apache.http.util.EntityUtils; import org.apache.jackrabbit.api.security.user.Authorizable; import org.apache.jackrabbit.api.security.user.User; import org.apache.jackrabbit.api.security.user.UserManager; import org.apache.sling.api.resource.LoginException; import org.apache.sling.api.resource.ResourceResolver; import org.apache.sling.api.resource.ResourceResolverFactory; import org.osgi.service.component.annotations.Activate; import org.osgi.service.component.annotations.Component; import org.osgi.service.component.annotations.ConfigurationPolicy; import org.osgi.service.component.annotations.Modified; import org.osgi.service.component.annotations.Reference; import org.osgi.service.metatype.annotations.Designate; import org.slf4j.Logger; import org.slf4j.LoggerFactory;

import com.wellsfargo.bc.core.services.lms.LMSConfiguration; import com.wellsfargo.bc.core.services.lms.LMSService; import com.wellsfargo.bc.core.services.user.BCUserConstants; import com.wellsfargo.bc.core.services.user.BCUserInfo; import com.wellsfargo.bc.core.services.user.BCUserManager;

/**

}

dhulipudi commented 7 months ago

package com.wellsfargo.bc.core.services.auth;

import static org.junit.jupiter.api.Assertions.; import static org.mockito.Mockito.;

import javax.servlet.http.HttpServletRequest;

import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.MockitoAnnotations;

import com.wellsfargo.bc.core.services.lms.LMSService; import com.wellsfargo.bc.core.services.user.BCUserInfo; import com.wellsfargo.bc.core.services.user.BCUserManager;

public class BrandCentralLoginCallbackTest {

@InjectMocks
private BrandCentralLoginCallback callback;

@Mock
private LMSService lmsService;

@Mock
private BCUserManager bcUserManager;

@Mock
private HttpServletRequest request;

@BeforeEach
public void setup() {
    MockitoAnnotations.openMocks(this);
}

@Test
public void testCanHandle() {
    assertTrue(callback.canHandle(request));
}

@Test
public void testOnLoginSuccess() {
    when(request.getParameter("j_username")).thenReturn("testUser");
    when(request.getParameter("SPID")).thenReturn("brandcentral");
    BCUserInfo userInfo = mock(BCUserInfo.class);
    when(bcUserManager.getUser("testUser")).thenReturn(userInfo);
    when(userInfo.getForceResetpassword()).thenReturn("false");
    when(userInfo.isInternal()).thenReturn(false);
    when(userInfo.getStatus()).thenReturn("NOT_CERTIFIED");
    when(lmsService.getLMSUrl("testUser")).thenReturn("testUrl");

    callback.onLoginSuccess(request);

    verify(request).setAttribute("resource", "testUrl");
}

}