import java.util.Date;
-import javax.ws.rs.NotAuthorizedException;
+import org.onap.clamp.clds.exception.NotAuthorizedException;
import org.apache.camel.Exchange;
import org.onap.clamp.clds.config.ClampProperties;
@Autowired
private ClampProperties refProp;
- private static final String PERM_PREFIX = "security.permission.type.";
+ public static final String PERM_PREFIX = "security.permission.type.";
private static final String PERM_INSTANCE = "security.permission.instance";
/**
import com.att.eelf.configuration.EELFLogger;
import com.att.eelf.configuration.EELFManager;
+
+import java.io.IOException;
+import java.security.Principal;
+import java.util.ArrayList;
+import java.util.List;
+import javax.servlet.ServletException;
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+
import org.apache.camel.component.servlet.CamelHttpTransportServlet;
import org.onap.clamp.clds.service.SecureServicePermission;
import org.springframework.context.ApplicationContext;
import org.springframework.security.core.userdetails.User;
import org.springframework.web.context.support.WebApplicationContextUtils;
-import javax.servlet.ServletException;
-import javax.servlet.http.HttpServletRequest;
-import javax.servlet.http.HttpServletResponse;
-import java.io.IOException;
-import java.security.Principal;
-import java.util.ArrayList;
-import java.util.List;
-
public class ClampServlet extends CamelHttpTransportServlet {
/**
permissionList.add(SecureServicePermission
.create(applicationContext.getEnvironment().getProperty(PERM_TOSCA), cldsPermissionInstance, READ));
permissionList.add(SecureServicePermission
- .create(applicationContext.getEnvironment().getProperty(PERM_TOSCA), cldsPermissionInstance, UPDATE));
+ .create(applicationContext.getEnvironment().getProperty(PERM_TOSCA), cldsPermissionInstance,
+ UPDATE));
}
return permissionList;
}
grantedAuths.add(new SimpleGrantedAuthority(permString));
}
}
- Authentication auth = new UsernamePasswordAuthenticationToken(new User(principal.getName(), "", grantedAuths), "",
- grantedAuths);
+ Authentication auth = new UsernamePasswordAuthenticationToken(new User(principal.getName(), "",
+ grantedAuths), "", grantedAuths);
SecurityContextHolder.getContext().setAuthentication(auth);
}
try {
}
/**
- * Helper method to setup the base template properties
+ * Helper method to setup the base template properties.
*
* @param template
* the template
}
/**
- * Helper method to setup the event prop to the CldsEvent class
+ * Helper method to setup the event prop to the CldsEvent class.
*
* @param event
* the clds event
String dictElementShortName) {
SimpleDateFormat sdf = new SimpleDateFormat(DATE_FORMAT);
List<CldsDictionaryItem> dictionaryItems = new ArrayList<>();
- String dictionarySql = new StringBuilder("SELECT de.dict_element_id, de.dictionary_id, de.dict_element_name, " +
- "de.dict_element_short_name, de.dict_element_description, de.dict_element_type, de.created_by, " +
- "de.modified_by, de.timestamp FROM dictionary_elements de, " +
- "dictionary d WHERE de.dictionary_id = d.dictionary_id")
+ String dictionarySql = new StringBuilder("SELECT de.dict_element_id, de.dictionary_id, de.dict_element_name, "
+ + "de.dict_element_short_name, de.dict_element_description, de.dict_element_type, de.created_by, "
+ + "de.modified_by, de.timestamp FROM dictionary_elements de, "
+ + "dictionary d WHERE de.dictionary_id = d.dictionary_id")
.append((dictionaryId != null) ? (" AND d.dictionary_id = '" + dictionaryId + "'") : "")
- .append((dictElementShortName != null) ? (" AND de.dict_element_short_name = '" + dictElementShortName + "'") : "")
+ .append((dictElementShortName != null) ? (" AND de.dict_element_short_name = '" + dictElementShortName
+ + "'") : "")
.append((dictionaryName != null) ? (" AND dictionary_name = '" + dictionaryName + "'") : "").toString();
List<Map<String, Object>> rows = jdbcTemplateObject.queryForList(dictionarySql);
*/
public Map<String, String> getDictionaryElementsByType(String dictionaryElementType) {
Map<String, String> dictionaryItems = new HashMap<>();
- String dictionarySql = new StringBuilder("SELECT dict_element_name, dict_element_short_name " +
- "FROM dictionary_elements WHERE dict_element_type = '")
+ String dictionarySql = new StringBuilder("SELECT dict_element_name, dict_element_short_name "
+ + "FROM dictionary_elements WHERE dict_element_type = '")
.append(dictionaryElementType).append("'").toString();
List<Map<String, Object>> rows = jdbcTemplateObject.queryForList(dictionarySql);
* Copyright (C) 2017-2019 AT&T Intellectual Property. All rights
* reserved.
* ================================================================================
+ * Modifications Copyright (c) 2019 Samsung
+ * ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
public List<CldsMonitoringDetails> getCldsDetails() {
util.entering(request, "CldsService: GET model details");
Date startTime = new Date();
- List<CldsMonitoringDetails> cldsMonitoringDetailsList = cldsDao.getCldsMonitoringDetails();
+ final List<CldsMonitoringDetails> cldsMonitoringDetailsList = cldsDao.getCldsMonitoringDetails();
// audit log
LoggingUtils.setTimeContext(startTime, new Date());
auditLogger.info("GET cldsDetails completed");
LoggingUtils.setTimeContext(startTime, new Date());
CldsInfoProvider cldsInfoProvider = new CldsInfoProvider(this);
- CldsInfo cldsInfo = cldsInfoProvider.getCldsInfo();
+ final CldsInfo cldsInfo = cldsInfoProvider.getCldsInfo();
// audit log
LoggingUtils.setTimeContext(startTime, new Date());
Date startTime = new Date();
isAuthorized(permissionReadCl);
logger.info("GET bpmnText for modelName={}", modelName);
- CldsModel model = CldsModel.retrieve(cldsDao, modelName, false);
+ final CldsModel model = CldsModel.retrieve(cldsDao, modelName, false);
// audit log
LoggingUtils.setTimeContext(startTime, new Date());
auditLogger.info("GET model bpmn completed");
Date startTime = new Date();
isAuthorized(permissionReadCl);
logger.info("GET imageText for modelName={}", modelName);
- CldsModel model = CldsModel.retrieve(cldsDao, modelName, false);
+ final CldsModel model = CldsModel.retrieve(cldsDao, modelName, false);
// audit log
LoggingUtils.setTimeContext(startTime, new Date());
auditLogger.info("GET model image completed");
*/
public CldsModel getModel(String modelName) {
util.entering(request, "CldsService: GET model");
- Date startTime = new Date();
+ final Date startTime = new Date();
isAuthorized(permissionReadCl);
logger.debug("GET model for modelName={}", modelName);
CldsModel cldsModel = CldsModel.retrieve(cldsDao, modelName, false);
*/
public CldsModel putModel(String modelName, CldsModel cldsModel) {
util.entering(request, "CldsService: PUT model");
- Date startTime = new Date();
+ final Date startTime = new Date();
isAuthorized(permissionUpdateCl);
isAuthorizedForVf(cldsModel);
logger.info("PUT model for modelName={}", modelName);
Date startTime = new Date();
isAuthorized(permissionReadCl);
logger.info("GET list of model names");
- List<ValueItem> names = cldsDao.getModelNames();
+ final List<ValueItem> names = cldsDao.getModelNames();
// audit log
LoggingUtils.setTimeContext(startTime, new Date());
auditLogger.info("GET model names completed");
model.save(cldsDao, getUserId());
// get vars and format if necessary
- String prop = model.getPropText();
- String bpmn = model.getBpmnText();
- String docText = model.getDocText();
- String controlName = model.getControlName();
- String bpmnJson = cldsBpmnTransformer.doXslTransformToString(bpmn);
+ final String prop = model.getPropText();
+ final String bpmn = model.getBpmnText();
+ final String docText = model.getDocText();
+ final String controlName = model.getControlName();
+ final String bpmnJson = cldsBpmnTransformer.doXslTransformToString(bpmn);
logger.info("PUT bpmnJson={}", bpmnJson);
// Test flag coming from UI or from Clamp config
boolean isTest = Boolean.parseBoolean(test)
*/
public String postDcaeEvent(String test, DcaeEvent dcaeEvent) {
util.entering(request, "CldsService: Post dcae event");
- Date startTime = new Date();
+ final Date startTime = new Date();
String userid = null;
// TODO: allow auth checking to be turned off by removing the permission
// type property
* Copyright (C) 2017-2018 AT&T Intellectual Property. All rights
* reserved.
* ================================================================================
+ * Modifications Copyright (c) 2019 Samsung
+ * ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
Date startTime = new Date();
isAuthorized(permissionReadTemplate);
logger.info("GET bpmnText for templateName=" + templateName);
- CldsTemplate template = CldsTemplate.retrieve(cldsDao, templateName, false);
+ final CldsTemplate template = CldsTemplate.retrieve(cldsDao, templateName, false);
// audit log
LoggingUtils.setTimeContext(startTime, new Date());
auditLogger.info("GET template bpmn completed");
Date startTime = new Date();
isAuthorized(permissionReadTemplate);
logger.info("GET imageText for templateName=" + templateName);
- CldsTemplate template = CldsTemplate.retrieve(cldsDao, templateName, false);
+ final CldsTemplate template = CldsTemplate.retrieve(cldsDao, templateName, false);
// audit log
LoggingUtils.setTimeContext(startTime, new Date());
auditLogger.info("GET template image completed");
*/
public CldsTemplate getTemplate(String templateName) {
util.entering(request, "CldsTemplateService: GET template");
- Date startTime = new Date();
+ final Date startTime = new Date();
isAuthorized(permissionReadTemplate);
logger.info("GET model for templateName=" + templateName);
CldsTemplate template = CldsTemplate.retrieve(cldsDao, templateName, false);
*/
public CldsTemplate putTemplate(String templateName, CldsTemplate cldsTemplate) {
util.entering(request, "CldsTemplateService: PUT template");
- Date startTime = new Date();
+ final Date startTime = new Date();
isAuthorized(permissionUpdateTemplate);
logger.info("PUT Template for templateName=" + templateName);
logger.info("PUT bpmnText=" + cldsTemplate.getBpmnText());
Date startTime = new Date();
isAuthorized(permissionReadTemplate);
logger.info("GET list of template names");
- List<ValueItem> names = cldsDao.getTemplateNames();
+ final List<ValueItem> names = cldsDao.getTemplateNames();
// audit log
LoggingUtils.setTimeContext(startTime, new Date());
auditLogger.info("GET template names completed");
* Copyright (C) 2018 AT&T Intellectual Property. All rights
* reserved.
* ================================================================================
+ * Modifications Copyright (c) 2019 Samsung
+ * ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* type
*/
public ResponseEntity<?> parseToscaModelAndSave(String toscaModelName, CldsToscaModel cldsToscaModel) {
- Date startTime = new Date();
+ final Date startTime = new Date();
LoggingUtils.setRequestContext("CldsToscaService: Parse Tosca model and save", getPrincipalName());
// TODO revisit based on new permissions
isAuthorized(permissionUpdateTosca);
LoggingUtils.setRequestContext("CldsToscaService: Get All tosca models", getPrincipalName());
// TODO revisit based on new permissions
isAuthorized(permissionReadTosca);
- List<CldsToscaModel> cldsToscaModels = Optional.ofNullable(cldsDao.getAllToscaModels()).get();
+ final List<CldsToscaModel> cldsToscaModels = Optional.ofNullable(cldsDao.getAllToscaModels()).get();
LoggingUtils.setTimeContext(startTime, new Date());
LoggingUtils.setResponseContext("0", "Get All tosca models success", this.getClass().getName());
auditLogger.info("Get All tosca models");
LoggingUtils.setRequestContext("CldsToscaService: Get tosca models by model name", getPrincipalName());
// TODO revisit based on new permissions
isAuthorized(permissionReadTosca);
- List<CldsToscaModel> cldsToscaModels = Optional.ofNullable(cldsDao.getToscaModelByName(toscaModelName)).get();
+ final List<CldsToscaModel> cldsToscaModels = Optional.ofNullable(cldsDao.getToscaModelByName(toscaModelName))
+ .get();
LoggingUtils.setTimeContext(startTime, new Date());
LoggingUtils.setResponseContext("0", "Get tosca models by model name success", this.getClass().getName());
auditLogger.info("GET tosca models by model name completed");
* from the database.
*
* @param policyType
+ * The type of the policy
* @return clds tosca model - CLDS tosca model for a given policy type
*/
public CldsToscaModel getToscaModelsByPolicyType(String policyType) {
LoggingUtils.setRequestContext("CldsToscaService: Get tosca models by policyType", getPrincipalName());
// TODO revisit based on new permissions
isAuthorized(permissionReadTosca);
- List<CldsToscaModel> cldsToscaModels = Optional.ofNullable(cldsDao.getToscaModelByPolicyType(policyType)).get();
+ final List<CldsToscaModel> cldsToscaModels = Optional.ofNullable(cldsDao.getToscaModelByPolicyType(policyType))
+ .get();
LoggingUtils.setTimeContext(startTime, new Date());
LoggingUtils.setResponseContext("0", "Get tosca models by policyType success", this.getClass().getName());
auditLogger.info("GET tosca models by policyType completed");
private static SecretKeySpec readSecretKeySpec(String propertiesFileName) {
Properties props = new Properties();
try {
- //Workaround fix to make encryption key configurable
+ // Workaround fix to make encryption key configurable
// System environment variable takes precedence for over clds/key.properties
String encryptionKey = System.getenv(AES_ENCRYPTION_KEY);
if(encryptionKey != null && encryptionKey.trim().length() > 0) {
package org.onap.clamp.clds.util;
import java.io.StringWriter;
+import javax.xml.XMLConstants;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
public class XmlTools {
+ /**
+ * Private constructor to avoid creating instances of util class.
+ */
+ private XmlTools(){
+ }
+
/**
* Transforms document to XML string.
*
public static String exportXmlDocumentAsString(Document doc) {
try {
TransformerFactory tf = TransformerFactory.newInstance();
+ tf.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
Transformer transformer = tf.newTransformer();
transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
StringWriter writer = new StringWriter();
private static UserNameHandler userNameHandler = new DefaultUserNameHandler();
private static SecurityContext securityContext = SecurityContextHolder.getContext();
+ /**
+ * Private constructor to avoid creating instances of util class.
+ */
+ private PrincipalUtils(){
+ }
+
/**
* Get the Full name.
*
*/
function updateMsProperties(type, newMsProperties) {
- var newMsProperties = JSON.parse(JSON.stringify(cl_props["microServicePolicies"]));
- for (p in newMsProperties) {
- if (newMsProperties[p]["name"] == type) {
- cl_props["microServicePolicies"][p] = newMsProperties;
+ if (newMsProperties["name"] == type) {
+ for (p in cl_props["microServicePolicies"]) {
+ if (cl_props["microServicePolicies"][p]["name"] == type) {
+ cl_props["microServicePolicies"][p] = newMsProperties;
+ }
}
}
}
return cl_props.loopLogs;
}
-module.exports = { getOperationalPolicyProperty,getGlobalProperty,getMsProperty,getMsUI,getLastUpdatedStatus,getDeploymentID,getDeploymentStatusURL,getResourceDetailsVfProperty,getResourceDetailsVfModuleProperty };
\ No newline at end of file
+module.exports = { getOperationalPolicyProperty,getGlobalProperty,getMsProperty,getMsUI,getLastUpdatedStatus,getDeploymentID,getDeploymentStatusURL,getResourceDetailsVfProperty,getResourceDetailsVfModuleProperty };
--- /dev/null
+/*-
+ * ============LICENSE_START=======================================================
+ * ONAP CLAMP
+ * ================================================================================
+ * Copyright (C) 2019 Samsung. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END============================================
+ * ===================================================================
+ *
+ */
+
+package org.onap.clamp.clds.client;
+
+import static org.mockito.Matchers.any;
+import static org.mockito.Matchers.eq;
+import static org.mockito.Mockito.never;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.when;
+
+import org.apache.camel.Exchange;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.mockito.InjectMocks;
+import org.mockito.Mock;
+import org.mockito.runners.MockitoJUnitRunner;
+import org.onap.clamp.clds.dao.CldsDao;
+
+@RunWith(MockitoJUnitRunner.class)
+public class CldsEventDelegateTest {
+
+ private static final String CONTROL_NAME_KEY = "controlName";
+ private static final String TEST_KEY = "isTest";
+ private static final String INSERT_TEST_EVENT_KEY = "isInsertTestEvent";
+ private static final String PREFIX = "abcdef-";
+ private static final String UUID = "ABCDEFGHIJKLMNOPQRSTUVWXYZ-123456789";
+
+ @Mock
+ private Exchange exchange;
+
+ @Mock
+ private CldsDao cldsDao;
+
+ @InjectMocks
+ private CldsEventDelegate cldsEventDelegate;
+
+ @Test
+ public void shouldExecuteSuccessfully() {
+ // given
+ when(exchange.getProperty(eq(CONTROL_NAME_KEY))).thenReturn(PREFIX + UUID);
+ when(exchange.getProperty(eq(TEST_KEY))).thenReturn(false);
+ when(exchange.getProperty(eq(INSERT_TEST_EVENT_KEY))).thenReturn(false);
+
+ // when
+ cldsEventDelegate.addEvent(exchange, null);
+
+ // then
+ verify(cldsDao).insEvent(eq(null), eq(PREFIX), eq(UUID), any());
+ }
+
+ @Test
+ public void shouldExecuteWithoutInsertingEventIntoDatabase() {
+ // given
+ when(exchange.getProperty(eq(TEST_KEY))).thenReturn(true);
+ when(exchange.getProperty(eq(INSERT_TEST_EVENT_KEY))).thenReturn(false);
+
+ // when
+ cldsEventDelegate.addEvent(exchange, null);
+
+ // then
+ verify(cldsDao, never()).insEvent(any(), any(), any(), any());
+ }
+}
\ No newline at end of file
--- /dev/null
+/*-
+ * ============LICENSE_START=======================================================
+ * ONAP CLAMP
+ * ================================================================================
+ * Copyright (C) 2019 Samsung. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END============================================
+ * ===================================================================
+ *
+ */
+
+package org.onap.clamp.clds.client;
+
+import static org.mockito.Matchers.any;
+import static org.mockito.Matchers.eq;
+import static org.mockito.Mockito.never;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.when;
+
+import org.apache.camel.Exchange;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.mockito.InjectMocks;
+import org.mockito.Mock;
+import org.mockito.runners.MockitoJUnitRunner;
+import org.onap.clamp.clds.client.req.policy.PolicyClient;
+import org.onap.clamp.clds.exception.ModelBpmnException;
+
+@RunWith(MockitoJUnitRunner.class)
+public class GuardPolicyDelegateTest {
+
+ private static final String TEST_KEY = "isTest";
+ private static final String MODEL_BPMN_KEY = "modelBpmnProp";
+ private static final String MODEL_PROP_KEY = "modelProp";
+ private static final String POLICY_ID_FROM_JSON = "{policy:[{id:guard,from:''}]}";
+ private static final String ID_WITH_CHAIN_JSON = "{guard:{q:["
+ + "{name:timeout,value:200},"
+ + "{policyConfigurations:["
+ + "[{name:maxRetries,value:3},"
+ + "{name:retryTimeLimit,value:800},"
+ + "{name:enableGuardPolicy,value:on}]]}]}}";
+ private static final String SIMPLE_JSON = "{}";
+ private static final String NOT_JSON = "not json";
+
+ @Mock
+ private Exchange exchange;
+
+ @Mock
+ private PolicyClient policyClient;
+
+ @InjectMocks
+ private GuardPolicyDelegate guardPolicyDelegate;
+
+ @Test
+ public void shouldExecuteSuccessfully() {
+ // given
+ when(exchange.getProperty(eq(TEST_KEY))).thenReturn(false);
+ when(exchange.getProperty(eq(MODEL_BPMN_KEY))).thenReturn(POLICY_ID_FROM_JSON);
+ when(exchange.getProperty(eq(MODEL_PROP_KEY))).thenReturn(ID_WITH_CHAIN_JSON);
+
+ // when
+ guardPolicyDelegate.execute(exchange);
+
+ // then
+ verify(policyClient).sendGuardPolicy(any(), any(), any(), any());
+ }
+
+ @Test
+ public void shouldExecutePolicyNotFound() {
+ // given
+ when(exchange.getProperty(eq(TEST_KEY))).thenReturn(false);
+ when(exchange.getProperty(eq(MODEL_BPMN_KEY))).thenReturn(SIMPLE_JSON);
+ when(exchange.getProperty(eq(MODEL_PROP_KEY))).thenReturn(SIMPLE_JSON);
+
+ // when
+ guardPolicyDelegate.execute(exchange);
+
+ // then
+ verify(policyClient, never()).sendGuardPolicy(any(), any(), any(), any());
+ }
+
+ @Test(expected = ModelBpmnException.class)
+ public void shouldThrowModelBpmnException() {
+ // given
+ when(exchange.getProperty(eq(TEST_KEY))).thenReturn(true);
+ when(exchange.getProperty(eq(MODEL_BPMN_KEY))).thenReturn(NOT_JSON);
+
+ // when
+ guardPolicyDelegate.execute(exchange);
+ }
+
+ @Test(expected = NullPointerException.class)
+ public void shouldThrowNullPointerException() {
+ // when
+ guardPolicyDelegate.execute(exchange);
+ }
+}
--- /dev/null
+/*-
+ * ============LICENSE_START=======================================================
+ * ONAP CLAMP
+ * ================================================================================
+ * Copyright (C) 2019 Samsung. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END============================================
+ * ===================================================================
+ *
+ */
+
+package org.onap.clamp.clds.client;
+
+import static org.junit.Assert.assertEquals;
+import static org.mockito.Mockito.any;
+import static org.mockito.Mockito.anyString;
+import static org.mockito.Mockito.eq;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.never;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.when;
+
+import com.google.gson.JsonElement;
+import com.google.gson.JsonObject;
+
+import java.io.IOException;
+
+import org.apache.camel.Exchange;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.mockito.InjectMocks;
+import org.mockito.Mock;
+import org.mockito.runners.MockitoJUnitRunner;
+import org.onap.clamp.clds.client.req.policy.PolicyClient;
+import org.onap.clamp.clds.config.ClampProperties;
+import org.onap.clamp.clds.dao.CldsDao;
+import org.onap.clamp.clds.exception.ModelBpmnException;
+import org.onap.clamp.clds.model.CldsModel;
+import org.onap.clamp.clds.model.properties.Holmes;
+import org.onap.clamp.clds.model.properties.ModelProperties;
+import org.onap.clamp.clds.util.JsonUtils;
+
+@RunWith(MockitoJUnitRunner.class)
+public class HolmesPolicyDelegateTest {
+
+ private static final String ID_JSON = "{\"id\":{\"r\":[{},{\"serviceConfigurations\":"
+ + "[[\"x\",\"+\",\"2\",\"y\"]]}]}}";
+ private static final String METRICS_JSON = "{\"metricsPerEventName\":[{\"thresholds\":[]}]}";
+ private static final String CONTENT_JSON = "{\"content\":{}}";
+ private static final String NULL_JSON = "{}";
+ private static final String HOLMES_ID_FROM_JSON = "{\"holmes\":[{\"id\":\"id\",\"from\":\"\"}]}";
+ private static final String TCA_ID_FROM_JSON = "{\"tca\":[{\"id\":\"\",\"from\":\"\"}]}";
+ private static final String CORRELATION_LOGIC_JSON = "{\"name\":\"correlationalLogic\"}";
+ private static final String NOT_JSON = "not json";
+ private static final String MODEL_BPMN_KEY = "modelBpmnProp";
+ private static final String MODEL_PROP_KEY = "modelProp";
+ private static final String MODEL_NAME_KEY = "modelName";
+ private static final String TEST_KEY = "isTest";
+ private static final String USERID_KEY = "userid";
+ private static final String TCA_TEMPLATE_KEY = "tca.template";
+ private static final String TCA_POLICY_TEMPLATE_KEY = "tca.policy.template";
+ private static final String TCA_THRESHOLDS_TEMPLATE_KEY = "tca.thresholds.template";
+ private static final String HOLMES_POLICY_RESPONSE_MESSAGE_KEY = "holmesPolicyResponseMessage";
+ private static final String RESPONSE_MESSAGE_VALUE = "responseMessage";
+ private static final String MODEL_NAME_VALUE = "model.name";
+ private static final String CONTROL_NAME_VALUE = "control.name";
+ private static final String USERID_VALUE = "user";
+ private static final String CLDS_MODEL_ID = "id";
+ private static final String CLDS_MODEL_PROP_TEXT = "propText";
+
+ @Mock
+ private Exchange exchange;
+
+ @Mock
+ private PolicyClient policyClient;
+
+ @Mock
+ private ClampProperties clampProperties;
+
+ @Mock
+ private CldsDao cldsDao;
+
+ @InjectMocks
+ private HolmesPolicyDelegate holmesPolicyDelegateTest;
+
+ @Test
+ public void shouldExecuteSuccessfully() throws IOException {
+ // given
+ when(exchange.getProperty(eq(MODEL_BPMN_KEY))).thenReturn(HOLMES_ID_FROM_JSON);
+ when(exchange.getProperty(eq(MODEL_PROP_KEY))).thenReturn(ID_JSON);
+ when(exchange.getProperty(eq(MODEL_NAME_KEY))).thenReturn(MODEL_NAME_VALUE);
+ when(exchange.getProperty(eq(TEST_KEY))).thenReturn(false);
+ when(exchange.getProperty(eq(USERID_KEY))).thenReturn(USERID_VALUE);
+
+ JsonElement jsonTemplateA = mock(JsonElement.class);
+ when(clampProperties.getJsonTemplate(eq(TCA_TEMPLATE_KEY), anyString())).thenReturn(jsonTemplateA);
+ when(jsonTemplateA.getAsJsonObject()).thenReturn(getJsonObject(METRICS_JSON));
+
+ JsonElement jsonTemplateB = mock(JsonElement.class);
+ when(clampProperties.getJsonTemplate(eq(TCA_POLICY_TEMPLATE_KEY), anyString())).thenReturn(jsonTemplateB);
+ when(jsonTemplateB.getAsJsonObject()).thenReturn(getJsonObject(CONTENT_JSON));
+
+ JsonElement jsonTemplateC = mock(JsonElement.class);
+ when(clampProperties.getJsonTemplate(eq(TCA_THRESHOLDS_TEMPLATE_KEY), anyString())).thenReturn(jsonTemplateC);
+ when(jsonTemplateC.getAsJsonObject()).thenReturn(getJsonObject(NULL_JSON));
+
+ when(policyClient.sendBasePolicyInOther(anyString(), anyString(), any(), anyString()))
+ .thenReturn(RESPONSE_MESSAGE_VALUE);
+
+ CldsModel cldsModel = new CldsModel();
+ cldsModel.setId(CLDS_MODEL_ID);
+ cldsModel.setPropText(CLDS_MODEL_PROP_TEXT);
+ when(cldsDao.getModelTemplate(eq(MODEL_NAME_VALUE))).thenReturn(cldsModel);
+
+ // when
+ holmesPolicyDelegateTest.execute(exchange);
+
+ // then
+ verify(exchange).setProperty(eq(HOLMES_POLICY_RESPONSE_MESSAGE_KEY), eq(RESPONSE_MESSAGE_VALUE.getBytes()));
+ verify(cldsDao).setModel(eq(cldsModel), eq(USERID_VALUE));
+ }
+
+ @Test
+ public void shouldExecuteHolmesNotFound() {
+ // given
+ when(exchange.getProperty(eq(MODEL_BPMN_KEY))).thenReturn(TCA_ID_FROM_JSON);
+ when(exchange.getProperty(eq(MODEL_PROP_KEY))).thenReturn(ID_JSON);
+ when(exchange.getProperty(eq(TEST_KEY))).thenReturn(false);
+
+ // when
+ holmesPolicyDelegateTest.execute(exchange);
+
+ // then
+ verify(policyClient, never()).sendBasePolicyInOther(anyString(), anyString(), any(), anyString());
+ verify(exchange, never()).setProperty(eq(HOLMES_POLICY_RESPONSE_MESSAGE_KEY), any());
+ verify(cldsDao, never()).setModel(any(), anyString());
+ }
+
+ @Test(expected = ModelBpmnException.class)
+ public void shouldThrowModelBpmnException() {
+ // given
+ when(exchange.getProperty(eq(MODEL_BPMN_KEY))).thenReturn(NOT_JSON);
+ when(exchange.getProperty(eq(TEST_KEY))).thenReturn(false);
+
+ // when
+ holmesPolicyDelegateTest.execute(exchange);
+ }
+
+ @Test(expected = NullPointerException.class)
+ public void shouldThrowNullPointerException() {
+ // when
+ holmesPolicyDelegateTest.execute(exchange);
+ }
+
+ @Test
+ public void shouldDoFormatHolmesConfigBodySuccessfully() {
+ // given
+ ModelProperties prop = new ModelProperties(null, CONTROL_NAME_VALUE, null, false,
+ HOLMES_ID_FROM_JSON, "{\"id\":" + CORRELATION_LOGIC_JSON + "}");
+ Holmes holmes = prop.getType(Holmes.class);
+
+ // when
+ String result = HolmesPolicyDelegate.formatHolmesConfigBody(prop, holmes);
+
+ // then
+ assertEquals(CONTROL_NAME_VALUE + "$$$" + CORRELATION_LOGIC_JSON, result);
+ }
+
+ private static JsonObject getJsonObject(String jsonText) {
+ return JsonUtils.GSON.fromJson(jsonText, JsonObject.class);
+ }
+}
--- /dev/null
+/*-
+ * ============LICENSE_START=======================================================
+ * ONAP CLAMP
+ * ================================================================================
+ * Copyright (C) 2019 Samsung. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END============================================
+ * ===================================================================
+ *
+ */
+
+package org.onap.clamp.clds.client;
+
+import static org.mockito.Mockito.any;
+import static org.mockito.Mockito.eq;
+import static org.mockito.Mockito.never;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.when;
+
+import org.apache.camel.Exchange;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.mockito.InjectMocks;
+import org.mockito.Mock;
+import org.mockito.runners.MockitoJUnitRunner;
+import org.onap.clamp.clds.client.req.policy.PolicyClient;
+import org.onap.clamp.clds.exception.ModelBpmnException;
+
+@RunWith(MockitoJUnitRunner.class)
+public class HolmesPolicyDeleteDelegateTest {
+
+ private static final String MODEL_BPMN_KEY = "modelBpmnProp";
+ private static final String MODEL_PROP_KEY = "modelProp";
+ private static final String TEST_KEY = "isTest";
+
+ private static final String HOLMES_ID_FROM_JSON = "{\"holmes\":[{\"id\":\"\",\"from\":\"\"}]}";
+ private static final String TCA_ID_FROM_JSON = "{\"tca\":[{\"id\":\"\",\"from\":\"\"}]}";
+ private static final String ID_JSON = "{\"id\":\"\"}";
+ private static final String NOT_JSON = "not json";
+
+ @Mock
+ private Exchange exchange;
+
+ @Mock
+ private PolicyClient policyClient;
+
+ @InjectMocks
+ private HolmesPolicyDeleteDelegate holmesPolicyDeleteDelegate;
+
+ @Test
+ public void shouldExecuteSuccessfully() {
+ // given
+ when(exchange.getProperty(eq(MODEL_BPMN_KEY))).thenReturn(HOLMES_ID_FROM_JSON);
+ when(exchange.getProperty(eq(MODEL_PROP_KEY))).thenReturn(ID_JSON);
+ when(exchange.getProperty(eq(TEST_KEY))).thenReturn(false);
+
+ // when
+ holmesPolicyDeleteDelegate.execute(exchange);
+
+ // then
+ verify(policyClient).deleteBasePolicy(any());
+ }
+
+ @Test
+ public void shouldExecuteHolmesNotFound() {
+ // given
+ when(exchange.getProperty(eq(MODEL_BPMN_KEY))).thenReturn(TCA_ID_FROM_JSON);
+ when(exchange.getProperty(eq(MODEL_PROP_KEY))).thenReturn(ID_JSON);
+ when(exchange.getProperty(eq(TEST_KEY))).thenReturn(false);
+
+ // when
+ holmesPolicyDeleteDelegate.execute(exchange);
+
+ // then
+ verify(policyClient, never()).deleteBasePolicy(any());
+ }
+
+ @Test(expected = ModelBpmnException.class)
+ public void shouldThrowModelBpmnException() {
+ // given
+ when(exchange.getProperty(eq(MODEL_BPMN_KEY))).thenReturn(NOT_JSON);
+ when(exchange.getProperty(eq(TEST_KEY))).thenReturn(false);
+
+ // when
+ holmesPolicyDeleteDelegate.execute(exchange);
+ }
+
+ @Test(expected = NullPointerException.class)
+ public void shouldThrowNullPointerException() {
+ // when
+ holmesPolicyDeleteDelegate.execute(exchange);
+ }
+}
--- /dev/null
+/*-
+ * ============LICENSE_START=======================================================
+ * ONAP CLAMP
+ * ================================================================================
+ * Copyright (C) 2019 Samsung. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END============================================
+ * ===================================================================
+ *
+ */
+
+package org.onap.clamp.clds.client;
+
+import static org.mockito.Mockito.eq;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.when;
+
+import org.apache.camel.Exchange;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.mockito.InjectMocks;
+import org.mockito.Mock;
+import org.mockito.runners.MockitoJUnitRunner;
+import org.onap.clamp.clds.dao.CldsDao;
+
+@RunWith(MockitoJUnitRunner.class)
+public class ModelDeleteDelegateTest {
+
+ private static final String NAME_KEY = "modelName";
+ private static final String NAME_VALUE = "model.name";
+
+ @Mock
+ private Exchange exchange;
+
+ @Mock
+ private CldsDao cldsDao;
+
+ @InjectMocks
+ private ModelDeleteDelegate modelDeleteDelegate;
+
+ @Test
+ public void shouldExecuteSuccessfully() {
+ // given
+ when(exchange.getProperty(eq(NAME_KEY))).thenReturn(NAME_VALUE);
+
+ // when
+ modelDeleteDelegate.execute(exchange);
+
+ // then
+ verify(cldsDao).deleteModel(eq(NAME_VALUE));
+ }
+}
--- /dev/null
+/*-
+ * ============LICENSE_START=======================================================
+ * ONAP CLAMP
+ * ================================================================================
+ * Copyright (C) 2019 Samsung. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END============================================
+ * ===================================================================
+ *
+ */
+
+package org.onap.clamp.clds.client;
+
+import static org.mockito.Mockito.any;
+import static org.mockito.Mockito.anyString;
+import static org.mockito.Mockito.eq;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.never;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.when;
+
+import com.google.gson.JsonElement;
+import com.google.gson.JsonObject;
+
+import java.io.IOException;
+
+import org.apache.camel.Exchange;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.mockito.InjectMocks;
+import org.mockito.Mock;
+import org.mockito.runners.MockitoJUnitRunner;
+import org.onap.clamp.clds.client.req.policy.PolicyClient;
+import org.onap.clamp.clds.config.ClampProperties;
+import org.onap.clamp.clds.dao.CldsDao;
+import org.onap.clamp.clds.exception.ModelBpmnException;
+import org.onap.clamp.clds.model.CldsModel;
+import org.onap.clamp.clds.util.JsonUtils;
+
+@RunWith(MockitoJUnitRunner.class)
+public class TcaPolicyDelegateTest {
+
+ private static final String MODEL_BPMN_KEY = "modelBpmnProp";
+ private static final String MODEL_PROP_KEY = "modelProp";
+ private static final String MODEL_NAME_KEY = "modelName";
+ private static final String TEST_KEY = "isTest";
+ private static final String USERID_KEY = "userid";
+ private static final String TCA_TEMPLATE_KEY = "tca.template";
+ private static final String TCA_POLICY_TEMPLATE_KEY = "tca.policy.template";
+ private static final String TCA_THRESHOLDS_TEMPLATE_KEY = "tca.thresholds.template";
+ private static final String TCA_POLICY_RESPONSE_MESSAGE_KEY = "tcaPolicyResponseMessage";
+
+ private static final String TCA_ID_FROM_JSON = "{\"tca\":[{\"id\":\"id\",\"from\":\"\"}]}";
+ private static final String ID_JSON = "{\"id\":{\"r\":[{},{\"serviceConfigurations\":"
+ + "[[\"x\",\"+\",\"2\",\"y\"]]}]}}";
+ private static final String TCA_TEMPLATE_JSON = "{\"metricsPerEventName\":[{\"thresholds\":[]}]}";
+ private static final String TCA_POLICY_TEMPLATE_JSON = "{\"content\":{}}";
+ private static final String TCA_THRESHOLDS_TEMPLATE_JSON = "{}";
+ private static final String HOLMES_ID_FROM_JSON = "{\"holmes\":[{\"id\":\"\",\"from\":\"\"}]}";
+ private static final String NOT_JSON = "not json";
+
+ private static final String RESPONSE_MESSAGE_VALUE = "responseMessage";
+ private static final String MODEL_NAME_VALUE = "ModelName";
+ private static final String USERID_VALUE = "user";
+
+ private static final String CLDS_MODEL_ID = "id";
+ private static final String CLDS_MODEL_PROP_TEXT = "propText";
+
+ @Mock
+ private Exchange camelExchange;
+
+ @Mock
+ private ClampProperties refProp;
+
+ @Mock
+ private PolicyClient policyClient;
+
+ @Mock
+ private CldsDao cldsDao;
+
+ @InjectMocks
+ private TcaPolicyDelegate tcaPolicyDelegate;
+
+ @Test
+ public void shouldExecuteSuccessfully() throws IOException {
+ //given
+ when(camelExchange.getProperty(eq(MODEL_BPMN_KEY))).thenReturn(TCA_ID_FROM_JSON);
+ when(camelExchange.getProperty(eq(MODEL_PROP_KEY))).thenReturn(ID_JSON);
+ when(camelExchange.getProperty(eq(MODEL_NAME_KEY))).thenReturn(MODEL_NAME_VALUE);
+ when(camelExchange.getProperty(eq(TEST_KEY))).thenReturn(false);
+ when(camelExchange.getProperty(eq(USERID_KEY))).thenReturn(USERID_VALUE);
+
+ JsonElement jsonTemplate;
+ JsonObject jsonObject;
+
+ jsonTemplate = mock(JsonElement.class);
+ when(refProp.getJsonTemplate(eq(TCA_TEMPLATE_KEY), anyString())).thenReturn(jsonTemplate);
+ jsonObject = JsonUtils.GSON.fromJson(TCA_TEMPLATE_JSON, JsonObject.class);
+ when(jsonTemplate.getAsJsonObject()).thenReturn(jsonObject);
+
+ jsonTemplate = mock(JsonElement.class);
+ when(refProp.getJsonTemplate(eq(TCA_POLICY_TEMPLATE_KEY), anyString())).thenReturn(jsonTemplate);
+ jsonObject = JsonUtils.GSON.fromJson(TCA_POLICY_TEMPLATE_JSON, JsonObject.class);
+ when(jsonTemplate.getAsJsonObject()).thenReturn(jsonObject);
+
+ jsonTemplate = mock(JsonElement.class);
+ when(refProp.getJsonTemplate(eq(TCA_THRESHOLDS_TEMPLATE_KEY), anyString())).thenReturn(jsonTemplate);
+ jsonObject = JsonUtils.GSON.fromJson(TCA_THRESHOLDS_TEMPLATE_JSON, JsonObject.class);
+ when(jsonTemplate.getAsJsonObject()).thenReturn(jsonObject);
+
+ when(policyClient.sendMicroServiceInOther(anyString(), any())).thenReturn(RESPONSE_MESSAGE_VALUE);
+
+ CldsModel cldsModel = new CldsModel();
+ cldsModel.setId(CLDS_MODEL_ID);
+ cldsModel.setPropText(CLDS_MODEL_PROP_TEXT);
+ when(cldsDao.getModelTemplate(eq(MODEL_NAME_VALUE))).thenReturn(cldsModel);
+
+ //when
+ tcaPolicyDelegate.execute(camelExchange);
+
+ //then
+ verify(camelExchange).setProperty(eq(TCA_POLICY_RESPONSE_MESSAGE_KEY), eq(RESPONSE_MESSAGE_VALUE.getBytes()));
+ verify(cldsDao).setModel(eq(cldsModel), eq(USERID_VALUE));
+ }
+
+ @Test
+ public void shouldExecuteTcaNotFound() {
+ //given
+ when(camelExchange.getProperty(eq(MODEL_BPMN_KEY))).thenReturn(HOLMES_ID_FROM_JSON);
+ when(camelExchange.getProperty(eq(MODEL_PROP_KEY))).thenReturn(ID_JSON);
+ when(camelExchange.getProperty(eq(TEST_KEY))).thenReturn(false);
+
+ //when
+ tcaPolicyDelegate.execute(camelExchange);
+
+ //then
+ verify(policyClient, never()).sendMicroServiceInOther(any(), any());
+ }
+
+ @Test(expected = ModelBpmnException.class)
+ public void shouldThrowModelBpmnException() {
+ //given
+ when(camelExchange.getProperty(eq(MODEL_BPMN_KEY))).thenReturn(NOT_JSON);
+ when(camelExchange.getProperty(eq(TEST_KEY))).thenReturn(false);
+
+ //when
+ tcaPolicyDelegate.execute(camelExchange);
+ }
+
+ @Test(expected = NullPointerException.class)
+ public void shouldThrowNullPointerException() {
+ //when
+ tcaPolicyDelegate.execute(camelExchange);
+ }
+}
* Copyright (C) 2019 AT&T Intellectual Property. All rights
* reserved.
* ================================================================================
+ * Modifications Copyright (c) 2019 Samsung
+ * ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
+import static org.junit.Assert.fail;
-import com.att.eelf.configuration.EELFLogger;
-import com.att.eelf.configuration.EELFManager;
-
-import java.io.IOException;
-import java.util.LinkedList;
import java.util.List;
+import org.apache.camel.Exchange;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
+import org.mockito.InjectMocks;
import org.mockito.Mockito;
+import org.mockito.Spy;
import org.onap.clamp.authorization.AuthorizationController;
+import org.onap.clamp.clds.config.ClampProperties;
+import org.onap.clamp.clds.exception.NotAuthorizedException;
import org.onap.clamp.clds.service.SecureServicePermission;
import org.onap.clamp.util.PrincipalUtils;
import org.springframework.boot.test.context.SpringBootTest;
+import org.springframework.mock.env.MockEnvironment;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
-import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
-import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.userdetails.User;
import org.springframework.test.context.junit4.SpringRunner;
@SpringBootTest
public class AuthorizationControllerItCase {
- protected static final EELFLogger logger = EELFManager.getInstance().getLogger(AuthorizationControllerItCase.class);
- private Authentication authentication;
- private List<GrantedAuthority> authList = new LinkedList<GrantedAuthority>();
+ private PermissionTestDefaultHelper permissionTestHelper = new PermissionTestDefaultHelper();
+
+ @Spy
+ MockEnvironment env;
+
+ @Spy
+ @InjectMocks
+ private ClampProperties clampProp = new ClampProperties();
+
+ @InjectMocks
+ private AuthorizationController auth;
/**
* Setup the variable before the tests execution.
- *
- * @throws IOException
- * In case of issues when opening the files
*/
@Before
- public void setupBefore() throws IOException {
- authList.add(new SimpleGrantedAuthority("permission-type-cl-manage|dev|*"));
- authList.add(new SimpleGrantedAuthority("permission-type-cl|dev|read"));
- authList.add(new SimpleGrantedAuthority("permission-type-cl|dev|update"));
- authList.add(new SimpleGrantedAuthority("permission-type-template|dev|read"));
- authList.add(new SimpleGrantedAuthority("permission-type-template|dev|update"));
- authList.add(new SimpleGrantedAuthority("permission-type-filter-vf|dev|*"));
- authList.add(new SimpleGrantedAuthority("permission-type-cl-event|dev|*"));
-
- authentication = new UsernamePasswordAuthenticationToken(new User("admin", "", authList), "", authList);
- }
+ public void setupBefore() {
+ permissionTestHelper.setupMockEnv(env);
+ List<GrantedAuthority> authList = permissionTestHelper.getAuthList();
- @Test
- public void testIsUserPermittedNoException() {
SecurityContext securityContext = Mockito.mock(SecurityContext.class);
- Mockito.when(securityContext.getAuthentication()).thenReturn(authentication);
+ Mockito.when(securityContext.getAuthentication()).thenReturn(
+ new UsernamePasswordAuthenticationToken(new User("admin", "", authList),
+ "", authList)
+ );
PrincipalUtils.setSecurityContext(securityContext);
+ }
- AuthorizationController auth = new AuthorizationController();
+ @Test
+ public void testIsUserPermitted() {
assertTrue(auth.isUserPermitted(new SecureServicePermission("permission-type-cl","dev","read")));
assertTrue(auth.isUserPermitted(new SecureServicePermission("permission-type-cl-manage","dev","DEPLOY")));
- assertTrue(auth.isUserPermitted(new SecureServicePermission("permission-type-filter-vf","dev","12345-55555-55555-5555")));
+ assertTrue(auth.isUserPermitted(new SecureServicePermission("permission-type-filter-vf","dev",
+ "12345-55555-55555-5555")));
assertFalse(auth.isUserPermitted(new SecureServicePermission("permission-type-cl","test","read")));
}
+
+ @Test
+ public void testIfUserAuthorize() {
+ Exchange ex = Mockito.mock(Exchange.class);
+ try {
+ permissionTestHelper.doActionOnAllPermissions(((type, instance, action) ->
+ auth.authorize(ex, type, instance, action)
+ )
+ );
+ } catch (NotAuthorizedException e) {
+ fail(e.getMessage());
+ }
+ }
+
+ @Test(expected = NotAuthorizedException.class)
+ public void testIfAuthorizeThrowException() {
+ Exchange ex = Mockito.mock(Exchange.class);
+ auth.authorize(ex,"permission-type-cl","test","read");
+ }
}
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
-import javax.ws.rs.core.Response;
-
import org.junit.Test;
import org.junit.runner.RunWith;
import org.onap.clamp.clds.model.CldsHealthCheck;
Properties prop = new Properties();
InputStream in = Thread.currentThread().getContextClassLoader().getResourceAsStream("clds-version.properties");
prop.load(in);
+ assertNotNull(in);
in.close();
assertEquals(cldsInfo.getCldsVersion(), prop.getProperty("clds.version"));
assertEquals(cldsInfo.getUserName(), "admin");
private String toscaModelYaml;
private Authentication authentication;
private CldsToscaModel cldsToscaModel;
- private List<GrantedAuthority> authList = new LinkedList<GrantedAuthority>();
+ private List<GrantedAuthority> authList = new LinkedList<>();
private LoggingUtils util;
/**
--- /dev/null
+/*-
+ * ============LICENSE_START=======================================================
+ * ONAP CLAMP
+ * ================================================================================
+ * Copyright (C) 2019 Samsung. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END============================================
+ * ===================================================================
+ *
+ */
+
+package org.onap.clamp.clds.it;
+
+import com.google.common.collect.ImmutableMap;
+
+import java.util.Map;
+
+public class PermissionTestDefaultHelper extends PermissionTestHelper {
+
+ private static final String[] ALL_ACTION = new String[] {"*"};
+ private static final String[] READ_UPDATE_ACTION = new String[] {"read", "update"};
+
+ private static final String DEV_INSTANCE = "dev";
+ private static final String TEST_INSTANCE = "test";
+
+ private static final Map<String, Map> defaultPermission = ImmutableMap.of(
+ "permission-type-cl", ImmutableMap.of(
+ DEV_INSTANCE, ALL_ACTION),
+ "permission-type-cl-event", ImmutableMap.of(
+ DEV_INSTANCE, ALL_ACTION,
+ TEST_INSTANCE, READ_UPDATE_ACTION),
+ "permission-type-cl-manage", ImmutableMap.of(
+ DEV_INSTANCE, ALL_ACTION,
+ TEST_INSTANCE, READ_UPDATE_ACTION),
+ "permission-type-filter-vf", ImmutableMap.of(
+ DEV_INSTANCE, ALL_ACTION,
+ TEST_INSTANCE, READ_UPDATE_ACTION),
+ "permission-type-template", ImmutableMap.of(
+ DEV_INSTANCE, ALL_ACTION,
+ TEST_INSTANCE, READ_UPDATE_ACTION)
+ );
+
+ /**
+ * Permission test default helper constructor.
+ * This class setup the default permission in the parent PermissionTestHelper class.
+ */
+ public PermissionTestDefaultHelper() {
+ super(defaultPermission);
+ }
+}
--- /dev/null
+/*-
+ * ============LICENSE_START=======================================================
+ * ONAP CLAMP
+ * ================================================================================
+ * Copyright (C) 2019 Samsung. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END============================================
+ * ===================================================================
+ *
+ */
+
+package org.onap.clamp.clds.it;
+
+import static org.onap.clamp.authorization.AuthorizationController.PERM_PREFIX;
+import static org.onap.clamp.clds.config.ClampProperties.CONFIG_PREFIX;
+
+import java.util.LinkedList;
+import java.util.List;
+import java.util.Map;
+
+import org.springframework.mock.env.MockEnvironment;
+import org.springframework.security.core.GrantedAuthority;
+import org.springframework.security.core.authority.SimpleGrantedAuthority;
+
+public class PermissionTestHelper {
+
+ private static final String securityPrefix = CONFIG_PREFIX + PERM_PREFIX;
+ private final Map<String, Map> permission;
+ private static final List<GrantedAuthority> authList = new LinkedList<>();
+
+ /**
+ * Permission Test Helper constructor
+ * Generate authList base on general permission collection
+ */
+ public PermissionTestHelper(Map<String, Map> permission) {
+ this.permission = permission;
+ this.createAuthList();
+ }
+
+ private void createAuthList() {
+ permission.forEach((type, instanceMap) -> instanceMap.forEach((instance, actionList) -> {
+ for (String action : (String[]) actionList) {
+ authList.add(new SimpleGrantedAuthority(type + "|" + instance + "|" + action));
+ }
+ }));
+ }
+
+ List<GrantedAuthority> getAuthList() {
+ return authList;
+ }
+
+ void setupMockEnv(MockEnvironment env) {
+ permission.forEach((type, instanceMap) -> env.withProperty(securityPrefix + type, type));
+ }
+
+ void doActionOnAllPermissions(PermissionAction action) {
+ permission.forEach((type, instanceMap) -> instanceMap.forEach((instance, actionList) -> {
+ for (String actionName : (String[]) actionList) {
+ action.doAction(type, (String) instance, actionName);
+ }
+ }));
+ }
+
+ @FunctionalInterface
+ public interface PermissionAction {
+ void doAction(String type, String instance, String action);
+ }
+}
* Copyright (C) 2018 AT&T Intellectual Property. All rights
* reserved.
* ================================================================================
+ * Modifications Copyright (c) 2019 Samsung
+ * ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
package org.onap.clamp.clds.it.sdc.controller;
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.mockito.Mockito.mock;
+import java.lang.reflect.Constructor;
+import java.lang.reflect.InvocationTargetException;
+import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;
-
import org.assertj.core.api.Assertions;
import org.junit.Before;
import org.junit.Test;
import org.mockito.Mockito;
import org.onap.clamp.clds.config.ClampProperties;
import org.onap.clamp.clds.config.sdc.SdcSingleControllerConfigurationTest;
+import org.onap.clamp.clds.exception.sdc.controller.SdcControllerException;
import org.onap.clamp.clds.sdc.controller.SdcSingleController;
+import org.onap.clamp.clds.sdc.controller.SdcSingleControllerStatus;
import org.onap.clamp.clds.sdc.controller.installer.CsarHandler;
import org.onap.clamp.clds.sdc.controller.installer.CsarInstaller;
import org.onap.sdc.api.notification.IArtifactInfo;
import org.onap.sdc.api.notification.INotificationData;
import org.onap.sdc.api.notification.IResourceInstance;
+import org.slf4j.MDC;
+import org.slf4j.spi.MDCAdapter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.ActiveProfiles;
private SdcSingleController sdcSingleController;
+ private CsarInstaller csarInstaller = mock(CsarInstaller.class);
+
private INotificationData buildFakeSdcNotification() {
// BUild what is needed for CSAR
- IArtifactInfo serviceArtifact = Mockito.mock(IArtifactInfo.class);
+ IArtifactInfo serviceArtifact = mock(IArtifactInfo.class);
Mockito.when(serviceArtifact.getArtifactType()).thenReturn(CsarHandler.CSAR_TYPE);
Mockito.when(serviceArtifact.getArtifactName()).thenReturn(CSAR_ARTIFACT_NAME);
List<IArtifactInfo> servicesList = new ArrayList<>();
servicesList.add(serviceArtifact);
- INotificationData notifData = Mockito.mock(INotificationData.class);
+ INotificationData notifData = mock(INotificationData.class);
Mockito.when(notifData.getServiceArtifacts()).thenReturn(servicesList);
// Build what is needed for UUID
Mockito.when(notifData.getServiceInvariantUUID()).thenReturn(SERVICE_UUID);
// Build fake resource with one artifact BLUEPRINT
- IResourceInstance resource1 = Mockito.mock(IResourceInstance.class);
+ IResourceInstance resource1 = mock(IResourceInstance.class);
Mockito.when(resource1.getResourceType()).thenReturn("VF");
Mockito.when(resource1.getResourceInvariantUUID()).thenReturn(RESOURCE1_UUID);
Mockito.when(resource1.getResourceInstanceName()).thenReturn(RESOURCE1_INSTANCE_NAME);
// Create a fake artifact for resource
- IArtifactInfo blueprintArtifact = Mockito.mock(IArtifactInfo.class);
+ IArtifactInfo blueprintArtifact = mock(IArtifactInfo.class);
Mockito.when(blueprintArtifact.getArtifactType()).thenReturn(CsarHandler.BLUEPRINT_TYPE);
List<IArtifactInfo> artifactsListForResource = new ArrayList<>();
artifactsListForResource.add(blueprintArtifact);
*/
@Before
public void init() {
- sdcSingleController = new SdcSingleController(clampProp, Mockito.mock(CsarInstaller.class),
+ sdcSingleController = new SdcSingleController(clampProp, csarInstaller,
SdcSingleControllerConfigurationTest.loadControllerConfiguration("clds/sdc-controller-config-TLS.json",
"sdc-controller1"),
null) {
@Test
public void testTreatNotification() {
+ //when
sdcSingleController.treatNotification(buildFakeSdcNotification());
+ //then
Assertions.assertThat(sdcSingleController.getNbOfNotificationsOngoing()).isEqualTo(0);
+ }
+ @Test
+ public void testCloseSdc() throws SdcControllerException {
+ //when
+ sdcSingleController.closeSdc();
+ //then
+ assertThat(sdcSingleController.getControllerStatus()).isEqualTo(SdcSingleControllerStatus.STOPPED);
}
+ @Test
+ public void testActivateCallback() throws InvocationTargetException, IllegalAccessException, NoSuchMethodException, InstantiationException, ClassNotFoundException {
+ //given
+ MDCAdapter mdcAdapter = MDC.getMDCAdapter();
+ Class<?> innerClass = Class.forName("org.onap.clamp.clds.sdc.controller.SdcSingleController$SdcNotificationCallBack");
+ Constructor<?> constructor = innerClass.getDeclaredConstructor(SdcSingleController.class, SdcSingleController.class);
+ constructor.setAccessible(true);
+ Object child = constructor.newInstance(sdcSingleController,sdcSingleController);
+ Method method = child.getClass().getDeclaredMethod("activateCallback",INotificationData.class);
+ method.setAccessible(true);
+ //when
+ method.invoke(child,buildFakeSdcNotification());
+ //then
+ assertThat(mdcAdapter.get("ResponseCode")).isEqualTo("0");
+ assertThat(mdcAdapter.get("StatusCode")).isEqualTo("COMPLETE");
+ assertThat(mdcAdapter.get("ResponseDescription")).isEqualTo("SDC Notification received and processed successfully");
+ assertThat(mdcAdapter.get("ClassName")).isEqualTo(child.getClass().getName());
+ }
}
* Copyright (C) 2017 AT&T Intellectual Property. All rights
* reserved.
* ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
+ * Modifications Copyright (c) 2019 Samsung
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotEquals;
import static org.junit.Assert.assertNotNull;
+import static org.mockito.Matchers.eq;
+
+import java.security.InvalidKeyException;
+
+import javax.crypto.KeyGenerator;
+import javax.crypto.SecretKey;
import org.apache.commons.codec.binary.Hex;
import org.apache.commons.lang3.ArrayUtils;
import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.powermock.api.mockito.PowerMockito;
+import org.powermock.core.classloader.annotations.PowerMockIgnore;
+import org.powermock.core.classloader.annotations.PrepareForTest;
+import org.powermock.modules.junit4.PowerMockRunner;
-
+@RunWith(PowerMockRunner.class)
+@PowerMockIgnore({"javax.crypto.*"})
public class CryptoUtilsTest {
private final String data = "This is a test string";
@Test
+ @PrepareForTest({CryptoUtils.class})
public final void testEncryption() throws Exception {
String encodedString = CryptoUtils.encrypt(data);
assertNotNull(encodedString);
}
@Test
+ @PrepareForTest({CryptoUtils.class})
public final void testEncryptedStringIsDifferent() throws Exception {
String encodedString1 = CryptoUtils.encrypt(data);
String encodedString2 = CryptoUtils.encrypt(data);
byte[] subData2 = ArrayUtils.subarray(encryptedMessage2, 16, encryptedMessage2.length);
assertNotEquals(subData1, subData2);
}
-}
\ No newline at end of file
+
+ @Test
+ @PrepareForTest({CryptoUtils.class})
+ public final void testEncryptionBaseOnRandomKey() throws Exception {
+ SecretKey secretKey = KeyGenerator.getInstance("AES").generateKey();
+ final String encryptionKey = String.valueOf(Hex.encodeHex(secretKey.getEncoded()));
+ setAesEncryptionKeyEnv(encryptionKey);
+
+ String encodedString = CryptoUtils.encrypt(data);
+ String decodedString = CryptoUtils.decrypt(encodedString);
+ assertEquals(data, decodedString);
+ }
+
+ @Test(expected = InvalidKeyException.class)
+ @PrepareForTest({CryptoUtils.class})
+ public final void testEncryptionBadKey() throws Exception {
+ final String badEncryptionKey = "93210sd";
+ setAesEncryptionKeyEnv(badEncryptionKey);
+
+ CryptoUtils.encrypt(data);
+ }
+
+ private static void setAesEncryptionKeyEnv(String value) {
+ PowerMockito.mockStatic(System.class);
+ PowerMockito.when(System.getenv(eq("AES_ENCRYPTION_KEY"))).thenReturn(value);
+ }
+}
* Copyright (C) 2018 AT&T Intellectual Property. All rights
* reserved.
* ================================================================================
+ * Modifications Copyright (c) 2019 Samsung
+ * ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
// then
assertThat(timeoutValue).isEqualTo(500);
}
+
+ @Test(expected = IllegalArgumentException.class)
+ public void shouldThrowExceptionFileNotExists() throws IOException {
+ ResourceFileUtil.getResourceAsString("example/notExist.json");
+ }
}
@Mock
private SVGGraphics2D mockG2d;
- @Mock
- private Document mockDomImpl;
-
@Test
public void pushChangestoDocumentTest() throws IOException, ParserConfigurationException, SAXException {
String dataElementId = "someId";
--- /dev/null
+/*-
+ * ============LICENSE_START=======================================================
+ * ONAP CLAMP
+ * ================================================================================
+ * Copyright (C) 2019 Samsung. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END============================================
+ * ===================================================================
+ *
+ */
+
+package org.onap.clamp.flow;
+
+import static junit.framework.Assert.assertEquals;
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.mockito.Mockito.mock;
+import org.apache.camel.CamelContext;
+import org.apache.camel.Exchange;
+import org.apache.camel.impl.DefaultExchange;
+import org.junit.Test;
+import org.mockito.Mockito;
+import org.onap.clamp.clds.util.LoggingUtils;
+import org.onap.clamp.clds.util.ONAPLogConstants;
+import org.onap.clamp.flow.log.FlowLogOperation;
+import org.slf4j.MDC;
+import org.slf4j.spi.MDCAdapter;
+import org.springframework.test.util.ReflectionTestUtils;
+
+public class FlowLogOperationTest {
+
+ private FlowLogOperation flowLogOperation = new FlowLogOperation();
+
+ @Test
+ public void testStratLog() {
+ //given
+ Exchange exchange = new DefaultExchange(mock(CamelContext.class));
+ LoggingUtils loggingUtils = mock(LoggingUtils.class);
+ ReflectionTestUtils.setField(flowLogOperation, "util", loggingUtils);
+
+ //when
+ Mockito.when(loggingUtils.getProperties(ONAPLogConstants.MDCs.REQUEST_ID)).thenReturn("MockRequestId");
+ Mockito.when(loggingUtils.getProperties(ONAPLogConstants.MDCs.INVOCATION_ID)).thenReturn("MockInvocationId");
+ Mockito.when(loggingUtils.getProperties(ONAPLogConstants.MDCs.PARTNER_NAME)).thenReturn("MockPartnerName");
+ flowLogOperation.startLog(exchange, "serviceName");
+
+ //then
+ assertThat(exchange.getProperty(ONAPLogConstants.Headers.REQUEST_ID)).isEqualTo("MockRequestId");
+ assertThat(exchange.getProperty(ONAPLogConstants.Headers.INVOCATION_ID)).isEqualTo("MockInvocationId");
+ assertThat(exchange.getProperty(ONAPLogConstants.Headers.PARTNER_NAME)).isEqualTo("MockPartnerName");
+ }
+
+ @Test
+ public void testInvokeLog() {
+ //given
+ final String mockEntity = "mockEntity";
+ final String mockServiceName = "mockSerivceName";
+ MDCAdapter mdcAdapter = MDC.getMDCAdapter();
+ //when
+ flowLogOperation.invokeLog(mockEntity, mockServiceName);
+ //then
+ String entity = mdcAdapter.get(ONAPLogConstants.MDCs.TARGET_ENTITY);
+ String serviceName = mdcAdapter.get(ONAPLogConstants.MDCs.TARGET_SERVICE_NAME);
+ assertEquals(entity,mockEntity);
+ assertEquals(serviceName,mockServiceName);
+ }
+
+ @Test
+ public void testEndLog() {
+ //given
+ MDC.put(ONAPLogConstants.MDCs.ENTRY_TIMESTAMP, "2019-05-19T00:00:00.007Z");
+ MDCAdapter mdcAdapter = MDC.getMDCAdapter();
+ ///when
+ flowLogOperation.endLog();
+ //then
+ assertThat(mdcAdapter.get(ONAPLogConstants.MDCs.ENTRY_TIMESTAMP)).isNull();
+ }
+
+ @Test
+ public void testErrorLog() {
+ //given
+ MDC.put(ONAPLogConstants.MDCs.ENTRY_TIMESTAMP, "2019-05-19T00:00:00.007Z");
+ MDCAdapter mdcAdapter = MDC.getMDCAdapter();
+ //when
+ flowLogOperation.errorLog();
+ //then
+ assertThat(mdcAdapter.get(ONAPLogConstants.MDCs.ENTRY_TIMESTAMP)).isNull();
+ }
+}
\ No newline at end of file
+++ /dev/null
-package org.onap.clamp.flow;
-
-import org.apache.camel.CamelContext;
-import org.apache.camel.Exchange;
-import org.apache.camel.impl.DefaultExchange;
-import org.junit.Test;
-import org.mockito.Mockito;
-import org.onap.clamp.clds.util.LoggingUtils;
-import org.onap.clamp.clds.util.ONAPLogConstants;
-import org.onap.clamp.flow.log.FlowLogOperation;
-import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.test.util.ReflectionTestUtils;
-import static org.assertj.core.api.Assertions.assertThat;
-import static org.mockito.Mockito.mock;
-
-
-public class FlowLogOperationTestItCase {
-
- @Autowired
- CamelContext camelContext;
-
- @Test
- public void testStratLog() {
- //given
- FlowLogOperation flowLogOperation = new FlowLogOperation();
- Exchange exchange = new DefaultExchange(camelContext);
- LoggingUtils loggingUtils = mock(LoggingUtils.class);
- ReflectionTestUtils.setField(flowLogOperation, "util", loggingUtils);
-
- //when
- Mockito.when(loggingUtils.getProperties(ONAPLogConstants.MDCs.REQUEST_ID)).thenReturn("MockRequestId");
- Mockito.when(loggingUtils.getProperties(ONAPLogConstants.MDCs.INVOCATION_ID)).thenReturn("MockInvocationId");
- Mockito.when(loggingUtils.getProperties(ONAPLogConstants.MDCs.PARTNER_NAME)).thenReturn("MockPartnerName");
- flowLogOperation.startLog(exchange, "serviceName");
-
- //then
- assertThat(exchange.getProperty(ONAPLogConstants.Headers.REQUEST_ID)).isEqualTo("MockRequestId");
- assertThat(exchange.getProperty(ONAPLogConstants.Headers.INVOCATION_ID)).isEqualTo("MockInvocationId");
- assertThat(exchange.getProperty(ONAPLogConstants.Headers.PARTNER_NAME)).isEqualTo("MockPartnerName");
- }
-}
\ No newline at end of file
* reserved.
* ================================================================================
* Modifications copyright (c) 2019 Nokia
- * ===================================================================
+ * Modifications Copyright (c) 2019 Samsung
+ * ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
package org.onap.clamp.loop;
import static org.assertj.core.api.Assertions.assertThat;
+import static org.mockito.Matchers.any;
import java.io.IOException;
import java.util.ArrayList;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.test.context.SpringBootTest;
-import org.springframework.test.annotation.Rollback;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.context.junit4.SpringRunner;
assertThat(((MicroServicePolicy) (loop.getMicroServicePolicies().toArray()[0])).getModelType()).isNotEmpty();
}
+ @Test(expected = SdcArtifactInstallerException.class)
+ @Transactional
+ public void shouldThrowSdcArtifactInstallerException() throws SdcArtifactInstallerException, SdcToscaParserException, IOException, InterruptedException, PolicyModelException {
+ String generatedName = RandomStringUtils.randomAlphanumeric(5);
+ CsarHandler csarHandler = buildFakeCsarHandler(generatedName);
+ Mockito.when(csarHandler.getMapOfBlueprints()).thenThrow(IOException.class);
+ csarInstaller.installTheCsar(csarHandler);
+ }
}