forked from community/device-mgt-core
# Conflicts: # components/device-mgt/org.wso2.carbon.device.mgt.core/src/test/java/org/wso2/carbon/device/mgt/core/service/DeviceManagementProviderServiceTest.javarevert-70aa11f8
commit
d214411f9a
@ -1,38 +1,10 @@
|
||||
package org.wso2.carbon.apimgt.webapp.publisher.config;
|
||||
|
||||
public class APIResourceManagementException extends Exception{
|
||||
private static final long serialVersionUID = -3151279311929070297L;
|
||||
public class APIResourceManagementException extends Exception {
|
||||
private static final long serialVersionUID = -3151279311929070297L;
|
||||
|
||||
private String errorMessage;
|
||||
|
||||
public String getErrorMessage() {
|
||||
return errorMessage;
|
||||
}
|
||||
|
||||
public void setErrorMessage(String errorMessage) {
|
||||
this.errorMessage = errorMessage;
|
||||
}
|
||||
|
||||
public APIResourceManagementException(String msg, Exception nestedEx) {
|
||||
super(msg, nestedEx);
|
||||
setErrorMessage(msg);
|
||||
}
|
||||
|
||||
public APIResourceManagementException(String message, Throwable cause) {
|
||||
super(message, cause);
|
||||
setErrorMessage(message);
|
||||
}
|
||||
|
||||
public APIResourceManagementException(String msg) {
|
||||
super(msg);
|
||||
setErrorMessage(msg);
|
||||
}
|
||||
|
||||
public APIResourceManagementException() {
|
||||
super();
|
||||
}
|
||||
|
||||
public APIResourceManagementException(Throwable cause) {
|
||||
super(cause);
|
||||
}
|
||||
public APIResourceManagementException(String msg, Exception nestedEx) {
|
||||
super(msg, nestedEx);
|
||||
}
|
||||
}
|
||||
|
@ -0,0 +1,48 @@
|
||||
/*
|
||||
* 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.apimgt.webapp.publisher.utils;
|
||||
|
||||
import org.wso2.carbon.apimgt.webapp.publisher.APIConfig;
|
||||
import org.wso2.carbon.apimgt.webapp.publisher.dto.ApiScope;
|
||||
import org.wso2.carbon.apimgt.webapp.publisher.dto.ApiUriTemplate;
|
||||
|
||||
import java.util.LinkedHashSet;
|
||||
import java.util.Set;
|
||||
|
||||
/**
|
||||
* Contains util methods for webAppPublisher tests.
|
||||
*/
|
||||
public class TestUtils {
|
||||
|
||||
public void setAPIURITemplates(APIConfig apiConfig, String uriTemplate) {
|
||||
Set<ApiUriTemplate> uriTemplates = new LinkedHashSet<>();
|
||||
ApiUriTemplate template = new ApiUriTemplate();
|
||||
template.setAuthType("Application & Application User");
|
||||
template.setHttpVerb("POST");
|
||||
template.setResourceURI("https://localhost:9443/api/device-mgt/windows/v1.0/admin/devices/reboot");
|
||||
template.setUriTemplate(uriTemplate);
|
||||
ApiScope scope = new ApiScope();
|
||||
scope.setKey("perm:windows:reboot");
|
||||
scope.setName("Reboot");
|
||||
scope.setRoles("/permission/admin/device-mgt/devices/owning-device/operations/windows/reboot");
|
||||
scope.setDescription("Lock reset on Windows devices");
|
||||
template.setScope(scope);
|
||||
uriTemplates.add(template);
|
||||
apiConfig.setUriTemplates(uriTemplates);
|
||||
}
|
||||
}
|
@ -0,0 +1,43 @@
|
||||
/*
|
||||
* 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.certificate.mgt.core.impl;
|
||||
|
||||
import org.testng.Assert;
|
||||
import org.testng.annotations.BeforeClass;
|
||||
import org.wso2.carbon.certificate.mgt.core.cache.CertificateCacheManager;
|
||||
import org.wso2.carbon.certificate.mgt.core.common.BaseDeviceManagementCertificateTest;
|
||||
import org.wso2.carbon.certificate.mgt.core.dao.CertificateManagementDAOFactory;
|
||||
|
||||
/**
|
||||
* This class tests CertificateCache manager methods
|
||||
*/
|
||||
public class CertificateCacheManagerImplTests extends BaseDeviceManagementCertificateTest {
|
||||
|
||||
private CertificateCacheManager manager;
|
||||
|
||||
@BeforeClass
|
||||
@Override
|
||||
public void init() throws Exception {
|
||||
initDataSource();
|
||||
CertificateManagementDAOFactory.init(this.getDataSource());
|
||||
manager = org.wso2.carbon.certificate.mgt.core.cache.impl.CertificateCacheManagerImpl.getInstance();
|
||||
Assert.assertNotNull(manager);
|
||||
}
|
||||
|
||||
}
|
@ -0,0 +1,244 @@
|
||||
/*
|
||||
* 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.certificate.mgt.core.impl;
|
||||
import org.bouncycastle.asn1.ASN1Encodable;
|
||||
import org.bouncycastle.asn1.ASN1ObjectIdentifier;
|
||||
import org.bouncycastle.cert.CertIOException;
|
||||
import org.bouncycastle.cert.X509CertificateHolder;
|
||||
import org.bouncycastle.cert.X509v3CertificateBuilder;
|
||||
import org.bouncycastle.cert.jcajce.JcaX509CertificateConverter;
|
||||
import org.bouncycastle.operator.OperatorCreationException;
|
||||
import org.bouncycastle.operator.jcajce.JcaContentSignerBuilder;
|
||||
import org.bouncycastle.pkcs.PKCS10CertificationRequest;
|
||||
import org.mockito.Matchers;
|
||||
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.modules.testng.PowerMockTestCase;
|
||||
import org.testng.annotations.BeforeClass;
|
||||
import org.testng.annotations.Test;
|
||||
import org.wso2.carbon.base.MultitenantConstants;
|
||||
import org.wso2.carbon.certificate.mgt.core.dao.CertificateManagementDAOFactory;
|
||||
import org.wso2.carbon.certificate.mgt.core.exception.KeystoreException;
|
||||
import org.wso2.carbon.certificate.mgt.core.util.CSRGenerator;
|
||||
import org.wso2.carbon.certificate.mgt.core.util.CertificateManagementConstants;
|
||||
import org.wso2.carbon.context.PrivilegedCarbonContext;
|
||||
import javax.sql.DataSource;
|
||||
import java.io.File;
|
||||
import java.security.KeyPair;
|
||||
import java.security.PrivateKey;
|
||||
import java.security.NoSuchProviderException;
|
||||
import java.security.NoSuchAlgorithmException;
|
||||
import java.security.SignatureException;
|
||||
import java.security.InvalidKeyException;
|
||||
import java.security.cert.CertificateException;
|
||||
import java.security.cert.X509Certificate;
|
||||
import java.sql.SQLException;
|
||||
|
||||
/**
|
||||
* This class has the negative tests for CertificateGenerator class
|
||||
*/
|
||||
@PowerMockIgnore({"java.net.ssl", "javax.security.auth.x500.X500Principal"})
|
||||
@PrepareForTest({CertificateGenerator.class})
|
||||
public class CertificateGeneratorNegativeTests extends PowerMockTestCase {
|
||||
|
||||
@Test(description = "This test case tests behaviour when a certificate IO error occurs",
|
||||
expectedExceptions = KeystoreException.class)
|
||||
public void negativeTestGenerateCertificateFromCSR() throws Exception {
|
||||
CertificateGenerator generator = new CertificateGenerator();
|
||||
//Prepare mock objects
|
||||
X509v3CertificateBuilder mock = Mockito.mock(X509v3CertificateBuilder.class);
|
||||
Mockito.when(mock.addExtension(Matchers.any(ASN1ObjectIdentifier.class), Matchers.anyBoolean(),
|
||||
Matchers.any(ASN1Encodable.class))).thenThrow(new CertIOException("CERTIO"));
|
||||
PowerMockito.whenNew(X509v3CertificateBuilder.class).withAnyArguments().thenReturn(mock);
|
||||
//prepare input parameters
|
||||
CSRGenerator csrGeneration = new CSRGenerator();
|
||||
KeyStoreReader keyStoreReader = new KeyStoreReader();
|
||||
KeyPair keyPair = csrGeneration.generateKeyPair("RSA", 1024);
|
||||
byte[] csrData = csrGeneration.generateCSR("SHA256WithRSA", keyPair);
|
||||
PKCS10CertificationRequest certificationRequest;
|
||||
PrivateKey privateKeyCA = keyStoreReader.getCAPrivateKey();
|
||||
X509Certificate certCA = (X509Certificate) keyStoreReader.getCACertificate();
|
||||
certificationRequest = new PKCS10CertificationRequest(csrData);
|
||||
generator.generateCertificateFromCSR(privateKeyCA, certificationRequest, certCA.getIssuerX500Principal().getName());
|
||||
|
||||
}
|
||||
|
||||
@Test(description = "This test case tests behaviour when Certificate Operator creation error occurs",
|
||||
expectedExceptions = KeystoreException.class)
|
||||
public void negativeTestGenerateCertificateFromCSR2() throws Exception {
|
||||
CertificateGenerator generator = new CertificateGenerator();
|
||||
//Prepare mock objects
|
||||
JcaContentSignerBuilder mock = Mockito.mock(JcaContentSignerBuilder.class);
|
||||
Mockito.when(mock.setProvider(Matchers.eq(CertificateManagementConstants.PROVIDER))).thenReturn(mock);
|
||||
Mockito.when(mock.build(Matchers.any(PrivateKey.class))).thenThrow(new OperatorCreationException("OPERATOR"));
|
||||
PowerMockito.whenNew(JcaContentSignerBuilder.class).withAnyArguments().thenReturn(mock);
|
||||
//prepare input parameters
|
||||
CSRGenerator csrGeneration = new CSRGenerator();
|
||||
KeyStoreReader keyStoreReader = new KeyStoreReader();
|
||||
KeyPair keyPair = csrGeneration.generateKeyPair("RSA", 1024);
|
||||
byte[] csrData = csrGeneration.generateCSR("SHA256WithRSA", keyPair);
|
||||
PKCS10CertificationRequest certificationRequest;
|
||||
PrivateKey privateKeyCA = keyStoreReader.getCAPrivateKey();
|
||||
X509Certificate certCA = (X509Certificate) keyStoreReader.getCACertificate();
|
||||
certificationRequest = new PKCS10CertificationRequest(csrData);
|
||||
generator.generateCertificateFromCSR(privateKeyCA, certificationRequest, certCA.getIssuerX500Principal().getName());
|
||||
}
|
||||
|
||||
@Test(description = "This test case tests the behaviour when certificate exception occurs when verifying"
|
||||
, expectedExceptions = KeystoreException.class)
|
||||
public void negativeTestGenerateCertificateFromCSR3() throws Exception {
|
||||
CertificateGenerator generator = new CertificateGenerator();
|
||||
//Prepare mock objects
|
||||
JcaX509CertificateConverter mock = Mockito.mock(JcaX509CertificateConverter.class);
|
||||
Mockito.when(mock.setProvider(Matchers.eq(CertificateManagementConstants.PROVIDER))).thenReturn(mock);
|
||||
Mockito.when(mock.getCertificate(Matchers.any(X509CertificateHolder.class))).thenThrow(new CertificateException());
|
||||
PowerMockito.whenNew(JcaX509CertificateConverter.class).withAnyArguments().thenReturn(mock);
|
||||
//prepare input parameters
|
||||
CSRGenerator csrGeneration = new CSRGenerator();
|
||||
KeyStoreReader keyStoreReader = new KeyStoreReader();
|
||||
KeyPair keyPair = csrGeneration.generateKeyPair("RSA", 1024);
|
||||
byte[] csrData = csrGeneration.generateCSR("SHA256WithRSA", keyPair);
|
||||
PKCS10CertificationRequest certificationRequest;
|
||||
PrivateKey privateKeyCA = keyStoreReader.getCAPrivateKey();
|
||||
X509Certificate certCA = (X509Certificate) keyStoreReader.getCACertificate();
|
||||
certificationRequest = new PKCS10CertificationRequest(csrData);
|
||||
generator.generateCertificateFromCSR(privateKeyCA, certificationRequest, certCA.getIssuerX500Principal().getName());
|
||||
|
||||
}
|
||||
|
||||
@Test(description = "This test case tests behaviour when the Certificate provider does not exist"
|
||||
, expectedExceptions = KeystoreException.class)
|
||||
public void negativeTestGenerateX509Certificate1() throws Exception {
|
||||
CertificateGenerator generator = new CertificateGenerator();
|
||||
//prepare mock objects
|
||||
X509Certificate mock = Mockito.mock(X509Certificate.class);
|
||||
PowerMockito.doThrow(new NoSuchProviderException()).when(mock).verify(Matchers.any());
|
||||
JcaX509CertificateConverter conv = Mockito.mock(JcaX509CertificateConverter.class);
|
||||
Mockito.when(conv.setProvider(Mockito.anyString())).thenReturn(conv);
|
||||
Mockito.when(conv.getCertificate(Mockito.any())).thenReturn(mock);
|
||||
PowerMockito.whenNew(JcaX509CertificateConverter.class).withNoArguments().thenReturn(conv);
|
||||
generator.generateX509Certificate();
|
||||
}
|
||||
|
||||
@Test(description = "This test case tests behaviour when the Certificate Algorithm does not exist"
|
||||
, expectedExceptions = KeystoreException.class)
|
||||
public void negativeTestGenerateX509Certificate2() throws Exception {
|
||||
CertificateGenerator generator = new CertificateGenerator();
|
||||
//prepare mock objects
|
||||
X509Certificate mock = Mockito.mock(X509Certificate.class);
|
||||
PowerMockito.doThrow(new NoSuchAlgorithmException()).when(mock).verify(Matchers.any());
|
||||
JcaX509CertificateConverter conv = Mockito.mock(JcaX509CertificateConverter.class);
|
||||
Mockito.when(conv.setProvider(Mockito.anyString())).thenReturn(conv);
|
||||
Mockito.when(conv.getCertificate(Mockito.any())).thenReturn(mock);
|
||||
PowerMockito.whenNew(JcaX509CertificateConverter.class).withNoArguments().thenReturn(conv);
|
||||
generator.generateX509Certificate();
|
||||
}
|
||||
|
||||
@Test(description = "This test case tests behaviour when the Signature validation fails"
|
||||
, expectedExceptions = KeystoreException.class)
|
||||
public void negativeTestGenerateX509Certificate3() throws Exception {
|
||||
CertificateGenerator generator = new CertificateGenerator();
|
||||
//prepare mock objects
|
||||
X509Certificate mock = Mockito.mock(X509Certificate.class);
|
||||
PowerMockito.doThrow(new SignatureException()).when(mock).verify(Matchers.any());
|
||||
JcaX509CertificateConverter conv = Mockito.mock(JcaX509CertificateConverter.class);
|
||||
Mockito.when(conv.setProvider(Mockito.anyString())).thenReturn(conv);
|
||||
Mockito.when(conv.getCertificate(Mockito.any())).thenReturn(mock);
|
||||
PowerMockito.whenNew(JcaX509CertificateConverter.class).withNoArguments().thenReturn(conv);
|
||||
generator.generateX509Certificate();
|
||||
}
|
||||
|
||||
@Test(description = "This test case tests behaviour when the Certificate exception occurs"
|
||||
, expectedExceptions = KeystoreException.class)
|
||||
public void negativeTestGenerateX509Certificate4() throws Exception {
|
||||
CertificateGenerator generator = new CertificateGenerator();
|
||||
//prepare mock objects
|
||||
X509Certificate mock = Mockito.mock(X509Certificate.class);
|
||||
PowerMockito.doThrow(new CertificateException()).when(mock).verify(Matchers.any());
|
||||
JcaX509CertificateConverter conv = Mockito.mock(JcaX509CertificateConverter.class);
|
||||
Mockito.when(conv.setProvider(Mockito.anyString())).thenReturn(conv);
|
||||
Mockito.when(conv.getCertificate(Mockito.any())).thenReturn(mock);
|
||||
PowerMockito.whenNew(JcaX509CertificateConverter.class).withNoArguments().thenReturn(conv);
|
||||
generator.generateX509Certificate();
|
||||
}
|
||||
|
||||
@Test(description = "This test case tests behaviour when the Certificate key is invalid"
|
||||
, expectedExceptions = KeystoreException.class)
|
||||
public void negativeTestGenerateX509Certificate5() throws Exception {
|
||||
CertificateGenerator generator = new CertificateGenerator();
|
||||
//prepare mock objects
|
||||
X509Certificate mock = Mockito.mock(X509Certificate.class);
|
||||
PowerMockito.doThrow(new InvalidKeyException()).when(mock).verify(Matchers.any());
|
||||
JcaX509CertificateConverter conv = Mockito.mock(JcaX509CertificateConverter.class);
|
||||
Mockito.when(conv.setProvider(Mockito.anyString())).thenReturn(conv);
|
||||
Mockito.when(conv.getCertificate(Mockito.any())).thenReturn(mock);
|
||||
PowerMockito.whenNew(JcaX509CertificateConverter.class).withNoArguments().thenReturn(conv);
|
||||
generator.generateX509Certificate();
|
||||
}
|
||||
|
||||
@Test(description = "This test case tests behavior when the CA certificate is null"
|
||||
, expectedExceptions = KeystoreException.class)
|
||||
public void negativeTestGetRootCertificates1() throws KeystoreException {
|
||||
CertificateGenerator generator = new CertificateGenerator();
|
||||
generator.getRootCertificates(null, new byte[10]);
|
||||
}
|
||||
|
||||
@Test(description = "This test case tests behavior when the CA certificate is null",
|
||||
expectedExceptions = KeystoreException.class)
|
||||
public void negativeTestGetRootCertificates2() throws KeystoreException {
|
||||
CertificateGenerator generator = new CertificateGenerator();
|
||||
generator.getRootCertificates(new byte[10], null);
|
||||
}
|
||||
|
||||
|
||||
@BeforeClass
|
||||
public void init() throws SQLException {
|
||||
if (System.getProperty("carbon.home") == null) {
|
||||
File file = new File("src/test/resources/carbon-home");
|
||||
if (file.exists()) {
|
||||
System.setProperty("carbon.home", file.getAbsolutePath());
|
||||
}
|
||||
file = new File("../resources/carbon-home");
|
||||
if (file.exists()) {
|
||||
System.setProperty("carbon.home", file.getAbsolutePath());
|
||||
}
|
||||
file = new File("../../resources/carbon-home");
|
||||
if (file.exists()) {
|
||||
System.setProperty("carbon.home", file.getAbsolutePath());
|
||||
}
|
||||
file = new File("../../../resources/carbon-home");
|
||||
if (file.exists()) {
|
||||
System.setProperty("carbon.home", file.getAbsolutePath());
|
||||
}
|
||||
}
|
||||
PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantDomain(MultitenantConstants
|
||||
.SUPER_TENANT_DOMAIN_NAME);
|
||||
PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantId(MultitenantConstants.SUPER_TENANT_ID);
|
||||
|
||||
DataSource normalDatasource = Mockito.mock(DataSource.class, Mockito.RETURNS_DEEP_STUBS);
|
||||
DataSource daoExceptionDatasource = Mockito.mock(DataSource.class, Mockito.RETURNS_DEEP_STUBS);
|
||||
Mockito.when(normalDatasource.getConnection().getMetaData().getDatabaseProductName()).thenReturn("H2");
|
||||
|
||||
CertificateManagementDAOFactory.init(normalDatasource);
|
||||
Mockito.when(daoExceptionDatasource.getConnection().getMetaData().getDatabaseProductName()).thenReturn("H2");
|
||||
Mockito.when(daoExceptionDatasource.getConnection().prepareStatement(Mockito.anyString())).thenThrow(new SQLException());
|
||||
}
|
||||
}
|
@ -0,0 +1,177 @@
|
||||
/*
|
||||
* 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.certificate.mgt.core.impl;
|
||||
|
||||
import org.bouncycastle.cert.jcajce.JcaX509CertificateConverter;
|
||||
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.modules.testng.PowerMockTestCase;
|
||||
import org.testng.IObjectFactory;
|
||||
import org.testng.annotations.BeforeClass;
|
||||
import org.testng.annotations.ObjectFactory;
|
||||
import org.testng.annotations.Test;
|
||||
import org.wso2.carbon.base.MultitenantConstants;
|
||||
import org.wso2.carbon.certificate.mgt.core.dao.CertificateManagementDAOFactory;
|
||||
import org.wso2.carbon.certificate.mgt.core.exception.CertificateManagementException;
|
||||
import org.wso2.carbon.certificate.mgt.core.exception.TransactionManagementException;
|
||||
import org.wso2.carbon.certificate.mgt.core.service.CertificateManagementServiceImpl;
|
||||
import org.wso2.carbon.context.PrivilegedCarbonContext;
|
||||
|
||||
import javax.sql.DataSource;
|
||||
import java.io.File;
|
||||
import java.sql.SQLException;
|
||||
|
||||
/**
|
||||
* This class covers the negative tests for CertificateManagementServiceImpl class
|
||||
*/
|
||||
@PowerMockIgnore({"java.net.ssl", "javax.security.auth.x500.X500Principal"})
|
||||
@PrepareForTest({CertificateManagementServiceImpl.class, JcaX509CertificateConverter.class, CertificateGenerator.class,
|
||||
CertificateManagementDAOFactory.class})
|
||||
public class CertificateManagementServiceImplNegativeTests extends PowerMockTestCase {
|
||||
|
||||
private CertificateManagementServiceImpl instance;
|
||||
private DataSource daoExceptionDatasource;
|
||||
private static final String MOCK_SERIAL = "1234";
|
||||
private static final String MOCK_DATASOURCE = "H2";
|
||||
|
||||
@BeforeClass
|
||||
public void init() throws SQLException {
|
||||
if (System.getProperty("carbon.home") == null) {
|
||||
File file = new File("src/test/resources/carbon-home");
|
||||
if (file.exists()) {
|
||||
System.setProperty("carbon.home", file.getAbsolutePath());
|
||||
}
|
||||
file = new File("../resources/carbon-home");
|
||||
if (file.exists()) {
|
||||
System.setProperty("carbon.home", file.getAbsolutePath());
|
||||
}
|
||||
file = new File("../../resources/carbon-home");
|
||||
if (file.exists()) {
|
||||
System.setProperty("carbon.home", file.getAbsolutePath());
|
||||
}
|
||||
file = new File("../../../resources/carbon-home");
|
||||
if (file.exists()) {
|
||||
System.setProperty("carbon.home", file.getAbsolutePath());
|
||||
}
|
||||
}
|
||||
PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantDomain(MultitenantConstants
|
||||
.SUPER_TENANT_DOMAIN_NAME);
|
||||
PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantId(MultitenantConstants.SUPER_TENANT_ID);
|
||||
DataSource normalDatasource = Mockito.mock(DataSource.class, Mockito.RETURNS_DEEP_STUBS);
|
||||
Mockito.when(normalDatasource.getConnection().getMetaData().getDatabaseProductName()).thenReturn(MOCK_DATASOURCE);
|
||||
CertificateManagementDAOFactory.init(normalDatasource);
|
||||
|
||||
//configure datasource to throw dao exception
|
||||
daoExceptionDatasource = Mockito.mock(DataSource.class, Mockito.RETURNS_DEEP_STUBS);
|
||||
Mockito.when(daoExceptionDatasource.getConnection().getMetaData().getDatabaseProductName()).thenReturn(MOCK_DATASOURCE);
|
||||
Mockito.when(daoExceptionDatasource.getConnection().prepareStatement(Mockito.anyString())).thenThrow(new SQLException());
|
||||
|
||||
//save as class variable
|
||||
instance = CertificateManagementServiceImpl.getInstance();
|
||||
}
|
||||
|
||||
|
||||
@Test(description = "This test case tests behaviour when an error occurs when opening the data source"
|
||||
, expectedExceptions = CertificateManagementException.class)
|
||||
public void negativeTestRetrieveCertificate2() throws Exception {
|
||||
PowerMockito.mockStatic(CertificateManagementDAOFactory.class);
|
||||
PowerMockito.doThrow(new SQLException()).when(CertificateManagementDAOFactory.class, "openConnection");
|
||||
instance.retrieveCertificate(MOCK_SERIAL);
|
||||
}
|
||||
|
||||
@Test(description = "This test case tests behaviour when an error occurs when looking for a certificate with " +
|
||||
"a serial number", expectedExceptions = CertificateManagementException.class)
|
||||
public void negativeTestRetrieveCertificate() throws Exception {
|
||||
CertificateManagementDAOFactory.init(daoExceptionDatasource);
|
||||
CertificateManagementServiceImpl instance1 = CertificateManagementServiceImpl.getInstance();
|
||||
instance1.retrieveCertificate(MOCK_SERIAL);
|
||||
}
|
||||
|
||||
@Test(description = "This test case tests behaviour when an error occurs when opening the data source",
|
||||
expectedExceptions = CertificateManagementException.class)
|
||||
public void negativeTestGetAllCertificates() throws Exception {
|
||||
PowerMockito.mockStatic(CertificateManagementDAOFactory.class);
|
||||
PowerMockito.doThrow(new SQLException()).when(CertificateManagementDAOFactory.class, "openConnection");
|
||||
instance.getAllCertificates(1, 2);
|
||||
}
|
||||
|
||||
@Test(description = "This test case tests behaviour when an error occurs getting the list of certificates from repository"
|
||||
, expectedExceptions = CertificateManagementException.class)
|
||||
public void negativeTestGetAllCertificates2() throws Exception {
|
||||
CertificateManagementDAOFactory.init(daoExceptionDatasource);
|
||||
CertificateManagementServiceImpl instance1 = CertificateManagementServiceImpl.getInstance();
|
||||
instance1.getAllCertificates(1, 2);
|
||||
}
|
||||
|
||||
@Test(description = "This test case tests behaviour when data source transaction error occurs when removing the certificate"
|
||||
, expectedExceptions = CertificateManagementException.class)
|
||||
public void negativeTestRemoveCertificate() throws Exception {
|
||||
PowerMockito.mockStatic(CertificateManagementDAOFactory.class);
|
||||
PowerMockito.doThrow(new TransactionManagementException()).when(CertificateManagementDAOFactory.class, "beginTransaction");
|
||||
instance.removeCertificate(MOCK_SERIAL);
|
||||
}
|
||||
|
||||
@Test(description = "This test case tests behaviour when an error occurs while removing the certificate from the certificate " +
|
||||
"repository", expectedExceptions = CertificateManagementException.class)
|
||||
public void negativeTestRemoveCertificate2() throws Exception {
|
||||
CertificateManagementDAOFactory.init(daoExceptionDatasource);
|
||||
CertificateManagementServiceImpl instance1 = CertificateManagementServiceImpl.getInstance();
|
||||
instance1.removeCertificate(MOCK_SERIAL);
|
||||
}
|
||||
|
||||
@Test(description = "This test case tests behaviour when an error occurs when opening the data source",
|
||||
expectedExceptions = CertificateManagementException.class)
|
||||
public void negativeTestGetCertificates() throws Exception {
|
||||
PowerMockito.mockStatic(CertificateManagementDAOFactory.class);
|
||||
PowerMockito.doThrow(new SQLException()).when(CertificateManagementDAOFactory.class, "openConnection");
|
||||
instance.getCertificates();
|
||||
}
|
||||
|
||||
@Test(description = "This test case tests behaviour when an error occurs while looking up for the list of certificates"
|
||||
, expectedExceptions = CertificateManagementException.class)
|
||||
public void negativeTestGetCertificates2() throws CertificateManagementException {
|
||||
CertificateManagementDAOFactory.init(daoExceptionDatasource);
|
||||
CertificateManagementServiceImpl instance1 = CertificateManagementServiceImpl.getInstance();
|
||||
instance1.getCertificates();
|
||||
}
|
||||
|
||||
@Test(description = "This test case tests behaviour when an error occurs when opening the data source",
|
||||
expectedExceptions = CertificateManagementException.class)
|
||||
public void negativeTestSearchCertificates() throws Exception {
|
||||
PowerMockito.mockStatic(CertificateManagementDAOFactory.class);
|
||||
PowerMockito.doThrow(new SQLException()).when(CertificateManagementDAOFactory.class, "openConnection");
|
||||
instance.searchCertificates(MOCK_SERIAL);
|
||||
}
|
||||
|
||||
@Test(description = "This test case tests behaviour when an error occurs while searching for the certificate by the serial"
|
||||
, expectedExceptions = CertificateManagementException.class)
|
||||
public void negativeTestSearchCertificates2() throws CertificateManagementException {
|
||||
CertificateManagementDAOFactory.init(daoExceptionDatasource);
|
||||
CertificateManagementServiceImpl instance1 = CertificateManagementServiceImpl.getInstance();
|
||||
instance1.searchCertificates(MOCK_SERIAL);
|
||||
}
|
||||
|
||||
//Powermockito requirement
|
||||
@ObjectFactory
|
||||
public IObjectFactory getObjectFactory() {
|
||||
return new org.powermock.modules.testng.PowerMockObjectFactory();
|
||||
}
|
||||
}
|
@ -0,0 +1,49 @@
|
||||
/*
|
||||
* 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.certificate.mgt.core.impl;
|
||||
|
||||
import org.testng.Assert;
|
||||
import org.testng.annotations.Test;
|
||||
import org.wso2.carbon.certificate.mgt.core.bean.Certificate;
|
||||
import org.wso2.carbon.certificate.mgt.core.util.DummyCertificate;
|
||||
|
||||
/**
|
||||
* This class tests the DTO for certificates
|
||||
*/
|
||||
public class CertificateTests {
|
||||
|
||||
private static String SERIAL = "1234";
|
||||
private static String TENANT_DOMAIN = "tenant_domain";
|
||||
private static int TENANT_ID = 1234;
|
||||
|
||||
@Test(description = "This test case tests the Certificate object getters and setters")
|
||||
public void certificateCreationTest() {
|
||||
|
||||
Certificate certificate = new Certificate();
|
||||
certificate.setSerial(SERIAL);
|
||||
certificate.setCertificate(new DummyCertificate());
|
||||
certificate.setTenantDomain(TENANT_DOMAIN);
|
||||
certificate.setTenantId(TENANT_ID);
|
||||
|
||||
Assert.assertEquals(certificate.getCertificate(), new DummyCertificate());
|
||||
Assert.assertEquals(certificate.getSerial(), SERIAL);
|
||||
Assert.assertEquals(certificate.getTenantDomain(), TENANT_DOMAIN);
|
||||
Assert.assertEquals(certificate.getTenantId(), TENANT_ID);
|
||||
}
|
||||
}
|
@ -0,0 +1,655 @@
|
||||
/*
|
||||
* 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.apache.axis2.AxisFault;
|
||||
import org.apache.commons.logging.Log;
|
||||
import org.apache.commons.logging.LogFactory;
|
||||
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.caching.impl.CacheImpl;
|
||||
import org.wso2.carbon.context.CarbonContext;
|
||||
import org.wso2.carbon.context.PrivilegedCarbonContext;
|
||||
import org.wso2.carbon.device.mgt.analytics.data.publisher.exception.DataPublisherConfigurationException;
|
||||
import org.wso2.carbon.device.mgt.analytics.data.publisher.service.EventsPublisherService;
|
||||
import org.wso2.carbon.device.mgt.analytics.data.publisher.service.EventsPublisherServiceImpl;
|
||||
import org.wso2.carbon.device.mgt.common.Device;
|
||||
import org.wso2.carbon.device.mgt.common.DeviceIdentifier;
|
||||
import org.wso2.carbon.device.mgt.common.DeviceManagementException;
|
||||
import org.wso2.carbon.device.mgt.common.EnrolmentInfo;
|
||||
import org.wso2.carbon.device.mgt.common.authorization.DeviceAccessAuthorizationException;
|
||||
import org.wso2.carbon.device.mgt.common.authorization.DeviceAccessAuthorizationService;
|
||||
import org.wso2.carbon.device.mgt.core.authorization.DeviceAccessAuthorizationServiceImpl;
|
||||
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.service.api.DeviceAgentService;
|
||||
import org.wso2.carbon.device.mgt.jaxrs.service.api.admin.DeviceTypeManagementAdminService;
|
||||
import org.wso2.carbon.device.mgt.jaxrs.service.impl.util.DeviceMgtAPITestHelper;
|
||||
import org.wso2.carbon.device.mgt.jaxrs.util.DeviceMgtAPIUtils;
|
||||
import org.wso2.carbon.event.stream.stub.EventStreamAdminServiceStub;
|
||||
import org.wso2.carbon.event.stream.stub.types.EventStreamAttributeDto;
|
||||
import org.wso2.carbon.event.stream.stub.types.EventStreamDefinitionDto;
|
||||
import org.wso2.carbon.identity.jwt.client.extension.exception.JWTClientException;
|
||||
import org.wso2.carbon.user.api.UserStoreException;
|
||||
import org.wso2.carbon.utils.CarbonUtils;
|
||||
|
||||
import javax.cache.CacheManager;
|
||||
import javax.ws.rs.core.Response;
|
||||
import java.rmi.RemoteException;
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
|
||||
import static org.mockito.MockitoAnnotations.initMocks;
|
||||
|
||||
/**
|
||||
* This class holds the unit tests for the class {@link DeviceAgentServiceImpl}
|
||||
*/
|
||||
@PowerMockIgnore("javax.ws.rs.*")
|
||||
@SuppressStaticInitializationFor({"org.wso2.carbon.device.mgt.jaxrs.util.DeviceMgtAPIUtils",
|
||||
"org.wso2.carbon.context.CarbonContext", "org.wso2.carbon.context.internal.CarbonContextDataHolder"})
|
||||
@PrepareForTest({DeviceMgtAPIUtils.class, DeviceManagementProviderService.class,
|
||||
DeviceAccessAuthorizationService.class, EventStreamAdminServiceStub.class, PrivilegedCarbonContext.class,
|
||||
CarbonContext.class, CarbonUtils.class})
|
||||
public class DeviceAgentServiceTest {
|
||||
|
||||
private static final Log log = LogFactory.getLog(DeviceTypeManagementAdminService.class);
|
||||
private DeviceManagementProviderService deviceManagementProviderService;
|
||||
private DeviceAgentService deviceAgentService;
|
||||
private EventStreamAdminServiceStub eventStreamAdminServiceStub;
|
||||
private PrivilegedCarbonContext privilegedCarbonContext;
|
||||
private CarbonContext carbonContext;
|
||||
private CacheManager cacheManager;
|
||||
private DeviceAccessAuthorizationService deviceAccessAuthorizationService;
|
||||
private static final String TEST_DEVICE_TYPE = "TEST-DEVICE-TYPE";
|
||||
private static final String TEST_DEVICE_IDENTIFIER = "11222334455";
|
||||
private static final String AUTHENTICATED_USER = "admin";
|
||||
private static final String TENANT_DOMAIN = "carbon.super";
|
||||
private static Device demoDevice;
|
||||
|
||||
@ObjectFactory
|
||||
public IObjectFactory getObjectFactory() {
|
||||
return new org.powermock.modules.testng.PowerMockObjectFactory();
|
||||
}
|
||||
|
||||
@BeforeClass
|
||||
public void init() {
|
||||
log.info("Initializing DeviceAgent tests");
|
||||
initMocks(this);
|
||||
this.deviceManagementProviderService = Mockito
|
||||
.mock(DeviceManagementProviderServiceImpl.class, Mockito.RETURNS_MOCKS);
|
||||
this.deviceAgentService = new DeviceAgentServiceImpl();
|
||||
this.deviceAccessAuthorizationService = Mockito.mock(DeviceAccessAuthorizationServiceImpl.class,
|
||||
Mockito.RETURNS_MOCKS);
|
||||
this.privilegedCarbonContext = Mockito.mock(PrivilegedCarbonContext.class, Mockito.RETURNS_MOCKS);
|
||||
this.carbonContext = Mockito.mock(CarbonContext.class, Mockito.RETURNS_MOCKS);
|
||||
this.eventStreamAdminServiceStub = Mockito.mock(EventStreamAdminServiceStub.class, Mockito.RETURNS_MOCKS);
|
||||
demoDevice = DeviceMgtAPITestHelper.generateDummyDevice(TEST_DEVICE_TYPE, TEST_DEVICE_IDENTIFIER);
|
||||
this.cacheManager = Mockito.mock(CacheManager.class, Mockito.RETURNS_MOCKS);
|
||||
}
|
||||
|
||||
@Test(description = "Test device Enrollment when the device is null")
|
||||
public void testEnrollDeviceWithDeviceIsNULL() {
|
||||
PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getDeviceManagementService"))
|
||||
.toReturn(this.deviceManagementProviderService);
|
||||
Response response = this.deviceAgentService.enrollDevice(null);
|
||||
|
||||
Assert.assertNotNull(response, "Response should not be null");
|
||||
Assert.assertEquals(response.getStatus(), Response.Status.BAD_REQUEST.getStatusCode(),
|
||||
"The response status should be 400");
|
||||
}
|
||||
|
||||
@Test(description = "Test device enrollment when device type is null.")
|
||||
public void testEnrollDeviceWithDeviceTypeNull() {
|
||||
PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getDeviceManagementService"))
|
||||
.toReturn(this.deviceManagementProviderService);
|
||||
Device device = DeviceMgtAPITestHelper.generateDummyDevice(null, TEST_DEVICE_IDENTIFIER);
|
||||
Response response = this.deviceAgentService.enrollDevice(device);
|
||||
|
||||
Assert.assertNotNull(response, "Response should not be null");
|
||||
Assert.assertEquals(response.getStatus(), Response.Status.BAD_REQUEST.getStatusCode(),
|
||||
"The response status should be 400");
|
||||
}
|
||||
|
||||
@Test(description = "Test device enrollment of a device with null device identifier.")
|
||||
public void testEnrollNewDeviceWithDeviceIdentifierIsNull() {
|
||||
PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getDeviceManagementService"))
|
||||
.toReturn(this.deviceManagementProviderService);
|
||||
Device device = DeviceMgtAPITestHelper.generateDummyDevice(TEST_DEVICE_TYPE, null);
|
||||
Response response = this.deviceAgentService.enrollDevice(device);
|
||||
|
||||
Assert.assertNotNull(response, "Response should not be null");
|
||||
Assert.assertEquals(response.getStatus(), Response.Status.BAD_REQUEST.getStatusCode(),
|
||||
"The response status should be 400");
|
||||
}
|
||||
|
||||
@Test(description = "Test an already enrolled device")
|
||||
public void testEnrollExistingDevice() throws DeviceManagementException {
|
||||
PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getDeviceManagementService"))
|
||||
.toReturn(this.deviceManagementProviderService);
|
||||
Mockito.when(this.deviceManagementProviderService.getDevice(Mockito.any())).thenReturn(demoDevice);
|
||||
Device device = DeviceMgtAPITestHelper.generateDummyDevice(TEST_DEVICE_TYPE, TEST_DEVICE_IDENTIFIER);
|
||||
Mockito.when(this.deviceManagementProviderService.getDevice(Mockito.any())).thenReturn(device);
|
||||
Response response = this.deviceAgentService.enrollDevice(device);
|
||||
Assert.assertNotNull(response, "Response should not be null");
|
||||
Assert.assertEquals(response.getStatus(), Response.Status.BAD_REQUEST.getStatusCode(),
|
||||
"The response status should be 400");
|
||||
Mockito.reset(this.deviceManagementProviderService);
|
||||
}
|
||||
|
||||
@Test(description = "Test the device enrollment success scenario.")
|
||||
public void testEnrollDeviceSuccess() throws DeviceManagementException {
|
||||
PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getDeviceManagementService"))
|
||||
.toReturn(this.deviceManagementProviderService);
|
||||
PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getAuthenticatedUser"))
|
||||
.toReturn(AUTHENTICATED_USER);
|
||||
|
||||
EnrolmentInfo enrolmentInfo = demoDevice.getEnrolmentInfo();
|
||||
enrolmentInfo.setStatus(EnrolmentInfo.Status.INACTIVE);
|
||||
demoDevice.setEnrolmentInfo(enrolmentInfo);
|
||||
Mockito.when(this.deviceManagementProviderService.getDevice(Mockito.any())).thenReturn(demoDevice);
|
||||
|
||||
Response response = this.deviceAgentService.enrollDevice(demoDevice);
|
||||
Assert.assertNotNull(response, "Response should not be null");
|
||||
Assert.assertEquals(response.getStatus(), Response.Status.OK.getStatusCode(),
|
||||
"The response status should be 200");
|
||||
Mockito.reset(this.deviceManagementProviderService);
|
||||
}
|
||||
|
||||
@Test(description = "Test the device enrollment with device management exception.")
|
||||
public void testEnrollDeviceWithException() throws DeviceManagementException {
|
||||
PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getDeviceManagementService"))
|
||||
.toReturn(this.deviceManagementProviderService);
|
||||
PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getAuthenticatedUser"))
|
||||
.toReturn(AUTHENTICATED_USER);
|
||||
|
||||
Device device = DeviceMgtAPITestHelper.generateDummyDevice(TEST_DEVICE_TYPE, TEST_DEVICE_IDENTIFIER);
|
||||
EnrolmentInfo enrolmentInfo = device.getEnrolmentInfo();
|
||||
enrolmentInfo.setStatus(EnrolmentInfo.Status.INACTIVE);
|
||||
device.setEnrolmentInfo(enrolmentInfo);
|
||||
Mockito.when(this.deviceManagementProviderService.getDevice(Mockito.any())).thenReturn(device);
|
||||
Mockito.when(this.deviceManagementProviderService.enrollDevice(Mockito.any()))
|
||||
.thenThrow(new DeviceManagementException());
|
||||
|
||||
Response response = this.deviceAgentService.enrollDevice(device);
|
||||
Assert.assertNotNull(response, "Response should not be null");
|
||||
Assert.assertEquals(response.getStatus(), Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(),
|
||||
"The response status should be 500");
|
||||
Mockito.reset(this.deviceManagementProviderService);
|
||||
}
|
||||
|
||||
@Test(description = "Test dis-enrolling the device success scenario.")
|
||||
public void testDisEnrollDeviceSuccess() throws DeviceManagementException {
|
||||
PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getDeviceManagementService"))
|
||||
.toReturn(this.deviceManagementProviderService);
|
||||
Mockito.when(this.deviceManagementProviderService.disenrollDevice(Mockito.any())).thenReturn(true);
|
||||
Response response = deviceAgentService.disEnrollDevice(TEST_DEVICE_TYPE, TEST_DEVICE_IDENTIFIER);
|
||||
Assert.assertNotNull(response, "Response should not be null");
|
||||
Assert.assertEquals(response.getStatus(), Response.Status.OK.getStatusCode(),
|
||||
"The response status should be 200");
|
||||
Mockito.reset(this.deviceManagementProviderService);
|
||||
}
|
||||
|
||||
@Test(description = "Test dis-enrolling non existing device.")
|
||||
public void testDisEnrollNonExistingDevice() throws DeviceManagementException {
|
||||
PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getDeviceManagementService"))
|
||||
.toReturn(this.deviceManagementProviderService);
|
||||
Response response = deviceAgentService.disEnrollDevice(TEST_DEVICE_TYPE, TEST_DEVICE_IDENTIFIER);
|
||||
Assert.assertNotNull(response, "Response should not be null");
|
||||
Assert.assertEquals(response.getStatus(), Response.Status.NO_CONTENT.getStatusCode(),
|
||||
"The response status should be 204");
|
||||
}
|
||||
|
||||
@Test(description = "Test dis-enrolling device error")
|
||||
public void testDisEnrollingDeviceError() throws DeviceManagementException {
|
||||
PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getDeviceManagementService"))
|
||||
.toReturn(this.deviceManagementProviderService);
|
||||
Mockito.when(this.deviceManagementProviderService.disenrollDevice(Mockito.any())).thenThrow(new
|
||||
DeviceManagementException());
|
||||
Response response = deviceAgentService.disEnrollDevice(TEST_DEVICE_TYPE, TEST_DEVICE_IDENTIFIER);
|
||||
Assert.assertNotNull(response, "Response should not be null");
|
||||
Assert.assertEquals(response.getStatus(), Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(),
|
||||
"The response status should be 500");
|
||||
Mockito.reset(this.deviceManagementProviderService);
|
||||
}
|
||||
|
||||
@Test(description = "Test device update scenario with device management exception.")
|
||||
public void testUpdateDeviceDMException() throws DeviceManagementException {
|
||||
PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getDeviceManagementService"))
|
||||
.toReturn(this.deviceManagementProviderService);
|
||||
Mockito.when(this.deviceManagementProviderService.getDevice(Mockito.any())).thenThrow(new
|
||||
DeviceManagementException());
|
||||
Device testDevice = DeviceMgtAPITestHelper.generateDummyDevice(TEST_DEVICE_TYPE, TEST_DEVICE_IDENTIFIER);
|
||||
Response response = deviceAgentService.updateDevice(TEST_DEVICE_TYPE, TEST_DEVICE_IDENTIFIER, testDevice);
|
||||
|
||||
Assert.assertNotNull(response, "Response should not be null");
|
||||
Assert.assertEquals(response.getStatus(), Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(),
|
||||
"The response status should be 500");
|
||||
Mockito.reset(this.deviceManagementProviderService);
|
||||
}
|
||||
|
||||
@Test(description = "Test update device scenario when the device is null.")
|
||||
public void testUpdateDeviceWithNoDevice() {
|
||||
PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getDeviceManagementService"))
|
||||
.toReturn(this.deviceManagementProviderService);
|
||||
Response response = deviceAgentService.updateDevice(TEST_DEVICE_TYPE, TEST_DEVICE_IDENTIFIER, null);
|
||||
|
||||
Assert.assertNotNull(response, "Response should not be null");
|
||||
Assert.assertEquals(response.getStatus(), Response.Status.BAD_REQUEST.getStatusCode(),
|
||||
"The response status should be 400");
|
||||
}
|
||||
|
||||
@Test(description = "Test the update device scenario when there is no enrolled device.")
|
||||
public void testUpdatingNonExistingDevice() throws DeviceManagementException {
|
||||
PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getDeviceManagementService"))
|
||||
.toReturn(this.deviceManagementProviderService);
|
||||
Mockito.when(this.deviceManagementProviderService.getDevice(Mockito.any())).thenReturn(null);
|
||||
Device testDevice = DeviceMgtAPITestHelper.generateDummyDevice(TEST_DEVICE_TYPE, TEST_DEVICE_IDENTIFIER);
|
||||
Response response = deviceAgentService.updateDevice(TEST_DEVICE_TYPE, TEST_DEVICE_IDENTIFIER, testDevice);
|
||||
|
||||
Assert.assertNotNull(response, "Response should not be null");
|
||||
Assert.assertEquals(response.getStatus(), Response.Status.NOT_FOUND.getStatusCode(),
|
||||
"The response status should be 404");
|
||||
Mockito.reset(this.deviceManagementProviderService);
|
||||
}
|
||||
|
||||
@Test(description = "Test update device with device access authorization exception.")
|
||||
public void testEnrollDeviceWithDeviceAccessAuthException() throws DeviceManagementException,
|
||||
DeviceAccessAuthorizationException {
|
||||
PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getDeviceManagementService"))
|
||||
.toReturn(this.deviceManagementProviderService);
|
||||
PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class,
|
||||
"getDeviceAccessAuthorizationService")).toReturn(this.deviceAccessAuthorizationService);
|
||||
Device testDevice = DeviceMgtAPITestHelper.generateDummyDevice(TEST_DEVICE_TYPE, TEST_DEVICE_IDENTIFIER);
|
||||
|
||||
Mockito.when(this.deviceManagementProviderService.getDevice(Mockito.any())).thenReturn(testDevice);
|
||||
Mockito.when(this.deviceAccessAuthorizationService.isUserAuthorized(Mockito.any(DeviceIdentifier.class)))
|
||||
.thenThrow(new DeviceAccessAuthorizationException());
|
||||
Response response = deviceAgentService.updateDevice(TEST_DEVICE_TYPE, TEST_DEVICE_IDENTIFIER, testDevice);
|
||||
Assert.assertNotNull(response, "Response should not be null");
|
||||
Assert.assertEquals(response.getStatus(), Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(),
|
||||
"The response status should be 500");
|
||||
Mockito.reset(this.deviceManagementProviderService);
|
||||
Mockito.reset(this.deviceAccessAuthorizationService);
|
||||
}
|
||||
|
||||
@Test(description = "Test update device when user does not have device access permission.")
|
||||
public void testUpdateDeviceWithNoDeviceAccessPermission() throws DeviceManagementException,
|
||||
DeviceAccessAuthorizationException {
|
||||
PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getDeviceManagementService"))
|
||||
.toReturn(this.deviceManagementProviderService);
|
||||
PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class,
|
||||
"getDeviceAccessAuthorizationService")).toReturn(this.deviceAccessAuthorizationService);
|
||||
Device testDevice = DeviceMgtAPITestHelper.generateDummyDevice(TEST_DEVICE_TYPE, TEST_DEVICE_IDENTIFIER);
|
||||
|
||||
Mockito.when(this.deviceManagementProviderService.getDevice(Mockito.any())).thenReturn(testDevice);
|
||||
Mockito.when(this.deviceAccessAuthorizationService.isUserAuthorized(Mockito.any(DeviceIdentifier.class)))
|
||||
.thenReturn(false);
|
||||
Response response = deviceAgentService.updateDevice(TEST_DEVICE_TYPE, TEST_DEVICE_IDENTIFIER, testDevice);
|
||||
Assert.assertNotNull(response, "Response should not be null");
|
||||
Assert.assertEquals(response.getStatus(), Response.Status.UNAUTHORIZED.getStatusCode(),
|
||||
"The response status should be 401");
|
||||
Mockito.reset(this.deviceManagementProviderService);
|
||||
Mockito.reset(this.deviceAccessAuthorizationService);
|
||||
}
|
||||
|
||||
@Test(description = "Test update device when device modification is unsuccessful.")
|
||||
public void testUpdateDeviceNOTModify() throws DeviceManagementException, DeviceAccessAuthorizationException {
|
||||
PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getDeviceManagementService"))
|
||||
.toReturn(this.deviceManagementProviderService);
|
||||
PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class,
|
||||
"getDeviceAccessAuthorizationService")).toReturn(this.deviceAccessAuthorizationService);
|
||||
PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class,
|
||||
"getAuthenticatedUser")).toReturn(AUTHENTICATED_USER);
|
||||
|
||||
Device testDevice = DeviceMgtAPITestHelper.generateDummyDevice(TEST_DEVICE_TYPE, TEST_DEVICE_IDENTIFIER);
|
||||
|
||||
Mockito.when(this.deviceManagementProviderService.getDevice(Mockito.any())).thenReturn(testDevice);
|
||||
Mockito.when(this.deviceAccessAuthorizationService.isUserAuthorized(Mockito.any(DeviceIdentifier.class)))
|
||||
.thenReturn(true);
|
||||
Mockito.when(this.deviceManagementProviderService.modifyEnrollment(Mockito.any())).thenReturn(false);
|
||||
Response response = deviceAgentService.updateDevice(TEST_DEVICE_TYPE, TEST_DEVICE_IDENTIFIER, testDevice);
|
||||
Assert.assertNotNull(response, "Response should not be null");
|
||||
Assert.assertEquals(response.getStatus(), Response.Status.NOT_MODIFIED.getStatusCode(),
|
||||
"The response status should be 304");
|
||||
Mockito.reset(this.deviceManagementProviderService);
|
||||
Mockito.reset(this.deviceAccessAuthorizationService);
|
||||
}
|
||||
|
||||
@Test(description = "Test updating device when modify enrollment throws exception")
|
||||
public void testUpdateDeviceWithModifyEnrollmentFailure() throws DeviceManagementException, DeviceAccessAuthorizationException {
|
||||
PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getDeviceManagementService"))
|
||||
.toReturn(this.deviceManagementProviderService);
|
||||
PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class,
|
||||
"getDeviceAccessAuthorizationService")).toReturn(this.deviceAccessAuthorizationService);
|
||||
PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class,
|
||||
"getAuthenticatedUser")).toReturn(AUTHENTICATED_USER);
|
||||
|
||||
Device testDevice = DeviceMgtAPITestHelper.generateDummyDevice(TEST_DEVICE_TYPE, TEST_DEVICE_IDENTIFIER);
|
||||
|
||||
Mockito.when(this.deviceManagementProviderService.getDevice(Mockito.any())).thenReturn(testDevice);
|
||||
Mockito.when(this.deviceAccessAuthorizationService.isUserAuthorized(Mockito.any(DeviceIdentifier.class)))
|
||||
.thenReturn(true);
|
||||
Mockito.when(this.deviceManagementProviderService.modifyEnrollment(Mockito.any())).thenThrow(new DeviceManagementException());
|
||||
Response response = deviceAgentService.updateDevice(TEST_DEVICE_TYPE, TEST_DEVICE_IDENTIFIER, testDevice);
|
||||
Assert.assertNotNull(response, "Response should not be null");
|
||||
Assert.assertEquals(response.getStatus(), Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(),
|
||||
"The response status should be 500");
|
||||
Mockito.reset(this.deviceManagementProviderService);
|
||||
Mockito.reset(this.deviceAccessAuthorizationService);
|
||||
}
|
||||
@Test(description = "Test updating device success scenario.")
|
||||
public void testUpdateDeviceSuccess() throws DeviceManagementException, DeviceAccessAuthorizationException {
|
||||
PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getDeviceManagementService"))
|
||||
.toReturn(this.deviceManagementProviderService);
|
||||
PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class,
|
||||
"getDeviceAccessAuthorizationService")).toReturn(this.deviceAccessAuthorizationService);
|
||||
PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class,
|
||||
"getAuthenticatedUser")).toReturn(AUTHENTICATED_USER);
|
||||
|
||||
Device testDevice = DeviceMgtAPITestHelper.generateDummyDevice(TEST_DEVICE_TYPE, TEST_DEVICE_IDENTIFIER);
|
||||
|
||||
Mockito.when(this.deviceManagementProviderService.getDevice(Mockito.any())).thenReturn(testDevice);
|
||||
Mockito.when(this.deviceAccessAuthorizationService.isUserAuthorized(Mockito.any(DeviceIdentifier.class)))
|
||||
.thenReturn(true);
|
||||
Mockito.when(this.deviceManagementProviderService.modifyEnrollment(Mockito.any())).thenReturn((true));
|
||||
Response response = deviceAgentService.updateDevice(TEST_DEVICE_TYPE, TEST_DEVICE_IDENTIFIER, testDevice);
|
||||
Assert.assertNotNull(response, "Response should not be null");
|
||||
Assert.assertEquals(response.getStatus(), Response.Status.ACCEPTED.getStatusCode(),
|
||||
"The response status should be 202");
|
||||
Mockito.reset(this.deviceManagementProviderService);
|
||||
Mockito.reset(this.deviceAccessAuthorizationService);
|
||||
}
|
||||
|
||||
@Test(description = "Test publish events with null payload.")
|
||||
public void testPublishEventsWithNullPayload() {
|
||||
PowerMockito.stub(PowerMockito.method(PrivilegedCarbonContext.class, "getThreadLocalCarbonContext"))
|
||||
.toReturn(this.privilegedCarbonContext);
|
||||
Mockito.when(this.privilegedCarbonContext.getTenantDomain()).thenReturn(TENANT_DOMAIN);
|
||||
|
||||
Map<String, Object> payload = null;
|
||||
Response response = this.deviceAgentService.publishEvents(payload, TEST_DEVICE_TYPE, TEST_DEVICE_IDENTIFIER);
|
||||
Assert.assertNotNull(response, "Response should not be null");
|
||||
Assert.assertEquals(response.getStatus(), Response.Status.BAD_REQUEST.getStatusCode(),
|
||||
"The response status should be 400");
|
||||
}
|
||||
|
||||
@Test(description = "Test publish events with no device access authorization.")
|
||||
public void testPublishEventsWithOutAuthorization() throws DeviceAccessAuthorizationException {
|
||||
PowerMockito.stub(PowerMockito.method(PrivilegedCarbonContext.class, "getThreadLocalCarbonContext"))
|
||||
.toReturn(this.privilegedCarbonContext);
|
||||
PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class,
|
||||
"getDeviceAccessAuthorizationService")).toReturn(this.deviceAccessAuthorizationService);
|
||||
|
||||
Mockito.when(this.deviceAccessAuthorizationService.isUserAuthorized(Mockito.any(DeviceIdentifier.class)))
|
||||
.thenReturn(false);
|
||||
Mockito.when(this.privilegedCarbonContext.getTenantDomain()).thenReturn(TENANT_DOMAIN);
|
||||
Map<String, Object> payload = new HashMap<>();
|
||||
Response response = this.deviceAgentService.publishEvents(payload, TEST_DEVICE_TYPE, TEST_DEVICE_IDENTIFIER);
|
||||
Assert.assertNotNull(response, "Response should not be null");
|
||||
Assert.assertEquals(response.getStatus(), Response.Status.UNAUTHORIZED.getStatusCode(),
|
||||
"The response status should be 401");
|
||||
Mockito.reset(this.deviceAccessAuthorizationService);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testPublishEventsWithDeviceAccessAuthException() throws DeviceAccessAuthorizationException {
|
||||
PowerMockito.stub(PowerMockito.method(PrivilegedCarbonContext.class, "getThreadLocalCarbonContext"))
|
||||
.toReturn(this.privilegedCarbonContext);
|
||||
PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getDeviceAccessAuthorizationService"))
|
||||
.toReturn(this.deviceAccessAuthorizationService);
|
||||
Mockito.when(this.deviceAccessAuthorizationService.isUserAuthorized(Mockito.any(DeviceIdentifier.class)))
|
||||
.thenThrow(new DeviceAccessAuthorizationException());
|
||||
Mockito.when(this.privilegedCarbonContext.getTenantDomain()).thenReturn(TENANT_DOMAIN);
|
||||
Map<String, Object> payload = new HashMap<>();
|
||||
Response response = this.deviceAgentService.publishEvents(payload, TEST_DEVICE_TYPE, TEST_DEVICE_IDENTIFIER);
|
||||
Assert.assertNotNull(response, "Response should not be null");
|
||||
Assert.assertEquals(response.getStatus(), Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(),
|
||||
"The response status should be 500");
|
||||
Mockito.reset(this.deviceAccessAuthorizationService);
|
||||
}
|
||||
|
||||
@Test(description = "Test event publishing when the event stream dao is null.")
|
||||
public void testEventPublishWithNullEventAttributesAndNullEventStreamDefDAO() throws DeviceAccessAuthorizationException, RemoteException {
|
||||
PowerMockito.stub(PowerMockito.method(PrivilegedCarbonContext.class, "getThreadLocalCarbonContext"))
|
||||
.toReturn(this.privilegedCarbonContext);
|
||||
PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getDeviceAccessAuthorizationService"))
|
||||
.toReturn(this.deviceAccessAuthorizationService);
|
||||
Mockito.when(this.deviceAccessAuthorizationService.isUserAuthorized(Mockito.any(DeviceIdentifier.class)))
|
||||
.thenReturn(true);
|
||||
PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getEventStreamAdminServiceStub"))
|
||||
.toReturn(this.eventStreamAdminServiceStub);
|
||||
Mockito.when(this.eventStreamAdminServiceStub.getStreamDefinitionDto(Mockito.anyString())).thenReturn(null);
|
||||
|
||||
Map<String, Object> payload = new HashMap<>();
|
||||
CacheImpl cache = Mockito.mock(CacheImpl.class);
|
||||
|
||||
PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getDynamicEventCache"))
|
||||
.toReturn(cache);
|
||||
|
||||
Response response = this.deviceAgentService.publishEvents(payload, TEST_DEVICE_TYPE, TEST_DEVICE_IDENTIFIER);
|
||||
Assert.assertNotNull(response, "Response should not be null");
|
||||
Assert.assertEquals(response.getStatus(), Response.Status.BAD_REQUEST.getStatusCode(),
|
||||
"The response status should be 400");
|
||||
Mockito.reset(eventStreamAdminServiceStub);
|
||||
}
|
||||
|
||||
@Test(description ="Test the error scenario of Publishing Events with null event attributes.")
|
||||
public void testEventPublishWithEventAttributesNULLAndPublishEventsFailure() throws
|
||||
DeviceAccessAuthorizationException, RemoteException {
|
||||
PowerMockito.stub(PowerMockito.method(PrivilegedCarbonContext.class, "getThreadLocalCarbonContext"))
|
||||
.toReturn(this.privilegedCarbonContext);
|
||||
PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class,
|
||||
"getDeviceAccessAuthorizationService")).toReturn(this.deviceAccessAuthorizationService);
|
||||
Mockito.when(this.deviceAccessAuthorizationService.isUserAuthorized(Mockito.any(DeviceIdentifier.class)))
|
||||
.thenReturn(true);
|
||||
PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getEventStreamAdminServiceStub"))
|
||||
.toReturn(this.eventStreamAdminServiceStub);
|
||||
EventStreamAttributeDto eventStreamAttributeDto = Mockito.mock(EventStreamAttributeDto.class,
|
||||
Mockito.RETURNS_MOCKS);
|
||||
EventStreamDefinitionDto eventStreamDefinitionDto = Mockito.mock(EventStreamDefinitionDto.class,
|
||||
Mockito.RETURNS_MOCKS);
|
||||
Mockito.when(this.eventStreamAdminServiceStub.getStreamDefinitionDto(Mockito.anyString()))
|
||||
.thenReturn(eventStreamDefinitionDto);
|
||||
Mockito.when(eventStreamDefinitionDto.getPayloadData()).thenReturn(new EventStreamAttributeDto[]{});
|
||||
EventsPublisherService eventPublisherService = Mockito.mock(EventsPublisherServiceImpl.class,
|
||||
Mockito.RETURNS_MOCKS);
|
||||
PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getEventPublisherService")).toReturn
|
||||
(eventPublisherService);
|
||||
|
||||
Map<String, Object> payload = new HashMap<>();
|
||||
CacheImpl cache = Mockito.mock(CacheImpl.class);
|
||||
|
||||
PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getDynamicEventCache"))
|
||||
.toReturn(cache);
|
||||
|
||||
Response response = this.deviceAgentService.publishEvents(payload, TEST_DEVICE_TYPE, TEST_DEVICE_IDENTIFIER);
|
||||
Assert.assertNotNull(response, "Response should not be null");
|
||||
Assert.assertEquals(response.getStatus(), Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(),
|
||||
"The response status should be 500");
|
||||
}
|
||||
|
||||
@Test(description = "Test Event publishing success scenario.")
|
||||
public void testEventPublishWithEventAttributesNULLAndPublishEventsSuccess()
|
||||
throws DeviceAccessAuthorizationException, RemoteException, DataPublisherConfigurationException {
|
||||
PowerMockito.stub(PowerMockito.method(PrivilegedCarbonContext.class, "getThreadLocalCarbonContext"))
|
||||
.toReturn(this.privilegedCarbonContext);
|
||||
PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class,
|
||||
"getDeviceAccessAuthorizationService")).toReturn(this.deviceAccessAuthorizationService);
|
||||
Mockito.when(this.deviceAccessAuthorizationService.isUserAuthorized(Mockito.any(DeviceIdentifier.class)))
|
||||
.thenReturn(true);
|
||||
PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getEventStreamAdminServiceStub"))
|
||||
.toReturn(this.eventStreamAdminServiceStub);
|
||||
EventStreamAttributeDto eventStreamAttributeDto = Mockito.mock(EventStreamAttributeDto.class,
|
||||
Mockito.RETURNS_MOCKS);
|
||||
EventStreamDefinitionDto eventStreamDefinitionDto = Mockito.mock(EventStreamDefinitionDto.class,
|
||||
Mockito.RETURNS_MOCKS);
|
||||
Mockito.when(this.eventStreamAdminServiceStub.getStreamDefinitionDto(Mockito.anyString()))
|
||||
.thenReturn(eventStreamDefinitionDto);
|
||||
Mockito.when(eventStreamDefinitionDto.getPayloadData()).thenReturn(new EventStreamAttributeDto[]{});
|
||||
EventsPublisherService eventPublisherService = Mockito.mock(EventsPublisherServiceImpl.class,
|
||||
Mockito.RETURNS_MOCKS);
|
||||
PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getEventPublisherService")).toReturn
|
||||
(eventPublisherService);
|
||||
Mockito.when(eventPublisherService.publishEvent(Mockito.anyString(), Mockito.anyString(), Mockito.any(),
|
||||
Mockito.any(), Mockito.any())).thenReturn(true);
|
||||
|
||||
Map<String, Object> payload = new HashMap<>();
|
||||
CacheImpl cache = Mockito.mock(CacheImpl.class);
|
||||
|
||||
PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getDynamicEventCache"))
|
||||
.toReturn(cache);
|
||||
|
||||
Response response = this.deviceAgentService.publishEvents(payload, TEST_DEVICE_TYPE, TEST_DEVICE_IDENTIFIER);
|
||||
Assert.assertNotNull(response, "Response should not be null");
|
||||
Assert.assertEquals(response.getStatus(), Response.Status.OK.getStatusCode(),
|
||||
"The response status should be 200");
|
||||
}
|
||||
|
||||
@Test(description = "Test event publishing when PublishEvents throws DataPublisherConfigurationException.")
|
||||
public void testPublishEventsDataPublisherConfig() throws DeviceAccessAuthorizationException, RemoteException, DataPublisherConfigurationException {
|
||||
PowerMockito.stub(PowerMockito.method(PrivilegedCarbonContext.class, "getThreadLocalCarbonContext"))
|
||||
.toReturn(this.privilegedCarbonContext);
|
||||
PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class,
|
||||
"getDeviceAccessAuthorizationService")).toReturn(this.deviceAccessAuthorizationService);
|
||||
Mockito.when(this.deviceAccessAuthorizationService.isUserAuthorized(Mockito.any(DeviceIdentifier.class)))
|
||||
.thenReturn(true);
|
||||
PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getEventStreamAdminServiceStub"))
|
||||
.toReturn(this.eventStreamAdminServiceStub);
|
||||
EventStreamAttributeDto eventStreamAttributeDto = Mockito.mock(EventStreamAttributeDto.class,
|
||||
Mockito.RETURNS_MOCKS);
|
||||
EventStreamDefinitionDto eventStreamDefinitionDto = Mockito.mock(EventStreamDefinitionDto.class,
|
||||
Mockito.RETURNS_MOCKS);
|
||||
Mockito.when(this.eventStreamAdminServiceStub.getStreamDefinitionDto(Mockito.anyString()))
|
||||
.thenReturn(eventStreamDefinitionDto);
|
||||
Mockito.when(eventStreamDefinitionDto.getPayloadData()).thenReturn(new EventStreamAttributeDto[]{});
|
||||
EventsPublisherService eventPublisherService = Mockito.mock(EventsPublisherServiceImpl.class,
|
||||
Mockito.RETURNS_MOCKS);
|
||||
PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getEventPublisherService"))
|
||||
.toReturn(eventPublisherService);
|
||||
Mockito.when(eventPublisherService.publishEvent(Mockito.anyString(), Mockito.anyString(), Mockito.any(),
|
||||
Mockito.any(), Mockito.any())).thenThrow(
|
||||
new DataPublisherConfigurationException("meta data[0] should have the device Id field"));
|
||||
|
||||
Map<String, Object> payload = new HashMap<>();
|
||||
CacheImpl cache = Mockito.mock(CacheImpl.class);
|
||||
|
||||
PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getDynamicEventCache"))
|
||||
.toReturn(cache);
|
||||
|
||||
Response response = this.deviceAgentService.publishEvents(payload, TEST_DEVICE_TYPE, TEST_DEVICE_IDENTIFIER);
|
||||
Assert.assertNotNull(response, "Response should not be null");
|
||||
Assert.assertEquals(response.getStatus(), Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(),
|
||||
"The response status should be 500");
|
||||
}
|
||||
|
||||
@Test(description = "Test Publish events with Axis Fault.")
|
||||
public void testPublishEventsWithAxisFault() throws DeviceAccessAuthorizationException {
|
||||
PowerMockito.stub(PowerMockito.method(PrivilegedCarbonContext.class, "getThreadLocalCarbonContext"))
|
||||
.toReturn(this.privilegedCarbonContext);
|
||||
PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class,
|
||||
"getDeviceAccessAuthorizationService")).toReturn(this.deviceAccessAuthorizationService);
|
||||
Mockito.when(this.deviceAccessAuthorizationService.isUserAuthorized(Mockito.any(DeviceIdentifier.class)))
|
||||
.thenReturn(true);
|
||||
PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getEventStreamAdminServiceStub"))
|
||||
.toThrow(new AxisFault(""));
|
||||
Map<String, Object> payload = new HashMap<>();
|
||||
CacheImpl cache = Mockito.mock(CacheImpl.class);
|
||||
|
||||
PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getDynamicEventCache"))
|
||||
.toReturn(cache);
|
||||
|
||||
Response response = this.deviceAgentService.publishEvents(payload, TEST_DEVICE_TYPE, TEST_DEVICE_IDENTIFIER);
|
||||
Assert.assertNotNull(response, "Response should not be null");
|
||||
Assert.assertEquals(response.getStatus(), Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(),
|
||||
"The response status should be 500");
|
||||
}
|
||||
|
||||
@Test(description = "Test Publishing events when EventStreamAdminService throws Remote exception.")
|
||||
public void testPublishEventsWithRemoteException() throws DeviceAccessAuthorizationException {
|
||||
PowerMockito.stub(PowerMockito.method(PrivilegedCarbonContext.class, "getThreadLocalCarbonContext"))
|
||||
.toReturn(this.privilegedCarbonContext);
|
||||
PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class,
|
||||
"getDeviceAccessAuthorizationService")).toReturn(this.deviceAccessAuthorizationService);
|
||||
Mockito.when(this.deviceAccessAuthorizationService.isUserAuthorized(Mockito.any(DeviceIdentifier.class)))
|
||||
.thenReturn(true);
|
||||
PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getEventStreamAdminServiceStub"))
|
||||
.toThrow(new RemoteException());
|
||||
Map<String, Object> payload = new HashMap<>();
|
||||
CacheImpl cache = Mockito.mock(CacheImpl.class);
|
||||
|
||||
PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getDynamicEventCache"))
|
||||
.toReturn(cache);
|
||||
|
||||
Response response = this.deviceAgentService.publishEvents(payload, TEST_DEVICE_TYPE, TEST_DEVICE_IDENTIFIER);
|
||||
Assert.assertNotNull(response, "Response should not be null");
|
||||
Assert.assertEquals(response.getStatus(), Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(),
|
||||
"The response status should be 500");
|
||||
}
|
||||
|
||||
@Test(description = "Test Publishing events when EventStreamAdminService throws JWT exception.")
|
||||
public void testPublishEventsWithJWTException() throws DeviceAccessAuthorizationException {
|
||||
PowerMockito.stub(PowerMockito.method(PrivilegedCarbonContext.class, "getThreadLocalCarbonContext"))
|
||||
.toReturn(this.privilegedCarbonContext);
|
||||
PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class,
|
||||
"getDeviceAccessAuthorizationService")).toReturn(this.deviceAccessAuthorizationService);
|
||||
Mockito.when(this.deviceAccessAuthorizationService.isUserAuthorized(Mockito.any(DeviceIdentifier.class)))
|
||||
.thenReturn(true);
|
||||
PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getEventStreamAdminServiceStub"))
|
||||
.toThrow(new JWTClientException());
|
||||
Map<String, Object> payload = new HashMap<>();
|
||||
CacheImpl cache = Mockito.mock(CacheImpl.class);
|
||||
|
||||
PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getDynamicEventCache"))
|
||||
.toReturn(cache);
|
||||
|
||||
Response response = this.deviceAgentService.publishEvents(payload, TEST_DEVICE_TYPE, TEST_DEVICE_IDENTIFIER);
|
||||
Assert.assertNotNull(response, "Response should not be null");
|
||||
Assert.assertEquals(response.getStatus(), Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(),
|
||||
"The response status should be 500");
|
||||
}
|
||||
|
||||
@Test(description = "Test Publishing events when EventStreamAdminService throws User Store exception.")
|
||||
public void testPublishEventsWithUserStoreException() throws DeviceAccessAuthorizationException {
|
||||
PowerMockito.stub(PowerMockito.method(PrivilegedCarbonContext.class, "getThreadLocalCarbonContext"))
|
||||
.toReturn(this.privilegedCarbonContext);
|
||||
PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class,
|
||||
"getDeviceAccessAuthorizationService")).toReturn(this.deviceAccessAuthorizationService);
|
||||
Mockito.when(this.deviceAccessAuthorizationService.isUserAuthorized(Mockito.any(DeviceIdentifier.class)))
|
||||
.thenReturn(true);
|
||||
PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getEventStreamAdminServiceStub"))
|
||||
.toThrow(new UserStoreException());
|
||||
Map<String, Object> payload = new HashMap<>();
|
||||
CacheImpl cache = Mockito.mock(CacheImpl.class);
|
||||
|
||||
PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getDynamicEventCache"))
|
||||
.toReturn(cache);
|
||||
|
||||
Response response = this.deviceAgentService.publishEvents(payload, TEST_DEVICE_TYPE, TEST_DEVICE_IDENTIFIER);
|
||||
Assert.assertNotNull(response, "Response should not be null");
|
||||
Assert.assertEquals(response.getStatus(), Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(),
|
||||
"The response status should be 500");
|
||||
}
|
||||
}
|
@ -0,0 +1,556 @@
|
||||
/*
|
||||
* 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.apache.commons.logging.Log;
|
||||
import org.apache.commons.logging.LogFactory;
|
||||
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.DeviceIdentifier;
|
||||
import org.wso2.carbon.device.mgt.common.DeviceManagementException;
|
||||
import org.wso2.carbon.device.mgt.common.PaginationRequest;
|
||||
import org.wso2.carbon.device.mgt.common.app.mgt.ApplicationManagementException;
|
||||
import org.wso2.carbon.device.mgt.common.authorization.DeviceAccessAuthorizationException;
|
||||
import org.wso2.carbon.device.mgt.common.authorization.DeviceAccessAuthorizationService;
|
||||
import org.wso2.carbon.device.mgt.common.operation.mgt.OperationManagementException;
|
||||
import org.wso2.carbon.device.mgt.common.search.SearchContext;
|
||||
import org.wso2.carbon.device.mgt.core.app.mgt.ApplicationManagementProviderService;
|
||||
import org.wso2.carbon.device.mgt.core.authorization.DeviceAccessAuthorizationServiceImpl;
|
||||
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.device.details.mgt.impl.DeviceInformationManagerImpl;
|
||||
import org.wso2.carbon.device.mgt.core.search.mgt.SearchManagerService;
|
||||
import org.wso2.carbon.device.mgt.core.search.mgt.SearchMgtException;
|
||||
import org.wso2.carbon.device.mgt.core.search.mgt.impl.SearchManagerServiceImpl;
|
||||
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.service.api.DeviceManagementService;
|
||||
import org.wso2.carbon.device.mgt.jaxrs.util.DeviceMgtAPIUtils;
|
||||
import org.wso2.carbon.policy.mgt.common.PolicyManagementException;
|
||||
import org.wso2.carbon.policy.mgt.core.PolicyManagerService;
|
||||
import org.wso2.carbon.utils.multitenancy.MultitenantUtils;
|
||||
|
||||
import java.text.SimpleDateFormat;
|
||||
import java.util.Date;
|
||||
import java.util.UUID;
|
||||
import javax.ws.rs.core.Response;
|
||||
|
||||
import static org.mockito.MockitoAnnotations.initMocks;
|
||||
|
||||
/**
|
||||
* This class includes unit tests for testing the functionality of {@link DeviceManagementServiceImpl}
|
||||
*/
|
||||
@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 DeviceManagementServiceImplTest {
|
||||
|
||||
private static final Log log = LogFactory.getLog(DeviceManagementServiceImplTest.class);
|
||||
private static final String TEST_DEVICE_TYPE = "TEST-DEVICE-TYPE";
|
||||
private static final String TEST_DEVICE_NAME = "TEST-DEVICE";
|
||||
private static final String DEFAULT_USERNAME = "admin";
|
||||
private static final String TENANT_AWARE_USERNAME = "admin@carbon.super";
|
||||
private static final String DEFAULT_ROLE = "admin";
|
||||
private static final String DEFAULT_OWNERSHIP = "BYOD";
|
||||
private static final String DEFAULT_STATUS = "ACTIVE";
|
||||
private static final String DEFAULT_DATE_FORMAT = "EEE, d MMM yyyy HH:mm:ss Z";
|
||||
private DeviceManagementService deviceManagementService;
|
||||
private DeviceAccessAuthorizationService deviceAccessAuthorizationService;
|
||||
private DeviceManagementProviderService deviceManagementProviderService;
|
||||
|
||||
@ObjectFactory
|
||||
public IObjectFactory getObjectFactory() {
|
||||
return new org.powermock.modules.testng.PowerMockObjectFactory();
|
||||
}
|
||||
|
||||
@BeforeClass
|
||||
public void init() {
|
||||
log.info("Initializing DeviceManagementServiceImpl tests");
|
||||
initMocks(this);
|
||||
this.deviceManagementProviderService = Mockito
|
||||
.mock(DeviceManagementProviderServiceImpl.class, Mockito.RETURNS_MOCKS);
|
||||
this.deviceManagementService = new DeviceManagementServiceImpl();
|
||||
this.deviceAccessAuthorizationService = Mockito.mock(DeviceAccessAuthorizationServiceImpl.class);
|
||||
}
|
||||
|
||||
@Test(description = "Testing if the device is enrolled when the device is enrolled.")
|
||||
public void testIsEnrolledWhenDeviceIsEnrolled() throws DeviceManagementException {
|
||||
PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getDeviceManagementService"))
|
||||
.toReturn(this.deviceManagementProviderService);
|
||||
Mockito.when(this.deviceManagementProviderService.isEnrolled(Mockito.any(DeviceIdentifier.class)))
|
||||
.thenReturn(true);
|
||||
Response response = this.deviceManagementService.isEnrolled(TEST_DEVICE_TYPE, UUID.randomUUID().toString());
|
||||
Assert.assertNotNull(response);
|
||||
Assert.assertEquals(response.getStatus(), Response.Status.OK.getStatusCode());
|
||||
Mockito.reset(this.deviceManagementProviderService);
|
||||
}
|
||||
|
||||
@Test(description = "Testing if the device is enrolled when the device is not enrolled.",
|
||||
dependsOnMethods = "testIsEnrolledWhenDeviceIsEnrolled")
|
||||
public void testIsEnrolledWhenDeviceIsNotEnrolled() throws DeviceManagementException {
|
||||
PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getDeviceManagementService"))
|
||||
.toReturn(this.deviceManagementProviderService);
|
||||
Mockito.when(this.deviceManagementProviderService.isEnrolled(Mockito.any(DeviceIdentifier.class)))
|
||||
.thenReturn(false);
|
||||
Response response = this.deviceManagementService.isEnrolled(TEST_DEVICE_TYPE, UUID.randomUUID().toString());
|
||||
Assert.assertNotNull(response);
|
||||
Assert.assertEquals(response.getStatus(), Response.Status.NO_CONTENT.getStatusCode());
|
||||
Mockito.reset(this.deviceManagementProviderService);
|
||||
}
|
||||
|
||||
@Test(description = "Testing if the device enrolled api when exception occurred.",
|
||||
dependsOnMethods = "testIsEnrolledWhenDeviceIsNotEnrolled")
|
||||
public void testIsEnrolledError() throws DeviceManagementException {
|
||||
PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getDeviceManagementService"))
|
||||
.toReturn(this.deviceManagementProviderService);
|
||||
Mockito.when(this.deviceManagementProviderService.isEnrolled(Mockito.any(DeviceIdentifier.class)))
|
||||
.thenThrow(new DeviceManagementException());
|
||||
Response response = this.deviceManagementService.isEnrolled(TEST_DEVICE_TYPE, UUID.randomUUID().toString());
|
||||
Assert.assertNotNull(response);
|
||||
Assert.assertEquals(response.getStatus(), Response.Status.INTERNAL_SERVER_ERROR.getStatusCode());
|
||||
Mockito.reset(this.deviceManagementProviderService);
|
||||
}
|
||||
|
||||
@Test(description = "Testing get devices when request exists both name and role.")
|
||||
public void testGetDevicesWhenBothNameAndRoleAvailable() {
|
||||
PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getDeviceManagementService"))
|
||||
.toReturn(this.deviceManagementProviderService);
|
||||
PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getDeviceAccessAuthorizationService"))
|
||||
.toReturn(this.deviceAccessAuthorizationService);
|
||||
Response response = this.deviceManagementService
|
||||
.getDevices(TEST_DEVICE_NAME, TEST_DEVICE_TYPE, DEFAULT_USERNAME, null, DEFAULT_ROLE, DEFAULT_OWNERSHIP,
|
||||
DEFAULT_STATUS, 1, null, null, false, 10, 5);
|
||||
Assert.assertEquals(response.getStatus(), Response.Status.BAD_REQUEST.getStatusCode());
|
||||
}
|
||||
|
||||
@Test(description = "Testing get devices with correct request.")
|
||||
public void testGetDevices() {
|
||||
PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getDeviceManagementService"))
|
||||
.toReturn(this.deviceManagementProviderService);
|
||||
PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getDeviceAccessAuthorizationService"))
|
||||
.toReturn(this.deviceAccessAuthorizationService);
|
||||
PowerMockito.stub(PowerMockito.method(MultitenantUtils.class, "getTenantAwareUsername"))
|
||||
.toReturn(TENANT_AWARE_USERNAME);
|
||||
PowerMockito.stub(PowerMockito.method(CarbonContext.class, "getThreadLocalCarbonContext"))
|
||||
.toReturn(Mockito.mock(CarbonContext.class, Mockito.RETURNS_MOCKS));
|
||||
|
||||
Response response = this.deviceManagementService
|
||||
.getDevices(null, TEST_DEVICE_TYPE, DEFAULT_USERNAME, null, DEFAULT_ROLE, DEFAULT_OWNERSHIP,
|
||||
DEFAULT_STATUS, 1, null, null, false, 10, 5);
|
||||
Assert.assertEquals(response.getStatus(), Response.Status.OK.getStatusCode());
|
||||
response = this.deviceManagementService
|
||||
.getDevices(TEST_DEVICE_NAME, TEST_DEVICE_TYPE, DEFAULT_USERNAME, null, null, DEFAULT_OWNERSHIP,
|
||||
DEFAULT_STATUS, 1, null, null, false, 10, 5);
|
||||
Assert.assertEquals(response.getStatus(), Response.Status.OK.getStatusCode());
|
||||
response = this.deviceManagementService
|
||||
.getDevices(TEST_DEVICE_NAME, TEST_DEVICE_TYPE, null, null, null, DEFAULT_OWNERSHIP,
|
||||
DEFAULT_STATUS, 1, null, null, false, 10, 5);
|
||||
Assert.assertEquals(response.getStatus(), Response.Status.OK.getStatusCode());
|
||||
response = this.deviceManagementService
|
||||
.getDevices(TEST_DEVICE_NAME, TEST_DEVICE_TYPE, null, null, null, DEFAULT_OWNERSHIP,
|
||||
DEFAULT_STATUS, 1, null, null, true, 10, 5);
|
||||
Assert.assertEquals(response.getStatus(), Response.Status.OK.getStatusCode());
|
||||
}
|
||||
|
||||
@Test(description = "Testing get devices when DeviceAccessAuthorizationService is not available")
|
||||
public void testGetDevicesWithErroneousDeviceAccessAuthorizationService() {
|
||||
PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getDeviceManagementService"))
|
||||
.toReturn(this.deviceManagementProviderService);
|
||||
PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getDeviceAccessAuthorizationService"))
|
||||
.toReturn(null);
|
||||
Response response = this.deviceManagementService
|
||||
.getDevices(null, TEST_DEVICE_TYPE, DEFAULT_USERNAME, null, DEFAULT_ROLE, DEFAULT_OWNERSHIP,
|
||||
DEFAULT_STATUS, 1, null, null, false, 10, 5);
|
||||
Assert.assertEquals(response.getStatus(), Response.Status.INTERNAL_SERVER_ERROR.getStatusCode());
|
||||
}
|
||||
|
||||
@Test(description = "Testing get devices when user is the device admin")
|
||||
public void testGetDevicesWhenUserIsAdmin() throws DeviceAccessAuthorizationException {
|
||||
PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getDeviceManagementService"))
|
||||
.toReturn(this.deviceManagementProviderService);
|
||||
PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getDeviceAccessAuthorizationService"))
|
||||
.toReturn(this.deviceAccessAuthorizationService);
|
||||
PowerMockito.stub(PowerMockito.method(MultitenantUtils.class, "getTenantAwareUsername"))
|
||||
.toReturn(TENANT_AWARE_USERNAME);
|
||||
PowerMockito.stub(PowerMockito.method(CarbonContext.class, "getThreadLocalCarbonContext"))
|
||||
.toReturn(Mockito.mock(CarbonContext.class, Mockito.RETURNS_MOCKS));
|
||||
Mockito.when(deviceAccessAuthorizationService.isDeviceAdminUser()).thenReturn(true);
|
||||
|
||||
Response response = this.deviceManagementService
|
||||
.getDevices(null, TEST_DEVICE_TYPE, DEFAULT_USERNAME, null, DEFAULT_ROLE, DEFAULT_OWNERSHIP,
|
||||
DEFAULT_STATUS, 1, null, null, false, 10, 5);
|
||||
Assert.assertEquals(response.getStatus(), Response.Status.OK.getStatusCode());
|
||||
response = this.deviceManagementService
|
||||
.getDevices(null, TEST_DEVICE_TYPE, null, DEFAULT_USERNAME, DEFAULT_ROLE, DEFAULT_OWNERSHIP,
|
||||
DEFAULT_STATUS, 1, null, null, false, 10, 5);
|
||||
Assert.assertEquals(response.getStatus(), Response.Status.OK.getStatusCode());
|
||||
}
|
||||
|
||||
@Test(description = "Testing get devices when user is unauthorized.")
|
||||
public void testGetDevicesWhenUserIsUnauthorized() throws Exception {
|
||||
PowerMockito.spy(MultitenantUtils.class);
|
||||
PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getDeviceManagementService"))
|
||||
.toReturn(this.deviceManagementProviderService);
|
||||
PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getDeviceAccessAuthorizationService"))
|
||||
.toReturn(this.deviceAccessAuthorizationService);
|
||||
PowerMockito.stub(PowerMockito.method(CarbonContext.class, "getThreadLocalCarbonContext"))
|
||||
.toReturn(Mockito.mock(CarbonContext.class, Mockito.RETURNS_MOCKS));
|
||||
PowerMockito.doReturn(TENANT_AWARE_USERNAME)
|
||||
.when(MultitenantUtils.class, "getTenantAwareUsername", DEFAULT_USERNAME);
|
||||
PowerMockito.doReturn("newuser@carbon.super").when(MultitenantUtils.class, "getTenantAwareUsername", "newuser");
|
||||
Mockito.when(this.deviceAccessAuthorizationService.isDeviceAdminUser()).thenReturn(false);
|
||||
|
||||
Response response = this.deviceManagementService
|
||||
.getDevices(null, TEST_DEVICE_TYPE, "newuser", null, DEFAULT_ROLE, DEFAULT_OWNERSHIP, DEFAULT_STATUS, 1,
|
||||
null, null, false, 10, 5);
|
||||
Assert.assertEquals(response.getStatus(), Response.Status.UNAUTHORIZED.getStatusCode());
|
||||
Mockito.reset(this.deviceAccessAuthorizationService);
|
||||
}
|
||||
|
||||
@Test(description = "Testing get devices with IF-Modified-Since")
|
||||
public void testGetDevicesWithModifiedSince() {
|
||||
String ifModifiedSince = new SimpleDateFormat(DEFAULT_DATE_FORMAT).format(new Date());
|
||||
PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getDeviceManagementService"))
|
||||
.toReturn(this.deviceManagementProviderService);
|
||||
PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getDeviceAccessAuthorizationService"))
|
||||
.toReturn(this.deviceAccessAuthorizationService);
|
||||
PowerMockito.stub(PowerMockito.method(MultitenantUtils.class, "getTenantAwareUsername"))
|
||||
.toReturn(TENANT_AWARE_USERNAME);
|
||||
PowerMockito.stub(PowerMockito.method(CarbonContext.class, "getThreadLocalCarbonContext"))
|
||||
.toReturn(Mockito.mock(CarbonContext.class, Mockito.RETURNS_MOCKS));
|
||||
|
||||
Response response = this.deviceManagementService
|
||||
.getDevices(null, TEST_DEVICE_TYPE, DEFAULT_USERNAME, null, DEFAULT_ROLE, DEFAULT_OWNERSHIP,
|
||||
DEFAULT_STATUS, 1, null, ifModifiedSince, false, 10, 5);
|
||||
Assert.assertEquals(response.getStatus(), Response.Status.NOT_MODIFIED.getStatusCode());
|
||||
response = this.deviceManagementService
|
||||
.getDevices(null, TEST_DEVICE_TYPE, DEFAULT_USERNAME, null, DEFAULT_ROLE, DEFAULT_OWNERSHIP,
|
||||
DEFAULT_STATUS, 1, null, ifModifiedSince, true, 10, 5);
|
||||
Assert.assertEquals(response.getStatus(), Response.Status.NOT_MODIFIED.getStatusCode());
|
||||
response = this.deviceManagementService
|
||||
.getDevices(null, TEST_DEVICE_TYPE, DEFAULT_USERNAME, null, DEFAULT_ROLE, DEFAULT_OWNERSHIP,
|
||||
DEFAULT_STATUS, 1, null, "ErrorModifiedSince", false, 10, 5);
|
||||
Assert.assertEquals(response.getStatus(), Response.Status.BAD_REQUEST.getStatusCode());
|
||||
}
|
||||
|
||||
@Test(description = "Testing get devices with Since")
|
||||
public void testGetDevicesWithSince() {
|
||||
String since = new SimpleDateFormat(DEFAULT_DATE_FORMAT).format(new Date());
|
||||
PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getDeviceManagementService"))
|
||||
.toReturn(this.deviceManagementProviderService);
|
||||
PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getDeviceAccessAuthorizationService"))
|
||||
.toReturn(this.deviceAccessAuthorizationService);
|
||||
PowerMockito.stub(PowerMockito.method(MultitenantUtils.class, "getTenantAwareUsername"))
|
||||
.toReturn(TENANT_AWARE_USERNAME);
|
||||
PowerMockito.stub(PowerMockito.method(CarbonContext.class, "getThreadLocalCarbonContext"))
|
||||
.toReturn(Mockito.mock(CarbonContext.class, Mockito.RETURNS_MOCKS));
|
||||
|
||||
Response response = this.deviceManagementService
|
||||
.getDevices(null, TEST_DEVICE_TYPE, DEFAULT_USERNAME, null, DEFAULT_ROLE, DEFAULT_OWNERSHIP,
|
||||
DEFAULT_STATUS, 1, since, null, false, 10, 5);
|
||||
Assert.assertEquals(response.getStatus(), Response.Status.OK.getStatusCode());
|
||||
response = this.deviceManagementService
|
||||
.getDevices(null, TEST_DEVICE_TYPE, DEFAULT_USERNAME, null, DEFAULT_ROLE, DEFAULT_OWNERSHIP,
|
||||
DEFAULT_STATUS, 1, since, null, true, 10, 5);
|
||||
Assert.assertEquals(response.getStatus(), Response.Status.OK.getStatusCode());
|
||||
response = this.deviceManagementService
|
||||
.getDevices(null, TEST_DEVICE_TYPE, DEFAULT_USERNAME, null, DEFAULT_ROLE, DEFAULT_OWNERSHIP,
|
||||
DEFAULT_STATUS, 1, "ErrorSince", null, false, 10, 5);
|
||||
Assert.assertEquals(response.getStatus(), Response.Status.BAD_REQUEST.getStatusCode());
|
||||
}
|
||||
|
||||
@Test(description = "Testing get devices when unable to retrieve devices")
|
||||
public void testGetDeviceServerErrorWhenGettingDeviceList() throws DeviceManagementException {
|
||||
PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getDeviceManagementService"))
|
||||
.toReturn(this.deviceManagementProviderService);
|
||||
PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getDeviceAccessAuthorizationService"))
|
||||
.toReturn(this.deviceAccessAuthorizationService);
|
||||
PowerMockito.stub(PowerMockito.method(MultitenantUtils.class, "getTenantAwareUsername"))
|
||||
.toReturn(TENANT_AWARE_USERNAME);
|
||||
PowerMockito.stub(PowerMockito.method(CarbonContext.class, "getThreadLocalCarbonContext"))
|
||||
.toReturn(Mockito.mock(CarbonContext.class, Mockito.RETURNS_MOCKS));
|
||||
Mockito.when(this.deviceManagementProviderService
|
||||
.getAllDevices(Mockito.any(PaginationRequest.class), Mockito.anyBoolean()))
|
||||
.thenThrow(new DeviceManagementException());
|
||||
|
||||
Response response = this.deviceManagementService
|
||||
.getDevices(null, TEST_DEVICE_TYPE, DEFAULT_USERNAME, null, DEFAULT_ROLE, DEFAULT_OWNERSHIP,
|
||||
DEFAULT_STATUS, 1, null, null, false, 10, 5);
|
||||
Assert.assertEquals(response.getStatus(), Response.Status.INTERNAL_SERVER_ERROR.getStatusCode());
|
||||
Mockito.reset(this.deviceManagementProviderService);
|
||||
}
|
||||
|
||||
@Test(description = "Testing get devices when unable to check if the user is the admin user")
|
||||
public void testGetDevicesServerErrorWhenCheckingAdminUser() throws DeviceAccessAuthorizationException {
|
||||
PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getDeviceManagementService"))
|
||||
.toReturn(this.deviceManagementProviderService);
|
||||
PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getDeviceAccessAuthorizationService"))
|
||||
.toReturn(this.deviceAccessAuthorizationService);
|
||||
PowerMockito.stub(PowerMockito.method(MultitenantUtils.class, "getTenantAwareUsername"))
|
||||
.toReturn(TENANT_AWARE_USERNAME);
|
||||
PowerMockito.stub(PowerMockito.method(CarbonContext.class, "getThreadLocalCarbonContext"))
|
||||
.toReturn(Mockito.mock(CarbonContext.class, Mockito.RETURNS_MOCKS));
|
||||
Mockito.when(this.deviceAccessAuthorizationService.isDeviceAdminUser())
|
||||
.thenThrow(new DeviceAccessAuthorizationException());
|
||||
|
||||
Response response = this.deviceManagementService
|
||||
.getDevices(null, TEST_DEVICE_TYPE, DEFAULT_USERNAME, null, DEFAULT_ROLE, DEFAULT_OWNERSHIP,
|
||||
DEFAULT_STATUS, 1, null, null, false, 10, 5);
|
||||
Assert.assertEquals(response.getStatus(), Response.Status.INTERNAL_SERVER_ERROR.getStatusCode());
|
||||
Mockito.reset(this.deviceAccessAuthorizationService);
|
||||
}
|
||||
|
||||
@Test(description = "Testing get devices with correct request")
|
||||
public void testGetDeviceTypesByUser() throws DeviceManagementException {
|
||||
PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getDeviceManagementService"))
|
||||
.toReturn(this.deviceManagementProviderService);
|
||||
PowerMockito.stub(PowerMockito.method(CarbonContext.class, "getThreadLocalCarbonContext"))
|
||||
.toReturn(Mockito.mock(CarbonContext.class, Mockito.RETURNS_MOCKS));
|
||||
|
||||
Response response = this.deviceManagementService.getDeviceByUser(true, 10, 5);
|
||||
Assert.assertEquals(response.getStatus(), Response.Status.OK.getStatusCode());
|
||||
response = this.deviceManagementService.getDeviceByUser(false, 10, 5);
|
||||
Assert.assertEquals(response.getStatus(), Response.Status.OK.getStatusCode());
|
||||
}
|
||||
|
||||
@Test(description = "Testing get devices with correct request when unable to get devices.")
|
||||
public void testGetDeviceTypesByUserException() throws DeviceManagementException {
|
||||
PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getDeviceManagementService"))
|
||||
.toReturn(this.deviceManagementProviderService);
|
||||
PowerMockito.stub(PowerMockito.method(CarbonContext.class, "getThreadLocalCarbonContext"))
|
||||
.toReturn(Mockito.mock(CarbonContext.class, Mockito.RETURNS_MOCKS));
|
||||
Mockito.when(this.deviceManagementProviderService.getDevicesOfUser(Mockito.any(PaginationRequest.class)))
|
||||
.thenThrow(new DeviceManagementException());
|
||||
|
||||
Response response = this.deviceManagementService.getDeviceByUser(true, 10, 5);
|
||||
Assert.assertEquals(response.getStatus(), Response.Status.INTERNAL_SERVER_ERROR.getStatusCode());
|
||||
}
|
||||
|
||||
@Test(description = "Testing delete device with correct request.")
|
||||
public void testDeleteDevice() {
|
||||
PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getDeviceManagementService"))
|
||||
.toReturn(this.deviceManagementProviderService);
|
||||
Response response = this.deviceManagementService.deleteDevice(TEST_DEVICE_TYPE, UUID.randomUUID().toString());
|
||||
Assert.assertEquals(response.getStatus(), Response.Status.OK.getStatusCode());
|
||||
}
|
||||
|
||||
@Test(description = "Testing delete unavailable device.")
|
||||
public void testDeleteUnavailableDevice() throws DeviceManagementException {
|
||||
PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getDeviceManagementService"))
|
||||
.toReturn(this.deviceManagementProviderService);
|
||||
Mockito.when(this.deviceManagementProviderService
|
||||
.getDevice(Mockito.any(DeviceIdentifier.class), Mockito.anyBoolean())).thenReturn(null);
|
||||
Response response = this.deviceManagementService.deleteDevice(TEST_DEVICE_TYPE, UUID.randomUUID().toString());
|
||||
Assert.assertEquals(response.getStatus(), Response.Status.NOT_FOUND.getStatusCode());
|
||||
Mockito.reset(this.deviceManagementProviderService);
|
||||
}
|
||||
|
||||
@Test(description = "Testing delete device when unable to delete device.")
|
||||
public void testDeleteDeviceException() throws DeviceManagementException {
|
||||
PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getDeviceManagementService"))
|
||||
.toReturn(this.deviceManagementProviderService);
|
||||
Mockito.when(this.deviceManagementProviderService.disenrollDevice(Mockito.any(DeviceIdentifier.class)))
|
||||
.thenThrow(new DeviceManagementException());
|
||||
Response response = this.deviceManagementService.deleteDevice(TEST_DEVICE_TYPE, UUID.randomUUID().toString());
|
||||
Assert.assertEquals(response.getStatus(), Response.Status.BAD_REQUEST.getStatusCode());
|
||||
Mockito.reset(this.deviceManagementProviderService);
|
||||
}
|
||||
|
||||
@Test(description = "Testing getting device location")
|
||||
public void testGetDeviceLocation() {
|
||||
PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getDeviceInformationManagerService")).
|
||||
toReturn(Mockito.mock(DeviceInformationManagerImpl.class, Mockito.RETURNS_MOCKS));
|
||||
Response response = this.deviceManagementService
|
||||
.getDeviceLocation(TEST_DEVICE_TYPE, UUID.randomUUID().toString(), null);
|
||||
Assert.assertEquals(response.getStatus(), Response.Status.OK.getStatusCode());
|
||||
}
|
||||
|
||||
@Test(description = "Testing getting device location when unable to retrieve location")
|
||||
public void testGetDeviceLocationException() throws DeviceDetailsMgtException {
|
||||
DeviceInformationManager deviceInformationManager = Mockito
|
||||
.mock(DeviceInformationManagerImpl.class, Mockito.RETURNS_MOCKS);
|
||||
PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getDeviceInformationManagerService")).
|
||||
toReturn(deviceInformationManager);
|
||||
Mockito.when(deviceInformationManager.getDeviceLocation(Mockito.any(DeviceIdentifier.class)))
|
||||
.thenThrow(new DeviceDetailsMgtException());
|
||||
Response response = this.deviceManagementService
|
||||
.getDeviceLocation(TEST_DEVICE_TYPE, UUID.randomUUID().toString(), null);
|
||||
Assert.assertEquals(response.getStatus(), Response.Status.INTERNAL_SERVER_ERROR.getStatusCode());
|
||||
}
|
||||
|
||||
@Test(description = "Testing getting device information")
|
||||
public void testGetDeviceInformation() {
|
||||
PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getDeviceInformationManagerService")).
|
||||
toReturn(Mockito.mock(DeviceInformationManagerImpl.class, Mockito.RETURNS_MOCKS));
|
||||
Response response = this.deviceManagementService
|
||||
.getDeviceInformation(TEST_DEVICE_TYPE, UUID.randomUUID().toString(), null);
|
||||
Assert.assertEquals(response.getStatus(), Response.Status.OK.getStatusCode());
|
||||
}
|
||||
|
||||
@Test(description = "Testing getting device information when unable to retrieve information")
|
||||
public void testGetDeviceInformationException() throws DeviceDetailsMgtException {
|
||||
DeviceInformationManager deviceInformationManager = Mockito
|
||||
.mock(DeviceInformationManagerImpl.class, Mockito.RETURNS_MOCKS);
|
||||
PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getDeviceInformationManagerService")).
|
||||
toReturn(deviceInformationManager);
|
||||
Mockito.when(deviceInformationManager.getDeviceInfo(Mockito.any(DeviceIdentifier.class)))
|
||||
.thenThrow(new DeviceDetailsMgtException());
|
||||
Response response = this.deviceManagementService
|
||||
.getDeviceInformation(TEST_DEVICE_TYPE, UUID.randomUUID().toString(), null);
|
||||
Assert.assertEquals(response.getStatus(), Response.Status.INTERNAL_SERVER_ERROR.getStatusCode());
|
||||
}
|
||||
|
||||
@Test(description = "Testing getting device features")
|
||||
public void testGetFeaturesOfDevice() {
|
||||
PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getDeviceManagementService"))
|
||||
.toReturn(this.deviceManagementProviderService);
|
||||
Response response = this.deviceManagementService
|
||||
.getFeaturesOfDevice(TEST_DEVICE_TYPE, UUID.randomUUID().toString(), null);
|
||||
Assert.assertEquals(response.getStatus(), Response.Status.OK.getStatusCode());
|
||||
}
|
||||
|
||||
@Test(description = "Testing getting device features when feature manager is not registered for the device type")
|
||||
public void testGetFeaturesOfDeviceWhenFeatureManagerIsNotRegistered() throws DeviceManagementException {
|
||||
PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getDeviceManagementService"))
|
||||
.toReturn(this.deviceManagementProviderService);
|
||||
Mockito.when(this.deviceManagementProviderService.getFeatureManager(Mockito.anyString())).thenReturn(null);
|
||||
Response response = this.deviceManagementService
|
||||
.getFeaturesOfDevice(TEST_DEVICE_TYPE, UUID.randomUUID().toString(), null);
|
||||
Assert.assertEquals(response.getStatus(), Response.Status.NOT_FOUND.getStatusCode());
|
||||
Mockito.reset(this.deviceManagementProviderService);
|
||||
}
|
||||
|
||||
@Test(description = "Testing getting device features when unable to get the feature manager")
|
||||
public void testGetFeaturesException() throws DeviceManagementException {
|
||||
PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getDeviceManagementService"))
|
||||
.toReturn(this.deviceManagementProviderService);
|
||||
Mockito.when(this.deviceManagementProviderService.getFeatureManager(Mockito.anyString()))
|
||||
.thenThrow(new DeviceManagementException());
|
||||
Response response = this.deviceManagementService
|
||||
.getFeaturesOfDevice(TEST_DEVICE_TYPE, UUID.randomUUID().toString(), null);
|
||||
Assert.assertEquals(response.getStatus(), Response.Status.INTERNAL_SERVER_ERROR.getStatusCode());
|
||||
Mockito.reset(this.deviceManagementProviderService);
|
||||
}
|
||||
|
||||
@Test(description = "Testing search devices")
|
||||
public void testSearchDevices() {
|
||||
SearchManagerService searchManagerService = Mockito.mock(SearchManagerServiceImpl.class, Mockito.RETURNS_MOCKS);
|
||||
PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getSearchManagerService"))
|
||||
.toReturn(searchManagerService);
|
||||
Response response = this.deviceManagementService
|
||||
.searchDevices(10, 5, new SearchContext());
|
||||
Assert.assertEquals(response.getStatus(), Response.Status.OK.getStatusCode(),
|
||||
"Expects to return HTTP 200 when the search is successful");
|
||||
}
|
||||
|
||||
@Test(description = "Testing search devices when unable to search devices")
|
||||
public void testSearchDevicesException() throws SearchMgtException {
|
||||
SearchManagerService searchManagerService = Mockito.mock(SearchManagerServiceImpl.class, Mockito.RETURNS_MOCKS);
|
||||
PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getSearchManagerService"))
|
||||
.toReturn(searchManagerService);
|
||||
Mockito.when(searchManagerService.search(Mockito.any(SearchContext.class))).thenThrow(new SearchMgtException());
|
||||
Response response = this.deviceManagementService
|
||||
.searchDevices(10, 5, new SearchContext());
|
||||
Assert.assertEquals(response.getStatus(), Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(),
|
||||
"Expects HTTP 500 when an exception occurred while searching the device");
|
||||
}
|
||||
|
||||
@Test(description = "Testing getting installed applications of a device")
|
||||
public void testGetInstalledApplications() {
|
||||
ApplicationManagementProviderService applicationManagementProviderService = Mockito
|
||||
.mock(ApplicationManagementProviderService.class, Mockito.RETURNS_MOCKS);
|
||||
PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getAppManagementService"))
|
||||
.toReturn(applicationManagementProviderService);
|
||||
Response response = this.deviceManagementService
|
||||
.getInstalledApplications(TEST_DEVICE_TYPE, UUID.randomUUID().toString(), "", 10, 5);
|
||||
Assert.assertEquals(response.getStatus(), Response.Status.OK.getStatusCode(),
|
||||
"Expects to return HTTP 200 when the application list is retrieved successfully.");
|
||||
}
|
||||
|
||||
@Test(description = "Testing getting installed applications of a device when unable to fetch applications")
|
||||
public void testGetInstalledApplicationsException() throws ApplicationManagementException {
|
||||
ApplicationManagementProviderService applicationManagementProviderService = Mockito
|
||||
.mock(ApplicationManagementProviderService.class, Mockito.RETURNS_MOCKS);
|
||||
PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getAppManagementService"))
|
||||
.toReturn(applicationManagementProviderService);
|
||||
Mockito.when(
|
||||
applicationManagementProviderService.getApplicationListForDevice(Mockito.any(DeviceIdentifier.class)))
|
||||
.thenThrow(new ApplicationManagementException());
|
||||
Response response = this.deviceManagementService
|
||||
.getInstalledApplications(TEST_DEVICE_TYPE, UUID.randomUUID().toString(), "", 10, 5);
|
||||
Assert.assertEquals(response.getStatus(), Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(),
|
||||
"Expects HTTP 500 when an exception occurred while retrieving application list of the device");
|
||||
}
|
||||
|
||||
@Test(description = "Testing getting operation list of a device")
|
||||
public void testGetDeviceOperations() {
|
||||
PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getDeviceManagementService"))
|
||||
.toReturn(this.deviceManagementProviderService);
|
||||
Response response = this.deviceManagementService
|
||||
.getDeviceOperations(TEST_DEVICE_TYPE, UUID.randomUUID().toString(), "", 10, 5, DEFAULT_USERNAME);
|
||||
Assert.assertEquals(response.getStatus(), Response.Status.OK.getStatusCode(),
|
||||
"Expects to return HTTP 200 when the operation is retrieved successfully.");
|
||||
}
|
||||
|
||||
@Test(description = "Testing getting operation list of a device when unable to retrieve operations")
|
||||
public void testGetDeviceOperationsException() throws OperationManagementException {
|
||||
PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getDeviceManagementService"))
|
||||
.toReturn(this.deviceManagementProviderService);
|
||||
Mockito.when(this.deviceManagementProviderService.getOperations(Mockito.any(DeviceIdentifier.class),
|
||||
Mockito.any(PaginationRequest.class))).thenThrow(new OperationManagementException());
|
||||
Response response = this.deviceManagementService
|
||||
.getDeviceOperations(TEST_DEVICE_TYPE, UUID.randomUUID().toString(), "", 10, 5, DEFAULT_USERNAME);
|
||||
Assert.assertEquals(response.getStatus(), Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(),
|
||||
"Expects to return HTTP 500 when an exception occurred while retrieving operation list of the device");
|
||||
}
|
||||
|
||||
@Test(description = "Testing getting effective policy of a device")
|
||||
public void testGetEffectivePolicyOfDevice() throws PolicyManagementException {
|
||||
PolicyManagerService policyManagerService = Mockito.mock(PolicyManagerService.class, Mockito.RETURNS_MOCKS);
|
||||
PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getPolicyManagementService"))
|
||||
.toReturn(policyManagerService);
|
||||
Response response = this.deviceManagementService
|
||||
.getEffectivePolicyOfDevice(TEST_DEVICE_TYPE, UUID.randomUUID().toString(), null);
|
||||
Assert.assertEquals(response.getStatus(), Response.Status.OK.getStatusCode(),
|
||||
"Expects to return HTTP 200 when retrieving effective policy is successful");
|
||||
}
|
||||
|
||||
@Test(description = "Testing getting effective policy of a device when unable to retrieve effective policy")
|
||||
public void testGetEffectivePolicyOfDeviceException() throws PolicyManagementException {
|
||||
PolicyManagerService policyManagerService = Mockito.mock(PolicyManagerService.class, Mockito.RETURNS_MOCKS);
|
||||
PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getPolicyManagementService"))
|
||||
.toReturn(policyManagerService);
|
||||
Mockito.when(policyManagerService.getAppliedPolicyToDevice(Mockito.any(DeviceIdentifier.class)))
|
||||
.thenThrow(new PolicyManagementException());
|
||||
Response response = this.deviceManagementService
|
||||
.getEffectivePolicyOfDevice(TEST_DEVICE_TYPE, UUID.randomUUID().toString(), null);
|
||||
Assert.assertEquals(response.getStatus(), Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(),
|
||||
"Expects to return HTTP 500 when an exception occurred while getting effective policy of the device");
|
||||
}
|
||||
}
|
@ -0,0 +1,252 @@
|
||||
/*
|
||||
* 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.apache.commons.logging.Log;
|
||||
import org.apache.commons.logging.LogFactory;
|
||||
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.DeviceManagementException;
|
||||
import org.wso2.carbon.device.mgt.common.spi.DeviceTypeGeneratorService;
|
||||
import org.wso2.carbon.device.mgt.core.dto.DeviceType;
|
||||
import org.wso2.carbon.device.mgt.core.service.DeviceManagementProviderService;
|
||||
import org.wso2.carbon.device.mgt.core.service.DeviceManagementProviderServiceImpl;
|
||||
import org.wso2.carbon.device.mgt.extensions.device.type.template.DeviceTypeGeneratorServiceImpl;
|
||||
import org.wso2.carbon.device.mgt.jaxrs.service.api.admin.DeviceTypeManagementAdminService;
|
||||
import org.wso2.carbon.device.mgt.jaxrs.service.impl.admin.DeviceTypeManagementAdminServiceImpl;
|
||||
import org.wso2.carbon.device.mgt.jaxrs.service.impl.util.DeviceMgtAPITestHelper;
|
||||
import org.wso2.carbon.device.mgt.jaxrs.util.DeviceMgtAPIUtils;
|
||||
|
||||
import javax.ws.rs.core.Response;
|
||||
|
||||
import static org.mockito.MockitoAnnotations.initMocks;
|
||||
|
||||
/**
|
||||
* This class holds the unit tests for the class {@link DeviceTypeManagementAdminService}
|
||||
*/
|
||||
@PowerMockIgnore("javax.ws.rs.*")
|
||||
@SuppressStaticInitializationFor({"org.wso2.carbon.device.mgt.jaxrs.util.DeviceMgtAPIUtils"})
|
||||
@PrepareForTest({DeviceMgtAPIUtils.class, DeviceManagementProviderService.class})
|
||||
public class DeviceTypeManagementAdminServiceTest {
|
||||
|
||||
private static final Log log = LogFactory.getLog(DeviceTypeManagementAdminService.class);
|
||||
private static final String TEST_DEVICE_TYPE = "TEST-DEVICE-TYPE";
|
||||
private static final String TEST_DEVICE_TYPE_1 = "DUMMY-DEVICE-TYPE-1";
|
||||
private static final String TEST_DEVICE_TYPE_2 = "DUMMY DEVICE TYPE";
|
||||
private static final int TEST_DEVICE_TYPE_ID = 12345;
|
||||
private static final int TEST_DEVICE_TYPE_ID_1 = 123452;
|
||||
private static final int TEST_DEVICE_TYPE_ID_2 = 121233452;
|
||||
private DeviceTypeManagementAdminService deviceTypeManagementAdminService;
|
||||
private DeviceManagementProviderService deviceManagementProviderService;
|
||||
private DeviceTypeGeneratorService deviceTypeGeneratorService;
|
||||
|
||||
@ObjectFactory
|
||||
public IObjectFactory getObjectFactory() {
|
||||
return new org.powermock.modules.testng.PowerMockObjectFactory();
|
||||
}
|
||||
|
||||
@BeforeClass
|
||||
public void init() throws DeviceManagementException {
|
||||
log.info("Initializing DeviceTypeManagementAdmin tests");
|
||||
initMocks(this);
|
||||
this.deviceManagementProviderService = Mockito
|
||||
.mock(DeviceManagementProviderServiceImpl.class, Mockito.RETURNS_MOCKS);
|
||||
this.deviceTypeGeneratorService = Mockito.mock(DeviceTypeGeneratorServiceImpl.class, Mockito.RETURNS_MOCKS);
|
||||
this.deviceTypeManagementAdminService = new DeviceTypeManagementAdminServiceImpl();
|
||||
}
|
||||
|
||||
@Test(description = "Test get all the device types.")
|
||||
public void testGetDeviceTypes() {
|
||||
PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getDeviceManagementService"))
|
||||
.toReturn(this.deviceManagementProviderService);
|
||||
|
||||
Response response = this.deviceTypeManagementAdminService.getDeviceTypes();
|
||||
|
||||
log.info(response.getEntity());
|
||||
|
||||
Assert.assertNotNull(response, "The response should not be null");
|
||||
Assert.assertEquals(response.getStatus(), Response.Status.OK.getStatusCode(), "The Response status code " +
|
||||
"should be 200.");
|
||||
}
|
||||
|
||||
@Test(description = "Test the error scenario of getting all the device types.")
|
||||
public void testGetDeviceTypesError() throws DeviceManagementException {
|
||||
PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getDeviceManagementService"))
|
||||
.toReturn(this.deviceManagementProviderService);
|
||||
|
||||
Mockito.when(deviceManagementProviderService.getDeviceTypes()).thenThrow(new DeviceManagementException());
|
||||
Response response = this.deviceTypeManagementAdminService.getDeviceTypes();
|
||||
|
||||
Assert.assertNotNull(response, "The response should not be null");
|
||||
Assert.assertEquals(response.getStatus(), Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(),
|
||||
"The expected status code is 500.");
|
||||
Mockito.reset(deviceManagementProviderService);
|
||||
}
|
||||
|
||||
@Test(description = "Test the new device type creation scenario.")
|
||||
public void testAddDeviceTypeWithExistingName() throws DeviceManagementException {
|
||||
PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getDeviceManagementService"))
|
||||
.toReturn(this.deviceManagementProviderService);
|
||||
|
||||
DeviceType deviceType = DeviceMgtAPITestHelper.getDummyDeviceType(TEST_DEVICE_TYPE_1, TEST_DEVICE_TYPE_ID_1);
|
||||
Response response = this.deviceTypeManagementAdminService.addDeviceType(deviceType);
|
||||
|
||||
log.info(response.getEntity());
|
||||
|
||||
Assert.assertNotNull(response, "The response should not be null");
|
||||
Assert.assertEquals(response.getStatus(), Response.Status.CONFLICT.getStatusCode(),
|
||||
"The Response Status code should be 409.");
|
||||
}
|
||||
|
||||
@Test(description = "Test the new device type creation scenario when device type name is unqualified.")
|
||||
public void testAddDeviceTypeWithUnqualifiedName() throws DeviceManagementException {
|
||||
PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getDeviceManagementService"))
|
||||
.toReturn(this.deviceManagementProviderService);
|
||||
|
||||
Mockito.when(deviceManagementProviderService.getDeviceType(Mockito.anyString())).thenReturn(null);
|
||||
|
||||
DeviceType deviceType = DeviceMgtAPITestHelper.getDummyDeviceType(TEST_DEVICE_TYPE_2, TEST_DEVICE_TYPE_ID_2);
|
||||
Response response = this.deviceTypeManagementAdminService.addDeviceType(deviceType);
|
||||
|
||||
log.info(response.getEntity());
|
||||
|
||||
Assert.assertNotNull(response, "The response should not be null");
|
||||
Assert.assertEquals(response.getStatus(), Response.Status.BAD_REQUEST.getStatusCode(),
|
||||
"The Response Status code should be 400.");
|
||||
Mockito.reset(deviceManagementProviderService);
|
||||
}
|
||||
|
||||
@Test(description = "Test creating a new device type success scenario.")
|
||||
public void testAddDeviceType() throws DeviceManagementException {
|
||||
PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getDeviceManagementService"))
|
||||
.toReturn(this.deviceManagementProviderService);
|
||||
PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getDeviceTypeGeneratorService"))
|
||||
.toReturn(this.deviceTypeGeneratorService);
|
||||
|
||||
Mockito.when(deviceManagementProviderService.getDeviceType(Mockito.anyString())).thenReturn(null);
|
||||
|
||||
DeviceType deviceType = DeviceMgtAPITestHelper.getDummyDeviceType(TEST_DEVICE_TYPE, TEST_DEVICE_TYPE_ID);
|
||||
Response response = this.deviceTypeManagementAdminService.addDeviceType(deviceType);
|
||||
|
||||
Assert.assertNotNull(response, "The response should not be null");
|
||||
Assert.assertEquals(response.getStatus(), Response.Status.OK.getStatusCode(),
|
||||
"The Response Status code should be 200.");
|
||||
Mockito.reset(deviceManagementProviderService);
|
||||
}
|
||||
|
||||
@Test(description = "Test the create device type scenario when the device type is null.")
|
||||
public void testAddDeviceTypeWithNoDeviceType() {
|
||||
PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getDeviceManagementService"))
|
||||
.toReturn(this.deviceManagementProviderService);
|
||||
|
||||
Response response = this.deviceTypeManagementAdminService.addDeviceType(null);
|
||||
|
||||
log.info(response.getEntity());
|
||||
|
||||
Assert.assertNotNull(response, "The response should not be null");
|
||||
Assert.assertEquals(response.getStatus(), Response.Status.BAD_REQUEST.getStatusCode(),
|
||||
"The Response Status code should be 409.");
|
||||
}
|
||||
|
||||
@Test(description = "Test the device type creation scenario with Device Management exception.")
|
||||
public void testAddDeviceTypeWithException() throws DeviceManagementException {
|
||||
PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getDeviceManagementService"))
|
||||
.toReturn(this.deviceManagementProviderService);
|
||||
Mockito.when(this.deviceManagementProviderService.getDeviceType(Mockito.anyString())).thenThrow(new
|
||||
DeviceManagementException());
|
||||
|
||||
DeviceType deviceType = DeviceMgtAPITestHelper.getDummyDeviceType(TEST_DEVICE_TYPE, TEST_DEVICE_TYPE_ID);
|
||||
Response response = this.deviceTypeManagementAdminService.addDeviceType(deviceType);
|
||||
|
||||
Assert.assertNotNull(response, "The response should not be null");
|
||||
Assert.assertEquals(response.getStatus(), Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(),
|
||||
"The Response Status code should be 500.");
|
||||
Mockito.reset(deviceManagementProviderService);
|
||||
}
|
||||
|
||||
@Test(description = "Test the update device type scenario.")
|
||||
public void testUpdateDeviceType() throws DeviceManagementException {
|
||||
PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getDeviceManagementService"))
|
||||
.toReturn(this.deviceManagementProviderService);
|
||||
PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getDeviceTypeGeneratorService"))
|
||||
.toReturn(this.deviceTypeGeneratorService);
|
||||
|
||||
DeviceType deviceType = DeviceMgtAPITestHelper.getDummyDeviceType(TEST_DEVICE_TYPE, TEST_DEVICE_TYPE_ID);
|
||||
Response response = this.deviceTypeManagementAdminService.updateDeviceType(deviceType);
|
||||
|
||||
Assert.assertNotNull(response, "The response should not be null");
|
||||
Assert.assertEquals(response.getStatus(), Response.Status.OK.getStatusCode(),
|
||||
"The Response Status code should be 200.");
|
||||
}
|
||||
|
||||
@Test(description = "Test the update device type scenario.")
|
||||
public void testUpdateNonExistingDeviceType() throws DeviceManagementException {
|
||||
PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getDeviceManagementService"))
|
||||
.toReturn(this.deviceManagementProviderService);
|
||||
PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getDeviceTypeGeneratorService"))
|
||||
.toReturn(this.deviceTypeGeneratorService);
|
||||
Mockito.when(deviceManagementProviderService.getDeviceType(Mockito.anyString())).thenReturn(null);
|
||||
|
||||
DeviceType deviceType = DeviceMgtAPITestHelper.getDummyDeviceType(TEST_DEVICE_TYPE, TEST_DEVICE_TYPE_ID);
|
||||
Response response = this.deviceTypeManagementAdminService.updateDeviceType(deviceType);
|
||||
|
||||
Assert.assertNotNull(response, "The response should not be null");
|
||||
Assert.assertEquals(response.getStatus(), Response.Status.BAD_REQUEST.getStatusCode(),
|
||||
"The Response Status code should be 400.");
|
||||
Mockito.reset(deviceManagementProviderService);
|
||||
}
|
||||
|
||||
@Test(description = "Test update device Type when device type is null")
|
||||
public void testUpdateDeviceTypeWithNullDeviceType() {
|
||||
PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getDeviceManagementService"))
|
||||
.toReturn(this.deviceManagementProviderService);
|
||||
|
||||
Response response = this.deviceTypeManagementAdminService.updateDeviceType(null);
|
||||
|
||||
Assert.assertNotNull(response, "The response should not be null");
|
||||
Assert.assertEquals(response.getStatus(), Response.Status.BAD_REQUEST.getStatusCode(),
|
||||
"The Response Status code should be 400.");
|
||||
Mockito.reset(deviceManagementProviderService);
|
||||
}
|
||||
|
||||
@Test(description = "Test update device Type with DeviceManagementException")
|
||||
public void testUpdateDeviceTypeWithException() throws DeviceManagementException {
|
||||
PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getDeviceManagementService"))
|
||||
.toReturn(this.deviceManagementProviderService);
|
||||
|
||||
Mockito.when(this.deviceManagementProviderService.getDeviceType(Mockito.anyString()))
|
||||
.thenThrow(new DeviceManagementException());
|
||||
|
||||
DeviceType deviceType = DeviceMgtAPITestHelper.getDummyDeviceType(TEST_DEVICE_TYPE, TEST_DEVICE_TYPE_ID);
|
||||
Response response = this.deviceTypeManagementAdminService.updateDeviceType(deviceType);
|
||||
|
||||
Assert.assertNotNull(response, "The response should not be null");
|
||||
Assert.assertEquals(response.getStatus(), Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(),
|
||||
"The Response Status code should be 500.");
|
||||
Mockito.reset(deviceManagementProviderService);
|
||||
}
|
||||
}
|
@ -0,0 +1,236 @@
|
||||
/*
|
||||
* 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.apache.commons.logging.Log;
|
||||
import org.apache.commons.logging.LogFactory;
|
||||
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.DeviceManagementException;
|
||||
import org.wso2.carbon.device.mgt.common.FeatureManager;
|
||||
import org.wso2.carbon.device.mgt.core.dto.DeviceType;
|
||||
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.service.api.DeviceTypeManagementService;
|
||||
import org.wso2.carbon.device.mgt.jaxrs.service.impl.util.DeviceMgtAPITestHelper;
|
||||
import org.wso2.carbon.device.mgt.jaxrs.util.DeviceMgtAPIUtils;
|
||||
|
||||
import javax.ws.rs.core.Response;
|
||||
import java.lang.reflect.InvocationTargetException;
|
||||
import java.lang.reflect.Method;
|
||||
import java.util.List;
|
||||
|
||||
import static org.mockito.MockitoAnnotations.initMocks;
|
||||
|
||||
/**
|
||||
* This class holds the unit tests for the class {@link DeviceTypeManagementService}
|
||||
*/
|
||||
@PowerMockIgnore("javax.ws.rs.*")
|
||||
@SuppressStaticInitializationFor({"org.wso2.carbon.device.mgt.jaxrs.util.DeviceMgtAPIUtils"})
|
||||
@PrepareForTest({DeviceMgtAPIUtils.class, DeviceManagementProviderService.class})
|
||||
public class DeviceTypeManagementServiceTest {
|
||||
|
||||
private static final Log log = LogFactory.getLog(DeviceManagementServiceImplTest.class);
|
||||
private static final String TEST_DEVICE_TYPE = "TEST-DEVICE-TYPE";
|
||||
private static final int TEST_DEVICE_TYPE_ID = 12345;
|
||||
private static final String MODIFIED_SINCE = "1234503934242";
|
||||
private DeviceTypeManagementService deviceTypeManagementService;
|
||||
private DeviceManagementProviderService deviceManagementProviderService;
|
||||
|
||||
@ObjectFactory
|
||||
public IObjectFactory getObjectFactory() {
|
||||
return new org.powermock.modules.testng.PowerMockObjectFactory();
|
||||
}
|
||||
|
||||
@BeforeClass
|
||||
public void init() throws DeviceManagementException {
|
||||
log.info("Initializing DeviceTypeManagement tests");
|
||||
initMocks(this);
|
||||
this.deviceManagementProviderService = Mockito
|
||||
.mock(DeviceManagementProviderServiceImpl.class, Mockito.RETURNS_MOCKS);
|
||||
this.deviceTypeManagementService = new DeviceTypeManagementServiceImpl();
|
||||
}
|
||||
|
||||
@Test(description = "Testing for existing device types.")
|
||||
public void testExistingDeviceType() throws Exception {
|
||||
PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getDeviceManagementService"))
|
||||
.toReturn(this.deviceManagementProviderService);
|
||||
Response response = this.deviceTypeManagementService.getDeviceTypes("");
|
||||
Assert.assertNotNull(response, "The response object is null.");
|
||||
Assert.assertEquals(response.getStatus(), Response.Status.OK.getStatusCode(),
|
||||
"The response states should be 200.");
|
||||
}
|
||||
|
||||
@Test(description = "Testing get existing device types error")
|
||||
public void testExistingDeviceTypesError() throws Exception {
|
||||
PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getDeviceManagementService"))
|
||||
.toReturn(this.deviceManagementProviderService);
|
||||
Mockito.when(this.deviceManagementProviderService.getDeviceTypes()).thenThrow(new DeviceManagementException());
|
||||
|
||||
Response response = this.deviceTypeManagementService.getDeviceTypes();
|
||||
Assert.assertNotNull(response, "The response object is null.");
|
||||
Assert.assertEquals(response.getStatus(), Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(),
|
||||
"The response status should be 500.");
|
||||
Mockito.reset(deviceManagementProviderService);
|
||||
}
|
||||
|
||||
@Test(description = "Testing get existing device types error")
|
||||
public void testExistingDeviceTypesModifiedError() throws Exception {
|
||||
PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getDeviceManagementService"))
|
||||
.toReturn(this.deviceManagementProviderService);
|
||||
Mockito.when(this.deviceManagementProviderService.getAvailableDeviceTypes()).thenThrow(new
|
||||
DeviceManagementException());
|
||||
|
||||
Response response = this.deviceTypeManagementService.getDeviceTypes(MODIFIED_SINCE);
|
||||
Assert.assertNotNull(response, "The response object is null.");
|
||||
Assert.assertEquals(response.getStatus(), Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(),
|
||||
"The response status should be 500.");
|
||||
Mockito.reset(deviceManagementProviderService);
|
||||
}
|
||||
|
||||
@Test(description = "Test case to retrieve the Features of specified device type.")
|
||||
public void testGetDeviceTypeFeatures() throws Exception {
|
||||
PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getDeviceManagementService"))
|
||||
.toReturn(this.deviceManagementProviderService);
|
||||
Response response = this.deviceTypeManagementService.getFeatures(TEST_DEVICE_TYPE, MODIFIED_SINCE);
|
||||
Assert.assertNotNull(response, "The response object is null.");
|
||||
Assert.assertEquals(response.getStatus(), Response.Status.OK.getStatusCode(),
|
||||
"The response status should be 200.");
|
||||
}
|
||||
|
||||
@Test(description = "Test case to test the error scenario when retrieving the Features of specified device type.")
|
||||
public void testGetDeviceTypeFeaturesError() throws Exception {
|
||||
PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getDeviceManagementService"))
|
||||
.toReturn(this.deviceManagementProviderService);
|
||||
FeatureManager featureManager = Mockito.mock(FeatureManager.class);
|
||||
Mockito.when(this.deviceManagementProviderService.getFeatureManager(Mockito.anyString())).thenReturn
|
||||
(featureManager);
|
||||
Mockito.when((featureManager).getFeatures()).thenThrow(new DeviceManagementException());
|
||||
Response response = this.deviceTypeManagementService.getFeatures(TEST_DEVICE_TYPE, MODIFIED_SINCE);
|
||||
Assert.assertNotNull(response, "The response object is null.");
|
||||
Assert.assertEquals(response.getStatus(), Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(),
|
||||
"The response status should be 500.");
|
||||
Mockito.reset(deviceManagementProviderService);
|
||||
Mockito.reset(featureManager);
|
||||
}
|
||||
|
||||
@Test(description = "Test getting device type features when feature manager is null.")
|
||||
public void testGetDeviceTypeFeaturesWithNoFeatureManager() throws Exception {
|
||||
PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getDeviceManagementService"))
|
||||
.toReturn(this.deviceManagementProviderService);
|
||||
Mockito.when(this.deviceManagementProviderService.getFeatureManager(Mockito.anyString())).thenReturn(null);
|
||||
Response response = this.deviceTypeManagementService.getFeatures(TEST_DEVICE_TYPE, MODIFIED_SINCE);
|
||||
Assert.assertNotNull(response, "The response object is null.");
|
||||
Assert.assertEquals(response.getStatus(), Response.Status.NOT_FOUND.getStatusCode(),
|
||||
"The response status should be 404.");
|
||||
Mockito.reset(deviceManagementProviderService);
|
||||
}
|
||||
|
||||
@Test(description = "Test to get all the device types.")
|
||||
public void testGetDeviceTypes() throws Exception {
|
||||
PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getDeviceManagementService"))
|
||||
.toReturn(this.deviceManagementProviderService);
|
||||
Response response = this.deviceTypeManagementService.getDeviceTypes();
|
||||
Assert.assertNotNull(response, "The response object is null.");
|
||||
Assert.assertEquals(response.getStatus(), Response.Status.OK.getStatusCode(),
|
||||
"The response status should be 200.");
|
||||
}
|
||||
|
||||
@Test(description = "Test to get all the device types.")
|
||||
public void testGetDeviceTypesWithDeviceTypes() throws Exception {
|
||||
PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getDeviceManagementService"))
|
||||
.toReturn(this.deviceManagementProviderService);
|
||||
|
||||
List<DeviceType> deviceTypes = DeviceMgtAPITestHelper.getDummyDeviceTypeList(5);
|
||||
Mockito.when(this.deviceManagementProviderService.getDeviceTypes()).thenReturn(deviceTypes);
|
||||
|
||||
Response response = this.deviceTypeManagementService.getDeviceTypes();
|
||||
Assert.assertNotNull(response, "The response object is null.");
|
||||
Assert.assertEquals(response.getStatus(), Response.Status.OK.getStatusCode(),
|
||||
"The response state should be 200");
|
||||
Mockito.reset(deviceManagementProviderService);
|
||||
}
|
||||
|
||||
@Test(description = "Test to get all the device types for the given name")
|
||||
public void testGetDeviceTypeByName() throws Exception {
|
||||
PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getDeviceManagementService"))
|
||||
.toReturn(this.deviceManagementProviderService);
|
||||
Response response = this.deviceTypeManagementService.getDeviceTypeByName(TEST_DEVICE_TYPE);
|
||||
Assert.assertNotNull(response, "The response object is null.");
|
||||
Assert.assertEquals(response.getStatus(), Response.Status.OK.getStatusCode(),
|
||||
"The response status should be 200.");
|
||||
}
|
||||
|
||||
@Test(description = "Test the scenario when there are no device types for the given name.")
|
||||
public void testGetDeviceTypeByNameError() throws Exception {
|
||||
PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getDeviceManagementService"))
|
||||
.toReturn(this.deviceManagementProviderService);
|
||||
Mockito.when(this.deviceManagementProviderService.getDeviceType(Mockito.anyString())).thenReturn(null);
|
||||
|
||||
Response response = this.deviceTypeManagementService.getDeviceTypeByName(TEST_DEVICE_TYPE);
|
||||
Assert.assertNotNull(response, "The response object is null.");
|
||||
Assert.assertEquals(response.getStatus(), Response.Status.NO_CONTENT.getStatusCode(),
|
||||
"The response status should be 204.");
|
||||
Mockito.reset(deviceManagementProviderService);
|
||||
}
|
||||
|
||||
@Test(description = "Test the scenario when there are no device types for the given name.")
|
||||
public void testGetDeviceTypeByNameException() throws Exception {
|
||||
PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getDeviceManagementService"))
|
||||
.toReturn(this.deviceManagementProviderService);
|
||||
Mockito.when(this.deviceManagementProviderService.getDeviceType(Mockito.anyString()))
|
||||
.thenThrow(new DeviceManagementException());
|
||||
|
||||
Response response = this.deviceTypeManagementService.getDeviceTypeByName(TEST_DEVICE_TYPE);
|
||||
Assert.assertNotNull(response, "The response object is null.");
|
||||
Assert.assertEquals(response.getStatus(), Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(),
|
||||
"The response status should be 500");
|
||||
Mockito.reset(deviceManagementProviderService);
|
||||
}
|
||||
|
||||
@Test(description = "Test to get all the device types when given name is null")
|
||||
public void testGetDeviceTypeByNameBadRequest() throws Exception {
|
||||
PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getDeviceManagementService"))
|
||||
.toReturn(this.deviceManagementProviderService);
|
||||
Response response = this.deviceTypeManagementService.getDeviceTypeByName(null);
|
||||
Assert.assertNotNull(response, "The response object is null.");
|
||||
Assert.assertEquals(response.getStatus(), Response.Status.BAD_REQUEST.getStatusCode(),
|
||||
"The response status should be 400");
|
||||
}
|
||||
|
||||
@Test(description = "Test to clear the sensitive metadata information of device type")
|
||||
public void testClearMetaEntryInfo() throws NoSuchMethodException, InvocationTargetException,
|
||||
IllegalAccessException {
|
||||
Method clearMetaEntryInfo = DeviceTypeManagementServiceImpl.class.getDeclaredMethod("clearMetaEntryInfo",
|
||||
DeviceType.class);
|
||||
clearMetaEntryInfo.setAccessible(true);
|
||||
|
||||
DeviceType deviceType = DeviceMgtAPITestHelper.getDummyDeviceType(TEST_DEVICE_TYPE, TEST_DEVICE_TYPE_ID);
|
||||
DeviceType returned = (DeviceType) clearMetaEntryInfo.invoke(this.deviceTypeManagementService, deviceType);
|
||||
|
||||
Assert.assertNotNull(returned.getDeviceTypeMetaDefinition(), "The response object is null.");
|
||||
}
|
||||
}
|
@ -0,0 +1,132 @@
|
||||
/*
|
||||
* 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.util;
|
||||
|
||||
import org.wso2.carbon.device.mgt.common.Device;
|
||||
import org.wso2.carbon.device.mgt.common.EnrolmentInfo;
|
||||
import org.wso2.carbon.device.mgt.common.Feature;
|
||||
import org.wso2.carbon.device.mgt.common.device.details.DeviceInfo;
|
||||
import org.wso2.carbon.device.mgt.common.push.notification.PushNotificationConfig;
|
||||
import org.wso2.carbon.device.mgt.common.type.mgt.DeviceTypeMetaDefinition;
|
||||
import org.wso2.carbon.device.mgt.core.dto.DeviceType;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Date;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* Helper class for Device Management API test cases.
|
||||
*/
|
||||
public class DeviceMgtAPITestHelper {
|
||||
|
||||
private static final String DEVICE_TYPE_DESCRIPTION = "Dummy Description";
|
||||
public static final String DEVICE_TYPE = "TEST_DEVICE_TYPE";
|
||||
public static final String DEVICE_NAME = "TEST_DEVICE";
|
||||
public static final String DEVICE_IDENTIFIER = "12345";
|
||||
public final static String OWNER = "admin";
|
||||
|
||||
/**
|
||||
* Creates a Device Type with given name and given id.
|
||||
* If the name is null, the TEST_DEVICE_TYPE will be used as the name.
|
||||
*
|
||||
* @param name : Name of the device type.
|
||||
* @param deviceTypeId : The Id of the device type.
|
||||
* @return DeviceType
|
||||
*/
|
||||
public static DeviceType getDummyDeviceType(String name, int deviceTypeId) {
|
||||
DeviceType deviceType = new DeviceType();
|
||||
deviceType.setId(deviceTypeId);
|
||||
deviceType.setName(name != null ? name : DEVICE_TYPE);
|
||||
|
||||
DeviceTypeMetaDefinition deviceTypeMetaDefinition = new DeviceTypeMetaDefinition();
|
||||
deviceTypeMetaDefinition.setClaimable(true);
|
||||
deviceTypeMetaDefinition.setDescription(DEVICE_TYPE_DESCRIPTION);
|
||||
|
||||
PushNotificationConfig pushNotificationConfig =
|
||||
new PushNotificationConfig(name, true, null);
|
||||
deviceTypeMetaDefinition.setPushNotificationConfig(pushNotificationConfig);
|
||||
|
||||
deviceType.setDeviceTypeMetaDefinition(deviceTypeMetaDefinition);
|
||||
return deviceType;
|
||||
}
|
||||
|
||||
/**
|
||||
* Generates a list of device types.
|
||||
*
|
||||
* @param count: The number of device types that is needed.
|
||||
* @return List<DeviceType> : A list of device types.
|
||||
*/
|
||||
public static List<DeviceType> getDummyDeviceTypeList(int count) {
|
||||
List<DeviceType> deviceTypes = new ArrayList<>();
|
||||
|
||||
for (int i = 0; i < count; i++) {
|
||||
DeviceType deviceType = getDummyDeviceType(DEVICE_TYPE + count, count);
|
||||
deviceTypes.add(deviceType);
|
||||
}
|
||||
|
||||
return deviceTypes;
|
||||
}
|
||||
|
||||
public static Device generateDummyDevice(String deviceType, String identifier) {
|
||||
Device device = new Device();
|
||||
device.setEnrolmentInfo(generateEnrollmentInfo(new Date().getTime(), new Date().getTime(), OWNER, EnrolmentInfo
|
||||
.OwnerShip.BYOD, EnrolmentInfo.Status.ACTIVE));
|
||||
device.setDescription("Test Description");
|
||||
device.setDeviceIdentifier(identifier);
|
||||
device.setType(deviceType);
|
||||
device.setDeviceInfo(generateDeviceInfo());
|
||||
device.setName(DEVICE_NAME);
|
||||
device.setFeatures(new ArrayList<>());
|
||||
device.setProperties(new ArrayList<>());
|
||||
return device;
|
||||
}
|
||||
|
||||
public static EnrolmentInfo generateEnrollmentInfo(long dateOfEnrollment, long dateOfLastUpdate,
|
||||
String owner, EnrolmentInfo.OwnerShip ownership,
|
||||
EnrolmentInfo.Status status) {
|
||||
EnrolmentInfo enrolmentInfo = new EnrolmentInfo();
|
||||
enrolmentInfo.setDateOfEnrolment(dateOfEnrollment);
|
||||
enrolmentInfo.setDateOfLastUpdate(dateOfLastUpdate);
|
||||
enrolmentInfo.setOwner(owner);
|
||||
enrolmentInfo.setOwnership(ownership);
|
||||
enrolmentInfo.setStatus(status);
|
||||
return enrolmentInfo;
|
||||
}
|
||||
|
||||
public static DeviceInfo generateDeviceInfo() {
|
||||
DeviceInfo deviceInfo = new DeviceInfo();
|
||||
deviceInfo.setIMEI("IMEI-12345");
|
||||
deviceInfo.setIMSI("IMSI-12344");
|
||||
deviceInfo.setDeviceModel("DUMMY_MODEL");
|
||||
deviceInfo.setVendor("WSO2");
|
||||
deviceInfo.setOsVersion("OREO");
|
||||
deviceInfo.setOsBuildDate("24-05-2017");
|
||||
deviceInfo.setBatteryLevel(25.0);
|
||||
deviceInfo.setInternalTotalMemory(1.5);
|
||||
deviceInfo.setInternalAvailableMemory(2.5);
|
||||
deviceInfo.setExternalTotalMemory(16.76);
|
||||
deviceInfo.setExternalAvailableMemory(4.56);
|
||||
deviceInfo.setConnectionType("CON_TYPE");
|
||||
deviceInfo.setSsid("SSID");
|
||||
deviceInfo.setCpuUsage(23.5);
|
||||
deviceInfo.setTotalRAMMemory(1.5);
|
||||
deviceInfo.setAvailableRAMMemory(2.33);
|
||||
deviceInfo.setPluggedIn(true);
|
||||
return deviceInfo;
|
||||
}
|
||||
}
|
@ -0,0 +1,34 @@
|
||||
#
|
||||
# Copyright (c) 2016, 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.
|
||||
#
|
||||
|
||||
#
|
||||
# This is the log4j configuration file used by WSO2 Carbon
|
||||
#
|
||||
# IMPORTANT : Please do not remove or change the names of any
|
||||
# of the Appender defined here. The layout pattern & log file
|
||||
# can be changed using the WSO2 Carbon Management Console, and those
|
||||
# settings will override the settings in this file.
|
||||
#
|
||||
|
||||
log4j.rootLogger=DEBUG, STD_OUT
|
||||
|
||||
# Redirect log messages to console
|
||||
log4j.appender.STD_OUT=org.apache.log4j.ConsoleAppender
|
||||
log4j.appender.STD_OUT.Target=System.out
|
||||
log4j.appender.STD_OUT.layout=org.apache.log4j.PatternLayout
|
||||
log4j.appender.STD_OUT.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n
|
@ -0,0 +1,33 @@
|
||||
|
||||
<!--
|
||||
~ 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.
|
||||
-->
|
||||
|
||||
<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd" >
|
||||
|
||||
<suite name="DeviceManagementAPI">
|
||||
<parameter name="useDefaultListeners" value="false"/>
|
||||
|
||||
<test name="API Unit Tests" preserve-order="true">
|
||||
<classes>
|
||||
<class name="org.wso2.carbon.device.mgt.jaxrs.service.impl.DeviceManagementServiceImplTest"/>
|
||||
<class name="org.wso2.carbon.device.mgt.jaxrs.service.impl.DeviceTypeManagementServiceTest"/>
|
||||
<class name="org.wso2.carbon.device.mgt.jaxrs.service.impl.DeviceTypeManagementAdminServiceTest"/>
|
||||
<class name="org.wso2.carbon.device.mgt.jaxrs.service.impl.DeviceAgentServiceTest"/>
|
||||
</classes>
|
||||
</test>
|
||||
</suite>
|
@ -0,0 +1,129 @@
|
||||
/*
|
||||
* 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.core.cache;
|
||||
|
||||
import org.mockito.Mockito;
|
||||
import org.testng.Assert;
|
||||
import org.testng.annotations.BeforeClass;
|
||||
import org.testng.annotations.Test;
|
||||
import org.wso2.carbon.context.PrivilegedCarbonContext;
|
||||
import org.wso2.carbon.device.mgt.common.Device;
|
||||
import org.wso2.carbon.device.mgt.common.DeviceIdentifier;
|
||||
import org.wso2.carbon.device.mgt.common.DeviceManagementException;
|
||||
import org.wso2.carbon.device.mgt.core.cache.impl.DeviceCacheManagerImpl;
|
||||
import org.wso2.carbon.device.mgt.core.common.BaseDeviceManagementTest;
|
||||
import org.wso2.carbon.device.mgt.core.common.TestDataHolder;
|
||||
import org.wso2.carbon.device.mgt.core.config.DeviceConfigurationManager;
|
||||
import org.wso2.carbon.device.mgt.core.config.DeviceManagementConfig;
|
||||
import org.wso2.carbon.device.mgt.core.config.cache.DeviceCacheConfiguration;
|
||||
import org.wso2.carbon.utils.multitenancy.MultitenantConstants;
|
||||
import java.io.File;
|
||||
import java.io.IOException;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
/*
|
||||
Unit tests for DeviceCacheManagerImpl
|
||||
*/
|
||||
public class DeviceCacheManagerImplTest extends BaseDeviceManagementTest {
|
||||
private static final int NO_OF_DEVICES = 5;
|
||||
private static final String UPDATE_NAME = "updatedName";
|
||||
private static final String DEVICE_TYPE = "TEST_TYPE";
|
||||
private static final String DEVICE_ID_PREFIX = "TEST-DEVICE-ID-";
|
||||
private DeviceCacheManagerImpl deviceCacheManager;
|
||||
private List<DeviceIdentifier> deviceIds = new ArrayList<>();
|
||||
private List<Device> devices = new ArrayList<>();
|
||||
private List<DeviceCacheKey> deviceCacheKeyList = new ArrayList<>();
|
||||
|
||||
@BeforeClass
|
||||
public void init() throws DeviceManagementException, IOException {
|
||||
DeviceConfigurationManager.getInstance().initConfig();
|
||||
for (int i = 0; i < NO_OF_DEVICES; i++) {
|
||||
deviceIds.add(new DeviceIdentifier(DEVICE_ID_PREFIX + i, DEVICE_TYPE));
|
||||
}
|
||||
devices = TestDataHolder.generateDummyDeviceData(this.deviceIds);
|
||||
deviceCacheManager = Mockito.mock(DeviceCacheManagerImpl.class, Mockito.CALLS_REAL_METHODS);
|
||||
DeviceCacheConfiguration configuration = new DeviceCacheConfiguration();
|
||||
configuration.setEnabled(true);
|
||||
DeviceManagementConfig config = DeviceConfigurationManager.getInstance().getDeviceManagementConfig();
|
||||
config.setDeviceCacheConfiguration(configuration);
|
||||
initializeCarbonContext();
|
||||
}
|
||||
|
||||
private void initializeCarbonContext() throws IOException {
|
||||
if (System.getProperty("carbon.home") == null) {
|
||||
File file = new File("src/test/resources");
|
||||
if (file.exists()) {
|
||||
System.setProperty("carbon.home", file.getAbsolutePath());
|
||||
}
|
||||
}
|
||||
PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantDomain(
|
||||
org.wso2.carbon.base.MultitenantConstants.SUPER_TENANT_DOMAIN_NAME);
|
||||
PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantId(
|
||||
org.wso2.carbon.base.MultitenantConstants.SUPER_TENANT_ID);
|
||||
}
|
||||
|
||||
@Test(description = "Adding all test devices to the cache")
|
||||
public void testAddDeviceToCache() throws DeviceManagementException {
|
||||
for (int i = 0; i < NO_OF_DEVICES; i++) {
|
||||
deviceCacheManager.addDeviceToCache(deviceIds.get(i), devices.get(i), MultitenantConstants.SUPER_TENANT_ID);
|
||||
}
|
||||
}
|
||||
|
||||
@Test(description = "Adding existing device again", dependsOnMethods = {"testAddDeviceToCache"})
|
||||
public void testAddExistingDeviceToCache() throws DeviceManagementException {
|
||||
deviceCacheManager.addDeviceToCache(deviceIds.get(0), devices.get(0), MultitenantConstants.SUPER_TENANT_ID);
|
||||
}
|
||||
|
||||
@Test(description = "test updating and getting a device in Cache",
|
||||
dependsOnMethods = {"testAddExistingDeviceToCache"})
|
||||
public void testUpdateDeviceInCache() {
|
||||
devices.get(0).setName(UPDATE_NAME);
|
||||
deviceCacheManager.updateDeviceInCache(deviceIds.get(0), devices.get(0), MultitenantConstants.SUPER_TENANT_ID);
|
||||
Device tempDevice = deviceCacheManager.getDeviceFromCache(deviceIds.get(0), MultitenantConstants
|
||||
.SUPER_TENANT_ID);
|
||||
Assert.assertEquals(tempDevice.getName(), UPDATE_NAME,"Device name not updated in the cache");
|
||||
}
|
||||
|
||||
@Test(description = "test getting a device from cache", dependsOnMethods = {"testAddDeviceToCache"})
|
||||
public void testGetDeviceFromCache() throws DeviceManagementException {
|
||||
Device tempDevice = deviceCacheManager.getDeviceFromCache(deviceIds.get(1), MultitenantConstants
|
||||
.SUPER_TENANT_ID);
|
||||
Assert.assertEquals(tempDevice, devices.get(1),"Received device from cache is not matching " +
|
||||
"with the saved device");
|
||||
}
|
||||
|
||||
@Test(description = "test removing a device from cache", dependsOnMethods = {"testUpdateDeviceInCache"})
|
||||
public void testRemoveDeviceFromCache() throws DeviceManagementException {
|
||||
deviceCacheManager.removeDeviceFromCache(deviceIds.get(0), MultitenantConstants.SUPER_TENANT_ID);
|
||||
}
|
||||
|
||||
@Test(description = "test removing list of devices from cache", dependsOnMethods = {"testRemoveDeviceFromCache"})
|
||||
public void testRemoveDevicesFromCache() {
|
||||
//starting from index 1 since 0 is already deleted
|
||||
for (int i = 1; i < NO_OF_DEVICES; i++) {
|
||||
DeviceCacheKey deviceCacheKey = new DeviceCacheKey();
|
||||
deviceCacheKey.setDeviceId(devices.get(i).getDeviceIdentifier());
|
||||
deviceCacheKey.setDeviceType(devices.get(i).getType());
|
||||
deviceCacheKey.setTenantId(MultitenantConstants.SUPER_TENANT_ID);
|
||||
deviceCacheKeyList.add(deviceCacheKey);
|
||||
}
|
||||
deviceCacheManager.removeDevicesFromCache(deviceCacheKeyList);
|
||||
}
|
||||
}
|
@ -0,0 +1,157 @@
|
||||
/*
|
||||
* 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.core.service;
|
||||
|
||||
import org.testng.annotations.BeforeClass;
|
||||
import org.testng.annotations.Test;
|
||||
import org.wso2.carbon.device.mgt.common.DeviceIdentifier;
|
||||
import org.wso2.carbon.device.mgt.common.DeviceNotFoundException;
|
||||
import org.wso2.carbon.device.mgt.common.group.mgt.GroupManagementException;
|
||||
import org.wso2.carbon.device.mgt.common.group.mgt.RoleDoesNotExistException;
|
||||
import org.wso2.carbon.device.mgt.core.TestUtils;
|
||||
import org.wso2.carbon.device.mgt.core.common.BaseDeviceManagementTest;
|
||||
import org.wso2.carbon.device.mgt.core.dao.GroupManagementDAOFactory;
|
||||
|
||||
import javax.sql.DataSource;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* This test class is used for for testing negative scenarios of {@link GroupManagementProviderService}
|
||||
*/
|
||||
public class GroupManagementProviderServiceNegativeTest extends BaseDeviceManagementTest {
|
||||
private GroupManagementProviderService groupManagementProviderService;
|
||||
|
||||
@BeforeClass
|
||||
@Override
|
||||
public void init() throws Exception {
|
||||
DataSource datasource = this.getDataSource(this.
|
||||
readDataSourceConfig("src/test/resources/config/datasource/no-table-data-source-config.xml"));
|
||||
GroupManagementDAOFactory.init(datasource);
|
||||
groupManagementProviderService = new GroupManagementProviderServiceImpl();
|
||||
}
|
||||
|
||||
@Test(description = "This method tests the addDevices method under negative scenarios",
|
||||
expectedExceptions = {GroupManagementException.class},
|
||||
expectedExceptionsMessageRegExp = "Error occurred while adding device to group.*")
|
||||
public void testAddDevicesScenario1() throws GroupManagementException, DeviceNotFoundException {
|
||||
List<DeviceIdentifier> list = TestUtils.getDeviceIdentifiersList();
|
||||
groupManagementProviderService.addDevices(1, list);
|
||||
}
|
||||
|
||||
@Test(description = "This method tests the addDevices method under negative circumstances", expectedExceptions =
|
||||
{GroupManagementException.class}, expectedExceptionsMessageRegExp = "Error occurred in addDevices for.*")
|
||||
public void testAddDevicesScenario2() throws GroupManagementException, DeviceNotFoundException {
|
||||
DeviceIdentifier deviceIdentifier = new DeviceIdentifier("test", "test");
|
||||
List<DeviceIdentifier> list = new ArrayList<>();
|
||||
list.add(deviceIdentifier);
|
||||
groupManagementProviderService.addDevices(1, list);
|
||||
}
|
||||
|
||||
@Test(description = "This method tests the getGroup method of the GroupManagementProviderService under "
|
||||
+ "negative conditions", expectedExceptions = {GroupManagementException.class},
|
||||
expectedExceptionsMessageRegExp = "Error occurred while obtaining group.*")
|
||||
public void testGetGroup() throws GroupManagementException {
|
||||
groupManagementProviderService.getGroup(1);
|
||||
}
|
||||
|
||||
@Test(description = "This method tests the getGroup method of the GroupManagementProviderService under "
|
||||
+ "negative conditions", expectedExceptions = {GroupManagementException.class},
|
||||
expectedExceptionsMessageRegExp = "Error occurred while obtaining group with name.*")
|
||||
public void testGetGroupWithName() throws GroupManagementException {
|
||||
groupManagementProviderService.getGroup("1");
|
||||
}
|
||||
|
||||
@Test(description = "This method tests the getGroups method of the GroupManagementProviderService under negative "
|
||||
+ "conditions", expectedExceptions = {GroupManagementException.class}, expectedExceptionsMessageRegExp =
|
||||
"Error occurred while retrieving all groups in tenant.*")
|
||||
public void testGetGroups() throws GroupManagementException {
|
||||
groupManagementProviderService.getGroups();
|
||||
}
|
||||
|
||||
@Test(description = "This method tests the getGroups method of the GroupManagementProviderService under negative "
|
||||
+ "conditions", expectedExceptions = {GroupManagementException.class}, expectedExceptionsMessageRegExp =
|
||||
"Error occurred while retrieving all groups accessible to user.*")
|
||||
public void testGetGroupsWithUserName() throws GroupManagementException {
|
||||
groupManagementProviderService.getGroups("test");
|
||||
}
|
||||
|
||||
@Test(description = "This method tests the getGroupCount method under negative circumstances", expectedExceptions
|
||||
= {GroupManagementException.class}, expectedExceptionsMessageRegExp = "Error occurred while retrieving all "
|
||||
+ "groups in tenant")
|
||||
public void testGetGroupCount() throws GroupManagementException {
|
||||
groupManagementProviderService.getGroupCount();
|
||||
}
|
||||
|
||||
@Test(description = "This method tests the getGroupCount method with username under negative circumstances",
|
||||
expectedExceptions = {GroupManagementException.class}, expectedExceptionsMessageRegExp = "Error occurred "
|
||||
+ "while retrieving group count of user.*")
|
||||
public void testGetGroupCountWithUserName() throws GroupManagementException {
|
||||
groupManagementProviderService.getGroupCount("test");
|
||||
|
||||
}
|
||||
|
||||
@Test(description = "This method tests the getGroups method with pagination request under negative "
|
||||
+ "circumstances", expectedExceptions = {GroupManagementException.class},
|
||||
expectedExceptionsMessageRegExp = "Error occurred while retrieving all groups in tenant")
|
||||
public void testGetGroupsWithPaginationRequest() throws GroupManagementException {
|
||||
groupManagementProviderService.getGroups(TestUtils.createPaginationRequest());
|
||||
}
|
||||
|
||||
@Test(description = "This method tests the getGroups method with pagination request and username under negative "
|
||||
+ "circumstances", expectedExceptions = {GroupManagementException.class},
|
||||
expectedExceptionsMessageRegExp = "Error occurred while retrieving all groups accessible to user.")
|
||||
public void testGetGroupsWithPaginationRequestAndUserName() throws GroupManagementException {
|
||||
groupManagementProviderService.getGroups("test", TestUtils.createPaginationRequest());
|
||||
}
|
||||
|
||||
@Test(description = "This method tests the get roles method under negative circumstances",
|
||||
expectedExceptions = {GroupManagementException.class}, expectedExceptionsMessageRegExp = "Error occurred "
|
||||
+ "while retrieving all groups in tenant.*")
|
||||
public void testManageGroupSharing() throws GroupManagementException, RoleDoesNotExistException {
|
||||
groupManagementProviderService.getRoles(1);
|
||||
}
|
||||
|
||||
@Test(description = "This method tests the getDeviceCount under negative circumstances.", expectedExceptions =
|
||||
{GroupManagementException.class}, expectedExceptionsMessageRegExp = "Error occurred while retrieving all "
|
||||
+ "groups in tenant.*")
|
||||
public void testGetDeviceCount() throws GroupManagementException {
|
||||
groupManagementProviderService.getDeviceCount(1);
|
||||
}
|
||||
|
||||
@Test(description = "This method tests the getDevices method under negative circumstances", expectedExceptions =
|
||||
{GroupManagementException.class})
|
||||
public void testGetDevicesWithPagination() throws GroupManagementException {
|
||||
groupManagementProviderService.getDevices(1, 0, 10);
|
||||
}
|
||||
|
||||
@Test(description = "This method tests the getGroupCount with username when the user name is given as null",
|
||||
expectedExceptions = {GroupManagementException.class}, expectedExceptionsMessageRegExp = "Received empty "
|
||||
+ "user name for getGroupCount.*")
|
||||
public void testGetGroupCountWithUserName2() throws GroupManagementException {
|
||||
groupManagementProviderService.getGroupCount(null);
|
||||
}
|
||||
|
||||
@Test(description = "This method tests getGroups method under negative circumstances",
|
||||
expectedExceptionsMessageRegExp = "Received empty device identifier for getGroups",
|
||||
expectedExceptions = {GroupManagementException.class})
|
||||
public void testGetGroupsWithDeviceIdentifier() throws GroupManagementException {
|
||||
groupManagementProviderService.getGroups((DeviceIdentifier) null);
|
||||
}
|
||||
}
|
@ -0,0 +1,490 @@
|
||||
/*
|
||||
* 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.policy.mgt.core.mgt.impl;
|
||||
|
||||
import org.apache.commons.logging.Log;
|
||||
import org.apache.commons.logging.LogFactory;
|
||||
import org.powermock.api.mockito.PowerMockito;
|
||||
import org.testng.Assert;
|
||||
import org.testng.annotations.BeforeClass;
|
||||
import org.testng.annotations.Test;
|
||||
import org.testng.internal.collections.Pair;
|
||||
import org.wso2.carbon.context.PrivilegedCarbonContext;
|
||||
import org.wso2.carbon.device.mgt.common.DeviceIdentifier;
|
||||
import org.wso2.carbon.device.mgt.common.IllegalTransactionStateException;
|
||||
import org.wso2.carbon.device.mgt.common.group.mgt.DeviceGroup;
|
||||
import org.wso2.carbon.device.mgt.common.operation.mgt.OperationManager;
|
||||
import org.wso2.carbon.device.mgt.common.policy.mgt.Profile;
|
||||
import org.wso2.carbon.device.mgt.common.policy.mgt.ProfileFeature;
|
||||
import org.wso2.carbon.device.mgt.core.operation.mgt.OperationManagerImpl;
|
||||
import org.wso2.carbon.policy.mgt.common.FeatureManagementException;
|
||||
import org.wso2.carbon.policy.mgt.core.BasePolicyManagementDAOTest;
|
||||
import org.wso2.carbon.policy.mgt.core.PolicyManagerServiceImpl;
|
||||
import org.wso2.carbon.policy.mgt.core.dao.FeatureDAO;
|
||||
import org.wso2.carbon.policy.mgt.core.dao.FeatureManagerDAOException;
|
||||
import org.wso2.carbon.policy.mgt.core.dao.PolicyManagementDAOFactory;
|
||||
import org.wso2.carbon.policy.mgt.core.dao.ProfileDAO;
|
||||
import org.wso2.carbon.policy.mgt.core.dao.ProfileManagerDAOException;
|
||||
import org.wso2.carbon.policy.mgt.core.mgt.FeatureManager;
|
||||
import org.wso2.carbon.policy.mgt.core.mock.TypeXDeviceManagementService;
|
||||
import org.wso2.carbon.policy.mgt.core.util.FeatureCreator;
|
||||
import org.wso2.carbon.policy.mgt.core.util.ProfileCreator;
|
||||
|
||||
import javax.sql.DataSource;
|
||||
import java.sql.Connection;
|
||||
import java.sql.SQLException;
|
||||
import java.sql.Timestamp;
|
||||
import java.util.List;
|
||||
|
||||
import static org.mockito.Matchers.any;
|
||||
import static org.mockito.Matchers.anyBoolean;
|
||||
import static org.mockito.Matchers.anyInt;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
public class FeatureManagerImplTest extends BasePolicyManagementDAOTest {
|
||||
|
||||
private static final Log log = LogFactory.getLog(PolicyManagerServiceImpl.class);
|
||||
|
||||
private static final String DEVICE4 = "device4";
|
||||
private static final String GROUP4 = "group4";
|
||||
private static final String POLICY4 = "policy4";
|
||||
private static final String DEVICE_TYPE_D = "deviceTypeD";
|
||||
|
||||
private OperationManager operationManager;
|
||||
private FeatureManager featureManager;
|
||||
private Profile profile1;
|
||||
private List<ProfileFeature> profileFeaturesList1;
|
||||
|
||||
@BeforeClass
|
||||
public void initialize() throws Exception {
|
||||
log.info("Initializing feature manager tests");
|
||||
super.initializeServices();
|
||||
|
||||
int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId();
|
||||
|
||||
deviceMgtService.registerDeviceType(new TypeXDeviceManagementService(DEVICE_TYPE_D));
|
||||
operationManager = new OperationManagerImpl(DEVICE_TYPE_D);
|
||||
featureManager = new FeatureManagerImpl();
|
||||
|
||||
enrollDevice(DEVICE4, DEVICE_TYPE_D);
|
||||
createDeviceGroup(GROUP4);
|
||||
DeviceGroup group4 = groupMgtService.getGroup(GROUP4);
|
||||
addDeviceToGroup(new DeviceIdentifier(DEVICE4, DEVICE_TYPE_D), GROUP4);
|
||||
|
||||
Profile profile = new Profile();
|
||||
profile.setTenantId(tenantId);
|
||||
profile.setCreatedDate(new Timestamp(System.currentTimeMillis()));
|
||||
profile.setDeviceType(DEVICE_TYPE_D);
|
||||
}
|
||||
|
||||
@Test(description = "This test case tests handling UnsupportedOperationException when adding new profile feature",
|
||||
expectedExceptions = {UnsupportedOperationException.class})
|
||||
public void testAddProfileFeature() throws Exception {
|
||||
Profile profile = ProfileCreator.getProfile(FeatureCreator.getFeatureList(), DEVICE_TYPE_D);
|
||||
profile1 = profileManager.addProfile(profile);
|
||||
ProfileFeature profileFeature = profile.getProfileFeaturesList().get(0);
|
||||
featureManager.addProfileFeature(profileFeature, profile1.getProfileId());
|
||||
}
|
||||
|
||||
|
||||
@Test(description = "This test case tests adding new profile feature to a non existent profile",
|
||||
dependsOnMethods = "testAddProfileFeature",
|
||||
expectedExceptions = {FeatureManagementException.class})
|
||||
public void testAddProfileFeatureThrowingFeatureManagementException() throws Exception {
|
||||
Profile profile = ProfileCreator.getProfile(FeatureCreator.getFeatureList(), DEVICE_TYPE_D);
|
||||
int nonExistentProfileId = 9999;
|
||||
ProfileFeature profileFeature = profile.getProfileFeaturesList().get(0);
|
||||
//Adding profile
|
||||
featureManager.addProfileFeature(profileFeature, nonExistentProfileId);
|
||||
}
|
||||
|
||||
@Test(description = "This test case tests handling ProfileManagerDAOException when adding new profile feature",
|
||||
dependsOnMethods = "testAddProfileFeature")
|
||||
public void testAddProfileFeatureThrowingProfileManagerDAOException() throws Exception {
|
||||
Profile profile = ProfileCreator.getProfile(FeatureCreator.getFeatureList(), DEVICE_TYPE_D);
|
||||
profile1 = profileManager.addProfile(profile);
|
||||
|
||||
ProfileDAO profileDAO = mock(ProfileDAO.class);
|
||||
when(profileDAO.getProfile(anyInt())).thenThrow(new ProfileManagerDAOException());
|
||||
|
||||
ProfileFeature profileFeature = profile.getProfileFeaturesList().get(0);
|
||||
testThrowingException(featureManager,
|
||||
profileFeature,
|
||||
p -> featureManager.addProfileFeature((ProfileFeature) p, profile1.getProfileId()),
|
||||
"profileDAO", profileDAO,
|
||||
ProfileManagerDAOException.class);
|
||||
}
|
||||
|
||||
@Test(description = "This test case tests handling FeatureManagerDAOException when adding new profile feature",
|
||||
dependsOnMethods = "testAddProfileFeatureThrowingProfileManagerDAOException")
|
||||
public void testAddProfileFeatureThrowingFeatureManagerDAOException() throws Exception {
|
||||
Profile profile = ProfileCreator.getProfile(FeatureCreator.getFeatureList(), DEVICE_TYPE_D);
|
||||
profile1 = profileManager.addProfile(profile);
|
||||
|
||||
FeatureDAO featureDAO = mock(FeatureDAO.class);
|
||||
when(featureDAO.addProfileFeature(any(ProfileFeature.class), anyInt())).thenThrow(
|
||||
new FeatureManagerDAOException());
|
||||
|
||||
ProfileFeature profileFeature = profile.getProfileFeaturesList().get(0);
|
||||
testThrowingException(featureManager,
|
||||
profileFeature,
|
||||
p -> featureManager.addProfileFeature((ProfileFeature) p, profile1.getProfileId()),
|
||||
"featureDAO", featureDAO,
|
||||
FeatureManagerDAOException.class);
|
||||
}
|
||||
|
||||
@Test(description = "This test case tests handling SQLException when adding new profile feature",
|
||||
dependsOnMethods = "testAddProfileFeatureThrowingFeatureManagerDAOException",
|
||||
expectedExceptions = IllegalTransactionStateException.class)
|
||||
public void testAddProfileThrowingIllegalTransactionStateException() throws Exception {
|
||||
//Creating profile object
|
||||
Profile profile = ProfileCreator.getProfile(FeatureCreator.getFeatureList(), DEVICE_TYPE_D);
|
||||
ProfileFeature profileFeature = profile.getProfileFeaturesList().get(0);
|
||||
|
||||
Pair<Connection, Pair<DataSource, DataSource>> pair = mockConnection();
|
||||
PowerMockito.doThrow(new SQLException()).when(pair.first()).setAutoCommit(anyBoolean());
|
||||
try {
|
||||
featureManager.addProfileFeature(profileFeature, profile.getProfileId());
|
||||
} finally {
|
||||
PolicyManagementDAOFactory.init(pair.second().first());
|
||||
}
|
||||
}
|
||||
|
||||
@Test(description = "This test case tests adding new profile features",
|
||||
dependsOnMethods = "testAddProfileThrowingIllegalTransactionStateException")
|
||||
public void testAddProfileFeatures() throws Exception {
|
||||
Profile profile = ProfileCreator.getProfile(FeatureCreator.getFeatureList(), DEVICE_TYPE_D);
|
||||
//Adding profile
|
||||
profile1 = profileManager.addProfile(profile);
|
||||
profileFeaturesList1 = featureManager.addProfileFeatures(profile.getProfileFeaturesList(),
|
||||
profile1.getProfileId());
|
||||
Assert.assertEquals(profileFeaturesList1.size(), profile.getProfileFeaturesList().size());
|
||||
}
|
||||
|
||||
@Test(description = "This test case tests adding new profile features to a non existent profile",
|
||||
dependsOnMethods = "testAddProfileFeatures",
|
||||
expectedExceptions = {FeatureManagementException.class})
|
||||
public void testAddProfileFeaturesThrowingFeatureManagementException() throws Exception {
|
||||
Profile profile = ProfileCreator.getProfile(FeatureCreator.getFeatureList(), DEVICE_TYPE_D);
|
||||
int nonExistentProfileId = 9999;
|
||||
//Adding profile
|
||||
featureManager.addProfileFeatures(profile.getProfileFeaturesList(), nonExistentProfileId);
|
||||
}
|
||||
|
||||
@Test(description = "This test case tests handling ProfileManagerDAOException when adding new profile feature",
|
||||
dependsOnMethods = "testAddProfileFeatures")
|
||||
public void testAddProfileFeaturesThrowingProfileManagerDAOException() throws Exception {
|
||||
Profile profile = ProfileCreator.getProfile(FeatureCreator.getFeatureList(), DEVICE_TYPE_D);
|
||||
profile1 = profileManager.addProfile(profile);
|
||||
|
||||
ProfileDAO profileDAO = mock(ProfileDAO.class);
|
||||
when(profileDAO.getProfile(anyInt())).thenThrow(new ProfileManagerDAOException());
|
||||
|
||||
List<ProfileFeature> profileFeaturesList = profile.getProfileFeaturesList();
|
||||
testThrowingException(featureManager,
|
||||
profileFeaturesList,
|
||||
p -> featureManager.addProfileFeatures((List<ProfileFeature>) p, profile1.getProfileId()),
|
||||
"profileDAO", profileDAO,
|
||||
ProfileManagerDAOException.class);
|
||||
}
|
||||
|
||||
@Test(description = "This test case tests handling FeatureManagerDAOException when adding new profile feature",
|
||||
dependsOnMethods = "testAddProfileFeaturesThrowingProfileManagerDAOException")
|
||||
public void testAddProfileFeaturesThrowingFeatureManagerDAOException() throws Exception {
|
||||
Profile profile = ProfileCreator.getProfile(FeatureCreator.getFeatureList(), DEVICE_TYPE_D);
|
||||
profile1 = profileManager.addProfile(profile);
|
||||
|
||||
FeatureDAO featureDAO = mock(FeatureDAO.class);
|
||||
when(featureDAO.addProfileFeature(any(ProfileFeature.class), anyInt())).thenThrow(
|
||||
new FeatureManagerDAOException());
|
||||
|
||||
List<ProfileFeature> profileFeaturesList = profile.getProfileFeaturesList();
|
||||
testThrowingException(featureManager,
|
||||
profileFeaturesList,
|
||||
p -> featureManager.addProfileFeatures((List<ProfileFeature>) p, profile1.getProfileId()),
|
||||
"featureDAO", featureDAO,
|
||||
FeatureManagerDAOException.class);
|
||||
}
|
||||
|
||||
@Test(description = "This test case tests handling SQLException when adding new profile feature",
|
||||
dependsOnMethods = "testAddProfileFeaturesThrowingFeatureManagerDAOException",
|
||||
expectedExceptions = IllegalTransactionStateException.class)
|
||||
public void testAddProfileFeaturesThrowingIllegalTransactionStateException() throws Exception {
|
||||
//Creating profile object
|
||||
Profile profile = ProfileCreator.getProfile(FeatureCreator.getFeatureList(), DEVICE_TYPE_D);
|
||||
List<ProfileFeature> profileFeaturesList = profile.getProfileFeaturesList();
|
||||
|
||||
Pair<Connection, Pair<DataSource, DataSource>> pair = mockConnection();
|
||||
PowerMockito.doThrow(new SQLException()).when(pair.first()).setAutoCommit(anyBoolean());
|
||||
try {
|
||||
featureManager.addProfileFeatures(profileFeaturesList, profile.getProfileId());
|
||||
} finally {
|
||||
PolicyManagementDAOFactory.init(pair.second().first());
|
||||
}
|
||||
}
|
||||
|
||||
@Test(description = "This test case tests handling UnsupportedOperationException when updating a profile feature",
|
||||
expectedExceptions = {UnsupportedOperationException.class})
|
||||
public void testUpdateProfileFeature() throws Exception {
|
||||
Profile profile = ProfileCreator.getProfile(FeatureCreator.getFeatureList(), DEVICE_TYPE_D);
|
||||
profile1 = profileManager.addProfile(profile);
|
||||
ProfileFeature profileFeature = profile.getProfileFeaturesList().get(0);
|
||||
featureManager.updateProfileFeature(profileFeature, profile1.getProfileId());
|
||||
}
|
||||
|
||||
@Test(description = "This test case tests updating a non existent profile feature",
|
||||
expectedExceptions = {FeatureManagementException.class},
|
||||
dependsOnMethods = "testUpdateProfileFeature")
|
||||
public void testUpdateProfileFeatureThrowingFeatureManagementException() throws Exception {
|
||||
Profile profile = ProfileCreator.getProfile(FeatureCreator.getFeatureList(), DEVICE_TYPE_D);
|
||||
int nonExistentProfileId = 9999;
|
||||
ProfileFeature profileFeature = profile.getProfileFeaturesList().get(0);
|
||||
featureManager.updateProfileFeature(profileFeature, nonExistentProfileId);
|
||||
}
|
||||
|
||||
@Test(description = "This test case tests handling ProfileManagerDAOException when adding new profile feature",
|
||||
dependsOnMethods = "testAddProfileFeature")
|
||||
public void testUpdateProfileFeatureThrowingProfileManagerDAOException() throws Exception {
|
||||
Profile profile = ProfileCreator.getProfile(FeatureCreator.getFeatureList(), DEVICE_TYPE_D);
|
||||
profile1 = profileManager.addProfile(profile);
|
||||
|
||||
ProfileDAO profileDAO = mock(ProfileDAO.class);
|
||||
when(profileDAO.getProfile(anyInt())).thenThrow(new ProfileManagerDAOException());
|
||||
|
||||
ProfileFeature profileFeature = profile.getProfileFeaturesList().get(0);
|
||||
testThrowingException(featureManager,
|
||||
profileFeature,
|
||||
p -> featureManager.updateProfileFeature((ProfileFeature) p, profile1.getProfileId()),
|
||||
"profileDAO", profileDAO,
|
||||
ProfileManagerDAOException.class);
|
||||
}
|
||||
|
||||
@Test(description = "This test case tests handling FeatureManagerDAOException when adding new profile feature",
|
||||
dependsOnMethods = "testUpdateProfileFeatureThrowingProfileManagerDAOException")
|
||||
public void testUpdateProfileFeatureThrowingFeatureManagerDAOException() throws Exception {
|
||||
Profile profile = ProfileCreator.getProfile(FeatureCreator.getFeatureList(), DEVICE_TYPE_D);
|
||||
profile1 = profileManager.addProfile(profile);
|
||||
|
||||
FeatureDAO featureDAO = mock(FeatureDAO.class);
|
||||
when(featureDAO.updateProfileFeature(any(ProfileFeature.class), anyInt())).thenThrow(
|
||||
new FeatureManagerDAOException());
|
||||
|
||||
ProfileFeature profileFeature = profile.getProfileFeaturesList().get(0);
|
||||
testThrowingException(featureManager,
|
||||
profileFeature,
|
||||
p -> featureManager.updateProfileFeature((ProfileFeature) p, profile1.getProfileId()),
|
||||
"featureDAO", featureDAO,
|
||||
FeatureManagerDAOException.class);
|
||||
}
|
||||
|
||||
@Test(description = "This test case tests updating profile features",
|
||||
dependsOnMethods = "testAddProfileFeatures")
|
||||
public void testUpdateProfileFeatures() throws Exception {
|
||||
String newFeatureCode = "C002";
|
||||
Profile profile = ProfileCreator.getProfile(FeatureCreator.getFeatureList(), DEVICE_TYPE_D);
|
||||
int createdProfileId = profileManager.addProfile(profile).getProfileId();
|
||||
profileFeaturesList1.get(0).setFeatureCode(newFeatureCode);
|
||||
List<ProfileFeature> updatedProfileFeatures = featureManager.updateProfileFeatures(profileFeaturesList1,
|
||||
createdProfileId);
|
||||
Assert.assertEquals(updatedProfileFeatures.get(0).getFeatureCode(), newFeatureCode);
|
||||
}
|
||||
|
||||
@Test(description = "This test case tests handling FeatureManagementException when updating profile features",
|
||||
dependsOnMethods = "testUpdateProfileFeatures",
|
||||
expectedExceptions = {FeatureManagementException.class})
|
||||
public void testUpdateProfileFeaturesThrowingFeatureManagementException() throws Exception {
|
||||
String newFeatureCode = "C002";
|
||||
int nonExistentProfileId = 9999;
|
||||
profileFeaturesList1.get(0).setFeatureCode(newFeatureCode);
|
||||
List<ProfileFeature> updatedProfileFeatures = featureManager.updateProfileFeatures(profileFeaturesList1,
|
||||
nonExistentProfileId);
|
||||
Assert.assertEquals(updatedProfileFeatures.get(0).getFeatureCode(), newFeatureCode);
|
||||
}
|
||||
|
||||
@Test(description = "This test case tests handling ProfileManagerDAOException when adding new profile feature",
|
||||
dependsOnMethods = "testUpdateProfileFeaturesThrowingFeatureManagementException")
|
||||
public void testUpdateProfileFeaturesThrowingProfileManagerDAOException() throws Exception {
|
||||
Profile profile = ProfileCreator.getProfile(FeatureCreator.getFeatureList(), DEVICE_TYPE_D);
|
||||
profile1 = profileManager.addProfile(profile);
|
||||
|
||||
ProfileDAO profileDAO = mock(ProfileDAO.class);
|
||||
when(profileDAO.getProfile(anyInt())).thenThrow(new ProfileManagerDAOException());
|
||||
|
||||
List<ProfileFeature> profileFeaturesList = profile.getProfileFeaturesList();
|
||||
testThrowingException(featureManager,
|
||||
profileFeaturesList,
|
||||
p -> featureManager
|
||||
.updateProfileFeatures((List<ProfileFeature>) p, profile1.getProfileId()),
|
||||
"profileDAO", profileDAO,
|
||||
ProfileManagerDAOException.class);
|
||||
}
|
||||
|
||||
@Test(description = "This test case tests handling FeatureManagerDAOException when adding new profile feature",
|
||||
dependsOnMethods = "testUpdateProfileFeaturesThrowingProfileManagerDAOException")
|
||||
public void testUpdateProfileFeaturesThrowingFeatureManagerDAOException() throws Exception {
|
||||
Profile profile = ProfileCreator.getProfile(FeatureCreator.getFeatureList(), DEVICE_TYPE_D);
|
||||
profile1 = profileManager.addProfile(profile);
|
||||
|
||||
FeatureDAO featureDAO = mock(FeatureDAO.class);
|
||||
when(featureDAO.addProfileFeature(any(ProfileFeature.class), anyInt())).thenThrow(
|
||||
new FeatureManagerDAOException());
|
||||
|
||||
List<ProfileFeature> profileFeaturesList = profile.getProfileFeaturesList();
|
||||
testThrowingException(featureManager,
|
||||
profileFeaturesList,
|
||||
p -> featureManager
|
||||
.updateProfileFeatures((List<ProfileFeature>) p, profile1.getProfileId()),
|
||||
"featureDAO", featureDAO,
|
||||
FeatureManagerDAOException.class);
|
||||
}
|
||||
|
||||
@Test(description = "This test case tests handling SQLException when adding new profile feature",
|
||||
dependsOnMethods = "testUpdateProfileFeaturesThrowingFeatureManagerDAOException",
|
||||
expectedExceptions = IllegalTransactionStateException.class)
|
||||
public void testUpdateProfileFeaturesThrowingIllegalTransactionStateException() throws Exception {
|
||||
//Creating profile object
|
||||
Profile profile = ProfileCreator.getProfile(FeatureCreator.getFeatureList(), DEVICE_TYPE_D);
|
||||
List<ProfileFeature> profileFeaturesList = profile.getProfileFeaturesList();
|
||||
|
||||
Pair<Connection, Pair<DataSource, DataSource>> pair = mockConnection();
|
||||
PowerMockito.doThrow(new SQLException()).when(pair.first()).setAutoCommit(anyBoolean());
|
||||
try {
|
||||
featureManager.updateProfileFeatures(profileFeaturesList, profile.getProfileId());
|
||||
} finally {
|
||||
PolicyManagementDAOFactory.init(pair.second().first());
|
||||
}
|
||||
}
|
||||
|
||||
@Test(description = "This test case tests retrieving all features of a device type",
|
||||
dependsOnMethods = "testUpdateProfileFeaturesThrowingIllegalTransactionStateException",
|
||||
expectedExceptions = FeatureManagementException.class)
|
||||
public void testGetAllFeatures() throws Exception {
|
||||
featureManager.getAllFeatures(DEVICE_TYPE_D);
|
||||
}
|
||||
|
||||
@Test(description = "This test case tests handling SQLException when all features of a device type",
|
||||
dependsOnMethods = "testGetAllFeatures",
|
||||
expectedExceptions = {IllegalTransactionStateException.class, FeatureManagementException.class})
|
||||
public void testGetAllFeaturesThrowingIllegalTransactionStateException() throws Exception {
|
||||
Pair<Connection, Pair<DataSource, DataSource>> pair = mockConnection();
|
||||
PowerMockito.doThrow(new SQLException()).when(pair.second().second()).getConnection();
|
||||
try {
|
||||
featureManager.getAllFeatures(DEVICE_TYPE_D);
|
||||
} finally {
|
||||
PolicyManagementDAOFactory.init(pair.second().first());
|
||||
}
|
||||
}
|
||||
|
||||
@Test(description = "This test case tests retrieving features of a profile",
|
||||
dependsOnMethods = "testGetAllFeaturesThrowingIllegalTransactionStateException")
|
||||
public void testGetFeaturesForProfile() throws Exception {
|
||||
featureManager.getFeaturesForProfile(profile1.getProfileId());
|
||||
}
|
||||
|
||||
@Test(description = "This test case tests retrieving features to a non existent profile",
|
||||
dependsOnMethods = "testGetFeaturesForProfile",
|
||||
expectedExceptions = {FeatureManagementException.class})
|
||||
public void testGetFeaturesForProfileThrowingFeatureManagementException() throws Exception {
|
||||
int nonExistentProfileId = 9999;
|
||||
featureManager.getFeaturesForProfile(nonExistentProfileId);
|
||||
}
|
||||
|
||||
@Test(description = "This test case tests handling ProfileManagerDAOException when retrieving features of a " +
|
||||
"profile",
|
||||
dependsOnMethods = "testGetFeaturesForProfile")
|
||||
public void testGetFeaturesForProfileThrowingProfileManagerDAOException() throws Exception {
|
||||
Profile profile = ProfileCreator.getProfile(FeatureCreator.getFeatureList(), DEVICE_TYPE_D);
|
||||
profile1 = profileManager.addProfile(profile);
|
||||
|
||||
ProfileDAO profileDAO = mock(ProfileDAO.class);
|
||||
when(profileDAO.getProfile(anyInt())).thenThrow(new ProfileManagerDAOException());
|
||||
|
||||
testThrowingException(featureManager,
|
||||
null,
|
||||
p -> featureManager.getFeaturesForProfile(profile1.getProfileId()),
|
||||
"profileDAO", profileDAO,
|
||||
ProfileManagerDAOException.class);
|
||||
}
|
||||
|
||||
@Test(description = "This test case tests handling FeatureManagerDAOException when retrieving features of a " +
|
||||
"profile",
|
||||
dependsOnMethods = "testGetFeaturesForProfileThrowingProfileManagerDAOException")
|
||||
public void testGetFeaturesForProfileThrowingFeatureManagerDAOException() throws Exception {
|
||||
Profile profile = ProfileCreator.getProfile(FeatureCreator.getFeatureList(), DEVICE_TYPE_D);
|
||||
profile1 = profileManager.addProfile(profile);
|
||||
|
||||
FeatureDAO featureDAO = mock(FeatureDAO.class);
|
||||
when(featureDAO.addProfileFeature(any(ProfileFeature.class), anyInt())).thenThrow(
|
||||
new FeatureManagerDAOException());
|
||||
|
||||
testThrowingException(featureManager,
|
||||
null,
|
||||
p -> featureManager.getFeaturesForProfile(profile1.getProfileId()),
|
||||
"featureDAO", featureDAO,
|
||||
FeatureManagerDAOException.class);
|
||||
}
|
||||
|
||||
@Test(description = "This test case tests handling SQLException when retrieving features of a profile",
|
||||
dependsOnMethods = "testGetFeaturesForProfileThrowingFeatureManagerDAOException",
|
||||
expectedExceptions = IllegalTransactionStateException.class)
|
||||
public void testGetFeaturesForProfileThrowingIllegalTransactionStateException() throws Exception {
|
||||
Pair<Connection, Pair<DataSource, DataSource>> pair = mockConnection();
|
||||
PowerMockito.doThrow(new SQLException()).when(pair.second().second()).getConnection();
|
||||
try {
|
||||
featureManager.getFeaturesForProfile(profile1.getProfileId());
|
||||
} finally {
|
||||
PolicyManagementDAOFactory.init(pair.second().first());
|
||||
}
|
||||
}
|
||||
|
||||
@Test(description = "This test case tests handling FeatureManagerDAOException when deleting features of a profile",
|
||||
dependsOnMethods = "testGetFeaturesForProfile")
|
||||
public void testDeleteFeaturesOfProfileThrowingFeatureManagerDAOException() throws Exception {
|
||||
Profile profile = ProfileCreator.getProfile(FeatureCreator.getFeatureList(), DEVICE_TYPE_D);
|
||||
profile1 = profileManager.addProfile(profile);
|
||||
|
||||
FeatureDAO featureDAO = mock(FeatureDAO.class);
|
||||
when(featureDAO.deleteFeaturesOfProfile(any(Profile.class))).thenThrow(new FeatureManagerDAOException());
|
||||
|
||||
testThrowingException(featureManager,
|
||||
profile1,
|
||||
p -> featureManager.deleteFeaturesOfProfile(profile),
|
||||
"featureDAO", featureDAO,
|
||||
FeatureManagerDAOException.class);
|
||||
}
|
||||
|
||||
@Test(description = "This test case tests handling SQLException when deleting features of a profile",
|
||||
dependsOnMethods = "testDeleteFeaturesOfProfileThrowingFeatureManagerDAOException",
|
||||
expectedExceptions = IllegalTransactionStateException.class)
|
||||
public void testDeleteFeaturesOfProfileThrowingIllegalTransactionStateException() throws Exception {
|
||||
Pair<Connection, Pair<DataSource, DataSource>> pair = mockConnection();
|
||||
PowerMockito.doThrow(new SQLException()).when(pair.second().second()).getConnection();
|
||||
try {
|
||||
featureManager.deleteFeaturesOfProfile(profile1);
|
||||
} finally {
|
||||
PolicyManagementDAOFactory.init(pair.second().first());
|
||||
}
|
||||
}
|
||||
|
||||
@Test(description = "This test case tests deleting features of a profile",
|
||||
dependsOnMethods = "testDeleteFeaturesOfProfileThrowingIllegalTransactionStateException")
|
||||
public void testDeleteFeaturesOfProfile() throws Exception {
|
||||
featureManager.deleteFeaturesOfProfile(profile1);
|
||||
}
|
||||
}
|
@ -0,0 +1,369 @@
|
||||
/*
|
||||
* 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.policy.mgt.core.mgt.impl;
|
||||
|
||||
import org.apache.commons.logging.Log;
|
||||
import org.apache.commons.logging.LogFactory;
|
||||
import org.powermock.api.mockito.PowerMockito;
|
||||
import org.testng.Assert;
|
||||
import org.testng.annotations.BeforeClass;
|
||||
import org.testng.annotations.Test;
|
||||
import org.testng.internal.collections.Pair;
|
||||
import org.wso2.carbon.device.mgt.common.DeviceIdentifier;
|
||||
import org.wso2.carbon.device.mgt.common.IllegalTransactionStateException;
|
||||
import org.wso2.carbon.device.mgt.common.group.mgt.DeviceGroup;
|
||||
import org.wso2.carbon.device.mgt.common.operation.mgt.OperationManager;
|
||||
import org.wso2.carbon.device.mgt.common.policy.mgt.Profile;
|
||||
import org.wso2.carbon.device.mgt.common.policy.mgt.ProfileFeature;
|
||||
import org.wso2.carbon.device.mgt.core.operation.mgt.OperationManagerImpl;
|
||||
import org.wso2.carbon.policy.mgt.common.ProfileManagementException;
|
||||
import org.wso2.carbon.policy.mgt.core.BasePolicyManagementDAOTest;
|
||||
import org.wso2.carbon.policy.mgt.core.PolicyManagerServiceImpl;
|
||||
import org.wso2.carbon.policy.mgt.core.dao.FeatureDAO;
|
||||
import org.wso2.carbon.policy.mgt.core.dao.FeatureManagerDAOException;
|
||||
import org.wso2.carbon.policy.mgt.core.dao.PolicyManagementDAOFactory;
|
||||
import org.wso2.carbon.policy.mgt.core.dao.ProfileDAO;
|
||||
import org.wso2.carbon.policy.mgt.core.dao.ProfileManagerDAOException;
|
||||
import org.wso2.carbon.policy.mgt.core.dao.impl.ProfileDAOImpl;
|
||||
import org.wso2.carbon.policy.mgt.core.mock.TypeXDeviceManagementService;
|
||||
import org.wso2.carbon.policy.mgt.core.util.FeatureCreator;
|
||||
import org.wso2.carbon.policy.mgt.core.util.ProfileCreator;
|
||||
|
||||
import javax.sql.DataSource;
|
||||
import java.sql.Connection;
|
||||
import java.sql.SQLException;
|
||||
|
||||
import static org.mockito.Matchers.any;
|
||||
import static org.mockito.Matchers.anyBoolean;
|
||||
import static org.mockito.Matchers.anyInt;
|
||||
import static org.mockito.Matchers.anyListOf;
|
||||
import static org.mockito.Matchers.anyString;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
public class ProfileManagerImplTest extends BasePolicyManagementDAOTest {
|
||||
private static final Log log = LogFactory.getLog(PolicyManagerServiceImpl.class);
|
||||
|
||||
private static final String DEVICE3 = "device3";
|
||||
private static final String GROUP3 = "group3";
|
||||
private static final String POLICY3 = "policy3";
|
||||
private static final String DEVICE_TYPE_C = "deviceTypeC";
|
||||
|
||||
private Profile profile1;
|
||||
private OperationManager operationManager;
|
||||
|
||||
@BeforeClass
|
||||
public void initialize() throws Exception {
|
||||
log.info("Initializing policy manager tests");
|
||||
super.initializeServices();
|
||||
deviceMgtService.registerDeviceType(new TypeXDeviceManagementService(DEVICE_TYPE_C));
|
||||
operationManager = new OperationManagerImpl(DEVICE_TYPE_C);
|
||||
enrollDevice(DEVICE3, DEVICE_TYPE_C);
|
||||
createDeviceGroup(GROUP3);
|
||||
DeviceGroup group1 = groupMgtService.getGroup(GROUP3);
|
||||
addDeviceToGroup(new DeviceIdentifier(DEVICE3, DEVICE_TYPE_C), GROUP3);
|
||||
}
|
||||
|
||||
@Test(description = "This test case tests adding new profile")
|
||||
public void testAddProfile() throws Exception {
|
||||
//Creating profile object
|
||||
Profile profile = ProfileCreator.getProfile(FeatureCreator.getFeatureList(), DEVICE_TYPE_C);
|
||||
//Adding profile
|
||||
profile1 = profileManager.addProfile(profile);
|
||||
Assert.assertEquals(profile1.getProfileName(), profile.getProfileName());
|
||||
Assert.assertEquals(profile1.getTenantId(), profile.getTenantId());
|
||||
Assert.assertEquals(profile1.getDeviceType(), profile.getDeviceType());
|
||||
}
|
||||
|
||||
@Test(description = "This test case tests handling ProfileManagerDAOException when adding new profile",
|
||||
dependsOnMethods = "testAddProfile")
|
||||
public void testAddProfileThrowingProfileManagerDAOException() throws Exception {
|
||||
ProfileDAO profileDAO = mock(ProfileDAOImpl.class);
|
||||
when(profileDAO.addProfile(any(Profile.class))).thenThrow(new ProfileManagerDAOException());
|
||||
//Creating profile object
|
||||
Profile profile = ProfileCreator.getProfile(FeatureCreator.getFeatureList(), DEVICE_TYPE_C);
|
||||
testThrowingException(profileManager, profile, p -> profileManager.addProfile((Profile) p), "profileDAO",
|
||||
profileDAO,
|
||||
ProfileManagerDAOException.class);
|
||||
}
|
||||
|
||||
@Test(description = "This test case tests handling FeatureManagerDAOException when adding new profile",
|
||||
dependsOnMethods = "testAddProfileThrowingProfileManagerDAOException")
|
||||
public void testAddProfileThrowingFeatureManagerDAOException() throws Exception {
|
||||
FeatureDAO featureDAO = mock(FeatureDAO.class);
|
||||
when(featureDAO.addProfileFeatures(anyListOf(ProfileFeature.class), anyInt())).thenThrow(
|
||||
new FeatureManagerDAOException());
|
||||
//Creating profile object
|
||||
Profile profile = ProfileCreator.getProfile(FeatureCreator.getFeatureList(), DEVICE_TYPE_C);
|
||||
testThrowingException(profileManager, profile, p -> profileManager.addProfile((Profile) p), "featureDAO",
|
||||
featureDAO,
|
||||
FeatureManagerDAOException.class);
|
||||
}
|
||||
|
||||
@Test(description = "This test case tests handling SQLException when adding new profile",
|
||||
dependsOnMethods = "testAddProfileThrowingFeatureManagerDAOException",
|
||||
expectedExceptions = IllegalTransactionStateException.class)
|
||||
public void testAddProfileThrowingIllegalTransactionStateException() throws Exception {
|
||||
//Creating profile object
|
||||
Profile profile = ProfileCreator.getProfile(FeatureCreator.getFeatureList(), DEVICE_TYPE_C);
|
||||
Pair<Connection, Pair<DataSource, DataSource>> pair = mockConnection();
|
||||
PowerMockito.doThrow(new SQLException()).when(pair.first()).setAutoCommit(anyBoolean());
|
||||
try {
|
||||
profileManager.addProfile(profile);
|
||||
} finally {
|
||||
PolicyManagementDAOFactory.init(pair.second().first());
|
||||
}
|
||||
}
|
||||
|
||||
@Test(description = "This test case tests updating profile",
|
||||
dependsOnMethods = "testAddProfile")
|
||||
public void testUpdateProfile() throws Exception {
|
||||
String newProfileName = "Updated Test Profile";
|
||||
Profile savedProfile = profileManager.getProfile(profile1.getProfileId());
|
||||
savedProfile.setProfileName(newProfileName);
|
||||
Profile updateProfile = profileManager.updateProfile(savedProfile);
|
||||
Assert.assertEquals(updateProfile.getProfileName(), newProfileName);
|
||||
}
|
||||
|
||||
@Test(description = "This test case tests handling ProfileManagerDAOException when updating profile",
|
||||
dependsOnMethods = "testUpdateProfile")
|
||||
public void testUpdateProfileThrowingProfileManagerDAOException() throws Exception {
|
||||
ProfileDAO profileDAO = mock(ProfileDAOImpl.class);
|
||||
when(profileDAO.updateProfile(any(Profile.class))).thenThrow(new ProfileManagerDAOException());
|
||||
|
||||
String newProfileName = "Updated Test Profile";
|
||||
Profile savedProfile = profileManager.getProfile(profile1.getProfileId());
|
||||
savedProfile.setProfileName(newProfileName);
|
||||
testThrowingException(profileManager, savedProfile, p -> profileManager.updateProfile((Profile) p),
|
||||
"profileDAO", profileDAO,
|
||||
ProfileManagerDAOException.class);
|
||||
}
|
||||
|
||||
@Test(description = "This test case tests handling FeatureManagerDAOException when updating profile",
|
||||
dependsOnMethods = "testUpdateProfileThrowingProfileManagerDAOException")
|
||||
public void testUpdateProfileThrowingFeatureManagerDAOException() throws Exception {
|
||||
FeatureDAO featureDAO = mock(FeatureDAO.class);
|
||||
when(featureDAO.updateProfileFeatures(anyListOf(ProfileFeature.class), anyInt())).thenThrow(
|
||||
new FeatureManagerDAOException());
|
||||
|
||||
String newProfileName = "Updated Test Profile";
|
||||
Profile savedProfile = profileManager.getProfile(profile1.getProfileId());
|
||||
savedProfile.setProfileName(newProfileName);
|
||||
testThrowingException(profileManager, savedProfile, p -> profileManager.updateProfile((Profile) p),
|
||||
"featureDAO", featureDAO,
|
||||
FeatureManagerDAOException.class);
|
||||
}
|
||||
|
||||
@Test(description = "This test case tests handling SQLException when updating profile",
|
||||
dependsOnMethods = {"testUpdateProfileThrowingFeatureManagerDAOException"},
|
||||
expectedExceptions = IllegalTransactionStateException.class)
|
||||
public void testUpdateProfileThrowingIllegalTransactionStateException() throws Exception {
|
||||
//Retrieving profile object
|
||||
Profile savedProfile = profileManager.getProfile(profile1.getProfileId());
|
||||
|
||||
Pair<Connection, Pair<DataSource, DataSource>> pair = mockConnection();
|
||||
PowerMockito.doThrow(new SQLException()).when(pair.first()).setAutoCommit(anyBoolean());
|
||||
|
||||
String newProfileName = "Updated Test Profile";
|
||||
savedProfile.setProfileName(newProfileName);
|
||||
try {
|
||||
profileManager.updateProfile(savedProfile);
|
||||
} finally {
|
||||
PolicyManagementDAOFactory.init(pair.second().first());
|
||||
}
|
||||
}
|
||||
|
||||
@Test(description = "This test case tests retrieving profile", dependsOnMethods = "testAddProfile")
|
||||
public void testGetProfile() throws Exception {
|
||||
Profile savedProfile = profileManager.getProfile(profile1.getProfileId());
|
||||
Assert.assertEquals(profile1.getProfileName(), savedProfile.getProfileName());
|
||||
Assert.assertEquals(profile1.getTenantId(), savedProfile.getTenantId());
|
||||
Assert.assertEquals(profile1.getDeviceType(), savedProfile.getDeviceType());
|
||||
}
|
||||
|
||||
@Test(description = "This test case tests retrieving non existent profile", dependsOnMethods = "testGetProfile",
|
||||
expectedExceptions = ProfileManagementException.class)
|
||||
public void testGetProfileThrowingProfileManagementException() throws Exception {
|
||||
int nonExistentProfileId = 9999;
|
||||
profileManager.getProfile(nonExistentProfileId);
|
||||
}
|
||||
|
||||
@Test(description = "This test case tests handling ProfileManagerDAOException when retrieving profile",
|
||||
dependsOnMethods = "testGetProfile")
|
||||
public void testGetProfileThrowingProfileManagerDAOException() throws Exception {
|
||||
ProfileDAO profileDAO = mock(ProfileDAOImpl.class);
|
||||
when(profileDAO.getProfile(anyInt())).thenThrow(new ProfileManagerDAOException());
|
||||
testThrowingException(profileManager, profile1, p -> profileManager.getProfile(((Profile) p).getProfileId()),
|
||||
"profileDAO",
|
||||
profileDAO,
|
||||
ProfileManagerDAOException.class);
|
||||
}
|
||||
|
||||
@Test(description = "This test case tests handling FeatureManagerDAOException when retrieving profile",
|
||||
dependsOnMethods = "testGetProfileThrowingProfileManagerDAOException")
|
||||
public void testGetProfileThrowingFeatureManagerDAOException() throws Exception {
|
||||
FeatureDAO featureDAO = mock(FeatureDAO.class);
|
||||
when(featureDAO.getFeaturesForProfile(anyInt())).thenThrow(new FeatureManagerDAOException());
|
||||
testThrowingException(profileManager, profile1, p -> profileManager.getProfile(((Profile) p).getProfileId()),
|
||||
"featureDAO",
|
||||
featureDAO,
|
||||
FeatureManagerDAOException.class);
|
||||
}
|
||||
|
||||
@Test(description = "This test case tests handling SQLException when retrieving profile",
|
||||
dependsOnMethods = "testGetProfileThrowingFeatureManagerDAOException",
|
||||
expectedExceptions = IllegalTransactionStateException.class)
|
||||
public void testGetProfileThrowingIllegalTransactionStateException() throws Exception {
|
||||
//Creating profile object
|
||||
Pair<Connection, Pair<DataSource, DataSource>> pair = mockConnection();
|
||||
PowerMockito.doThrow(new SQLException()).when(pair.second().second()).getConnection();
|
||||
|
||||
try {
|
||||
profileManager.getProfile(profile1.getProfileId());
|
||||
} finally {
|
||||
PolicyManagementDAOFactory.init(pair.second().first());
|
||||
}
|
||||
}
|
||||
|
||||
@Test(description = "This test case tests retrieving all profiles",
|
||||
dependsOnMethods = "testAddProfile")
|
||||
public void testGetAllProfiles() throws Exception {
|
||||
profileManager.getAllProfiles();
|
||||
}
|
||||
|
||||
@Test(description = "This test case tests handling ProfileManagerDAOException when retrieving all profiles",
|
||||
dependsOnMethods = "testGetAllProfiles")
|
||||
public void testGetAllProfilesThrowingProfileManagerDAOException() throws Exception {
|
||||
ProfileDAO profileDAO = mock(ProfileDAOImpl.class);
|
||||
when(profileDAO.getAllProfiles()).thenThrow(new ProfileManagerDAOException());
|
||||
testThrowingException(profileManager, profile1, p -> profileManager.getAllProfiles(), "profileDAO", profileDAO,
|
||||
ProfileManagerDAOException.class);
|
||||
}
|
||||
|
||||
@Test(description = "This test case tests handling FeatureManagerDAOException when retrieving all profiles",
|
||||
dependsOnMethods = "testGetAllProfilesThrowingProfileManagerDAOException")
|
||||
public void testGetAllProfilesThrowingFeatureManagerDAOException() throws Exception {
|
||||
FeatureDAO featureDAO = mock(FeatureDAO.class);
|
||||
when(featureDAO.getAllProfileFeatures()).thenThrow(new FeatureManagerDAOException());
|
||||
testThrowingException(profileManager, profile1, p -> profileManager.getAllProfiles(), "featureDAO", featureDAO,
|
||||
FeatureManagerDAOException.class);
|
||||
}
|
||||
|
||||
@Test(description = "This test case tests handling SQLException when retrieving all profiles",
|
||||
dependsOnMethods = "testGetAllProfilesThrowingFeatureManagerDAOException",
|
||||
expectedExceptions = IllegalTransactionStateException.class)
|
||||
public void testGetAllProfilesThrowingIllegalTransactionStateException() throws Exception {
|
||||
//Creating profile object
|
||||
Pair<Connection, Pair<DataSource, DataSource>> pair = mockConnection();
|
||||
PowerMockito.doThrow(new SQLException()).when(pair.second().second()).getConnection();
|
||||
|
||||
try {
|
||||
profileManager.getAllProfiles();
|
||||
} finally {
|
||||
PolicyManagementDAOFactory.init(pair.second().first());
|
||||
}
|
||||
}
|
||||
|
||||
@Test(description = "This test case tests retrieving profiles of a device type",
|
||||
dependsOnMethods = "testAddProfile")
|
||||
public void testGetProfilesOfDeviceType() throws Exception {
|
||||
profileManager.getProfilesOfDeviceType(DEVICE_TYPE_C);
|
||||
}
|
||||
|
||||
@Test(description = "This test case tests handling ProfileManagerDAOException when retrieving all profiles of a " +
|
||||
"device type",
|
||||
dependsOnMethods = "testGetProfilesOfDeviceType")
|
||||
public void testGetProfilesOfDeviceTypeThrowingProfileManagerDAOException() throws Exception {
|
||||
ProfileDAO profileDAO = mock(ProfileDAOImpl.class);
|
||||
when(profileDAO.getProfilesOfDeviceType(anyString())).thenThrow(new ProfileManagerDAOException());
|
||||
testThrowingException(profileManager, profile1, p -> profileManager.getProfilesOfDeviceType(DEVICE_TYPE_C),
|
||||
"profileDAO",
|
||||
profileDAO,
|
||||
ProfileManagerDAOException.class);
|
||||
}
|
||||
|
||||
@Test(description = "This test case tests handling FeatureManagerDAOException when retrieving all profiles of a " +
|
||||
"device type",
|
||||
dependsOnMethods = "testGetProfilesOfDeviceTypeThrowingProfileManagerDAOException")
|
||||
public void testGetProfilesOfDeviceTypeThrowingFeatureManagerDAOException() throws Exception {
|
||||
FeatureDAO featureDAO = mock(FeatureDAO.class);
|
||||
when(featureDAO.getAllProfileFeatures()).thenThrow(new FeatureManagerDAOException());
|
||||
testThrowingException(profileManager, profile1, p -> profileManager.getProfilesOfDeviceType(DEVICE_TYPE_C),
|
||||
"featureDAO",
|
||||
featureDAO,
|
||||
FeatureManagerDAOException.class);
|
||||
}
|
||||
|
||||
@Test(description = "This test case tests handling SQLException when retrieving all profiles of a device type",
|
||||
dependsOnMethods = "testGetProfilesOfDeviceTypeThrowingFeatureManagerDAOException",
|
||||
expectedExceptions = IllegalTransactionStateException.class)
|
||||
public void testGetProfilesOfDeviceTypeThrowingIllegalTransactionStateException() throws Exception {
|
||||
//Creating profile object
|
||||
Pair<Connection, Pair<DataSource, DataSource>> pair = mockConnection();
|
||||
PowerMockito.doThrow(new SQLException()).when(pair.second().second()).getConnection();
|
||||
|
||||
try {
|
||||
profileManager.getProfilesOfDeviceType(DEVICE_TYPE_C);
|
||||
} finally {
|
||||
PolicyManagementDAOFactory.init(pair.second().first());
|
||||
}
|
||||
}
|
||||
|
||||
@Test(description = "This test case tests handling ProfileManagerDAOException when deleting a profile",
|
||||
dependsOnMethods = "testGetProfilesOfDeviceTypeThrowingIllegalTransactionStateException")
|
||||
public void testDeleteProfileThrowingProfileManagerDAOException() throws Exception {
|
||||
ProfileDAO profileDAO = mock(ProfileDAOImpl.class);
|
||||
when(profileDAO.deleteProfile(any(Profile.class))).thenThrow(new ProfileManagerDAOException());
|
||||
testThrowingException(profileManager, profile1, p -> profileManager.deleteProfile(profile1), "profileDAO",
|
||||
profileDAO,
|
||||
ProfileManagerDAOException.class);
|
||||
}
|
||||
|
||||
@Test(description = "This test case tests handling FeatureManagerDAOException when deleting a profile",
|
||||
dependsOnMethods = "testDeleteProfileThrowingProfileManagerDAOException")
|
||||
public void testDeleteProfileThrowingFeatureManagerDAOException() throws Exception {
|
||||
FeatureDAO featureDAO = mock(FeatureDAO.class);
|
||||
when(featureDAO.deleteFeaturesOfProfile(any(Profile.class))).thenThrow(new FeatureManagerDAOException());
|
||||
testThrowingException(profileManager, profile1, p -> profileManager.deleteProfile(profile1), "featureDAO",
|
||||
featureDAO,
|
||||
FeatureManagerDAOException.class);
|
||||
}
|
||||
|
||||
@Test(description = "This test case tests handling SQLException when deleting a profile",
|
||||
dependsOnMethods = "testDeleteProfileThrowingFeatureManagerDAOException",
|
||||
expectedExceptions = IllegalTransactionStateException.class)
|
||||
public void testDeleteProfileThrowingIllegalTransactionStateException() throws Exception {
|
||||
//Creating profile object
|
||||
Pair<Connection, Pair<DataSource, DataSource>> pair = mockConnection();
|
||||
PowerMockito.doThrow(new SQLException()).when(pair.second().second()).getConnection();
|
||||
|
||||
try {
|
||||
profileManager.deleteProfile(profile1);
|
||||
} finally {
|
||||
PolicyManagementDAOFactory.init(pair.second().first());
|
||||
}
|
||||
}
|
||||
|
||||
@Test(description = "This test case tests deleting a profile",
|
||||
dependsOnMethods = "testDeleteProfileThrowingIllegalTransactionStateException",
|
||||
expectedExceptions = {ProfileManagementException.class})
|
||||
public void testDeleteProfile() throws Exception {
|
||||
profileManager.deleteProfile(profile1);
|
||||
Profile savedProfile = profileManager.getProfile(profile1.getProfileId());
|
||||
}
|
||||
}
|
Some files were not shown because too many files have changed in this diff Show More
Loading…
Reference in new issue