Merge "Adding PM Mapper Test to BulkPMe2e tests"
authorGary Wu <gary.i.wu@huawei.com>
Thu, 11 Apr 2019 16:21:02 +0000 (16:21 +0000)
committerGerrit Code Review <gerrit@onap.org>
Thu, 11 Apr 2019 16:21:02 +0000 (16:21 +0000)
14 files changed:
plans/dcaegen2-collectors-hv-ves/testsuites/env.sh
plans/dcaegen2-collectors-hv-ves/testsuites/env_local.sh
tests/dcaegen2-collectors-hv-ves/testcases/__init__.robot
tests/dcaegen2-collectors-hv-ves/testcases/configuration.robot [new file with mode: 0644]
tests/dcaegen2-collectors-hv-ves/testcases/libraries/DcaeAppSimulatorLibrary.py
tests/dcaegen2-collectors-hv-ves/testcases/libraries/HttpRequests.py
tests/dcaegen2-collectors-hv-ves/testcases/resources/common-keywords.robot
tests/dcaegen2-collectors-hv-ves/testcases/resources/hv-ves-configuration-with-different-topic.json [new file with mode: 0644]
tests/dcaegen2-collectors-hv-ves/testcases/resources/scenarios/configuration-change/xnf-valid-messages-request.json [new file with mode: 0644]
tests/dcaegen2-pmmapper/pmmapper/pmmapper.robot
tests/dcaegen2/prh-testcases/resources/docker-compose.yml
tests/dcaegen2/prh-testcases/resources/simulator/AAI.py
tests/dcaegen2/prh-testcases/resources/simulator/DMaaP.py
tests/dcaegen2/prh-testcases/resources/simulator/httpServerLib.py

index a5a0a4f..0531484 100755 (executable)
@@ -18,7 +18,7 @@
 # ============LICENSE_END=========================================================
 
 # using WORKSPACE variable defined in run-csit.sh
-export ROBOT_VARIABLES="--pythonpath ${WORKSPACE}/tests/dcaegen2-collectors-hv-ves/testcases/libraries"
+export ROBOT_VARIABLES="--pythonpath ${WORKSPACE}/tests/dcaegen2-collectors-hv-ves/testcases/libraries --noncritical non-critical"
 
 export JAVA_OPTS="-Dio.netty.leakDetection.level=paranoid"
 export CONSUL_HOST="consul-server"
index 280f0c4..20b538b 100755 (executable)
@@ -18,7 +18,7 @@
 # ============LICENSE_END=========================================================
 
 export WORKSPACE=$(git rev-parse --show-toplevel)
-export ROBOT_VARIABLES="--pythonpath ${WORKSPACE}/tests/dcaegen2-collectors-hv-ves/testcases/libraries"
+export ROBOT_VARIABLES="--pythonpath ${WORKSPACE}/tests/dcaegen2-collectors-hv-ves/testcases/libraries --noncritical non-critical"
 
 export JAVA_OPTS="-Dio.netty.leakDetection.level=paranoid"
 export CONSUL_HOST="consul-server"
index 7fffd9c..92b65cd 100644 (file)
@@ -34,12 +34,14 @@ HV-VES Collector Suites Setup
 Configure collector
     ${CONSUL_API_ACCESS}=   Get Consul Api Access Url   ${HTTP_METHOD_URL}   ${CONSUL_CONTAINER_HOST}   ${CONSUL_CONTAINER_PORT}
     ${CONSUL_API_URL}=  Catenate   SEPARATOR=   ${CONSUL_API_ACCESS}   ${CONSUL_HV_VES_CONFIGURATION_KEY_PATH}
+    Set Suite Variable    ${CONSUL_API_URL}   children=True
     Publish HV VES Configuration In Consul    ${CONSUL_API_URL}   ${HV_VES_CONFIGURATION_JSON_FILEPATH}
 
 Configure Dcae App
     Wait until keyword succeeds   10 sec   5 sec
-    ...    Configure Dcae App Simulator To Consume Messages From Topics   ${DEFAULT_PERF3GPP_TOPIC}
+    ...    Configure Dcae App Simulator To Consume Messages From Topics   ${DEFAULT_PERF3GPP_TOPIC},${SECOND_PERF3GPP_TOPIC}
     Set Suite Variable   ${DEFAULT_PERF3GPP_TOPIC}   children=True
+    Set Suite Variable   ${SECOND_PERF3GPP_TOPIC}    children=True
 
 
 *** Variables ***
@@ -50,6 +52,7 @@ ${CONSUL_CONTAINER_PORT}                       8500
 ${CONSUL_HV_VES_CONFIGURATION_KEY_PATH}        /v1/kv/dcae-hv-ves-collector
 
 ${DEFAULT_PERF3GPP_TOPIC}                      TEST_HV_VES_PERF3GPP
+${SECOND_PERF3GPP_TOPIC}                       TEST_HV_VES_PERF3GPP_BUT_WITH_EXTRA_WORDS
 
 ${HV_VES_RESOURCES}                            %{WORKSPACE}/tests/dcaegen2-collectors-hv-ves/testcases/resources
 ${HV_VES_CONFIGURATION_JSON_FILEPATH}          ${HV_VES_RESOURCES}/hv-ves-configuration.json
diff --git a/tests/dcaegen2-collectors-hv-ves/testcases/configuration.robot b/tests/dcaegen2-collectors-hv-ves/testcases/configuration.robot
new file mode 100644 (file)
index 0000000..945cb81
--- /dev/null
@@ -0,0 +1,83 @@
+# ============LICENSE_START=======================================================
+# csit-dcaegen2-collectors-hv-ves
+# ================================================================================
+# Copyright (C) 2019 NOKIA
+# ================================================================================
+# 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=========================================================
+
+*** Settings ***
+Library       DcaeAppSimulatorLibrary
+Library       ConsulLibrary
+Library       BuiltIn
+
+Resource      resources/common-keywords.robot
+
+Suite Setup       Configuration Changes Suite Setup
+Suite Teardown    VES-HV Collector Suite Teardown
+Test Teardown     VES-HV Collector Test Shutdown
+
+*** Keywords ***
+Configuration Changes Suite Setup
+    Log   Started Suite: VES-HV Client Configuration Changes
+    Configure Single xNF Simulator
+    Log   Suite setup finished
+
+Change Configuration
+    [Arguments]   ${CONFIGURATION_JSON_FILEPATH}   ${MESSAGES_TOPIC}
+    Publish HV VES Configuration In Consul    ${CONSUL_API_URL}   ${CONFIGURATION_JSON_FILEPATH}
+    # Assure configuration fetch in hv-ves
+    Sleep  10
+
+*** Test Cases ***
+Configuration change
+    [Tags]   non-critical
+    [Documentation]   VES-HV Collector should adapt to changing configuration
+    # Given
+    Change Configuration   ${DIFFERENT_TOPIC_CONFIGURATION_JSON_FILEPATH}   ${SECOND_PERF3GPP_TOPIC}
+
+    # When
+    Send Messages From xNF Simulators   ${XNF_SIMULATOR}   ${XNF_VALID_MESSAGES_REQUEST}
+
+    # Then they are published to this topic
+    Wait until keyword succeeds   30 sec   3 sec
+    ...     Assert Dcae App Consumed   ${SECOND_PERF3GPP_TOPIC}   ${AMOUNT_1000}
+    Assert Dcae App Consumed   ${DEFAULT_PERF3GPP_TOPIC}   ${AMOUNT_0}
+
+    Log   First configuration change assertion passed
+    Reset DCAE App Simulator  ${DEFAULT_PERF3GPP_TOPIC}
+    Reset DCAE App Simulator  ${SECOND_PERF3GPP_TOPIC}
+
+    # Given configuration change
+    Change Configuration   ${HV_VES_CONFIGURATION_JSON_FILEPATH}   ${DEFAULT_PERF3GPP_TOPIC}
+
+    # When
+    Send Messages From xNF Simulators   ${XNF_SIMULATOR}   ${XNF_VALID_MESSAGES_REQUEST}
+
+    # Then they are published to this topic
+    Wait until keyword succeeds   30 sec   3 sec
+    ...     Assert Dcae App Consumed   ${DEFAULT_PERF3GPP_TOPIC}   ${AMOUNT_1000}
+    Assert Dcae App Consumed   ${SECOND_PERF3GPP_TOPIC}   ${AMOUNT_0}
+
+
+
+*** Variables ***
+${AMOUNT_0}                                         0
+${AMOUNT_1000}                                      1000
+
+${HV_VES_SCENARIOS}                                 %{WORKSPACE}/tests/dcaegen2-collectors-hv-ves/testcases/resources/scenarios
+${XNF_VALID_MESSAGES_REQUEST}                       ${HV_VES_SCENARIOS}/configuration-change/xnf-valid-messages-request.json
+
+${HV_VES_RESOURCES}                                 %{WORKSPACE}/tests/dcaegen2-collectors-hv-ves/testcases/resources
+${HV_VES_CONFIGURATION_JSON_FILEPATH}               ${HV_VES_RESOURCES}/hv-ves-configuration.json
+${DIFFERENT_TOPIC_CONFIGURATION_JSON_FILEPATH}      ${HV_VES_RESOURCES}/hv-ves-configuration-with-different-topic.json
index 60c2c46..ccad430 100644 (file)
@@ -47,7 +47,7 @@ class DcaeAppSimulatorLibrary:
 
     def assert_DCAE_app_consumed(self, topic, expected_messages_amount):
         app_url = MESSAGES_COUNT_PATH % topic
-        logger.info("GET at: " + app_url)
+        logger.info("GET at: " + str(app_url))
         resp = HttpRequests.session_without_env().get(app_url, timeout=10)
         HttpRequests.checkStatusCode(resp.status_code, DCAE_APP_NAME)
 
index 4aa55d6..48205f2 100644 (file)
@@ -33,4 +33,4 @@ def session_without_env():
 def checkStatusCode(status_code, server_name):
     if status_code not in valid_status_codes:
         logger.error("Response status code from " + server_name + ": " + str(status_code))
-        raise (Exception(server_name + " returned status code " + status_code))
+        raise (Exception(server_name + " returned status code " + str(status_code)))
index ecf2d02..fee8bfd 100644 (file)
@@ -61,6 +61,7 @@ Send Messages From xNF Simulators
 
 VES-HV Collector Test Shutdown
     Reset DCAE App Simulator  ${DEFAULT_PERF3GPP_TOPIC}
+    Reset DCAE App Simulator  ${SECOND_PERF3GPP_TOPIC}
 
 
 VES-HV Collector Suite Teardown
diff --git a/tests/dcaegen2-collectors-hv-ves/testcases/resources/hv-ves-configuration-with-different-topic.json b/tests/dcaegen2-collectors-hv-ves/testcases/resources/hv-ves-configuration-with-different-topic.json
new file mode 100644 (file)
index 0000000..d3d1f4c
--- /dev/null
@@ -0,0 +1,12 @@
+{
+  "streams_publishes": {
+    "perf3gpp": {
+      "type": "kafka",
+      "kafka_info": {
+        "bootstrap_servers": "kafka:9092",
+        "topic_name": "TEST_HV_VES_PERF3GPP_BUT_WITH_EXTRA_WORDS"
+      }
+    }
+  }
+}
+
diff --git a/tests/dcaegen2-collectors-hv-ves/testcases/resources/scenarios/configuration-change/xnf-valid-messages-request.json b/tests/dcaegen2-collectors-hv-ves/testcases/resources/scenarios/configuration-change/xnf-valid-messages-request.json
new file mode 100644 (file)
index 0000000..adbcf2a
--- /dev/null
@@ -0,0 +1,24 @@
+[
+  {
+    "commonEventHeader": {
+      "version": "sample-version",
+      "domain": "perf3gpp",
+      "sequence": 1,
+      "priority": 1,
+      "eventId": "sample-event-id",
+      "eventName": "sample-event-name",
+      "eventType": "sample-event-type",
+      "startEpochMicrosec": 120034455,
+      "lastEpochMicrosec": 120034455,
+      "nfNamingCode": "sample-nf-naming-code",
+      "nfcNamingCode": "sample-nfc-naming-code",
+      "reportingEntityId": "sample-reporting-entity-id",
+      "reportingEntityName": "sample-reporting-entity-name",
+      "sourceId": "sample-source-id",
+      "sourceName": "sample-source-name",
+      "vesEventListenerVersion": "7.2.0"
+    },
+    "messageType": "VALID",
+    "messagesAmount": 1000
+  }
+]
\ No newline at end of file
index 5315cc3..a103c5c 100644 (file)
@@ -26,15 +26,12 @@ ${CLI_EXEC_CLI_PM_LOG}                   docker exec pmmapper /bin/sh -c "tail -
 ${PUBLISH_NODE_URL}                      https://${DR_NODE_IP}:8443/publish/1
 ${TYPE-A_PM_DATA_FILE_PATH}              %{WORKSPACE}/tests/dcaegen2-pmmapper/pmmapper/assets/A20181002.0000-1000-0015-1000_5G.xml
 ${TYPE-C_PM_DATA_FILE_PATH}              %{WORKSPACE}/tests/dcaegen2-pmmapper/pmmapper/assets/C20190328.0000-0015.xml
-${PUBLISH_CONTENT_TYPE}                  application/octet-stream
 ${CLI_EXEC_VENDOR_FILTER}                curl 'http://${CONSUL_IP}:8500/v1/kv/pmmapper?dc=dc1' -X PUT -H 'Accept: application/^Con' -H 'Content-Type: application/json' -H 'X-Requested-With: XMLHttpRequest' --data @$WORKSPACE/tests/dcaegen2-pmmapper/pmmapper/assets/vendor_filter_config.json
 ${CLI_EXEC_PM_FILTER}                    curl 'http://${CONSUL_IP}:8500/v1/kv/pmmapper?dc=dc1' -X PUT -H 'Accept: application/^Con' -H 'Content-Type: application/json' -H 'X-Requested-With: XMLHttpRequest' --data @$WORKSPACE/tests/dcaegen2-pmmapper/pmmapper/assets/pm_filter_config.json
-${CLI_RESTART_PMMAPPER}                  docker restart pmmapper
-${CLI_DELETE_SUB1}                       curl -i -X DELETE -H "Content-Type:application/vnd.dmaap-dr.subscription" -H "X-DMAAP-DR-ON-BEHALF-OF:DGL" -k https://localhost:8443/subs/1
-${CLI_DELETE_SUB2}                       curl -i -X DELETE -H "Content-Type:application/vnd.dmaap-dr.subscription" -H "X-DMAAP-DR-ON-BEHALF-OF:DGL" -k https://localhost:8443/subs/2
 ${CLI_MESSAGE_ROUTER_TOPIC}              curl http://${DMAAP_MR_IP}:3904/events/PM_MAPPER/CG1/C1?timeout=1000 > /tmp/mr.log
 ${CLI_MR_LOG}                            cat /tmp/mr.log
 
+
 *** Test Cases ***
 Verify PM Mapper Receive Configuraton From Config Binding Service
     [Tags]                          PM_MAPPER_01
@@ -148,7 +145,7 @@ SendToDatarouter
     ${filename}                     Fetch From Right                 ${filepath}                /
     ${resp}=                        PutCall                          ${PUBLISH_NODE_URL}/${filename}        ${request_id}    ${pmdata}    ${metatdata.replace("\n","")}    pmmapper
     VerifyResponse                  ${resp.status_code}              204
-    Sleep                           5s
+    Sleep                           10s
 
 PutCall
     [Arguments]                     ${url}                           ${request_id}              ${data}            ${meta}          ${user}
index 863a427..45c71dc 100644 (file)
@@ -123,11 +123,13 @@ services:
 
                                               "streams_publishes":{
                                                 "pnf-update":{
+                                                  "type": "message_router",
                                                   "dmaap_info":{
                                                     "topic_url":"http://dmaap-mr:2222/events/unauthenticated.PNF_UPDATE"
                                                   }
                                                 },
                                                 "pnf-ready":{
+                                                  "type": "message_router",
                                                   "dmaap_info":{
                                                     "topic_url":"http://dmaap-mr:2222/events/unauthenticated.PNF_READY"
                                                   }
@@ -135,6 +137,7 @@ services:
                                               },
                                               "streams_subscribes":{
                                                 "ves-reg-output":{
+                                                  "type": "message_router",
                                                   "dmaap_info":{
                                                     "topic_url":"http://dmaap-mr:2222/events/unauthenticated.VES_PNFREG_OUTPUT"
                                                   }
index baa8165..010c523 100644 (file)
@@ -4,6 +4,7 @@ import sys
 import re
 import time
 from http.server import BaseHTTPRequestHandler
+from os.path import basename
 import httpServerLib
 
 ch = logging.StreamHandler(sys.stdout)
@@ -16,72 +17,125 @@ logging.basicConfig(
 
 logger = logging.getLogger('AAI-simulator-logger')
 
-pnf_name = 'Empty'
-pnf_entry = {}
-
-
-def _mark_response_as_http_ok(http_endpoint):
-    logger.info('Execution status 200')
-    httpServerLib.header_200_and_json(http_endpoint)
+AAI_RESOURCE_NOT_FOUND = b'{}'
 
+pnf_entries = {}
+patched_pnf = AAI_RESOURCE_NOT_FOUND
+created_logical_link = AAI_RESOURCE_NOT_FOUND
 
 class AAISetup(BaseHTTPRequestHandler):
 
-    def do_PUT(self):
-        logger.info('AAI SIM Setup Put execution')
-        if re.search('/set_pnf$', self.path): # to avoid regex collisions '$' must be added
-            global pnf_name
-            content_length = self._get_content_length()
-            pnf_name = self.rfile.read(content_length).decode()
-            _mark_response_as_http_ok(self)
-
-        if re.search('/set_pnf_entry',self.path):
-            global pnf_entry
-            content_length = self._get_content_length()
-            pnf_entry = json.loads(self.rfile.read(content_length))
-            _mark_response_as_http_ok(self)
+    def do_GET(self):
+        try:
+            if re.search('/setup/patched_pnf', self.path):
+                httpServerLib.set_response_200_ok(self, payload = patched_pnf)
+                logger.debug('AAISetup GET /setup/patched_pnf -> 200 OK')
+            elif re.search('/setup/created_logical_link', self.path):
+                httpServerLib.set_response_200_ok(self, payload = created_logical_link)
+                logger.debug('AAISetup GET /setup/created_logical_link -> 200 OK')
+            else:
+                httpServerLib.set_response_404_not_found(self)
+                logger.info('AAISetup GET ' + self.path + ' -> 404 Not found')
+        except Exception as e:
+            logger.error(e)
+            httpServerLib.set_response_500_server_error(self)
 
-        return
+    def do_PUT(self):
+        try:
+            if re.search('/setup/add_pnf_entry', self.path):
+                pnf_entry = httpServerLib.get_payload(self)
+                pnf_name = json.loads(pnf_entry).get("pnf-name")
+                if pnf_name == None:
+                    raise Exception("Invalid PNF entry, could not extract `pnf-name`")
+
+                global pnf_entries
+                pnf_entries[pnf_name] = pnf_entry
+
+                httpServerLib.set_response_200_ok(self)
+                logger.debug('AAISetup PUT /setup/add_pnf_entry [' + pnf_name + '] -> 200 OK')
+            elif re.search('/set_pnf', self.path):
+                pnf_name = httpServerLib.get_payload(self).decode()
+                pnf_entries[pnf_name] = AAI_RESOURCE_NOT_FOUND
+                httpServerLib.set_response_200_ok(self)
+            else:
+                httpServerLib.set_response_404_not_found(self)
+                logger.info('AAISetup PUT ' + self.path + ' -> 404 Not found')
+        except Exception as e:
+            logger.error(e)
+            httpServerLib.set_response_500_server_error(self)
 
     def do_POST(self):
-        logger.info('AAI SIM Setup Post execution')
-        if re.search('/reset', self.path):
-            global pnf_name
-            pnf_name = 'Empty'
-            _mark_response_as_http_ok(self)
-
-        return
-
-    def _get_content_length(self):
-        return int(self.headers['Content-Length'])
-
+        try:
+            if re.search('/reset', self.path):
+                global pnf_entries
+                global patched_pnf
+                global created_logical_link
+                pnf_entries = {}
+                patched_pnf = AAI_RESOURCE_NOT_FOUND
+                created_logical_link = AAI_RESOURCE_NOT_FOUND
+
+                httpServerLib.set_response_200_ok(self)
+                logger.debug('AAISetup POST /reset -> 200 OK')
+            else:
+                httpServerLib.set_response_404_not_found(self)
+                logger.info('AAISetup POST ' + self.path + ' -> 404 Not found')
+        except Exception as e:
+            logger.error(e)
+            httpServerLib.set_response_500_server_error(self)
 
 class AAIHandler(BaseHTTPRequestHandler):
 
     def do_GET(self):
-        logger.info('AAI SIM Get execution')
-        full_request_path = '/aai/v12/network/pnfs/pnf/' + pnf_name
-        if re.search(full_request_path, self.path):
-            _mark_response_as_http_ok(self)
-            body = json.dumps(pnf_entry)
-            logger.info('AAI SIM Get json prepared')
-            self.wfile.write(body.encode())
-        return
-
+        try:
+            if re.search('/aai/v12/network/pnfs/pnf/[^/]*$', self.path):
+                pnf_name = basename(self.path)
+                if pnf_name in pnf_entries:
+                    httpServerLib.set_response_200_ok(self, payload = pnf_entries[pnf_name])
+                    logger.debug('AAIHandler GET /aai/v12/network/pnfs/pnf/' + pnf_name + ' -> 200 OK')
+                else:
+                    httpServerLib.set_response_404_not_found(self)
+                    logger.info('AAIHandler GET /aai/v12/network/pnfs/pnf/' + pnf_name + ' -> 404 Not found, actual entries: ' + str(pnf_entries.keys()))
+            else:
+                httpServerLib.set_response_404_not_found(self)
+                logger.info('AAIHandler GET ' + self.path + ' -> 404 Not found')
+        except Exception as e:
+            logger.error(e)
+            httpServerLib.set_response_500_server_error(self)
 
     def do_PATCH(self):
-        logger.info('AAI SIM Patch execution')
-        pnfs_name = '/aai/v12/network/pnfs/pnf/' + pnf_name
-        if re.search('wrong_aai_record', self.path):
-            self.send_response(400)
-            logger.info('Execution status 400')
-            self.end_headers()
-        elif re.search(pnfs_name, self.path):
-            self.send_response(200)
-            logger.info('Execution status 200')
-            self.end_headers()
-            
-        return
+        try:
+            if re.search('/aai/v12/network/pnfs/pnf/[^/]*$', self.path):
+                pnf_name = basename(self.path)
+                if pnf_name in pnf_entries:
+                    global patched_pnf
+                    patched_pnf = httpServerLib.get_payload(self)
+
+                    httpServerLib.set_response_200_ok(self)
+                    logger.debug('AAIHandler PATCH /aai/v12/network/pnfs/pnf/' + pnf_name + ' -> 200 OK')
+                else:
+                    httpServerLib.set_response_404_not_found(self)
+                    logger.info('AAIHandler PATCH /aai/v12/network/pnfs/pnf/' + pnf_name + ' -> 404 Not found, actual entries: ' + str(pnf_entries.keys()))
+            else:
+                httpServerLib.set_response_404_not_found(self)
+                logger.info('AAIHandler PATCH ' + self.path + ' -> 404 Not found')
+        except Exception as e:
+            logger.error(e)
+            httpServerLib.set_response_500_server_error(self)
+
+    def do_PUT(self):
+        try:
+            if re.search('/aai/v12/network/logical-links/logical-link/[^/]*$', self.path):
+                global created_logical_link
+                created_logical_link = httpServerLib.get_payload(self)
+
+                httpServerLib.set_response_200_ok(self)
+                logger.debug('AAIHandler PUT /aai/v12/network/logical-links/logical-link/' + created_logical_link + ' -> 200 OK')
+            else:
+                httpServerLib.set_response_404_not_found(self)
+                logger.info('AAIHandler PUT ' + self.path + ' -> 404 Not found')
+        except Exception as e:
+            logger.error(e)
+            httpServerLib.set_response_500_server_error(self)
 
 
 def _main_(handler_class=AAIHandler, protocol="HTTP/1.0"):
index da113e6..7f590a5 100644 (file)
@@ -15,62 +15,85 @@ logging.basicConfig(
 
 logger = logging.getLogger('DMaaP-simulator-logger')
 
-posted_event_from_prh = b'Empty'
-received_event_to_get_method = b'Empty'
+DMAAP_EMPTY = b'[]'
 
+ves_event = DMAAP_EMPTY
+captured_prh_event = DMAAP_EMPTY
 
 class DmaapSetup(BaseHTTPRequestHandler):
 
-    def do_PUT(self):
-        logger.info('DMaaP SIM Setup Put execution')
-        if re.search('/set_get_event', self.path):
-            global received_event_to_get_method
-            content_length = int(self.headers['Content-Length'])
-            received_event_to_get_method = self.rfile.read(content_length)
-            httpServerLib.header_200_and_json(self)
-
-        return
-
     def do_GET(self):
-        logger.info('DMaaP SIM Setup Get execution')
-        if re.search('/events/pnfReady', self.path):
-            httpServerLib.header_200_and_json(self)
-            self.wfile.write(posted_event_from_prh)
+        try:
+            if re.search('/setup/pnf_ready', self.path) or re.search('events/pnfReady', self.path):
+                global captured_prh_event
+                httpServerLib.set_response_200_ok(self, payload = captured_prh_event)
+                logger.debug('DmaapSetup GET /setup/pnf_ready -> 200 OK')
+            else:
+                httpServerLib.set_response_404_not_found(self)
+                logger.info('DmaapSetup GET ' + self.path + ' -> 404 Not found')
+        except Exception as e:
+            logger.error(e)
+            httpServerLib.set_response_500_server_error(self)
 
-        return
+    def do_PUT(self):
+        try:
+            if re.search('/setup/ves_event', self.path) or re.search('/set_get_event', self.path):
+                global ves_event
+                ves_event = httpServerLib.get_payload(self)
+                httpServerLib.set_response_200_ok(self)
+                logger.debug('DmaapSetup PUT /setup/ves_event -> 200 OK')
+            else:
+                httpServerLib.set_response_404_not_found(self)
+                logger.info('DmaapSetup PUT ' + self.path + ' -> 404 Not found')
+        except Exception as e:
+            logger.error(e)
+            httpServerLib.set_response_500_server_error(self)
 
     def do_POST(self):
-        logger.info('DMaaP SIM Setup Post execution')
-        if re.search('/reset', self.path):
-            global posted_event_from_prh
-            global received_event_to_get_method
-            posted_event_from_prh = b'Empty'
-            received_event_to_get_method = b'Empty'
-            httpServerLib.header_200_and_json(self)
-
-        return
-
+        try:
+            if re.search('/reset', self.path):
+                global ves_event
+                global captured_prh_event
+                ves_event = DMAAP_EMPTY
+                captured_prh_event = DMAAP_EMPTY
+                httpServerLib.set_response_200_ok(self)
+                logger.debug('DmaapSetup POST /reset -> 200 OK')
+            else:
+                httpServerLib.set_response_404_not_found(self)
+                logger.info('DmaapSetup POST ' + self.path + ' -> 404 Not found')
+        except Exception as e:
+            logger.error(e)
+            httpServerLib.set_response_500_server_error(self)
 
 class DMaaPHandler(BaseHTTPRequestHandler):
 
     def do_POST(self):
-        logger.info('DMaaP SIM Post execution')
-        if re.search('/events/unauthenticated.PNF_READY', self.path):
-            global posted_event_from_prh
-            content_length = int(self.headers['Content-Length'])
-            posted_event_from_prh = self.rfile.read(content_length)
-            httpServerLib.header_200_and_json(self)
-
-        return
+        try:
+            if re.search('/events/unauthenticated.PNF_READY', self.path):
+                global captured_prh_event
+                captured_prh_event = httpServerLib.get_payload(self)
+                httpServerLib.set_response_200_ok(self)
+                logger.debug('DMaaPHandler POST /events/unauthenticated.PNF_READY -> 200')
+            else:
+                httpServerLib.set_response_404_not_found(self)
+                logger.info('DMaaPHandler POST ' + self.path + ' -> 404 Not found')
+        except Exception as e:
+            logger.error(e)
+            httpServerLib.set_response_500_server_error(self)
 
     def do_GET(self):
-        logger.info('DMaaP SIM Get execution')
-        if re.search('/events/unauthenticated.VES_PNFREG_OUTPUT/OpenDcae-c12/c12', self.path):
-            httpServerLib.header_200_and_json(self)
-            self.wfile.write(received_event_to_get_method)
-
-        return
-
+        try:
+            if re.search('/events/unauthenticated.VES_PNFREG_OUTPUT/OpenDcae-c12/c12', self.path):
+                global ves_event
+                httpServerLib.set_response_200_ok(self, payload = ves_event)
+                ves_event = DMAAP_EMPTY
+                logger.debug('DMaaPHandler GET /events/unauthenticated.VES_PNFREG_OUTPUT/OpenDcae-c12/c12 -> 200')
+            else:
+                httpServerLib.set_response_404_not_found(self)
+                logger.info('DMaaPHandler GET ' + self.path + ' -> 404 Not found')
+        except Exception as e:
+            logger.error(e)
+            httpServerLib.set_response_500_server_error(self)
 
 def _main_(handler_class=DMaaPHandler, protocol="HTTP/1.0"):
     handler_class.protocol_version = protocol
@@ -80,6 +103,5 @@ def _main_(handler_class=DMaaPHandler, protocol="HTTP/1.0"):
     while 1:
         time.sleep(10)
 
-
 if __name__ == '__main__':
-    _main_()
+    _main_()
\ No newline at end of file
index 7b54539..e91927e 100644 (file)
@@ -2,32 +2,44 @@ import _thread
 import ssl
 from http.server import HTTPServer
 
-
-def header_200_and_json(self):
+def set_response_200_ok(self, payload = None):
     self.send_response(200)
     self.send_header('Content-Type', 'application/json')
     self.end_headers()
+    if payload != None:
+        self.wfile.write(payload)
+
+def set_response_404_not_found(self):
+    self.send_response(404)
+    self.end_headers()
+
+def set_response_500_server_error(self):
+    self.send_response(500)
+    self.end_headers()
 
+def get_payload(self):
+    if self.headers['Content-Length'] == None:
+        raise Exception('Invalid payload, Content-Length not defined')
+
+    content_length = int(self.headers['Content-Length'])
+    return self.rfile.read(content_length)
 
 def start_http_endpoint(port, handler_class):
     _thread.start_new_thread(init_http_endpoints, (port, handler_class))
 
-
 def start_https_endpoint(port, handler_class, keyfile, certfile, ca_certs):
     _thread.start_new_thread(init_https_endpoints, (port, handler_class, keyfile, certfile, ca_certs))
 
-
 def init_http_endpoints(port, handler_class, server_class=HTTPServer):
     server = server_class(('', port), handler_class)
     sa = server.socket.getsockname()
     print("Serving HTTP on", sa[0], "port", sa[1], "for", handler_class, "...")
     server.serve_forever()
 
-
 def init_https_endpoints(port, handler_class, keyfile, certfile, ca_certs, server_class=HTTPServer):
     server = server_class(('', port), handler_class)
     server.socket = ssl.wrap_socket(server.socket, keyfile=keyfile, certfile=certfile,
                                     ca_certs=ca_certs, server_side=True)
     sa = server.socket.getsockname()
     print("Serving HTTPS on", sa[0], "port", sa[1], "for", handler_class, "...")
-    server.serve_forever()
+    server.serve_forever()
\ No newline at end of file