diff options
author | biniek <lukasz.biniek@nokia.com> | 2019-04-09 10:50:04 +0200 |
---|---|---|
committer | biniek <lukasz.biniek@nokia.com> | 2019-04-09 16:11:01 +0200 |
commit | 1b1fded0d7cdfbc9ea7ee1c9b533b01fb3dc9b35 (patch) | |
tree | 9ae811885af9159e46200acd74118f208da2a51d /test/mocks/pnfsimulator | |
parent | afb9786b012d43bef177e659e6f37c8017f2642c (diff) |
Refactor SimulatorFactory in PnfSimulator
Change-Id: Ie3e17a984d8fa92a68b923b09f759cfd5a4a980a
Issue-ID: INT-1018
Signed-off-by: biniek <lukasz.biniek@nokia.com>
Diffstat (limited to 'test/mocks/pnfsimulator')
22 files changed, 522 insertions, 462 deletions
diff --git a/test/mocks/pnfsimulator/config/config.json b/test/mocks/pnfsimulator/config/config.json index 3b5cd8a60..636e0132e 100644 --- a/test/mocks/pnfsimulator/config/config.json +++ b/test/mocks/pnfsimulator/config/config.json @@ -25,30 +25,30 @@ "attachmentPoint": "bla-bla-30-3", "svlan": "1005", "cvlan": "678" - }, - "notificationParams": { - "changeIdentifier": "PM_MEAS_FILES", - "changeType": "FileReady", - "arrayOfNamedHashMap": [ - { - "name": "A20161221.1031-1041.bin.gz", - "hashMap": { - "location": "ftpes://192.169.0.1:22/ftp/rop/A20161224.1030-1045.bin.gz", - "compression": "gzip", - "fileFormatType": "org.3GPP.32.435#measCollec", - "fileFormatVersion": "V10" - } - }, - { - "name": "A20161222.1042-1102.bin.gz", - "hashMap": { - "location": "ftpes://192.168.0.102:22/ftp/rop/A20161224.1045-1100.bin.gz", - "compression": "gzip", - "fileFormatType": "org.3GPP.32.435#measCollec", - "fileFormatVersion": "V10" - } - } - ] } + }, + "notificationParams": { + "changeIdentifier": "PM_MEAS_FILES", + "changeType": "FileReady", + "arrayOfNamedHashMap": [ + { + "name": "A20161221.1031-1041.bin.gz", + "hashMap": { + "location": "ftpes://192.169.0.1:22/ftp/rop/A20161224.1030-1045.bin.gz", + "compression": "gzip", + "fileFormatType": "org.3GPP.32.435#measCollec", + "fileFormatVersion": "V10" + } + }, + { + "name": "A20161222.1042-1102.bin.gz", + "hashMap": { + "location": "ftpes://192.168.0.102:22/ftp/rop/A20161224.1045-1100.bin.gz", + "compression": "gzip", + "fileFormatType": "org.3GPP.32.435#measCollec", + "fileFormatVersion": "V10" + } + } + ] } } diff --git a/test/mocks/pnfsimulator/src/main/java/org/onap/pnfsimulator/message/MessageBuilder.java b/test/mocks/pnfsimulator/src/main/java/org/onap/pnfsimulator/message/MessageBuilder.java new file mode 100644 index 000000000..ef0b2fdd2 --- /dev/null +++ b/test/mocks/pnfsimulator/src/main/java/org/onap/pnfsimulator/message/MessageBuilder.java @@ -0,0 +1,81 @@ +/* + * ============LICENSE_START======================================================= + * PNF-REGISTRATION-HANDLER + * ================================================================================ + * Copyright (C) 2019 NOKIA Intellectual Property. 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.pnfsimulator.message; + +import org.json.JSONObject; + +import static org.onap.pnfsimulator.message.MessageConstants.COMMON_EVENT_HEADER; +import static org.onap.pnfsimulator.message.MessageConstants.DOMAIN; +import static org.onap.pnfsimulator.message.MessageConstants.DOMAIN_NOTIFICATION; +import static org.onap.pnfsimulator.message.MessageConstants.DOMAIN_PNF_REGISTRATION; +import static org.onap.pnfsimulator.message.MessageConstants.EVENT; +import static org.onap.pnfsimulator.message.MessageConstants.EVENT_TYPE; +import static org.onap.pnfsimulator.message.MessageConstants.NOTIFICATION_FIELDS; +import static org.onap.pnfsimulator.message.MessageConstants.PNF_REGISTRATION_FIELDS; + +public final class MessageBuilder { + private JSONObject root; + private JSONObject event; + private JSONObject commonEventHeader; + + private MessageBuilder() { + } + + public static MessageBuilder withCommonEventHeaderParams(JSONObject commonEventHeaderParams) { + MessageBuilder builder = new MessageBuilder(); + builder.initializeBuilder(commonEventHeaderParams); + return builder; + } + + public MessageBuilder withNotificationParams(JSONObject notificationParams) { + JSONObject notificationFields = JSONObjectFactory.generateNotificationFields(); + merge(notificationParams, notificationFields); + commonEventHeader.put(DOMAIN, DOMAIN_NOTIFICATION); + event.put(NOTIFICATION_FIELDS, notificationFields); + return this; + } + + public MessageBuilder withPnfRegistrationParams(JSONObject pnfRegistrationParams) { + JSONObject pnfRegistrationFields = JSONObjectFactory.generatePnfRegistrationFields(); + merge(pnfRegistrationParams, pnfRegistrationFields); + commonEventHeader.put(DOMAIN, DOMAIN_PNF_REGISTRATION); + commonEventHeader.put(EVENT_TYPE, DOMAIN_PNF_REGISTRATION); + event.put(PNF_REGISTRATION_FIELDS, pnfRegistrationFields); + return this; + } + + public JSONObject build() { + return root; + } + + private void initializeBuilder(JSONObject commonEventHeaderParams) { + root = new JSONObject(); + event = new JSONObject(); + commonEventHeader = JSONObjectFactory.generateConstantCommonEventHeader(); + commonEventHeaderParams.toMap().forEach(commonEventHeader::put); + event.put(COMMON_EVENT_HEADER, commonEventHeader); + root.put(EVENT, event); + } + + private void merge(JSONObject source, JSONObject destination) { + source.toMap().forEach(destination::put); + } +} diff --git a/test/mocks/pnfsimulator/src/main/java/org/onap/pnfsimulator/message/MessageProvider.java b/test/mocks/pnfsimulator/src/main/java/org/onap/pnfsimulator/message/MessageProvider.java index 13114eefb..fee574597 100644 --- a/test/mocks/pnfsimulator/src/main/java/org/onap/pnfsimulator/message/MessageProvider.java +++ b/test/mocks/pnfsimulator/src/main/java/org/onap/pnfsimulator/message/MessageProvider.java @@ -2,7 +2,7 @@ * ============LICENSE_START======================================================= * PNF-REGISTRATION-HANDLER * ================================================================================ - * Copyright (C) 2018 NOKIA Intellectual Property. All rights reserved. + * Copyright (C) 2018-2019 NOKIA Intellectual Property. 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. @@ -20,61 +20,23 @@ package org.onap.pnfsimulator.message; -import static org.onap.pnfsimulator.message.MessageConstants.COMMON_EVENT_HEADER; -import static org.onap.pnfsimulator.message.MessageConstants.DOMAIN; -import static org.onap.pnfsimulator.message.MessageConstants.EVENT; -import static org.onap.pnfsimulator.message.MessageConstants.EVENT_TYPE; -import static org.onap.pnfsimulator.message.MessageConstants.NOTIFICATION_FIELDS; -import static org.onap.pnfsimulator.message.MessageConstants.DOMAIN_PNF_REGISTRATION; -import static org.onap.pnfsimulator.message.MessageConstants.DOMAIN_NOTIFICATION; -import static org.onap.pnfsimulator.message.MessageConstants.PNF_REGISTRATION_FIELDS; - -import java.util.Map; -import java.util.Optional; import org.json.JSONObject; public class MessageProvider { - public JSONObject createMessage(JSONObject commonEventHeaderParams, Optional<JSONObject> pnfRegistrationParams, - Optional<JSONObject> notificationParams) { - - if (!pnfRegistrationParams.isPresent() && !notificationParams.isPresent()) { - throw new IllegalArgumentException( - "Both PNF registration and notification parameters objects are not present"); - } - JSONObject event = new JSONObject(); - - JSONObject commonEventHeader = JSONObjectFactory.generateConstantCommonEventHeader(); - Map<String, Object> commonEventHeaderFields = commonEventHeaderParams.toMap(); - commonEventHeaderFields.forEach((key, value) -> { - commonEventHeader.put(key, value); - }); - - JSONObject pnfRegistrationFields = JSONObjectFactory.generatePnfRegistrationFields(); - pnfRegistrationParams.ifPresent(jsonObject -> { - copyParametersToFields(jsonObject.toMap(), pnfRegistrationFields); - commonEventHeader.put(DOMAIN, DOMAIN_PNF_REGISTRATION); - commonEventHeader.put(EVENT_TYPE, DOMAIN_PNF_REGISTRATION); - event.put(PNF_REGISTRATION_FIELDS, pnfRegistrationFields); - }); - - JSONObject notificationFields = JSONObjectFactory.generateNotificationFields(); - notificationParams.ifPresent(jsonObject -> { - copyParametersToFields(jsonObject.toMap(), notificationFields); - commonEventHeader.put(DOMAIN, DOMAIN_NOTIFICATION); - event.put(NOTIFICATION_FIELDS, notificationFields); - }); - - event.put(COMMON_EVENT_HEADER, commonEventHeader); - JSONObject root = new JSONObject(); - root.put(EVENT, event); - return root; + public JSONObject createMessageWithNotification(JSONObject commonEventHeaderParams, + JSONObject notificationParams) { + return MessageBuilder + .withCommonEventHeaderParams(commonEventHeaderParams) + .withNotificationParams(notificationParams) + .build(); } - private void copyParametersToFields(Map<String, Object> paramersMap, JSONObject fieldsJsonObject) { - paramersMap.forEach((key, value) -> { - fieldsJsonObject.put(key, value); - }); + public JSONObject createMessageWithPnfRegistration(JSONObject commonEventHeaderParams, JSONObject pnfRegistrationParams) { + return MessageBuilder + .withCommonEventHeaderParams(commonEventHeaderParams) + .withPnfRegistrationParams(pnfRegistrationParams) + .build(); } } diff --git a/test/mocks/pnfsimulator/src/main/java/org/onap/pnfsimulator/rest/SimulatorController.java b/test/mocks/pnfsimulator/src/main/java/org/onap/pnfsimulator/rest/SimulatorController.java index 506d21b6c..6b9f02622 100644 --- a/test/mocks/pnfsimulator/src/main/java/org/onap/pnfsimulator/rest/SimulatorController.java +++ b/test/mocks/pnfsimulator/src/main/java/org/onap/pnfsimulator/rest/SimulatorController.java @@ -2,7 +2,7 @@ * ============LICENSE_START======================================================= * PNF-REGISTRATION-HANDLER * ================================================================================ - * Copyright (C) 2018 NOKIA Intellectual Property. All rights reserved. + * Copyright (C) 2018-2019 NOKIA Intellectual Property. 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. @@ -20,32 +20,9 @@ package org.onap.pnfsimulator.rest; -import static org.onap.pnfsimulator.logging.MDCVariables.INSTANCE_UUID; -import static org.onap.pnfsimulator.logging.MDCVariables.INVOCATION_ID; -import static org.onap.pnfsimulator.logging.MDCVariables.REQUEST_ID; -import static org.onap.pnfsimulator.logging.MDCVariables.RESPONSE_CODE; -import static org.onap.pnfsimulator.logging.MDCVariables.SERVICE_NAME; -import static org.onap.pnfsimulator.logging.MDCVariables.X_INVOCATION_ID; -import static org.onap.pnfsimulator.logging.MDCVariables.X_ONAP_REQUEST_ID; -import static org.onap.pnfsimulator.message.MessageConstants.SIMULATOR_PARAMS; -import static org.onap.pnfsimulator.message.MessageConstants.COMMON_EVENT_HEADER_PARAMS; -import static org.onap.pnfsimulator.rest.util.ResponseBuilder.MESSAGE; -import static org.onap.pnfsimulator.rest.util.ResponseBuilder.REMAINING_TIME; -import static org.onap.pnfsimulator.rest.util.ResponseBuilder.SIMULATOR_STATUS; -import static org.onap.pnfsimulator.rest.util.ResponseBuilder.TIMESTAMP; -import static org.springframework.http.HttpStatus.BAD_REQUEST; -import static org.springframework.http.HttpStatus.INTERNAL_SERVER_ERROR; -import static org.springframework.http.HttpStatus.OK; - -import java.io.IOException; -import java.text.DateFormat; -import java.text.SimpleDateFormat; import com.github.fge.jsonschema.core.exceptions.ProcessingException; -import java.util.Optional; -import java.util.UUID; import org.json.JSONException; import org.json.JSONObject; -import org.onap.pnfsimulator.message.MessageConstants; import org.onap.pnfsimulator.rest.util.DateUtil; import org.onap.pnfsimulator.rest.util.ResponseBuilder; import org.onap.pnfsimulator.simulator.Simulator; @@ -67,6 +44,30 @@ import org.springframework.web.bind.annotation.RequestHeader; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; +import java.io.IOException; +import java.text.DateFormat; +import java.text.SimpleDateFormat; +import java.util.UUID; + +import static org.onap.pnfsimulator.logging.MDCVariables.INSTANCE_UUID; +import static org.onap.pnfsimulator.logging.MDCVariables.INVOCATION_ID; +import static org.onap.pnfsimulator.logging.MDCVariables.REQUEST_ID; +import static org.onap.pnfsimulator.logging.MDCVariables.RESPONSE_CODE; +import static org.onap.pnfsimulator.logging.MDCVariables.SERVICE_NAME; +import static org.onap.pnfsimulator.logging.MDCVariables.X_INVOCATION_ID; +import static org.onap.pnfsimulator.logging.MDCVariables.X_ONAP_REQUEST_ID; +import static org.onap.pnfsimulator.message.MessageConstants.COMMON_EVENT_HEADER_PARAMS; +import static org.onap.pnfsimulator.message.MessageConstants.NOTIFICATION_PARAMS; +import static org.onap.pnfsimulator.message.MessageConstants.PNF_REGISTRATION_PARAMS; +import static org.onap.pnfsimulator.message.MessageConstants.SIMULATOR_PARAMS; +import static org.onap.pnfsimulator.rest.util.ResponseBuilder.MESSAGE; +import static org.onap.pnfsimulator.rest.util.ResponseBuilder.REMAINING_TIME; +import static org.onap.pnfsimulator.rest.util.ResponseBuilder.SIMULATOR_STATUS; +import static org.onap.pnfsimulator.rest.util.ResponseBuilder.TIMESTAMP; +import static org.springframework.http.HttpStatus.BAD_REQUEST; +import static org.springframework.http.HttpStatus.INTERNAL_SERVER_ERROR; +import static org.springframework.http.HttpStatus.OK; + @RestController @RequestMapping("/simulator") public class SimulatorController { @@ -95,10 +96,10 @@ public class SimulatorController { if (isSimulatorRunning()) { MDC.put(RESPONSE_CODE, BAD_REQUEST.toString()); return ResponseBuilder - .status(BAD_REQUEST) - .put(TIMESTAMP, DateUtil.getTimestamp(RESPONSE_DATE_FORMAT)) - .put(MESSAGE, "Cannot start simulator since it's already running") - .build(); + .status(BAD_REQUEST) + .put(TIMESTAMP, DateUtil.getTimestamp(RESPONSE_DATE_FORMAT)) + .put(MESSAGE, "Cannot start simulator since it's already running") + .build(); } try { @@ -106,73 +107,81 @@ public class SimulatorController { JSONObject root = new JSONObject(message); JSONObject simulatorParams = root.getJSONObject(SIMULATOR_PARAMS); JSONObject commonEventHeaderParams = root.getJSONObject(COMMON_EVENT_HEADER_PARAMS); - Optional<JSONObject> pnfRegistrationFields = root.has(MessageConstants.PNF_REGISTRATION_PARAMS) ? Optional - .of(root.getJSONObject(MessageConstants.PNF_REGISTRATION_PARAMS)) : Optional.empty(); - Optional<JSONObject> notificationFields = root.has(MessageConstants.NOTIFICATION_PARAMS) ? Optional - .of(root.getJSONObject(MessageConstants.NOTIFICATION_PARAMS)) : Optional.empty(); - simulator = factory - .create(simulatorParams, commonEventHeaderParams, pnfRegistrationFields, notificationFields); + simulator = createSimulator(root, simulatorParams, commonEventHeaderParams); simulator.start(); MDC.put(RESPONSE_CODE, OK.toString()); return ResponseBuilder - .status(OK) - .put(TIMESTAMP, DateUtil.getTimestamp(RESPONSE_DATE_FORMAT)) - .put(MESSAGE, "Simulator started") - .build(); + .status(OK) + .put(TIMESTAMP, DateUtil.getTimestamp(RESPONSE_DATE_FORMAT)) + .put(MESSAGE, "Simulator started") + .build(); } catch (JSONException e) { MDC.put(RESPONSE_CODE, BAD_REQUEST.toString()); LOGGER.warn("Cannot start simulator, invalid json format: {}", e.getMessage()); LOGGER.debug("Received json has invalid format", e); return ResponseBuilder - .status(BAD_REQUEST) - .put(TIMESTAMP, DateUtil.getTimestamp(RESPONSE_DATE_FORMAT)) - .put(MESSAGE, "Cannot start simulator, invalid json format") - .build(); + .status(BAD_REQUEST) + .put(TIMESTAMP, DateUtil.getTimestamp(RESPONSE_DATE_FORMAT)) + .put(MESSAGE, "Cannot start simulator, invalid json format") + .build(); } catch (ProcessingException | ValidationException | IOException e) { MDC.put(RESPONSE_CODE, BAD_REQUEST.toString()); LOGGER.warn("Json validation failed: {}", e.getMessage()); return ResponseBuilder - .status(BAD_REQUEST) - .put(TIMESTAMP, DateUtil.getTimestamp(RESPONSE_DATE_FORMAT)) - .put(MESSAGE, "Cannot start simulator - Json format is not compatible with schema definitions") - .build(); + .status(BAD_REQUEST) + .put(TIMESTAMP, DateUtil.getTimestamp(RESPONSE_DATE_FORMAT)) + .put(MESSAGE, "Cannot start simulator - Json format is not compatible with schema definitions") + .build(); } catch (Exception e) { MDC.put(RESPONSE_CODE, INTERNAL_SERVER_ERROR.toString()); LOGGER.error("Cannot start simulator - unexpected exception", e); return ResponseBuilder - .status(INTERNAL_SERVER_ERROR) - .put(TIMESTAMP, DateUtil.getTimestamp(RESPONSE_DATE_FORMAT)) - .put(MESSAGE, "Unexpected exception: " + e.getMessage()) - .build(); + .status(INTERNAL_SERVER_ERROR) + .put(TIMESTAMP, DateUtil.getTimestamp(RESPONSE_DATE_FORMAT)) + .put(MESSAGE, "Unexpected exception: " + e.getMessage()) + .build(); } finally { MDC.clear(); } } + private Simulator createSimulator(JSONObject root, JSONObject simulatorParams, JSONObject commonEventHeaderParams) + throws ProcessingException, IOException, ValidationException { + JSONObject pnfRegistrationFields = root.optJSONObject(PNF_REGISTRATION_PARAMS); + JSONObject notificationFields = root.optJSONObject(NOTIFICATION_PARAMS); + if (pnfRegistrationFields != null && notificationFields == null) { + return factory.createSimulatorWithPnfRegistration(simulatorParams, commonEventHeaderParams, pnfRegistrationFields); + } else if (pnfRegistrationFields == null && notificationFields != null) { + return factory.createSimulatorWithNotification(simulatorParams, commonEventHeaderParams, notificationFields); + } else { + throw new ValidationException("Exactly one of pnfRegistrationFields or notificationFields should be present"); + } + } + @GetMapping("status") public ResponseEntity status() { if (isSimulatorRunning()) { ResponseBuilder responseBuilder = ResponseBuilder - .status(OK) - .put(TIMESTAMP, DateUtil.getTimestamp(RESPONSE_DATE_FORMAT)) - .put(SIMULATOR_STATUS, "RUNNING"); + .status(OK) + .put(TIMESTAMP, DateUtil.getTimestamp(RESPONSE_DATE_FORMAT)) + .put(SIMULATOR_STATUS, "RUNNING"); return !simulator.isEndless() ? - responseBuilder - .put(REMAINING_TIME, simulator.getRemainingTime()) - .build() : - responseBuilder - .build(); + responseBuilder + .put(REMAINING_TIME, simulator.getRemainingTime()) + .build() : + responseBuilder + .build(); } else { return ResponseBuilder - .status(OK) - .put(TIMESTAMP, DateUtil.getTimestamp(RESPONSE_DATE_FORMAT)) - .put(SIMULATOR_STATUS, "NOT RUNNING") - .build(); + .status(OK) + .put(TIMESTAMP, DateUtil.getTimestamp(RESPONSE_DATE_FORMAT)) + .put(SIMULATOR_STATUS, "NOT RUNNING") + .build(); } } @@ -182,16 +191,16 @@ public class SimulatorController { simulator.interrupt(); return ResponseBuilder - .status(OK) - .put(TIMESTAMP, DateUtil.getTimestamp(RESPONSE_DATE_FORMAT)) - .put(MESSAGE, "Simulator successfully stopped") - .build(); + .status(OK) + .put(TIMESTAMP, DateUtil.getTimestamp(RESPONSE_DATE_FORMAT)) + .put(MESSAGE, "Simulator successfully stopped") + .build(); } else { return ResponseBuilder - .status(BAD_REQUEST) - .put(TIMESTAMP, DateUtil.getTimestamp(RESPONSE_DATE_FORMAT)) - .put(MESSAGE, "Cannot stop simulator, because it's not running") - .build(); + .status(BAD_REQUEST) + .put(TIMESTAMP, DateUtil.getTimestamp(RESPONSE_DATE_FORMAT)) + .put(MESSAGE, "Cannot stop simulator, because it's not running") + .build(); } } diff --git a/test/mocks/pnfsimulator/src/main/java/org/onap/pnfsimulator/simulator/SimulatorFactory.java b/test/mocks/pnfsimulator/src/main/java/org/onap/pnfsimulator/simulator/SimulatorFactory.java index 046c97cad..8e16ad2ce 100644 --- a/test/mocks/pnfsimulator/src/main/java/org/onap/pnfsimulator/simulator/SimulatorFactory.java +++ b/test/mocks/pnfsimulator/src/main/java/org/onap/pnfsimulator/simulator/SimulatorFactory.java @@ -2,7 +2,7 @@ * ============LICENSE_START======================================================= * PNF-REGISTRATION-HANDLER * ================================================================================ - * Copyright (C) 2018 NOKIA Intellectual Property. All rights reserved. + * Copyright (C) 2018-2019 NOKIA Intellectual Property. 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. @@ -20,15 +20,7 @@ package org.onap.pnfsimulator.simulator; -import static java.lang.Integer.parseInt; -import static org.onap.pnfsimulator.message.MessageConstants.MESSAGE_INTERVAL; -import static org.onap.pnfsimulator.message.MessageConstants.TEST_DURATION; -import static org.onap.pnfsimulator.message.MessageConstants.VES_SERVER_URL; - import com.github.fge.jsonschema.core.exceptions.ProcessingException; -import java.io.IOException; -import java.time.Duration; -import java.util.Optional; import org.json.JSONObject; import org.onap.pnfsimulator.message.MessageProvider; import org.onap.pnfsimulator.simulator.validation.JSONValidator; @@ -36,6 +28,14 @@ import org.onap.pnfsimulator.simulator.validation.ValidationException; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; +import java.io.IOException; +import java.time.Duration; + +import static java.lang.Integer.parseInt; +import static org.onap.pnfsimulator.message.MessageConstants.MESSAGE_INTERVAL; +import static org.onap.pnfsimulator.message.MessageConstants.TEST_DURATION; +import static org.onap.pnfsimulator.message.MessageConstants.VES_SERVER_URL; + @Service public class SimulatorFactory { @@ -50,22 +50,34 @@ public class SimulatorFactory { this.validator = validator; } - public Simulator create(JSONObject simulatorParams, JSONObject commonEventHeaderParams, - Optional<JSONObject> pnfRegistrationParams, Optional<JSONObject> notificationParams) - throws ProcessingException, IOException, ValidationException { + public Simulator createSimulatorWithNotification(JSONObject simulatorParams, JSONObject commonEventHeaderParams, + JSONObject notificationParams) + throws ProcessingException, IOException, ValidationException { + JSONObject messageBody = messageProvider + .createMessageWithNotification(commonEventHeaderParams, notificationParams); + return createSimulatorWithMessage(simulatorParams, messageBody); + } + + public Simulator createSimulatorWithPnfRegistration(JSONObject simulatorParams, JSONObject commonEventHeaderParams, + JSONObject pnfRegistrationParams) + throws ProcessingException, IOException, ValidationException { + JSONObject messageBody = messageProvider + .createMessageWithPnfRegistration(commonEventHeaderParams, pnfRegistrationParams); + return createSimulatorWithMessage(simulatorParams, messageBody); + } + + private Simulator createSimulatorWithMessage(JSONObject simulatorParams, JSONObject messageBody) + throws ValidationException, ProcessingException, IOException { Duration duration = Duration.ofSeconds(parseInt(simulatorParams.getString(TEST_DURATION))); Duration interval = Duration.ofSeconds(parseInt(simulatorParams.getString(MESSAGE_INTERVAL))); String vesUrl = simulatorParams.getString(VES_SERVER_URL); - - JSONObject messageBody = messageProvider - .createMessage(commonEventHeaderParams, pnfRegistrationParams, notificationParams); validator.validate(messageBody.toString(), DEFAULT_OUTPUT_SCHEMA_PATH); return Simulator.builder() - .withVesUrl(vesUrl) - .withDuration(duration) - .withInterval(interval) - .withMessageBody(messageBody) - .build(); + .withVesUrl(vesUrl) + .withDuration(duration) + .withInterval(interval) + .withMessageBody(messageBody) + .build(); } }
\ No newline at end of file diff --git a/test/mocks/pnfsimulator/src/test/java/org/onap/pnfsimulator/message/MessageProviderTest.java b/test/mocks/pnfsimulator/src/test/java/org/onap/pnfsimulator/message/MessageProviderTest.java index aadb54cdc..4524b96c3 100644 --- a/test/mocks/pnfsimulator/src/test/java/org/onap/pnfsimulator/message/MessageProviderTest.java +++ b/test/mocks/pnfsimulator/src/test/java/org/onap/pnfsimulator/message/MessageProviderTest.java @@ -2,7 +2,7 @@ * ============LICENSE_START======================================================= * PNF-REGISTRATION-HANDLER * ================================================================================ - * Copyright (C) 2018 NOKIA Intellectual Property. All rights reserved. + * Copyright (C) 2018-2019 NOKIA Intellectual Property. 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. @@ -20,95 +20,100 @@ package org.onap.pnfsimulator.message; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertThrows; -import static org.junit.jupiter.api.Assertions.assertTrue; +import org.json.JSONObject; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; +import org.onap.pnfsimulator.simulator.ResourceReader; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.data.MapEntry.entry; import static org.onap.pnfsimulator.message.MessageConstants.COMMON_EVENT_HEADER; import static org.onap.pnfsimulator.message.MessageConstants.EVENT; import static org.onap.pnfsimulator.message.MessageConstants.NOTIFICATION_FIELDS; import static org.onap.pnfsimulator.message.MessageConstants.PNF_REGISTRATION_FIELDS; -import java.util.Optional; -import org.json.JSONObject; -import org.junit.jupiter.api.BeforeAll; -import org.junit.jupiter.api.Test; - public class MessageProviderTest { - private static final String testParamsPnfRegistration = - "{\"pnfKey1\": \"pnfVal1\",\"pnfKey2\": \"pnfVal2\",\"pnfKey3\": \"pnfVal3\",\"pnfKey4\": \"pnfVal4\"}"; + private static String testParamsPnfRegistration; - private static final String testParamsNotification = - "{\"notKey1\": \"notVal1\",\"notKey2\": \"notVal2\",\"notKey3\": \"notVal3\",\"notKey4\": \"notVal4\"}"; + private static String testParamsNotification; - private static MessageProvider messageProvider; + private MessageProvider messageProvider = new MessageProvider(); @BeforeAll public static void setup() { - messageProvider = new MessageProvider(); + ResourceReader reader = new ResourceReader("org/onap/pnfsimulator/message/MessageProviderTest/"); + testParamsPnfRegistration = reader.readResource("pnfRegistrationParams.json"); + testParamsNotification = reader.readResource("notificationParams.json"); } @Test - public void createMessage_should_throw_when_given_empty_arguments() { - assertThrows(IllegalArgumentException.class, - () -> messageProvider.createMessage(new JSONObject(), Optional.empty(), Optional.empty()), - "Params object cannot be null"); + public void createMessageWithPnfRegistration_should_create_constant_message_when_no_params_specified() { + JSONObject message = messageProvider.createMessageWithPnfRegistration(new JSONObject(), new JSONObject()); + JSONObject event = message.getJSONObject(EVENT); + + JSONObject commonEventHeader = event.getJSONObject(COMMON_EVENT_HEADER); + JSONObject pnfRegistrationFields = event.getJSONObject(PNF_REGISTRATION_FIELDS); + + JSONObject expectedCommonEventHeader = JSONObjectFactory.generateConstantCommonEventHeader(); + JSONObject expectedPnfRegistrationFields = JSONObjectFactory.generatePnfRegistrationFields(); + + assertThat(commonEventHeader.keySet()) + .containsAll(expectedCommonEventHeader.keySet()); + assertThat(pnfRegistrationFields.keySet()) + .containsAll(expectedPnfRegistrationFields.keySet()); } @Test - public void createMessage_should_create_constant_message_when_no_params_specified() { - JSONObject message = messageProvider.createMessage(new JSONObject(), Optional.ofNullable(new JSONObject()), - Optional.ofNullable(new JSONObject())); + public void createMessageWithNotification_should_create_constant_message_when_no_params_specified() { + JSONObject message = messageProvider.createMessageWithNotification(new JSONObject(), + new JSONObject()); JSONObject event = message.getJSONObject(EVENT); JSONObject commonEventHeader = event.getJSONObject(COMMON_EVENT_HEADER); - JSONObject pnfRegistrationFields = event.getJSONObject(PNF_REGISTRATION_FIELDS); JSONObject notificationFields = event.getJSONObject(NOTIFICATION_FIELDS); JSONObject expectedCommonEventHeader = JSONObjectFactory.generateConstantCommonEventHeader(); - JSONObject expectedPnfRegistrationFields = JSONObjectFactory.generatePnfRegistrationFields(); JSONObject expectedNotificationFields = JSONObjectFactory.generateNotificationFields(); - expectedCommonEventHeader - .toMap() - .forEach((key, val) -> assertTrue(commonEventHeader.has(key), - () -> String.format("Key %s is not present", key))); + assertThat(commonEventHeader.keySet()) + .containsAll(expectedCommonEventHeader.keySet()); - expectedPnfRegistrationFields - .toMap() - .forEach((key, val) -> assertTrue(pnfRegistrationFields.has(key), - () -> String.format("Key %s is not present", key))); - - expectedNotificationFields - .toMap() - .forEach((key, val) -> assertTrue(notificationFields.has(key), - () -> String.format("Key %s is not present", key))); + assertThat(notificationFields.keySet()) + .containsAll(expectedNotificationFields.keySet()); } @Test - public void createMessage_should_throw_exception_when_params_specified_as_empty() { - assertThrows(IllegalArgumentException.class, - () -> messageProvider.createMessage(new JSONObject(), Optional.empty(), - Optional.empty())); - } - - @Test - public void createMessage_should_add_specified_params_to_valid_subobjects() { + public void createMessageWithPnfRegistration_should_add_specified_params_to_valid_subobjects() { JSONObject message = messageProvider - .createMessage(new JSONObject(), Optional.of(new JSONObject(testParamsPnfRegistration)), - Optional.of(new JSONObject(testParamsNotification))); + .createMessageWithPnfRegistration(new JSONObject(), new JSONObject(testParamsPnfRegistration)); JSONObject event = message.getJSONObject(EVENT); JSONObject commonEventHeader = event.getJSONObject(COMMON_EVENT_HEADER); - assertEquals(10, commonEventHeader.keySet().size()); JSONObject pnfRegistrationFields = event.getJSONObject(PNF_REGISTRATION_FIELDS); - assertEquals("pnfVal1", pnfRegistrationFields.getString("pnfKey1")); - assertEquals("pnfVal2", pnfRegistrationFields.getString("pnfKey2")); + assertThat(pnfRegistrationFields.toMap()).contains( + entry("pnfKey1", "pnfVal1"), + entry("pnfKey2", "pnfVal2"), + entry("pnfKey3", "pnfVal3"), + entry("pnfKey4", "pnfVal4") + ); + } + + @Test + public void createMessageWithNotification_should_add_specified_params_to_valid_subobjects() { + JSONObject message = messageProvider + .createMessageWithNotification(new JSONObject(), + new JSONObject(testParamsNotification)); + JSONObject event = message.getJSONObject(EVENT); JSONObject notificationFields = event.getJSONObject(NOTIFICATION_FIELDS); - assertEquals("notVal1", notificationFields.getString("notKey1")); - assertEquals("notVal2", notificationFields.getString("notKey2")); + assertThat(notificationFields.toMap()).contains( + entry("notKey1", "notVal1"), + entry("notKey2", "notVal2"), + entry("notKey3", "notVal3"), + entry("notKey4", "notVal4") + ); } diff --git a/test/mocks/pnfsimulator/src/test/java/org/onap/pnfsimulator/rest/SimulatorControllerTest.java b/test/mocks/pnfsimulator/src/test/java/org/onap/pnfsimulator/rest/SimulatorControllerTest.java index 3603480bf..bed67e33e 100644 --- a/test/mocks/pnfsimulator/src/test/java/org/onap/pnfsimulator/rest/SimulatorControllerTest.java +++ b/test/mocks/pnfsimulator/src/test/java/org/onap/pnfsimulator/rest/SimulatorControllerTest.java @@ -2,7 +2,7 @@ * ============LICENSE_START======================================================= * PNF-REGISTRATION-HANDLER * ================================================================================ - * Copyright (C) 2018 NOKIA Intellectual Property. All rights reserved. + * Copyright (C) 2018-2019 NOKIA Intellectual Property. 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. @@ -20,24 +20,13 @@ package org.onap.pnfsimulator.rest; -import static org.mockito.ArgumentMatchers.anyString; -import static org.mockito.Mockito.any; -import static org.mockito.Mockito.doThrow; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.spy; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.when; -import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; -import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; -import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; -import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; - -import java.time.Duration; +import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.MockitoAnnotations; +import org.onap.pnfsimulator.simulator.ResourceReader; import org.onap.pnfsimulator.simulator.Simulator; import org.onap.pnfsimulator.simulator.SimulatorFactory; import org.onap.pnfsimulator.simulator.client.HttpClientAdapter; @@ -46,6 +35,20 @@ import org.onap.pnfsimulator.simulator.validation.ValidationException; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.setup.MockMvcBuilders; +import java.time.Duration; + +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.Mockito.any; +import static org.mockito.Mockito.doThrow; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.spy; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; + class SimulatorControllerTest { private static final String START_URL = "/simulator/start"; @@ -53,43 +56,8 @@ class SimulatorControllerTest { private static final String STATUS_URL = "/simulator/status"; private static final String JSON_MSG_EXPRESSION = "$.message"; private static final String JSON_STATUS_EXPRESSION = "$.simulatorStatus"; - private static final String PROPER_JSON = "{\n" + - " \"simulatorParams\": {\n" + - " \"vesServerUrl\": \"http://10.154.187.70:8080/eventListener/v7\",\n" + - " \"testDuration\": \"10\",\n" + - " \"messageInterval\": \"1\"\n" + - " },\n" + - " \"commonEventHeaderParams\": {\n" + - " \"eventName\": \"val11\",\n" + - " \"nfNamingCode\": \"val12\",\n" + - " \"nfcNamingCode\": \"val13\",\n" + - " \"sourceName\": \"val14\",\n" + - " \"sourceId\": \"val15\",\n" + - " \"reportingEntityName\": \"val16\",\n" + - " },\n" + - - " \"pnfRegistrationParams\": {\n" + - " \"SerialNumber\": \"val1\",\n" + - " \"VendorName\": \"val2\",\n" + - " \"OamIpv4Address\": \"val3\",\n" + - " \"OamIpv6Address\": \"val4\",\n" + - " \"Family\": \"val5\",\n" + - " \"ModelNumber\": \"val6\",\n" + - " \"SoftwareVersion\": \"val7\",\n" + - " }\n" + - "}"; - private static final String WRONG_JSON = "{\n" + - " \"mes\": {\n" + - " \"vesServerUrl\": \"http://10.154.187.70:8080/eventListener/v5\",\n" + - " \"testDuration\": \"10\",\n" + - " \"messageInterval\": \"1\"\n" + - " },\n" + - " \"messageParams\": {\n" + - " \"sourceName\": \"val12\",\n" + - " \"sourceId\": \"val13\",\n" + - " \"reportingEntityName\": \"val14\"\n" + - " }\n" + - "}\n"; + private static String pnfRegistrationJson; + private static String incorrectJson; private MockMvc mockMvc; @@ -98,100 +66,108 @@ class SimulatorControllerTest { @Mock private SimulatorFactory factory; + @Mock private JSONValidator validator; private Simulator simulator; + @BeforeAll + static void beforeAll() { + ResourceReader reader = new ResourceReader("org/onap/pnfsimulator/rest/SimulatorControllerTest/"); + pnfRegistrationJson = reader.readResource("pnfRegistration.json"); + incorrectJson = reader.readResource("incorrectJson.json"); + } + @BeforeEach void setup() { MockitoAnnotations.initMocks(this); simulator = createEndlessSimulator(); mockMvc = MockMvcBuilders - .standaloneSetup(controller) - .build(); + .standaloneSetup(controller) + .build(); } private Simulator createEndlessSimulator() { return spy(Simulator.builder() - .withCustomHttpClientAdapter(mock(HttpClientAdapter.class)) - .withInterval(Duration.ofMinutes(1)) - .build()); + .withCustomHttpClientAdapter(mock(HttpClientAdapter.class)) + .withInterval(Duration.ofMinutes(1)) + .build()); } @Test void wrongJSONFormatOnStart() throws Exception { - when(factory.create(any(),any(), any(),any())).thenReturn(simulator); + when(factory.createSimulatorWithNotification(any(), any(), any())).thenReturn(simulator); doThrow(new ValidationException("")).when(validator).validate(anyString(), anyString()); - mockMvc.perform(post("/simulator/start").content(WRONG_JSON)) - .andExpect(status().isBadRequest()) - .andExpect(jsonPath("$.message").value("Cannot start simulator - Json format " + - "is not compatible with schema definitions")); + mockMvc.perform(post("/simulator/start").content(incorrectJson)) + .andExpect(status().isBadRequest()) + .andExpect(jsonPath("$.message").value("Cannot start simulator - Json format " + + "is not compatible with schema definitions")); verify(validator).validate(anyString(), anyString()); } @Test void startSimulatorProperly() throws Exception { - startSimulator(); + startSimulatorWithPnfRegistration(); verify(validator).validate(anyString(), anyString()); - verify(factory).create(any(),any(), any(),any()); + verify(factory).createSimulatorWithPnfRegistration(any(), any(), any()); verify(simulator).start(); } @Test void notStartWhenAlreadyRunning() throws Exception { - startSimulator(); + startSimulatorWithPnfRegistration(); mockMvc - .perform(post(START_URL).content(PROPER_JSON)) - .andExpect(status().isBadRequest()) - .andExpect(jsonPath(JSON_MSG_EXPRESSION).value("Cannot start simulator since it's already running")); + .perform(post(START_URL).content(pnfRegistrationJson)) + .andExpect(status().isBadRequest()) + .andExpect(jsonPath(JSON_MSG_EXPRESSION).value("Cannot start simulator since it's already running")); } @Test void stopSimulatorWhenRunning() throws Exception { - startSimulator(); + startSimulatorWithPnfRegistration(); mockMvc - .perform(post(STOP_URL)) - .andExpect(status().isOk()) - .andExpect(jsonPath(JSON_MSG_EXPRESSION).value("Simulator successfully stopped")); + .perform(post(STOP_URL)) + .andExpect(status().isOk()) + .andExpect(jsonPath(JSON_MSG_EXPRESSION).value("Simulator successfully stopped")); } @Test void getNotRunningMessageWhenOff() throws Exception { mockMvc - .perform(post(STOP_URL)) - .andExpect(status().isBadRequest()) - .andExpect(jsonPath(JSON_MSG_EXPRESSION).value("Cannot stop simulator, because it's not running")); + .perform(post(STOP_URL)) + .andExpect(status().isBadRequest()) + .andExpect(jsonPath(JSON_MSG_EXPRESSION).value("Cannot stop simulator, because it's not running")); } @Test void getRunningStatusWhenOn() throws Exception { - startSimulator(); + startSimulatorWithPnfRegistration(); mockMvc - .perform(get(STATUS_URL)) - .andExpect(status().isOk()) - .andExpect(jsonPath(JSON_STATUS_EXPRESSION).value("RUNNING")); + .perform(get(STATUS_URL)) + .andExpect(status().isOk()) + .andExpect(jsonPath(JSON_STATUS_EXPRESSION).value("RUNNING")); } @Test void getNotRunningStatusWhenOff() throws Exception { mockMvc - .perform(get(STATUS_URL)) - .andExpect(status().isOk()) - .andExpect(jsonPath(JSON_STATUS_EXPRESSION).value("NOT RUNNING")); + .perform(get(STATUS_URL)) + .andExpect(status().isOk()) + .andExpect(jsonPath(JSON_STATUS_EXPRESSION).value("NOT RUNNING")); } - private void startSimulator() throws Exception { - when(factory.create(any(), any(), any(),any())).thenReturn(simulator); + private void startSimulatorWithPnfRegistration() throws Exception { + when(factory.createSimulatorWithPnfRegistration(any(), any(), any())).thenReturn(simulator); mockMvc - .perform(post(START_URL).content(PROPER_JSON)) - .andExpect(status().isOk()) - .andExpect(jsonPath(JSON_MSG_EXPRESSION).value("Simulator started")); + .perform(post(START_URL).content(pnfRegistrationJson)) + .andExpect(status().isOk()) + .andExpect(jsonPath(JSON_MSG_EXPRESSION).value("Simulator started")); } }
\ No newline at end of file diff --git a/test/mocks/pnfsimulator/src/test/java/org/onap/pnfsimulator/simulator/ResourceReader.java b/test/mocks/pnfsimulator/src/test/java/org/onap/pnfsimulator/simulator/ResourceReader.java new file mode 100644 index 000000000..b5721533f --- /dev/null +++ b/test/mocks/pnfsimulator/src/test/java/org/onap/pnfsimulator/simulator/ResourceReader.java @@ -0,0 +1,45 @@ +/* + * ============LICENSE_START======================================================= + * PNF-REGISTRATION-HANDLER + * ================================================================================ + * Copyright (C) 2019 NOKIA Intellectual Property. 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.pnfsimulator.simulator; + +import com.google.common.io.Resources; + +import java.io.IOException; +import java.net.URL; +import java.nio.charset.StandardCharsets; + +public class ResourceReader { + private final String baseDirectory; + + public ResourceReader(String baseDirectory) { + this.baseDirectory = baseDirectory; + } + + public String readResource(String resourceName) { + try { + URL pnfRegistrationJson = Resources.getResource(baseDirectory + resourceName); + return Resources.toString(pnfRegistrationJson, StandardCharsets.UTF_8); + } catch (IOException e) { + throw new RuntimeException(e); + } + } + +} diff --git a/test/mocks/pnfsimulator/src/test/java/org/onap/pnfsimulator/simulator/SimulatorFactoryTest.java b/test/mocks/pnfsimulator/src/test/java/org/onap/pnfsimulator/simulator/SimulatorFactoryTest.java index ea7a09785..5781bbc0b 100644 --- a/test/mocks/pnfsimulator/src/test/java/org/onap/pnfsimulator/simulator/SimulatorFactoryTest.java +++ b/test/mocks/pnfsimulator/src/test/java/org/onap/pnfsimulator/simulator/SimulatorFactoryTest.java @@ -2,7 +2,7 @@ * ============LICENSE_START======================================================= * PNF-REGISTRATION-HANDLER * ================================================================================ - * Copyright (C) 2018 NOKIA Intellectual Property. All rights reserved. + * Copyright (C) 2018-2019 NOKIA Intellectual Property. 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. @@ -20,81 +20,72 @@ package org.onap.pnfsimulator.simulator; -import static org.junit.jupiter.api.Assertions.assertNotNull; -import static org.junit.jupiter.api.Assertions.assertThrows; -import static org.onap.pnfsimulator.simulator.TestMessages.INVALID_NOTIFICATION_PARAMS; -import static org.onap.pnfsimulator.simulator.TestMessages.INVALID_PNF_REGISTRATION_PARAMS_1; -import static org.onap.pnfsimulator.simulator.TestMessages.INVALID_PNF_REGISTRATION_PARAMS_2; -import static org.onap.pnfsimulator.simulator.TestMessages.INVALID_PNF_REGISTRATION_PARAMS_3; -import static org.onap.pnfsimulator.simulator.TestMessages.INVALID_SIMULATOR_PARAMS; -import static org.onap.pnfsimulator.simulator.TestMessages.VALID_COMMON_EVENT_HEADER_PARAMS; -import static org.onap.pnfsimulator.simulator.TestMessages.VALID_NOTIFICATION_PARAMS; -import static org.onap.pnfsimulator.simulator.TestMessages.VALID_PNF_REGISTRATION_PARAMS; -import static org.onap.pnfsimulator.simulator.TestMessages.VALID_SIMULATOR_PARAMS; - import com.github.fge.jsonschema.core.exceptions.ProcessingException; -import java.io.IOException; -import java.util.Optional; import org.json.JSONException; -import org.junit.jupiter.api.BeforeEach; +import org.json.JSONObject; import org.junit.jupiter.api.Test; import org.onap.pnfsimulator.message.MessageProvider; import org.onap.pnfsimulator.simulator.validation.JSONValidator; import org.onap.pnfsimulator.simulator.validation.ValidationException; +import java.io.IOException; + +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertThrows; + class SimulatorFactoryTest { + private static final ResourceReader resourceReader = new ResourceReader("org/onap/pnfsimulator/simulator/SimulatorFactoryTest/"); + private static final JSONObject VALID_SIMULATOR_PARAMS = new JSONObject(resourceReader.readResource("validSimulatorParams.json")); + private static final JSONObject VALID_COMMON_EVENT_HEADER_PARAMS = new JSONObject(resourceReader.readResource("validCommonEventHeaderParams.json")); + private static final JSONObject VALID_PNF_REGISTRATION_PARAMS = new JSONObject(resourceReader.readResource("validPnfRegistrationParams.json")); + private static final JSONObject VALID_NOTIFICATION_PARAMS = new JSONObject(resourceReader.readResource("validNotificationParams.json")); - private SimulatorFactory simulatorFactory; + private static final JSONObject INVALID_SIMULATOR_PARAMS = new JSONObject(resourceReader.readResource("invalidSimulatorParams.json")); + private static final JSONObject INVALID_PNF_REGISTRATION_PARAMS_1 = new JSONObject(resourceReader.readResource("invalidPnfRegistrationParams1.json")); + private static final JSONObject INVALID_PNF_REGISTRATION_PARAMS_2 = new JSONObject(resourceReader.readResource("invalidPnfRegistrationParams2.json")); + private static final JSONObject INVALID_PNF_REGISTRATION_PARAMS_3 = new JSONObject(resourceReader.readResource("invalidPnfRegistrationParams3.json")); - @BeforeEach - void setUp() { - simulatorFactory = new SimulatorFactory(new MessageProvider(), new JSONValidator()); - } + private SimulatorFactory simulatorFactory = new SimulatorFactory(new MessageProvider(), new JSONValidator()); @Test void should_successfully_create_simulator_given_valid_pnf_registration_params_and_valid_output_message() - throws ValidationException, IOException, ProcessingException { - assertNotNull(simulatorFactory.create(VALID_SIMULATOR_PARAMS,VALID_COMMON_EVENT_HEADER_PARAMS, - VALID_PNF_REGISTRATION_PARAMS,Optional.empty())); + throws ValidationException, IOException, ProcessingException { + assertNotNull(simulatorFactory.createSimulatorWithPnfRegistration(VALID_SIMULATOR_PARAMS, VALID_COMMON_EVENT_HEADER_PARAMS, + VALID_PNF_REGISTRATION_PARAMS)); } @Test void should_successfully_create_simulator_given_valid_notification_params_and_valid_output_message() - throws ValidationException, IOException, ProcessingException { - assertNotNull(simulatorFactory.create(VALID_SIMULATOR_PARAMS, VALID_COMMON_EVENT_HEADER_PARAMS, - Optional.empty(), VALID_NOTIFICATION_PARAMS)); + throws ValidationException, IOException, ProcessingException { + assertNotNull(simulatorFactory.createSimulatorWithNotification(VALID_SIMULATOR_PARAMS, VALID_COMMON_EVENT_HEADER_PARAMS, + VALID_NOTIFICATION_PARAMS)); } @Test void should_throw_given_invalid_params() { assertThrows( - JSONException.class, - () -> simulatorFactory.create(INVALID_SIMULATOR_PARAMS,VALID_COMMON_EVENT_HEADER_PARAMS, - VALID_PNF_REGISTRATION_PARAMS,Optional.empty())); + JSONException.class, + () -> simulatorFactory.createSimulatorWithPnfRegistration(INVALID_SIMULATOR_PARAMS, VALID_COMMON_EVENT_HEADER_PARAMS, + VALID_PNF_REGISTRATION_PARAMS)); } @Test void should_throw_given_valid_params_and_invalid_output_message() { assertThrows( - ValidationException.class, - () -> simulatorFactory.create(VALID_SIMULATOR_PARAMS, VALID_COMMON_EVENT_HEADER_PARAMS, - INVALID_PNF_REGISTRATION_PARAMS_1, Optional.empty())); - - assertThrows( - ValidationException.class, - () -> simulatorFactory.create(VALID_SIMULATOR_PARAMS, VALID_COMMON_EVENT_HEADER_PARAMS, - INVALID_PNF_REGISTRATION_PARAMS_2, Optional.empty())); + ValidationException.class, + () -> simulatorFactory.createSimulatorWithPnfRegistration(VALID_SIMULATOR_PARAMS, VALID_COMMON_EVENT_HEADER_PARAMS, + INVALID_PNF_REGISTRATION_PARAMS_1)); assertThrows( - ValidationException.class, - () -> simulatorFactory.create(VALID_SIMULATOR_PARAMS, VALID_COMMON_EVENT_HEADER_PARAMS, - INVALID_PNF_REGISTRATION_PARAMS_3, Optional.empty())); + ValidationException.class, + () -> simulatorFactory.createSimulatorWithPnfRegistration(VALID_SIMULATOR_PARAMS, VALID_COMMON_EVENT_HEADER_PARAMS, + INVALID_PNF_REGISTRATION_PARAMS_2)); assertThrows( - ValidationException.class, - () -> simulatorFactory.create(VALID_SIMULATOR_PARAMS, VALID_COMMON_EVENT_HEADER_PARAMS, - VALID_PNF_REGISTRATION_PARAMS, INVALID_NOTIFICATION_PARAMS)); + ValidationException.class, + () -> simulatorFactory.createSimulatorWithPnfRegistration(VALID_SIMULATOR_PARAMS, VALID_COMMON_EVENT_HEADER_PARAMS, + INVALID_PNF_REGISTRATION_PARAMS_3)); } }
\ No newline at end of file diff --git a/test/mocks/pnfsimulator/src/test/java/org/onap/pnfsimulator/simulator/TestMessages.java b/test/mocks/pnfsimulator/src/test/java/org/onap/pnfsimulator/simulator/TestMessages.java deleted file mode 100644 index 7511084c4..000000000 --- a/test/mocks/pnfsimulator/src/test/java/org/onap/pnfsimulator/simulator/TestMessages.java +++ /dev/null @@ -1,116 +0,0 @@ -/* - * ============LICENSE_START======================================================= - * PNF-REGISTRATION-HANDLER - * ================================================================================ - * Copyright (C) 2018 NOKIA Intellectual Property. 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.pnfsimulator.simulator; - -import java.io.IOException; -import java.nio.file.Files; -import java.nio.file.Paths; -import java.util.Optional; -import org.json.JSONObject; - -final class TestMessages { - - static final JSONObject VALID_SIMULATOR_PARAMS = new JSONObject(getContent("validSimulatorParams.json")); - static final JSONObject VALID_COMMON_EVENT_HEADER_PARAMS = new JSONObject(getContent("validCommonEventHeaderParams.json")); - static final Optional<JSONObject> VALID_PNF_REGISTRATION_PARAMS = Optional - .of(new JSONObject(getContent("validPnfRegistrationParams.json"))); - static final Optional<JSONObject> VALID_NOTIFICATION_PARAMS = Optional - .of(new JSONObject(getContent("validNotificationParams.json"))); - - static final JSONObject INVALID_SIMULATOR_PARAMS = new JSONObject( - "{\n" + - " \"vesServerUrl\": \"http://10.42.111.42:8080/eventListener/v5\",\n" + - " \"messageInterval\": \"1\"\n" + - "}"); - - - static final Optional<JSONObject> INVALID_PNF_REGISTRATION_PARAMS_1 = Optional.of(new JSONObject( - "{\n" + - " \"pnfSerialNumber\": \"val1\",\n" + - " \"pnfVendorName\": \"val2\",\n" + - " \"pnfFamily\": \"val5\",\n" + - " \"pnfModelNumber\": \"val6\",\n" + - " \"pnfSoftwareVersion\": \"val7\",\n" + - " \"pnfType\": \"val8\",\n" + - " \"eventName\": \"val9\",\n" + - " \"nfNamingCode\": \"val10\",\n" + - " \"nfcNamingCode\": \"val11\",\n" + - " \"sourceName\": \"val12\",\n" + - " \"sourceId\": \"val13\",\n" + - " \"reportingEntityName\": \"val14\"\n" + - "}")); - - static final Optional<JSONObject> INVALID_PNF_REGISTRATION_PARAMS_2 = Optional.of(new JSONObject( - "{\n" + - " \"pnfVendorName\": \"val2\",\n" + - " \"pnfOamIpv4Address\": \"val3\",\n" + - " \"pnfOamIpv6Address\": \"val4\",\n" + - " \"pnfFamily\": \"val5\",\n" + - " \"pnfModelNumber\": \"val6\",\n" + - " \"pnfSoftwareVersion\": \"val7\",\n" + - " \"pnfType\": \"val8\",\n" + - " \"eventName\": \"val9\",\n" + - " \"nfNamingCode\": \"val10\",\n" + - " \"nfcNamingCode\": \"val11\",\n" + - " \"sourceName\": \"val12\",\n" + - " \"sourceId\": \"val13\",\n" + - " \"reportingEntityName\": \"val14\"\n" + - "}")); - - static final Optional<JSONObject> INVALID_PNF_REGISTRATION_PARAMS_3 = Optional.of(new JSONObject( - "{\n" + - " \"pnfSerialNumber\": \"val1\",\n" + - " \"pnfOamIpv4Address\": \"val3\",\n" + - " \"pnfFamily\": \"val5\",\n" + - " \"pnfModelNumber\": \"val6\",\n" + - " \"pnfSoftwareVersion\": \"val7\",\n" + - " \"pnfType\": \"val8\",\n" + - " \"eventName\": \"val9\",\n" + - " \"nfNamingCode\": \"val10\",\n" + - " \"nfcNamingCode\": \"val11\",\n" + - " \"sourceName\": \"val12\",\n" + - " \"sourceId\": \"val13\",\n" + - " \"reportingEntityName\": \"val14\"\n" + - "}")); - - static final Optional<JSONObject> INVALID_NOTIFICATION_PARAMS = Optional.of(new JSONObject( - "{\n" + - " \"mother\": \"val1\",\n" + - " \"father\": \"val3\",\n" + - "}")); - - - private TestMessages() { - } - - private static String getContent(String fileName) { - try { - String pathAsString = TestMessages.class.getResource(fileName).getPath(); - StringBuilder stringBuilder = new StringBuilder(); - Files.readAllLines(Paths.get(pathAsString)).forEach(line -> { - stringBuilder.append(line); - }); - return stringBuilder.toString(); - } catch (IOException e) { - throw new RuntimeException(String.format("Cannot read JSON file %s", fileName)); - } - } -} diff --git a/test/mocks/pnfsimulator/src/test/resources/org/onap/pnfsimulator/message/MessageProviderTest/notificationParams.json b/test/mocks/pnfsimulator/src/test/resources/org/onap/pnfsimulator/message/MessageProviderTest/notificationParams.json new file mode 100644 index 000000000..b73c379a8 --- /dev/null +++ b/test/mocks/pnfsimulator/src/test/resources/org/onap/pnfsimulator/message/MessageProviderTest/notificationParams.json @@ -0,0 +1,6 @@ +{ + "notKey1": "notVal1", + "notKey2": "notVal2", + "notKey3": "notVal3", + "notKey4": "notVal4" +}
\ No newline at end of file diff --git a/test/mocks/pnfsimulator/src/test/resources/org/onap/pnfsimulator/message/MessageProviderTest/pnfRegistrationParams.json b/test/mocks/pnfsimulator/src/test/resources/org/onap/pnfsimulator/message/MessageProviderTest/pnfRegistrationParams.json new file mode 100644 index 000000000..95446bf80 --- /dev/null +++ b/test/mocks/pnfsimulator/src/test/resources/org/onap/pnfsimulator/message/MessageProviderTest/pnfRegistrationParams.json @@ -0,0 +1,6 @@ +{ + "pnfKey1": "pnfVal1", + "pnfKey2": "pnfVal2", + "pnfKey3": "pnfVal3", + "pnfKey4": "pnfVal4" +}
\ No newline at end of file diff --git a/test/mocks/pnfsimulator/src/test/resources/org/onap/pnfsimulator/rest/SimulatorControllerTest/incorrectJson.json b/test/mocks/pnfsimulator/src/test/resources/org/onap/pnfsimulator/rest/SimulatorControllerTest/incorrectJson.json new file mode 100644 index 000000000..682afac9f --- /dev/null +++ b/test/mocks/pnfsimulator/src/test/resources/org/onap/pnfsimulator/rest/SimulatorControllerTest/incorrectJson.json @@ -0,0 +1,12 @@ +{ + "mes": { + "vesServerUrl": "http://10.154.187.70:8080/eventListener/v5", + "testDuration": "10", + "messageInterval": "1" + }, + "messageParams": { + "sourceName": "val12", + "sourceId": "val13", + "reportingEntityName": "val14" + } +}
\ No newline at end of file diff --git a/test/mocks/pnfsimulator/src/test/resources/org/onap/pnfsimulator/rest/SimulatorControllerTest/pnfRegistration.json b/test/mocks/pnfsimulator/src/test/resources/org/onap/pnfsimulator/rest/SimulatorControllerTest/pnfRegistration.json new file mode 100644 index 000000000..a7bf487e7 --- /dev/null +++ b/test/mocks/pnfsimulator/src/test/resources/org/onap/pnfsimulator/rest/SimulatorControllerTest/pnfRegistration.json @@ -0,0 +1,24 @@ +{ + "simulatorParams": { + "vesServerUrl": "http://10.154.187.70:8080/eventListener/v7", + "testDuration": "10", + "messageInterval": "1" + }, + "commonEventHeaderParams": { + "eventName": "val11", + "nfNamingCode": "val12", + "nfcNamingCode": "val13", + "sourceName": "val14", + "sourceId": "val15", + "reportingEntityName": "val16" + }, + "pnfRegistrationParams": { + "SerialNumber": "val1", + "VendorName": "val2", + "OamIpv4Address": "val3", + "OamIpv6Address": "val4", + "Family": "val5", + "ModelNumber": "val6", + "SoftwareVersion": "val7" + } +}
\ No newline at end of file diff --git a/test/mocks/pnfsimulator/src/test/resources/org/onap/pnfsimulator/simulator/SimulatorFactoryTest/invalidPnfRegistrationParams1.json b/test/mocks/pnfsimulator/src/test/resources/org/onap/pnfsimulator/simulator/SimulatorFactoryTest/invalidPnfRegistrationParams1.json new file mode 100644 index 000000000..eb9b4c156 --- /dev/null +++ b/test/mocks/pnfsimulator/src/test/resources/org/onap/pnfsimulator/simulator/SimulatorFactoryTest/invalidPnfRegistrationParams1.json @@ -0,0 +1,14 @@ +{ + "pnfSerialNumber": "val1", + "pnfVendorName": "val2", + "pnfFamily": "val5", + "pnfModelNumber": "val6", + "pnfSoftwareVersion": "val7", + "pnfType": "val8", + "eventName": "val9", + "nfNamingCode": "val10", + "nfcNamingCode": "val11", + "sourceName": "val12", + "sourceId": "val13", + "reportingEntityName": "val14" +}
\ No newline at end of file diff --git a/test/mocks/pnfsimulator/src/test/resources/org/onap/pnfsimulator/simulator/SimulatorFactoryTest/invalidPnfRegistrationParams2.json b/test/mocks/pnfsimulator/src/test/resources/org/onap/pnfsimulator/simulator/SimulatorFactoryTest/invalidPnfRegistrationParams2.json new file mode 100644 index 000000000..9196caa30 --- /dev/null +++ b/test/mocks/pnfsimulator/src/test/resources/org/onap/pnfsimulator/simulator/SimulatorFactoryTest/invalidPnfRegistrationParams2.json @@ -0,0 +1,15 @@ +{ + "pnfVendorName": "val2", + "pnfOamIpv4Address": "val3", + "pnfOamIpv6Address": "val4", + "pnfFamily": "val5", + "pnfModelNumber": "val6", + "pnfSoftwareVersion": "val7", + "pnfType": "val8", + "eventName": "val9", + "nfNamingCode": "val10", + "nfcNamingCode": "val11", + "sourceName": "val12", + "sourceId": "val13", + "reportingEntityName": "val14" +}
\ No newline at end of file diff --git a/test/mocks/pnfsimulator/src/test/resources/org/onap/pnfsimulator/simulator/SimulatorFactoryTest/invalidPnfRegistrationParams3.json b/test/mocks/pnfsimulator/src/test/resources/org/onap/pnfsimulator/simulator/SimulatorFactoryTest/invalidPnfRegistrationParams3.json new file mode 100644 index 000000000..e8734e6a0 --- /dev/null +++ b/test/mocks/pnfsimulator/src/test/resources/org/onap/pnfsimulator/simulator/SimulatorFactoryTest/invalidPnfRegistrationParams3.json @@ -0,0 +1,14 @@ +{ + "pnfSerialNumber": "val1", + "pnfOamIpv4Address": "val3", + "pnfFamily": "val5", + "pnfModelNumber": "val6", + "pnfSoftwareVersion": "val7", + "pnfType": "val8", + "eventName": "val9", + "nfNamingCode": "val10", + "nfcNamingCode": "val11", + "sourceName": "val12", + "sourceId": "val13", + "reportingEntityName": "val14" +}
\ No newline at end of file diff --git a/test/mocks/pnfsimulator/src/test/resources/org/onap/pnfsimulator/simulator/SimulatorFactoryTest/invalidSimulatorParams.json b/test/mocks/pnfsimulator/src/test/resources/org/onap/pnfsimulator/simulator/SimulatorFactoryTest/invalidSimulatorParams.json new file mode 100644 index 000000000..be7b79477 --- /dev/null +++ b/test/mocks/pnfsimulator/src/test/resources/org/onap/pnfsimulator/simulator/SimulatorFactoryTest/invalidSimulatorParams.json @@ -0,0 +1,4 @@ +{ + "vesServerUrl": "http://10.42.111.42:8080/eventListener/v5", + "messageInterval": "1" +}
\ No newline at end of file diff --git a/test/mocks/pnfsimulator/src/test/resources/org/onap/pnfsimulator/simulator/validCommonEventHeaderParams.json b/test/mocks/pnfsimulator/src/test/resources/org/onap/pnfsimulator/simulator/SimulatorFactoryTest/validCommonEventHeaderParams.json index e0f455045..e0f455045 100644 --- a/test/mocks/pnfsimulator/src/test/resources/org/onap/pnfsimulator/simulator/validCommonEventHeaderParams.json +++ b/test/mocks/pnfsimulator/src/test/resources/org/onap/pnfsimulator/simulator/SimulatorFactoryTest/validCommonEventHeaderParams.json diff --git a/test/mocks/pnfsimulator/src/test/resources/org/onap/pnfsimulator/simulator/validNotificationParams.json b/test/mocks/pnfsimulator/src/test/resources/org/onap/pnfsimulator/simulator/SimulatorFactoryTest/validNotificationParams.json index f7f463d3d..f7f463d3d 100644 --- a/test/mocks/pnfsimulator/src/test/resources/org/onap/pnfsimulator/simulator/validNotificationParams.json +++ b/test/mocks/pnfsimulator/src/test/resources/org/onap/pnfsimulator/simulator/SimulatorFactoryTest/validNotificationParams.json diff --git a/test/mocks/pnfsimulator/src/test/resources/org/onap/pnfsimulator/simulator/validPnfRegistrationParams.json b/test/mocks/pnfsimulator/src/test/resources/org/onap/pnfsimulator/simulator/SimulatorFactoryTest/validPnfRegistrationParams.json index b95f8e60a..b95f8e60a 100644 --- a/test/mocks/pnfsimulator/src/test/resources/org/onap/pnfsimulator/simulator/validPnfRegistrationParams.json +++ b/test/mocks/pnfsimulator/src/test/resources/org/onap/pnfsimulator/simulator/SimulatorFactoryTest/validPnfRegistrationParams.json diff --git a/test/mocks/pnfsimulator/src/test/resources/org/onap/pnfsimulator/simulator/validSimulatorParams.json b/test/mocks/pnfsimulator/src/test/resources/org/onap/pnfsimulator/simulator/SimulatorFactoryTest/validSimulatorParams.json index 6485ee4a4..6485ee4a4 100644 --- a/test/mocks/pnfsimulator/src/test/resources/org/onap/pnfsimulator/simulator/validSimulatorParams.json +++ b/test/mocks/pnfsimulator/src/test/resources/org/onap/pnfsimulator/simulator/SimulatorFactoryTest/validSimulatorParams.json |