From 68533808c5a57726c35154cad402ee7cb5fb4c19 Mon Sep 17 00:00:00 2001 From: megala21 Date: Thu, 19 Oct 2017 15:43:41 +0530 Subject: [PATCH 1/5] Adding test cases for UserManagementServicee --- .../impl/UserManagementServiceImpl.java | 55 +-- .../impl/UserManagementServiceImplTest.java | 362 ++++++++++++++++++ .../src/test/resources/testng.xml | 1 + .../DeviceManagementProviderServiceImpl.java | 101 ++--- 4 files changed, 421 insertions(+), 98 deletions(-) create mode 100644 components/device-mgt/org.wso2.carbon.device.mgt.api/src/test/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/UserManagementServiceImplTest.java diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/UserManagementServiceImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/UserManagementServiceImpl.java index cafed108565..165c1da85fb 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/UserManagementServiceImpl.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/UserManagementServiceImpl.java @@ -22,21 +22,13 @@ import org.apache.commons.lang.StringUtils; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.eclipse.wst.common.uriresolver.internal.util.URIEncoder; -import org.wso2.carbon.context.CarbonContext; import org.wso2.carbon.device.mgt.common.DeviceManagementException; import org.wso2.carbon.device.mgt.common.EnrolmentInfo; import org.wso2.carbon.device.mgt.common.configuration.mgt.ConfigurationManagementException; import org.wso2.carbon.device.mgt.core.DeviceManagementConstants; import org.wso2.carbon.device.mgt.core.service.DeviceManagementProviderService; import org.wso2.carbon.device.mgt.core.service.EmailMetaInfo; -import org.wso2.carbon.device.mgt.jaxrs.beans.BasicUserInfo; -import org.wso2.carbon.device.mgt.jaxrs.beans.BasicUserInfoList; -import org.wso2.carbon.device.mgt.jaxrs.beans.BasicUserInfoWrapper; -import org.wso2.carbon.device.mgt.jaxrs.beans.EnrollmentInvitation; -import org.wso2.carbon.device.mgt.jaxrs.beans.ErrorResponse; -import org.wso2.carbon.device.mgt.jaxrs.beans.OldPasswordResetWrapper; -import org.wso2.carbon.device.mgt.jaxrs.beans.RoleList; -import org.wso2.carbon.device.mgt.jaxrs.beans.UserInfo; +import org.wso2.carbon.device.mgt.jaxrs.beans.*; import org.wso2.carbon.device.mgt.jaxrs.service.api.UserManagementService; import org.wso2.carbon.device.mgt.jaxrs.service.impl.util.RequestValidationUtil; import org.wso2.carbon.device.mgt.jaxrs.util.Constants; @@ -50,16 +42,7 @@ import org.wso2.carbon.user.api.UserStoreException; import org.wso2.carbon.user.api.UserStoreManager; import org.wso2.carbon.utils.CarbonUtils; -import javax.ws.rs.Consumes; -import javax.ws.rs.DELETE; -import javax.ws.rs.GET; -import javax.ws.rs.HeaderParam; -import javax.ws.rs.POST; -import javax.ws.rs.PUT; -import javax.ws.rs.Path; -import javax.ws.rs.PathParam; -import javax.ws.rs.Produces; -import javax.ws.rs.QueryParam; +import javax.ws.rs.*; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import java.io.File; @@ -67,14 +50,7 @@ import java.io.UnsupportedEncodingException; import java.net.URI; import java.net.URISyntaxException; import java.security.SecureRandom; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Properties; -import java.util.Set; +import java.util.*; @Path("/users") @Produces(MediaType.APPLICATION_JSON) @@ -86,7 +62,6 @@ public class UserManagementServiceImpl implements UserManagementService { private static final Log log = LogFactory.getLog(UserManagementServiceImpl.class); private static final String DEFAULT_DEVICE_USER = "Internal/devicemgt-user"; - private static final String DEFAULT_DEVICE_ADMIN = "Internal/devicemgt-admin"; // Permissions that are given for a normal device user. private static final Permission[] PERMISSIONS_FOR_DEVICE_USER = { @@ -253,7 +228,11 @@ public class UserManagementServiceImpl implements UserManagementService { log.debug("User credential of username: " + username + " has been changed"); } List currentRoles = this.getFilteredRoles(userStoreManager, username); - List newRoles = Arrays.asList(userInfo.getRoles()); + + List newRoles = new ArrayList<>(); + if (userInfo.getRoles() != null) { + newRoles = Arrays.asList(userInfo.getRoles()); + } List rolesToAdd = new ArrayList<>(newRoles); List rolesToDelete = new ArrayList<>(); @@ -288,7 +267,7 @@ public class UserManagementServiceImpl implements UserManagementService { private List getFilteredRoles(UserStoreManager userStoreManager, String username) throws UserStoreException { - String[] roleListOfUser = new String[0]; + String[] roleListOfUser; roleListOfUser = userStoreManager.getRoleListOfUser(username); List filteredRoles = new ArrayList<>(); for (String role : roleListOfUser) { @@ -429,8 +408,8 @@ public class UserManagementServiceImpl implements UserManagementService { public Response getUserCount() { try { UserStoreCountRetriever userStoreCountRetrieverService = DeviceMgtAPIUtils.getUserStoreCountRetrieverService(); - RealmConfiguration secondaryRealmConfiguration = CarbonContext.getThreadLocalCarbonContext().getUserRealm(). - getRealmConfiguration().getSecondaryRealmConfig(); + RealmConfiguration secondaryRealmConfiguration = DeviceMgtAPIUtils.getUserRealm().getRealmConfiguration() + .getSecondaryRealmConfig(); if (secondaryRealmConfiguration != null) { if (!secondaryRealmConfiguration.isPrimary() && !Constants.JDBC_USERSTOREMANAGER. @@ -488,12 +467,10 @@ public class UserManagementServiceImpl implements UserManagementService { public Response isUserExists(@QueryParam("username") String userName) { try { UserStoreManager userStoreManager = DeviceMgtAPIUtils.getUserStoreManager(); - boolean userExists = false; if (userStoreManager.isExistingUser(userName)) { - userExists = true; - return Response.status(Response.Status.OK).entity(userExists).build(); + return Response.status(Response.Status.OK).entity(true).build(); } else { - return Response.status(Response.Status.OK).entity(userExists).build(); + return Response.status(Response.Status.OK).entity(false).build(); } } catch (UserStoreException e) { String msg = "Error while retrieving the user."; @@ -605,9 +582,7 @@ public class UserManagementServiceImpl implements UserManagementService { DeviceManagementProviderService dms = DeviceMgtAPIUtils.getDeviceManagementService(); try { Set recipients = new HashSet<>(); - for (String recipient : enrollmentInvitation.getRecipients()) { - recipients.add(recipient); - } + recipients.addAll(enrollmentInvitation.getRecipients()); Properties props = new Properties(); String username = DeviceMgtAPIUtils.getAuthenticatedUser(); String firstName = getClaimValue(username, Constants.USER_CLAIM_FIRST_NAME); @@ -621,6 +596,8 @@ public class UserManagementServiceImpl implements UserManagementService { } catch (DeviceManagementException e) { String msg = "Error occurred while inviting user to enrol their device"; log.error(msg, e); + return Response.serverError().entity( + new ErrorResponse.ErrorResponseBuilder().setMessage(msg).build()).build(); } catch (UserStoreException e) { String msg = "Error occurred while getting claim values to invite user"; log.error(msg, e); diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/test/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/UserManagementServiceImplTest.java b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/test/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/UserManagementServiceImplTest.java new file mode 100644 index 00000000000..9f9712443ac --- /dev/null +++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/test/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/UserManagementServiceImplTest.java @@ -0,0 +1,362 @@ +package org.wso2.carbon.device.mgt.jaxrs.service.impl; + +import org.mockito.Mockito; +import org.mockito.invocation.InvocationOnMock; +import org.mockito.stubbing.Answer; +import org.powermock.api.mockito.PowerMockito; +import org.powermock.core.classloader.annotations.PowerMockIgnore; +import org.powermock.core.classloader.annotations.PrepareForTest; +import org.powermock.core.classloader.annotations.SuppressStaticInitializationFor; +import org.testng.Assert; +import org.testng.IObjectFactory; +import org.testng.annotations.BeforeClass; +import org.testng.annotations.ObjectFactory; +import org.testng.annotations.Test; +import org.wso2.carbon.context.CarbonContext; +import org.wso2.carbon.device.mgt.common.DeviceManagementException; +import org.wso2.carbon.device.mgt.common.configuration.mgt.ConfigurationManagementException; +import org.wso2.carbon.device.mgt.core.service.DeviceManagementProviderService; +import org.wso2.carbon.device.mgt.core.service.DeviceManagementProviderServiceImpl; +import org.wso2.carbon.device.mgt.jaxrs.beans.BasicUserInfo; +import org.wso2.carbon.device.mgt.jaxrs.beans.EnrollmentInvitation; +import org.wso2.carbon.device.mgt.jaxrs.beans.UserInfo; +import org.wso2.carbon.device.mgt.jaxrs.service.api.UserManagementService; +import org.wso2.carbon.device.mgt.jaxrs.util.Constants; +import org.wso2.carbon.device.mgt.jaxrs.util.DeviceMgtAPIUtils; +import org.wso2.carbon.user.api.RealmConfiguration; +import org.wso2.carbon.user.api.UserRealm; +import org.wso2.carbon.user.api.UserStoreException; +import org.wso2.carbon.user.api.UserStoreManager; +import org.wso2.carbon.utils.multitenancy.MultitenantUtils; + +import javax.ws.rs.core.Response; +import java.net.URL; +import java.util.ArrayList; +import java.util.List; + +import static org.mockito.MockitoAnnotations.initMocks; + +@PowerMockIgnore("javax.ws.rs.*") +@SuppressStaticInitializationFor({"org.wso2.carbon.device.mgt.jaxrs.util.DeviceMgtAPIUtils", + "org.wso2.carbon.context.CarbonContext"}) +@PrepareForTest({DeviceMgtAPIUtils.class, MultitenantUtils.class, CarbonContext.class}) +public class UserManagementServiceImplTest { + private UserStoreManager userStoreManager; + private UserManagementService userManagementService; + private DeviceManagementProviderService deviceManagementProviderService; + private static final String DEFAULT_DEVICE_USER = "Internal/devicemgt-user"; + private UserRealm userRealm; + private EnrollmentInvitation enrollmentInvitation; + private List userList; + private static final String TEST_USERNAME = "test"; + private static final String TEST2_USERNAME = "test2"; + private static final String TEST3_USERNAME = "test3"; + + @ObjectFactory + public IObjectFactory getObjectFactory() { + return new org.powermock.modules.testng.PowerMockObjectFactory(); + } + + @BeforeClass + public void setup() throws UserStoreException { + initMocks(this); + userManagementService = new UserManagementServiceImpl(); + userStoreManager = Mockito.mock(UserStoreManager.class, Mockito.RETURNS_MOCKS); + deviceManagementProviderService = Mockito + .mock(DeviceManagementProviderServiceImpl.class, Mockito.CALLS_REAL_METHODS); + userRealm = Mockito.mock(UserRealm.class); + RealmConfiguration realmConfiguration = Mockito.mock(RealmConfiguration.class); + Mockito.doReturn(null).when(realmConfiguration).getSecondaryRealmConfig(); + Mockito.doReturn(realmConfiguration).when(userRealm).getRealmConfiguration(); + enrollmentInvitation = new EnrollmentInvitation(); + List recipients = new ArrayList<>(); + recipients.add(TEST_USERNAME); + enrollmentInvitation.setDeviceType("android"); + enrollmentInvitation.setRecipients(recipients); + userList = new ArrayList<>(); + userList.add(TEST_USERNAME); + } + + @Test(description = "This method tests the addUser method of UserManagementService") + public void testAddUser() throws UserStoreException, ConfigurationManagementException, DeviceManagementException { + PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getUserStoreManager")) + .toReturn(this.userStoreManager); + PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getDeviceManagementService")) + .toReturn(this.deviceManagementProviderService); + Mockito.doReturn(true).when(userStoreManager).isExistingUser("admin"); + Mockito.doAnswer(new Answer() { + private int count = 0; + + public Object answer(InvocationOnMock invocation) { + if (count == 0) { + count++; + return false; + } else { + return true; + } + } + }).when(userStoreManager).isExistingUser(TEST_USERNAME); + + Mockito.doReturn("test@test.com").when(userStoreManager) + .getUserClaimValue(TEST_USERNAME, Constants.USER_CLAIM_EMAIL_ADDRESS, null); + Mockito.doReturn(TEST_USERNAME).when(userStoreManager) + .getUserClaimValue(TEST_USERNAME, Constants.USER_CLAIM_FIRST_NAME, null); + Mockito.doReturn(TEST_USERNAME).when(userStoreManager) + .getUserClaimValue(TEST_USERNAME, Constants.USER_CLAIM_LAST_NAME, null); + Mockito.doNothing().when(userStoreManager) + .addUser(Mockito.any(), Mockito.any(), Mockito.any(), Mockito.any(), Mockito.any()); + UserInfo userInfo = new UserInfo(); + userInfo.setUsername("admin"); + Response response = userManagementService.addUser(userInfo); + Assert.assertEquals(response.getStatus(), Response.Status.CONFLICT.getStatusCode(), + "Same user can be added " + "twice"); + userInfo = getUserInfo(); + Mockito.doReturn(true).when(userStoreManager).isExistingRole(DEFAULT_DEVICE_USER); + Mockito.doNothing().when(deviceManagementProviderService).sendRegistrationEmail(Mockito.any()); + response = userManagementService.addUser(userInfo); + Assert.assertEquals(response.getStatus(), Response.Status.CREATED.getStatusCode(), "User addition failed"); + } + + @Test(description = "This method tests the getUser method of UserManagementService", dependsOnMethods = + "testAddUser") + public void testGetUser() throws UserStoreException { + PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getUserStoreManager")) + .toReturn(this.userStoreManager); + Response response = userManagementService.getUser(TEST_USERNAME, null, null); + Assert.assertEquals(response.getStatus(), Response.Status.OK.getStatusCode(), "User retrieval failed"); + BasicUserInfo userInfo = (BasicUserInfo) response.getEntity(); + Assert.assertEquals(userInfo.getFirstname(), TEST_USERNAME, + "Retrieved user object is different from the original one " + "saved"); + + Mockito.doReturn(false).when(userStoreManager).isExistingUser(TEST2_USERNAME); + response = userManagementService.getUser(TEST2_USERNAME, null, null); + Assert.assertEquals(response.getStatus(), Response.Status.NOT_FOUND.getStatusCode(), + "Non-existing user was retrieved successfully"); + } + + @Test(description = "This method tests the updateUser method of UserManagementService", dependsOnMethods = + {"testGetUser"}) + public void testUpdateUser() throws UserStoreException { + PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getUserStoreManager")) + .toReturn(this.userStoreManager); + Response response = userManagementService.updateUser(TEST2_USERNAME, null, null); + Assert.assertEquals(response.getStatus(), Response.Status.NOT_FOUND.getStatusCode(), + "Non-existing user was successfully updated"); + String[] roles = { "Internal/everyone", DEFAULT_DEVICE_USER }; + Mockito.doReturn(roles).when(userStoreManager).getRoleListOfUser(TEST_USERNAME); + Mockito.doNothing().when(userStoreManager).updateRoleListOfUser(Mockito.any(), Mockito.any(), Mockito.any()); + Mockito.doNothing().when(userStoreManager).setUserClaimValues(Mockito.any(), Mockito.any(), Mockito.any()); + response = userManagementService.updateUser(TEST_USERNAME, null, getUserInfo()); + Assert.assertEquals(response.getStatus(), Response.Status.OK.getStatusCode(), "Updating the user info failed"); + } + + + @Test(description = "This method tests the getRolesOfUser method of UserManagementService", dependsOnMethods = + {"testUpdateUser"}) + public void testGetRolesOfUser() { + PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getUserStoreManager")) + .toReturn(this.userStoreManager); + Response response = userManagementService.getRolesOfUser(TEST2_USERNAME, null); + Assert.assertEquals(response.getStatus(), Response.Status.NOT_FOUND.getStatusCode(), + "Roles of a non-existing user was successfully retrieved"); + response = userManagementService.getRolesOfUser(TEST_USERNAME, null); + Assert.assertEquals(response.getStatus(), Response.Status.OK.getStatusCode(), + "Retrieval of roles of a existing user failed."); + } + + @Test(description = "This method tests the IsUserExists method of UserManagementService", dependsOnMethods = + {"testGetRolesOfUser"}) + public void testIsUserExists() { + PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getUserStoreManager")) + .toReturn(this.userStoreManager); + Response response = userManagementService.isUserExists(TEST2_USERNAME); + boolean responseEntity = (boolean) response.getEntity(); + Assert.assertEquals(response.getStatus(), Response.Status.OK.getStatusCode(), + "Check for existence of user failed"); + Assert.assertFalse(responseEntity, "Non-existing user is identified as already existing user"); + response = userManagementService.isUserExists(TEST_USERNAME); + responseEntity = (boolean) response.getEntity(); + Assert.assertEquals(response.getStatus(), Response.Status.OK.getStatusCode(), + "Check for existence of user failed"); + Assert.assertTrue(responseEntity, "Existing user is identified as non-existing user"); + } + + @Test(description = "This method tests the send invitation method of UserManagementService", dependsOnMethods = + {"testIsUserExists"}) + public void testSendInvitation() throws ConfigurationManagementException, DeviceManagementException { + PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getUserStoreManager")) + .toReturn(this.userStoreManager); + PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getDeviceManagementService")) + .toReturn(this.deviceManagementProviderService); + Mockito.doNothing().when(deviceManagementProviderService).sendEnrolmentInvitation(Mockito.any(), Mockito.any()); + Response response = userManagementService.inviteExistingUsersToEnrollDevice(userList); + Assert.assertEquals(response.getStatus(), Response.Status.OK.getStatusCode(), + "Inviting existing users to enroll device failed"); + } + + @Test(description = "This method tests the getUserNames method of UserManagementService", dependsOnMethods = + {"testSendInvitation"}) + public void testGetUserNames() throws UserStoreException { + PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getUserStoreManager")) + .toReturn(this.userStoreManager); + Mockito.doReturn(new String[] { TEST_USERNAME }).when(userStoreManager).listUsers(Mockito.anyString(), Mockito.anyInt()); + Response response = userManagementService + .getUserNames(TEST_USERNAME, null, "00", 0, 0); + Assert.assertEquals(response.getStatus(), Response.Status.OK.getStatusCode(), + "Getting user names is failed for a valid request"); + + } + + @Test(description = "This method tests the getUsers method of UserManagementService", + dependsOnMethods = {"testGetUserNames"}) + public void testGetUsers() { + PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getUserStoreManager")) + .toReturn(userStoreManager); + Response response = userManagementService.getUsers(null, "00", 0, 10); + Assert.assertEquals(response.getStatus(), Response.Status.OK.getStatusCode(), "GetUsers request failed"); + } + + @Test(description = "This method tests the inviteToEnrollDevice method of UserManagementService", + dependsOnMethods = "testGetUsers") + public void testInviteToEnrollDevice() { + URL resourceUrl = ClassLoader.getSystemResource("testng.xml"); + System.setProperty("carbon.home", resourceUrl.getPath()); + PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getUserStoreManager")) + .toReturn(this.userStoreManager); + PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getAuthenticatedUser")).toReturn(TEST_USERNAME); + PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getDeviceManagementService")) + .toReturn(this.deviceManagementProviderService); + EnrollmentInvitation enrollmentInvitation = new EnrollmentInvitation(); + List recipients = new ArrayList<>(); + recipients.add(TEST_USERNAME); + enrollmentInvitation.setDeviceType("android"); + enrollmentInvitation.setRecipients(recipients); + Response response = userManagementService.inviteToEnrollDevice(enrollmentInvitation); + Assert.assertEquals(response.getStatus(), Response.Status.OK.getStatusCode(), + "Inviting users to enroll device failed"); + } + + @Test(description = "This method tests the removeUser method of UserManagementService", dependsOnMethods = + "testInviteToEnrollDevice") + public void testRemoveUser() throws DeviceManagementException, UserStoreException { + PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getUserStoreManager")) + .toReturn(this.userStoreManager); + PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getDeviceManagementService")) + .toReturn(this.deviceManagementProviderService); + Mockito.doReturn(true).when(deviceManagementProviderService).setStatus(Mockito.anyString(), Mockito.any()); + Mockito.doNothing().when(userStoreManager).deleteUser(Mockito.anyString()); + Response response = userManagementService.removeUser(TEST_USERNAME, null); + Assert.assertEquals(response.getStatus(), Response.Status.OK.getStatusCode(), + "Cannot remove user, the request failed"); + response = userManagementService.removeUser(TEST2_USERNAME, null); + Assert.assertEquals(response.getStatus(), Response.Status.NOT_FOUND.getStatusCode(), + "Successfully removed non-existing user"); + } + + @Test(description = "This method tests the behaviour of getUserCount method of UserManagementService", + dependsOnMethods = {"testRemoveUser"}) + public void testGetUserCount() throws UserStoreException { + PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getUserRealm")).toReturn(userRealm); + PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getUserStoreCountRetrieverService")) + .toReturn(null); + PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getUserStoreManager")) + .toReturn(this.userStoreManager); + Response response = userManagementService.getUserCount(); + Assert.assertEquals(response.getStatus(), Response.Status.OK.getStatusCode(), "User count retrieval failed"); + } + + @Test(description = "This method tests the behaviour of methods when there is an issue with " + + "DeviceManagementProviderService", dependsOnMethods = {"testGetUserCount"}) + public void testNegativeScenarios1() throws ConfigurationManagementException, DeviceManagementException { + PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getUserStoreManager")) + .toReturn(this.userStoreManager); + PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getDeviceManagementService")) + .toReturn(this.deviceManagementProviderService); + PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getAuthenticatedUser")).toReturn(TEST_USERNAME); + Mockito.reset(deviceManagementProviderService); + Mockito.doThrow(new DeviceManagementException()).when(deviceManagementProviderService) + .sendEnrolmentInvitation(Mockito.any(), Mockito.any()); + Response response = userManagementService.inviteExistingUsersToEnrollDevice(userList); + Assert.assertEquals(response.getStatus(), Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(), + "Invite existing users to enroll device succeeded under erroneous conditions"); + response = userManagementService.inviteToEnrollDevice(enrollmentInvitation); + Assert.assertEquals(response.getStatus(), Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(), + "Invite existing users to enroll device succeeded under erroneous conditions"); + } + + @Test(description = "This method tests the behaviour of the different methods when there is an issue is " + + "userStoreManager", dependsOnMethods = {"testNegativeScenarios1"}) + public void testNegativeScenarios2() throws UserStoreException { + PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getUserStoreManager")) + .toReturn(this.userStoreManager); + Mockito.doThrow(new UserStoreException()).when(userStoreManager).isExistingUser(TEST3_USERNAME); + Response response = userManagementService.getUser(TEST3_USERNAME, null, null); + Assert.assertEquals(response.getStatus(), Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(), + "Response returned successful for a user retrieval with problematic inputs"); + UserInfo userInfo = new UserInfo(); + userInfo.setUsername(TEST3_USERNAME); + response = userManagementService.addUser(userInfo); + Assert.assertEquals(response.getStatus(), Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(), + "Response returned successful for a user addition with problematic inputs"); + response = userManagementService.updateUser(TEST3_USERNAME, null, userInfo); + Assert.assertEquals(response.getStatus(), Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(), + "Response returned successful for a user updating request with problematic inputs"); + response = userManagementService.removeUser(TEST3_USERNAME, null); + Assert.assertEquals(response.getStatus(), Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(), + "Response returned successful for a user removal request with problematic inputs"); + response = userManagementService.getRolesOfUser(TEST3_USERNAME, null); + Assert.assertEquals(response.getStatus(), Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(), + "Response returned successful for a user role retrieval request with problematic inputs"); + response = userManagementService.isUserExists(TEST3_USERNAME); + Assert.assertEquals(response.getStatus(), Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(), + "Response returned successful for checking existence of user under problematic conditions"); + } + + @Test(description = "This method tests the behaviour of various methods when there is an issue with UserStore " + + "Manager", dependsOnMethods = {"testNegativeScenarios2"}) + public void testNegativeScenarios3() throws UserStoreException { + PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getUserStoreManager")) + .toReturn(this.userStoreManager); + PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getUserRealm")).toReturn(userRealm); + PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getUserStoreCountRetrieverService")) + .toReturn(null); + PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getAuthenticatedUser")).toReturn(TEST_USERNAME); + PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getDeviceManagementService")) + .toReturn(this.deviceManagementProviderService); + Mockito.reset(this.userStoreManager); + Mockito.doThrow(new UserStoreException()).when(userStoreManager) + .getUserClaimValue(Mockito.any(), Mockito.any(), Mockito.any()); + Mockito.doThrow(new UserStoreException()).when(userStoreManager) + .listUsers(Mockito.anyString(), Mockito.anyInt()); + Response response = userManagementService.getUsers(TEST_USERNAME, "00", 0, 10); + Assert.assertEquals(response.getStatus(), Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(), + "Response returned successful for a users retrieval request."); + response = userManagementService.getUserCount(); + Assert.assertEquals(response.getStatus(), Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(), + "Response returned successful for a user count retrieval request."); + response = userManagementService.getUserNames(TEST_USERNAME, null, "00", 0, 10); + Assert.assertEquals(response.getStatus(), Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(), + "Response returned successful for a user count retrieval request."); + response = userManagementService.inviteToEnrollDevice(enrollmentInvitation); + Assert.assertEquals(response.getStatus(), Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(), + "Invite existing users to enroll device succeeded under erroneous conditions"); + response = userManagementService.inviteExistingUsersToEnrollDevice(userList); + Assert.assertEquals(response.getStatus(), Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(), + "Invite existing users to enroll device succeeded under erroneous conditions"); + } + + /** + * To get the user info of a user + * + * @return UserInfo of the User. + */ + private UserInfo getUserInfo() { + UserInfo userInfo = new UserInfo(); + userInfo.setUsername(TEST_USERNAME); + userInfo.setFirstname(TEST_USERNAME); + userInfo.setLastname(TEST_USERNAME); + userInfo.setEmailAddress("test@test.com"); + return userInfo; + } + +} diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/test/resources/testng.xml b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/test/resources/testng.xml index aa09de781ff..0f3d1607668 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/test/resources/testng.xml +++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/test/resources/testng.xml @@ -28,6 +28,7 @@ + diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/service/DeviceManagementProviderServiceImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/service/DeviceManagementProviderServiceImpl.java index a57bc75bc73..9682f26664a 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/service/DeviceManagementProviderServiceImpl.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/service/DeviceManagementProviderServiceImpl.java @@ -60,17 +60,9 @@ import org.wso2.carbon.device.mgt.common.spi.DeviceManagementService; import org.wso2.carbon.device.mgt.core.DeviceManagementConstants; import org.wso2.carbon.device.mgt.core.DeviceManagementPluginRepository; import org.wso2.carbon.device.mgt.core.cache.impl.DeviceCacheManagerImpl; -import org.wso2.carbon.device.mgt.core.dao.ApplicationDAO; -import org.wso2.carbon.device.mgt.core.dao.DeviceDAO; -import org.wso2.carbon.device.mgt.core.dao.DeviceManagementDAOException; -import org.wso2.carbon.device.mgt.core.dao.DeviceManagementDAOFactory; -import org.wso2.carbon.device.mgt.core.dao.DeviceTypeDAO; -import org.wso2.carbon.device.mgt.core.dao.EnrollmentDAO; -import org.wso2.carbon.device.mgt.core.device.details.mgt.DeviceDetailsMgtException; -import org.wso2.carbon.device.mgt.core.device.details.mgt.DeviceInformationManager; +import org.wso2.carbon.device.mgt.core.dao.*; import org.wso2.carbon.device.mgt.core.device.details.mgt.dao.DeviceDetailsDAO; import org.wso2.carbon.device.mgt.core.device.details.mgt.dao.DeviceDetailsMgtDAOException; -import org.wso2.carbon.device.mgt.core.device.details.mgt.impl.DeviceInformationManagerImpl; import org.wso2.carbon.device.mgt.core.dto.DeviceType; import org.wso2.carbon.device.mgt.core.dto.DeviceTypeServiceIdentifier; import org.wso2.carbon.device.mgt.core.internal.DeviceManagementDataHolder; @@ -250,7 +242,7 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv } } } else { - int enrolmentId = 0; + int enrolmentId; try { DeviceManagementDAOFactory.beginTransaction(); DeviceType type = deviceTypeDAO.getDeviceType(device.getType(), tenantId); @@ -363,7 +355,7 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv if (log.isDebugEnabled()) { log.debug("Get enrollments for user '" + user + "' device: " + deviceId); } - List enrolmentInfos = new ArrayList<>(); + List enrolmentInfos; try { DeviceManagementDAOFactory.openConnection(); enrolmentInfos = enrollmentDAO.getEnrollmentsOfUser(deviceId, user, this.getTenantId()); @@ -453,10 +445,7 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv @Override public boolean isEnrolled(DeviceIdentifier deviceId) throws DeviceManagementException { Device device = this.getDevice(deviceId, false); - if (device != null) { - return true; - } - return false; + return device != null; } @Override @@ -627,8 +616,8 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv + requireDeviceInfo); } PaginationResult paginationResult = new PaginationResult(); - List allDevices = new ArrayList<>(); - int count = 0; + List allDevices; + int count; int tenantId = this.getTenantId(); String deviceType = request.getDeviceType(); request = DeviceManagerUtil.validateDeviceListPageSize(request); @@ -679,9 +668,9 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv if (log.isDebugEnabled()) { log.debug("Get devices with pagination " + request.toString() + " and requiredDeviceInfo: " + requireDeviceInfo); } - List devicesForRoles = null; + List devicesForRoles; PaginationResult paginationResult = new PaginationResult(); - List allDevices = new ArrayList<>(); + List allDevices; int count = 0; int tenantId = this.getTenantId(); request = DeviceManagerUtil.validateDeviceListPageSize(request); @@ -785,7 +774,7 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv " and owner '" + owner + "' and requiredDeviceInfo: " + requireDeviceInfo); } int tenantId = this.getTenantId(); - Device device = null; + Device device; try { DeviceManagementDAOFactory.openConnection(); device = deviceDAO.getDevice(deviceId, owner, tenantId); @@ -835,12 +824,12 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv Enumeration e = props.propertyNames(); while (e.hasMoreElements()) { String key = (String) e.nextElement(); - params.put(key, new TypedValue, Object>(String.class, props.getProperty(key))); + params.put(key, new TypedValue<>(String.class, props.getProperty(key))); } params.put(org.wso2.carbon.device.mgt.core.DeviceManagementConstants.EmailAttributes.SERVER_BASE_URL_HTTPS, - new TypedValue, Object>(String.class, DeviceManagerUtil.getServerBaseHttpsUrl())); + new TypedValue<>(String.class, DeviceManagerUtil.getServerBaseHttpsUrl())); params.put(org.wso2.carbon.device.mgt.core.DeviceManagementConstants.EmailAttributes.SERVER_BASE_URL_HTTP, - new TypedValue, Object>(String.class, DeviceManagerUtil.getServerBaseHttpUrl())); + new TypedValue<>(String.class, DeviceManagerUtil.getServerBaseHttpUrl())); try { EmailContext ctx = new EmailContext.EmailContextBuilder(new ContentProviderInfo(templateName, params), @@ -875,17 +864,17 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv if (emailSenderService != null) { Map, Object>> params = new HashMap<>(); params.put(org.wso2.carbon.device.mgt.core.DeviceManagementConstants.EmailAttributes.FIRST_NAME, - new TypedValue, Object>(String.class, metaInfo.getProperty("first-name"))); + new TypedValue<>(String.class, metaInfo.getProperty("first-name"))); params.put(org.wso2.carbon.device.mgt.core.DeviceManagementConstants.EmailAttributes.USERNAME, - new TypedValue, Object>(String.class, metaInfo.getProperty("username"))); + new TypedValue<>(String.class, metaInfo.getProperty("username"))); params.put(org.wso2.carbon.device.mgt.core.DeviceManagementConstants.EmailAttributes.PASSWORD, - new TypedValue, Object>(String.class, metaInfo.getProperty("password"))); + new TypedValue<>(String.class, metaInfo.getProperty("password"))); params.put(org.wso2.carbon.device.mgt.core.DeviceManagementConstants.EmailAttributes.DOMAIN, - new TypedValue, Object>(String.class, metaInfo.getProperty("domain"))); + new TypedValue<>(String.class, metaInfo.getProperty("domain"))); params.put(org.wso2.carbon.device.mgt.core.DeviceManagementConstants.EmailAttributes.SERVER_BASE_URL_HTTPS, - new TypedValue, Object>(String.class, DeviceManagerUtil.getServerBaseHttpsUrl())); + new TypedValue<>(String.class, DeviceManagerUtil.getServerBaseHttpsUrl())); params.put(org.wso2.carbon.device.mgt.core.DeviceManagementConstants.EmailAttributes.SERVER_BASE_URL_HTTP, - new TypedValue, Object>(String.class, DeviceManagerUtil.getServerBaseHttpUrl())); + new TypedValue<>(String.class, DeviceManagerUtil.getServerBaseHttpUrl())); try { EmailContext ctx = new EmailContext.EmailContextBuilder( @@ -1284,7 +1273,7 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv log.debug("Update enrollment with status"); } try { - boolean success = false; + boolean success; int tenantId = this.getTenantId(); DeviceManagementDAOFactory.beginTransaction(); success = enrollmentDAO.setStatus(currentOwner, status, tenantId); @@ -1607,10 +1596,10 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv + requireDeviceInfo); } PaginationResult result = new PaginationResult(); - int deviceCount = 0; + int deviceCount; int tenantId = this.getTenantId(); String username = request.getOwner(); - List userDevices = new ArrayList<>(); + List userDevices; request = DeviceManagerUtil.validateDeviceListPageSize(request); try { DeviceManagementDAOFactory.openConnection(); @@ -1662,7 +1651,7 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv } PaginationResult result = new PaginationResult(); List allDevices; - int deviceCount = 0; + int deviceCount; int tenantId = this.getTenantId(); String ownerShip = request.getOwnership(); request = DeviceManagerUtil.validateDeviceListPageSize(request); @@ -1729,7 +1718,6 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv List userDevices; for (String user : users) { - userDevices = new ArrayList<>(); try { DeviceManagementDAOFactory.openConnection(); userDevices = deviceDAO.getDevicesOfUser(user, tenantId); @@ -1865,7 +1853,7 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv } PaginationResult result = new PaginationResult(); int tenantId = this.getTenantId(); - List allDevices = new ArrayList<>(); + List allDevices; String deviceName = request.getDeviceName(); request = DeviceManagerUtil.validateDeviceListPageSize(request); try { @@ -2019,10 +2007,7 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv @Override public boolean isEnrolled(DeviceIdentifier deviceId, String user) throws DeviceManagementException { Device device = this.getDevice(deviceId, false); - if (device != null && device.getEnrolmentInfo() != null && device.getEnrolmentInfo().getOwner().equals(user)) { - return true; - } - return false; + return device != null && device.getEnrolmentInfo() != null && device.getEnrolmentInfo().getOwner().equals(user); } @Override @@ -2056,7 +2041,7 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv log.debug("Change device status of device: " + deviceIdentifier.getId() + " of type '" + deviceIdentifier.getType() + "'"); } - boolean isDeviceUpdated = false; + boolean isDeviceUpdated; Device device = getDevice(deviceIdentifier, false); int deviceId = device.getId(); EnrolmentInfo enrolmentInfo = device.getEnrolmentInfo(); @@ -2251,7 +2236,7 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv * @param service {@link GroupManagementProviderService} instance. * @param groupName of the group to create. * @return Group with details. - * @throws GroupManagementException + * @throws GroupManagementException Group Management Exception */ private DeviceGroup createDefaultGroup(GroupManagementProviderService service, String groupName) throws GroupManagementException { @@ -2460,27 +2445,25 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv log.debug("Get all device info of devices, num of devices: " + allDevices.size()); } List devices = new ArrayList<>(); - if (allDevices != null) { - for (Device device : allDevices) { - device.setDeviceInfo(this.getDeviceInfo(device)); - device.setApplications(this.getInstalledApplications(device)); - DeviceManager deviceManager = this.getDeviceManager(device.getType()); - if (deviceManager == null) { - if (log.isDebugEnabled()) { - log.debug("Device Manager associated with the device type '" + device.getType() + "' is null. " + - "Therefore, not attempting method 'isEnrolled'"); - } - devices.add(device); - continue; - } - Device dmsDevice = - deviceManager.getDevice(new DeviceIdentifier(device.getDeviceIdentifier(), device.getType())); - if (dmsDevice != null) { - device.setFeatures(dmsDevice.getFeatures()); - device.setProperties(dmsDevice.getProperties()); + for (Device device : allDevices) { + device.setDeviceInfo(this.getDeviceInfo(device)); + device.setApplications(this.getInstalledApplications(device)); + DeviceManager deviceManager = this.getDeviceManager(device.getType()); + if (deviceManager == null) { + if (log.isDebugEnabled()) { + log.debug("Device Manager associated with the device type '" + device.getType() + "' is null. " + + "Therefore, not attempting method 'isEnrolled'"); } devices.add(device); + continue; + } + Device dmsDevice = + deviceManager.getDevice(new DeviceIdentifier(device.getDeviceIdentifier(), device.getType())); + if (dmsDevice != null) { + device.setFeatures(dmsDevice.getFeatures()); + device.setProperties(dmsDevice.getProperties()); } + devices.add(device); } return devices; } From 4228ddd4168e68fac2d3d8a6528bf8096f6d2771 Mon Sep 17 00:00:00 2001 From: megala21 Date: Thu, 19 Oct 2017 15:46:28 +0530 Subject: [PATCH 2/5] Refactoring --- .../impl/UserManagementServiceImplTest.java | 22 +++++++++++++++++++ 1 file changed, 22 insertions(+) diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/test/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/UserManagementServiceImplTest.java b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/test/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/UserManagementServiceImplTest.java index 9f9712443ac..6d47f8ef9bd 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/test/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/UserManagementServiceImplTest.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/test/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/UserManagementServiceImplTest.java @@ -1,3 +1,22 @@ +/* + * Copyright (c) 2017, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. + * + * WSO2 Inc. licenses this file to you 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 org.wso2.carbon.device.mgt.jaxrs.service.impl; import org.mockito.Mockito; @@ -36,6 +55,9 @@ import java.util.List; import static org.mockito.MockitoAnnotations.initMocks; +/** + * This is a test case for {@link UserManagementService}. + */ @PowerMockIgnore("javax.ws.rs.*") @SuppressStaticInitializationFor({"org.wso2.carbon.device.mgt.jaxrs.util.DeviceMgtAPIUtils", "org.wso2.carbon.context.CarbonContext"}) From 37248de07f80033630e9b7c2131edbe26d82dc95 Mon Sep 17 00:00:00 2001 From: megala21 Date: Thu, 19 Oct 2017 16:47:35 +0530 Subject: [PATCH 3/5] Adding test cases for notification managementservice --- .../NotificationManagementServiceImpl.java | 9 +- ...NotificationManagementServiceImplTest.java | 117 ++++++++++++++++++ .../src/test/resources/testng.xml | 1 + 3 files changed, 122 insertions(+), 5 deletions(-) create mode 100644 components/device-mgt/org.wso2.carbon.device.mgt.api/src/test/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/NotificationManagementServiceImplTest.java diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/NotificationManagementServiceImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/NotificationManagementServiceImpl.java index 3bc4fec7df8..8e2322cd0a0 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/NotificationManagementServiceImpl.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/NotificationManagementServiceImpl.java @@ -80,8 +80,7 @@ public class NotificationManagementServiceImpl implements NotificationManagement @PUT @Path("/{id}/mark-checked") - public Response updateNotificationStatus( - @PathParam("id") @Max(45)int id) { + public Response updateNotificationStatus(@PathParam("id") @Max(45)int id) { String msg; Notification.Status status = Notification.Status.CHECKED; Notification notification; @@ -90,8 +89,8 @@ public class NotificationManagementServiceImpl implements NotificationManagement } catch (NotificationManagementException e) { msg = "Error occurred while updating notification status."; log.error(msg, e); - throw new UnexpectedServerErrorException( - new ErrorResponse.ErrorResponseBuilder().setCode(500l).setMessage(msg).build()); + return Response.serverError().entity( + new ErrorResponse.ErrorResponseBuilder().setMessage(msg).build()).build(); } try { notification = DeviceMgtAPIUtils.getNotificationManagementService().getNotification(id); @@ -99,7 +98,7 @@ public class NotificationManagementServiceImpl implements NotificationManagement } catch (NotificationManagementException e) { msg = "Notification updated successfully. But the retrial of the updated notification failed"; log.error(msg, e); - return Response.status(Response.Status.OK).build(); + return Response.status(Response.Status.OK).entity(msg).build(); } } diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/test/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/NotificationManagementServiceImplTest.java b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/test/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/NotificationManagementServiceImplTest.java new file mode 100644 index 00000000000..92e321745f3 --- /dev/null +++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/test/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/NotificationManagementServiceImplTest.java @@ -0,0 +1,117 @@ +/* + * Copyright (c) 2017, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. + * + * WSO2 Inc. licenses this file to you 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 org.wso2.carbon.device.mgt.jaxrs.service.impl; + +import org.mockito.Mockito; +import org.powermock.api.mockito.PowerMockito; +import org.powermock.core.classloader.annotations.PowerMockIgnore; +import org.powermock.core.classloader.annotations.PrepareForTest; +import org.powermock.core.classloader.annotations.SuppressStaticInitializationFor; +import org.testng.Assert; +import org.testng.IObjectFactory; +import org.testng.annotations.BeforeClass; +import org.testng.annotations.ObjectFactory; +import org.testng.annotations.Test; +import org.wso2.carbon.context.CarbonContext; +import org.wso2.carbon.device.mgt.common.PaginationResult; +import org.wso2.carbon.device.mgt.common.notification.mgt.Notification; +import org.wso2.carbon.device.mgt.common.notification.mgt.NotificationManagementException; +import org.wso2.carbon.device.mgt.common.notification.mgt.NotificationManagementService; +import org.wso2.carbon.device.mgt.jaxrs.util.DeviceMgtAPIUtils; +import org.wso2.carbon.user.api.UserStoreException; +import org.wso2.carbon.utils.multitenancy.MultitenantUtils; +import javax.ws.rs.core.Response; +import java.util.ArrayList; +import java.util.List; + +import static org.mockito.MockitoAnnotations.initMocks; + +/** + * This is a test class for {@link NotificationManagementServiceImpl}. + */ +@PowerMockIgnore("javax.ws.rs.*") +@SuppressStaticInitializationFor({"org.wso2.carbon.device.mgt.jaxrs.util.DeviceMgtAPIUtils", + "org.wso2.carbon.context.CarbonContext"}) +@PrepareForTest({DeviceMgtAPIUtils.class, MultitenantUtils.class, CarbonContext.class}) +public class NotificationManagementServiceImplTest { + private NotificationManagementService notificationManagementService; + private org.wso2.carbon.device.mgt.jaxrs.service.api.NotificationManagementService notificationManagement; + + @ObjectFactory + public IObjectFactory getObjectFactory() { + return new org.powermock.modules.testng.PowerMockObjectFactory(); + } + + @BeforeClass + public void setup() throws UserStoreException, NotificationManagementException { + initMocks(this); + notificationManagementService = Mockito.mock(NotificationManagementService.class); + PaginationResult paginationResult = new PaginationResult(); + List notifications = new ArrayList<>(); + notifications.add(new Notification()); + paginationResult.setData(notifications); + paginationResult.setRecordsTotal(1); + Mockito.doReturn(paginationResult).when(notificationManagementService).getAllNotifications(Mockito.any()); + Mockito.doReturn(paginationResult).when(notificationManagementService) + .getNotificationsByStatus(Mockito.any(), Mockito.any()); + notificationManagement = new NotificationManagementServiceImpl(); + } + + @Test(description = "This method tests the behaviour of getNotifications method under different conditions") + public void testGetNotifications() throws NotificationManagementException { + PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getNotificationManagementService")) + .toReturn(this.notificationManagementService); + Response response = notificationManagement.getNotifications("NEW", "test", 0, 10); + Assert.assertEquals(response.getStatus(), Response.Status.OK.getStatusCode(), "Notification retrieval failed"); + response = notificationManagement.getNotifications(null, "test", 0, 10); + Assert.assertEquals(response.getStatus(), Response.Status.OK.getStatusCode(), "Notification retrieval failed"); + Mockito.reset(this.notificationManagementService); + Mockito.doThrow(new NotificationManagementException()).when(notificationManagementService) + .getAllNotifications(Mockito.any()); + response = notificationManagement.getNotifications(null, "test", 0, 10); + Assert.assertEquals(response.getStatus(), Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(), + "Notification retrieval succeeded with issues in NotificationManagement OSGI service"); + Mockito.reset(this.notificationManagementService); + } + + @Test(description = "This method tests the behaviour of updateNotificationStatus method under different conditions") + public void testUpdateNotificationStatus() throws NotificationManagementException { + PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getNotificationManagementService")) + .toReturn(this.notificationManagementService); + Mockito.doReturn(true).when(notificationManagementService) + .updateNotificationStatus(1, Notification.Status.CHECKED); + Mockito.doThrow(NotificationManagementException.class).when(notificationManagementService) + .updateNotificationStatus(2, Notification.Status.CHECKED); + Mockito.doReturn(true).when(notificationManagementService) + .updateNotificationStatus(3, Notification.Status.CHECKED); + Mockito.doReturn(new Notification()).when(notificationManagementService).getNotification(1); + Mockito.doThrow(new NotificationManagementException()).when(notificationManagementService).getNotification(3); + Response response = notificationManagement.updateNotificationStatus(1); + Assert.assertEquals(response.getStatus(), Response.Status.OK.getStatusCode(), + "Notification status update failed under correct conditions"); + response = notificationManagement.updateNotificationStatus(2); + Assert.assertEquals(response.getStatus(), Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(), + "Notification status update succeeded under erroneous conditions"); + response = notificationManagement.updateNotificationStatus(3); + Assert.assertEquals(response.getEntity(), + "Notification updated successfully. But the retrial of the updated " + "notification failed", + "Notification status update succeeded under erroneous conditions"); + } +} diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/test/resources/testng.xml b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/test/resources/testng.xml index 0f3d1607668..c7c6f5eb9bf 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/test/resources/testng.xml +++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/test/resources/testng.xml @@ -29,6 +29,7 @@ + From 5f0712dd3831b950784b80abff8825b04aee2378 Mon Sep 17 00:00:00 2001 From: megala21 Date: Thu, 19 Oct 2017 16:54:16 +0530 Subject: [PATCH 4/5] Refactoring --- .../impl/UserManagementServiceImpl.java | 29 +++++++++++++++++-- .../impl/UserManagementServiceImplTest.java | 6 ++-- .../DeviceManagementProviderServiceImpl.java | 7 ++++- 3 files changed, 35 insertions(+), 7 deletions(-) diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/UserManagementServiceImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/UserManagementServiceImpl.java index 165c1da85fb..25794c833b0 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/UserManagementServiceImpl.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/UserManagementServiceImpl.java @@ -28,7 +28,14 @@ import org.wso2.carbon.device.mgt.common.configuration.mgt.ConfigurationManageme import org.wso2.carbon.device.mgt.core.DeviceManagementConstants; import org.wso2.carbon.device.mgt.core.service.DeviceManagementProviderService; import org.wso2.carbon.device.mgt.core.service.EmailMetaInfo; -import org.wso2.carbon.device.mgt.jaxrs.beans.*; +import org.wso2.carbon.device.mgt.jaxrs.beans.BasicUserInfo; +import org.wso2.carbon.device.mgt.jaxrs.beans.BasicUserInfoList; +import org.wso2.carbon.device.mgt.jaxrs.beans.BasicUserInfoWrapper; +import org.wso2.carbon.device.mgt.jaxrs.beans.EnrollmentInvitation; +import org.wso2.carbon.device.mgt.jaxrs.beans.ErrorResponse; +import org.wso2.carbon.device.mgt.jaxrs.beans.OldPasswordResetWrapper; +import org.wso2.carbon.device.mgt.jaxrs.beans.RoleList; +import org.wso2.carbon.device.mgt.jaxrs.beans.UserInfo; import org.wso2.carbon.device.mgt.jaxrs.service.api.UserManagementService; import org.wso2.carbon.device.mgt.jaxrs.service.impl.util.RequestValidationUtil; import org.wso2.carbon.device.mgt.jaxrs.util.Constants; @@ -42,7 +49,16 @@ import org.wso2.carbon.user.api.UserStoreException; import org.wso2.carbon.user.api.UserStoreManager; import org.wso2.carbon.utils.CarbonUtils; -import javax.ws.rs.*; +import javax.ws.rs.Consumes; +import javax.ws.rs.DELETE; +import javax.ws.rs.GET; +import javax.ws.rs.HeaderParam; +import javax.ws.rs.POST; +import javax.ws.rs.PUT; +import javax.ws.rs.Path; +import javax.ws.rs.PathParam; +import javax.ws.rs.Produces; +import javax.ws.rs.QueryParam; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import java.io.File; @@ -50,7 +66,14 @@ import java.io.UnsupportedEncodingException; import java.net.URI; import java.net.URISyntaxException; import java.security.SecureRandom; -import java.util.*; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Properties; +import java.util.Set; @Path("/users") @Produces(MediaType.APPLICATION_JSON) diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/test/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/UserManagementServiceImplTest.java b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/test/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/UserManagementServiceImplTest.java index 6d47f8ef9bd..bcee738b6e2 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/test/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/UserManagementServiceImplTest.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/test/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/UserManagementServiceImplTest.java @@ -221,9 +221,9 @@ public class UserManagementServiceImplTest { public void testGetUserNames() throws UserStoreException { PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getUserStoreManager")) .toReturn(this.userStoreManager); - Mockito.doReturn(new String[] { TEST_USERNAME }).when(userStoreManager).listUsers(Mockito.anyString(), Mockito.anyInt()); - Response response = userManagementService - .getUserNames(TEST_USERNAME, null, "00", 0, 0); + Mockito.doReturn(new String[] { TEST_USERNAME }).when(userStoreManager) + .listUsers(Mockito.anyString(), Mockito.anyInt()); + Response response = userManagementService.getUserNames(TEST_USERNAME, null, "00", 0, 0); Assert.assertEquals(response.getStatus(), Response.Status.OK.getStatusCode(), "Getting user names is failed for a valid request"); diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/service/DeviceManagementProviderServiceImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/service/DeviceManagementProviderServiceImpl.java index 9682f26664a..9ee72d040a6 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/service/DeviceManagementProviderServiceImpl.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/service/DeviceManagementProviderServiceImpl.java @@ -60,7 +60,12 @@ import org.wso2.carbon.device.mgt.common.spi.DeviceManagementService; import org.wso2.carbon.device.mgt.core.DeviceManagementConstants; import org.wso2.carbon.device.mgt.core.DeviceManagementPluginRepository; import org.wso2.carbon.device.mgt.core.cache.impl.DeviceCacheManagerImpl; -import org.wso2.carbon.device.mgt.core.dao.*; +import org.wso2.carbon.device.mgt.core.dao.ApplicationDAO; +import org.wso2.carbon.device.mgt.core.dao.DeviceDAO; +import org.wso2.carbon.device.mgt.core.dao.DeviceManagementDAOException; +import org.wso2.carbon.device.mgt.core.dao.DeviceManagementDAOFactory; +import org.wso2.carbon.device.mgt.core.dao.DeviceTypeDAO; +import org.wso2.carbon.device.mgt.core.dao.EnrollmentDAO; import org.wso2.carbon.device.mgt.core.device.details.mgt.dao.DeviceDetailsDAO; import org.wso2.carbon.device.mgt.core.device.details.mgt.dao.DeviceDetailsMgtDAOException; import org.wso2.carbon.device.mgt.core.dto.DeviceType; From fc82bf3f954771638bac3082f2ec8172cc2e61fb Mon Sep 17 00:00:00 2001 From: megala21 Date: Fri, 20 Oct 2017 10:48:45 +0530 Subject: [PATCH 5/5] Adding test cases for ConfigurationManagementService --- .../impl/ConfigurationServiceImplTest.java | 140 ++++++++++++++++++ .../src/test/resources/testng.xml | 1 + 2 files changed, 141 insertions(+) create mode 100644 components/device-mgt/org.wso2.carbon.device.mgt.api/src/test/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/ConfigurationServiceImplTest.java diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/test/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/ConfigurationServiceImplTest.java b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/test/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/ConfigurationServiceImplTest.java new file mode 100644 index 00000000000..5a4b0cd13b8 --- /dev/null +++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/test/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/ConfigurationServiceImplTest.java @@ -0,0 +1,140 @@ +/* + * Copyright (c) 2017, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. + * + * WSO2 Inc. licenses this file to you 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 org.wso2.carbon.device.mgt.jaxrs.service.impl; + +import org.mockito.Mockito; +import org.powermock.api.mockito.PowerMockito; +import org.powermock.core.classloader.annotations.PowerMockIgnore; +import org.powermock.core.classloader.annotations.PrepareForTest; +import org.powermock.core.classloader.annotations.SuppressStaticInitializationFor; +import org.testng.Assert; +import org.testng.IObjectFactory; +import org.testng.annotations.BeforeClass; +import org.testng.annotations.ObjectFactory; +import org.testng.annotations.Test; +import org.wso2.carbon.device.mgt.common.configuration.mgt.ConfigurationEntry; +import org.wso2.carbon.device.mgt.common.configuration.mgt.ConfigurationManagementException; +import org.wso2.carbon.device.mgt.common.configuration.mgt.PlatformConfiguration; +import org.wso2.carbon.device.mgt.common.configuration.mgt.PlatformConfigurationManagementService; +import org.wso2.carbon.device.mgt.jaxrs.service.api.ConfigurationManagementService; +import org.wso2.carbon.device.mgt.jaxrs.util.DeviceMgtAPIUtils; +import org.wso2.carbon.policy.mgt.core.util.PolicyManagerUtil; + +import javax.ws.rs.core.Response; +import java.util.ArrayList; +import java.util.List; + +/** + * This is a test class for {@link ConfigurationServiceImpl}. + */ +@PowerMockIgnore("javax.ws.rs.*") +@SuppressStaticInitializationFor({"org.wso2.carbon.device.mgt.jaxrs.util.DeviceMgtAPIUtils", + "org.wso2.carbon.context.CarbonContext"}) +@PrepareForTest({DeviceMgtAPIUtils.class, PolicyManagerUtil.class}) +public class ConfigurationServiceImplTest { + private ConfigurationManagementService configurationManagementService; + private PlatformConfigurationManagementService platformConfigurationManagementService; + private PlatformConfiguration platformConfiguration; + + @ObjectFactory + public IObjectFactory getObjectFactory() { + return new org.powermock.modules.testng.PowerMockObjectFactory(); + } + + @BeforeClass + public void init() { + configurationManagementService = new ConfigurationServiceImpl(); + platformConfigurationManagementService = Mockito.mock(PlatformConfigurationManagementService.class); + platformConfiguration = new PlatformConfiguration(); + platformConfiguration.setType("test"); + } + + @Test(description = "This method tests the getConfiguration method of ConfigurationManagementService under valid " + + "conditions") + public void testGetConfigurationWithSuccessConditions() throws ConfigurationManagementException { + PowerMockito.stub(PowerMockito.method(PolicyManagerUtil.class, "getMonitoringFrequency")).toReturn(60); + PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getPlatformConfigurationManagementService")) + .toReturn(platformConfigurationManagementService); + Mockito.doReturn(platformConfiguration).when(platformConfigurationManagementService) + .getConfiguration(Mockito.any()); + Response response = configurationManagementService.getConfiguration("test"); + Assert.assertEquals(response.getStatus(), Response.Status.OK.getStatusCode(), + "getConfiguration request " + "failed with valid parameters"); + + List configurationEntryList = new ArrayList<>(); + ConfigurationEntry configurationEntry = new ConfigurationEntry(); + configurationEntry.setContentType("String"); + configurationEntry.setName("test"); + configurationEntry.setValue("test"); + configurationEntryList.add(configurationEntry); + platformConfiguration.setConfiguration(configurationEntryList); + Mockito.reset(platformConfigurationManagementService); + Mockito.doReturn(platformConfiguration).when(platformConfigurationManagementService) + .getConfiguration(Mockito.any()); + response = configurationManagementService.getConfiguration("test"); + Assert.assertEquals(response.getStatus(), Response.Status.OK.getStatusCode(), + "getConfiguration request " + "failed with valid parameters"); + } + + @Test(description = "This method tests the getConfiguration method under negative conditions") + public void testGetConfigurationUnderNegativeConditions() throws ConfigurationManagementException { + PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getPlatformConfigurationManagementService")) + .toReturn(platformConfigurationManagementService); + Mockito.reset(platformConfigurationManagementService); + Mockito.doThrow(new ConfigurationManagementException()).when(platformConfigurationManagementService) + .getConfiguration(Mockito.any()); + Response response = configurationManagementService.getConfiguration("test"); + Assert.assertEquals(response.getStatus(), Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(), + "getConfiguration request " + "succeeded under negative conditions"); + } + + @Test(description = "This method tests the updateConfiguration method under valid conditions.", dependsOnMethods + = {"testGetConfigurationWithSuccessConditions"}) + public void testUpdateConfigurationUnderValidConditions() throws ConfigurationManagementException { + Mockito.reset(platformConfigurationManagementService); + PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getPlatformConfigurationManagementService")) + .toReturn(platformConfigurationManagementService); + PowerMockito + .stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getNotifierFrequency", PlatformConfiguration.class)) + .toReturn(60); + PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "scheduleTaskService", int.class)) + .toReturn(null); + Mockito.doReturn(platformConfiguration).when(platformConfigurationManagementService) + .getConfiguration(Mockito.any()); + Mockito.doReturn(true).when(platformConfigurationManagementService) + .saveConfiguration(Mockito.any(), Mockito.any()); + Response response = configurationManagementService.updateConfiguration(platformConfiguration); + Assert.assertEquals(response.getStatus(), Response.Status.OK.getStatusCode(), + "updateConfiguration request failed with valid parameters"); + } + + @Test(description = "This method tests the updateConfiguration method under negative conditions.", + dependsOnMethods = {"testGetConfigurationWithSuccessConditions"}) + public void testUpdateConfigurationUnderNegativeConditions() throws ConfigurationManagementException { + Mockito.reset(platformConfigurationManagementService); + PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getPlatformConfigurationManagementService")) + .toReturn(platformConfigurationManagementService); + Mockito.doThrow(new ConfigurationManagementException()).when(platformConfigurationManagementService) + .saveConfiguration(Mockito.any(), Mockito.any()); + Response response = configurationManagementService.updateConfiguration(platformConfiguration); + Assert.assertEquals(response.getStatus(), Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(), + "updateConfiguration request succeeded with in-valid parameters"); + } +} diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/test/resources/testng.xml b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/test/resources/testng.xml index c7c6f5eb9bf..1968f172a3e 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/test/resources/testng.xml +++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/test/resources/testng.xml @@ -30,6 +30,7 @@ +