Refactor the notification process code 97/99697/8
authorhongyuzhao <zhao.hongyu@zte.com.cn>
Tue, 17 Dec 2019 08:37:25 +0000 (16:37 +0800)
committerhongyuzhao <zhao.hongyu@zte.com.cn>
Sat, 4 Jan 2020 07:35:30 +0000 (15:35 +0800)
Change-Id: Ie12527c77e5cacc55bdc3bc1505ec130e9d3c582
Issue-ID: MODELING-269
Signed-off-by: hongyuzhao <zhao.hongyu@zte.com.cn>
catalog/packages/biz/notificationsutil.py
catalog/packages/biz/ns_descriptor.py
catalog/packages/biz/pnf_descriptor.py
catalog/packages/biz/vnf_package.py
catalog/packages/serializers/vnf_pkg_notifications.py
catalog/packages/tests/test_nsdm_subscription.py
catalog/packages/tests/test_vnf_pkg_subscription.py
catalog/pub/database/models.py
catalog/swagger/etsicatalog.swagger.notification.json
tox.ini

index 8a653b4..8cdfd80 100644 (file)
@@ -17,51 +17,50 @@ import uuid
 import requests
 from rest_framework import status
 from catalog.packages import const
-from catalog.pub.database.models import VnfPkgSubscriptionModel, NsdmSubscriptionModel
-from catalog.pub.database.models import VnfPackageModel
+from catalog.pub.database.models import VnfPackageModel, VnfPkgSubscriptionModel, NsdmSubscriptionModel
 import catalog.pub.utils.timeutil
 from catalog.pub.utils.values import remove_none_key
 from catalog.pub.config import config as pub_config
 import traceback
 from django.db.models import Q
+from catalog.packages.serializers.vnf_pkg_notifications import PkgChangeNotificationSerializer, \
+    PkgOnboardingNotificationSerializer
 
 
 logger = logging.getLogger(__name__)
 
 
 class NotificationsUtil(object):
-    def __init__(self):
+    def __init__(self, notification_type):
+        self.notification_type = notification_type
+        self.notifyserializer = None
+
+    def prepare_notification(self, **kwargs):
         pass
 
-    def send_notification(self, notification, filters, isvnfpkg):
-        subscriptions_filter = {v + "__contains": notification[k] for k, v in filters.items()}
+    def send_notification(self):
+        notification = self.prepare_notification()
+
+        subscriptions_filter = {v + "__contains": notification[k] for k, v in self.filters.items()}
         subscriptions_filter = remove_none_key(subscriptions_filter)
         logger.debug('send_notification subscriptions_filter = %s' % subscriptions_filter)
         q1 = Q()
         q1.connector = 'OR'
         for k, v in subscriptions_filter.items():
             q1.children.append((k, v))
-        if isvnfpkg:
-            subscriptions = VnfPkgSubscriptionModel.objects.filter(q1)
-            subscription_root_uri = const.VNFPKG_SUBSCRIPTION_ROOT_URI
-        else:
-            subscriptions = NsdmSubscriptionModel.objects.filter(q1)
-            subscription_root_uri = const.NSDM_SUBSCRIPTION_ROOT_URI
 
+        subscriptions = self.SubscriptionModel.objects.filter(q1)
         if not subscriptions.exists():
             logger.info("No subscriptions created for the filters %s" % notification)
             return
         logger.info("Start sending notifications")
         for sub in subscriptions:
             # set subscription id
-            if isvnfpkg:
-                notification["subscriptionId"] = sub.subscription_id
-            else:
-                notification["subscriptionId"] = sub.subscriptionid
+            notification["subscriptionId"] = sub.get_subscription_id()
             notification['_links']['subscription'] = {
                 'href': 'http://%s:%s/%s%s' % (pub_config.MSB_SERVICE_IP,
                                                pub_config.MSB_SERVICE_PORT,
-                                               subscription_root_uri,
+                                               self.subscription_root_uri,
                                                notification["subscriptionId"])
             }
             callbackuri = sub.callback_uri
@@ -70,6 +69,10 @@ class NotificationsUtil(object):
             if auth_info["authType"] == const.OAUTH2_CLIENT_CREDENTIALS:
                 pass
             """
+            if self.notifyserializer:
+                serialized_data = self.notifyserializer(data=notification)
+                if not serialized_data.is_valid():
+                    logger.error('Notification Data is invalid:%s.' % serialized_data.errors)
             self.post_notification(callbackuri, notification)
 
     def post_notification(self, callbackuri, notification):
@@ -96,76 +99,135 @@ class NotificationsUtil(object):
             logger.error(traceback.format_exc())
 
 
-def prepare_vnfpkg_notification(vnf_pkg_id, notification_type, pkg_change_type, operational_state):
-    logger.info('Start to prepare notification')
-    vnf_pkg = VnfPackageModel.objects.filter(vnfPackageId=vnf_pkg_id)
-    vnfd_id = None
-    if vnf_pkg:
-        vnfd_id = vnf_pkg[0].vnfdId
-    notification_content = {
-        'id': str(uuid.uuid4()),  # shall be the same if sent multiple times due to multiple subscriptions.
-        'notificationType': notification_type,
-        # set 'subscriptionId' after filtering for subscribers
-        'timeStamp': catalog.pub.utils.timeutil.now_time(),
-        'vnfPkgId': vnf_pkg_id,
-        'vnfdId': vnfd_id,
-        '_links': {
-            'vnfPackage': {
-                'href': 'http://%s:%s/%s/vnf_packages/%s' % (pub_config.MSB_SERVICE_IP,
-                                                             pub_config.MSB_SERVICE_PORT,
-                                                             const.PKG_URL_PREFIX,
-                                                             vnf_pkg_id)
+class PkgNotifications(NotificationsUtil):
+    def __init__(self, notification_type, vnf_pkg_id, change_type=None, operational_state=None):
+        super(PkgNotifications, self).__init__(notification_type)
+        self.filters = {
+            'vnfdId': 'vnfd_id',
+            'vnfPkgId': 'vnf_pkg_id'
+        }
+        self.vnf_pkg_id = vnf_pkg_id
+        self.change_type = change_type
+        self.operational_state = operational_state
+        self.SubscriptionModel = VnfPkgSubscriptionModel
+        self.subscription_root_uri = const.VNFPKG_SUBSCRIPTION_ROOT_URI
+        if self.notification_type == "VnfPackageChangeNotification":
+            self.notifyserializer = PkgChangeNotificationSerializer
+        else:
+            self.notifyserializer = PkgOnboardingNotificationSerializer
+
+    def prepare_notification(self):
+        logger.info('Start to prepare Pkgnotification')
+
+        vnf_pkg = VnfPackageModel.objects.filter(vnfPackageId=self.vnf_pkg_id)
+        vnfd_id = None
+        if vnf_pkg:
+            vnfd_id = vnf_pkg[0].vnfdId
+        notification_content = {
+            'id': str(uuid.uuid4()),  # shall be the same if sent multiple times due to multiple subscriptions.
+            'notificationType': self.notification_type,
+            # set 'subscriptionId' after filtering for subscribers
+            'timeStamp': catalog.pub.utils.timeutil.now_time(),
+            'vnfPkgId': self.vnf_pkg_id,
+            'vnfdId': vnfd_id,
+            '_links': {
+                'vnfPackage': {
+                    'href': 'http://%s:%s/%s/vnf_packages/%s' % (pub_config.MSB_SERVICE_IP,
+                                                                 pub_config.MSB_SERVICE_PORT,
+                                                                 const.PKG_URL_PREFIX,
+                                                                 self.vnf_pkg_id)
+                }
             }
         }
-    }
-
-    if notification_type == "VnfPackageChangeNotification":
-        notification_content['changeType'] = pkg_change_type
-        notification_content['operationalState'] = operational_state
-
-    return notification_content
-
-
-def prepare_nsd_notification(nsd_info_id, nsd_id, notification_type, failure_details=None, operational_state=None):
-    logger.info('Start to prepare notification')
-    notification_content = {
-        'id': str(uuid.uuid4()),  # shall be the same if sent multiple times due to multiple subscriptions.
-        'notificationType': notification_type,
-        # set 'subscriptionId' after filtering for subscribers
-        'timeStamp': catalog.pub.utils.timeutil.now_time(),
-        'nsdInfoId': nsd_info_id,
-        'nsdId': nsd_id,
-        'onboardingFailureDetails': failure_details,
-        'nsdOperationalState': operational_state,
-        '_links': {
-            'nsdInfo': {
-                'href': 'http://%s:%s/%s/ns_descriptors/%s' % (pub_config.MSB_SERVICE_IP,
-                                                               pub_config.MSB_SERVICE_PORT,
-                                                               const.NSD_URL_PREFIX,
-                                                               nsd_info_id)
+
+        if self.notification_type == "VnfPackageChangeNotification":
+            notification_content['changeType'] = self.change_type
+            notification_content['operationalState'] = self.operational_state
+
+        return notification_content
+
+
+class NsdNotifications(NotificationsUtil):
+    def __init__(self, notification_type, nsd_info_id, nsd_id, failure_details=None, operational_state=None):
+        super(NsdNotifications, self).__init__(notification_type)
+        self.filters = {
+            'nsdInfoId': 'nsdInfoId',
+            'nsdId': 'nsdId',
+        }
+        self.SubscriptionModel = NsdmSubscriptionModel
+        self.subscription_root_uri = const.NSDM_SUBSCRIPTION_ROOT_URI
+        self.nsd_info_id = nsd_info_id
+        self.nsd_id = nsd_id
+        self.failure_details = failure_details
+        self.operational_state = operational_state
+        # todo:
+        # if self.notification_type == "VnfPackageChangeNotification":
+        #     self.notifyserializer = PkgChangeNotificationSerializer
+        # else:
+        #     self.notifyserializer = PkgOnboardingNotificationSerializer
+
+    def prepare_notification(self):
+        logger.info('Start to prepare Nsdnotification')
+
+        notification_content = {
+            'id': str(uuid.uuid4()),  # shall be the same if sent multiple times due to multiple subscriptions.
+            'notificationType': self.notification_type,
+            # set 'subscriptionId' after filtering for subscribers
+            'timeStamp': catalog.pub.utils.timeutil.now_time(),
+            'nsdInfoId': self.nsd_info_id,
+            'nsdId': self.nsd_id,
+            '_links': {
+                'nsdInfo': {
+                    'href': 'http://%s:%s/%s/ns_descriptors/%s' % (pub_config.MSB_SERVICE_IP,
+                                                                   pub_config.MSB_SERVICE_PORT,
+                                                                   const.NSD_URL_PREFIX,
+                                                                   self.nsd_info_id)
+                }
             }
         }
-    }
-    return notification_content
-
-
-def prepare_pnfd_notification(pnfd_info_id, pnfd_id, notification_type, failure_details=None):
-    logger.info('Start to prepare notification')
-    notification_content = {
-        'id': str(uuid.uuid4()),  # shall be the same if sent multiple times due to multiple subscriptions.
-        'notificationType': notification_type,
-        # set 'subscriptionId' after filtering for subscribers
-        'timeStamp': catalog.pub.utils.timeutil.now_time(),
-        'pnfdInfoIds': pnfd_info_id,
-        'pnfdId': pnfd_id,
-        'onboardingFailureDetails': failure_details,
-        '_links': {
-            'pnfdInfo': {
-                'href': 'http://%s:%s/%s/pnf_descriptors/%s' % (pub_config.MSB_SERVICE_IP,
-                                                                pub_config.MSB_SERVICE_PORT,
-                                                                const.NSD_URL_PREFIX,
-                                                                pnfd_info_id)
+        if self.notification_type == "NsdOnboardingFailureNotification":
+            notification_content['onboardingFailureDetails'] = self.failure_details
+        if self.notification_type == "NsdChangeNotification":
+            notification_content['nsdOperationalState'] = self.operational_state
+        return notification_content
+
+
+class PnfNotifications(NotificationsUtil):
+    def __init__(self, notification_type, pnfd_info_id, pnfd_id, failure_details=None):
+        super(PnfNotifications, self).__init__(notification_type)
+        self.filters = {
+            'pnfdId': 'pnfdId',
+            'pnfdInfoIds': 'pnfdInfoIds',
+        }
+        self.SubscriptionModel = NsdmSubscriptionModel
+        self.subscription_root_uri = const.NSDM_SUBSCRIPTION_ROOT_URI
+        self.pnfd_info_id = pnfd_info_id
+        self.pnfd_id = pnfd_id
+        self.failure_details = failure_details
+        # todo
+        # if self.notification_type == "VnfPackageChangeNotification":
+        #     self.notifyserializer = PkgChangeNotificationSerializer
+        # else:
+        #     self.notifyserializer = PkgOnboardingNotificationSerializer
+
+    def prepare_notification(self, *args, **kwargs):
+        logger.info('Start to prepare Pnfnotification')
+        notification_content = {
+            'id': str(uuid.uuid4()),  # shall be the same if sent multiple times due to multiple subscriptions.
+            'notificationType': self.notification_type,
+            # set 'subscriptionId' after filtering for subscribers
+            'timeStamp': catalog.pub.utils.timeutil.now_time(),
+            'pnfdInfoIds': self.pnfd_info_id,
+            'pnfdId': self.pnfd_id,
+            '_links': {
+                'pnfdInfo': {
+                    'href': 'http://%s:%s/%s/pnf_descriptors/%s' % (pub_config.MSB_SERVICE_IP,
+                                                                    pub_config.MSB_SERVICE_PORT,
+                                                                    const.NSD_URL_PREFIX,
+                                                                    self.pnfd_info_id)
+                }
             }
         }
-    }
-    return notification_content
+        if self.notification_type == "PnfdOnboardingFailureNotification":
+            notification_content['onboardingFailureDetails'] = self.failure_details
+        return notification_content
index ca1b684..8b337dc 100644 (file)
@@ -24,7 +24,7 @@ from catalog.pub.database.models import NSPackageModel, PnfPackageModel, VnfPack
 from catalog.pub.exceptions import CatalogException, ResourceNotFoundException
 from catalog.pub.utils import fileutil, toscaparser
 from catalog.pub.utils.values import ignore_case_get
-from catalog.packages.biz.notificationsutil import prepare_nsd_notification, NotificationsUtil
+from catalog.packages.biz.notificationsutil import NsdNotifications
 from catalog.packages import const
 
 logger = logging.getLogger(__name__)
@@ -141,8 +141,10 @@ class NsDescriptor(object):
             raise CatalogException("nsd_id(%s) does not exist in metadata." % nsd_id)
         other_nspkg = NSPackageModel.objects.filter(nsdId=nsd_id)
         if other_nspkg and other_nspkg[0].nsPackageId != nsd_info_id:
-            logger.warn("NSD(%s,%s) already exists.", nsd_id, other_nspkg[0].nsPackageId)
-            send_notification(const.NSD_NOTIFICATION_TYPE.NSD_ONBOARDING_FAILURE, nsd_info_id, nsd_id)
+            failure_details = "NSD(%s,%s) already exists.", nsd_id, other_nspkg[0].nsPackageId
+            logger.warn(failure_details)
+            send_notification(const.NSD_NOTIFICATION_TYPE.NSD_ONBOARDING_FAILURE, nsd_info_id, nsd_id,
+                              failure_details=failure_details)
             raise CatalogException("NSD(%s) already exists." % nsd_id)
 
         for vnf in nsd["vnfs"]:
@@ -244,15 +246,7 @@ class NsDescriptor(object):
 
 
 def send_notification(type, nsd_info_id, nsd_id=None, failure_details=None, operational_state=None):
-    data = prepare_nsd_notification(nsd_info_id=nsd_info_id,
-                                    nsd_id=nsd_id,
-                                    notification_type=type,
-                                    failure_details=failure_details,
-                                    operational_state=operational_state)
-    filters = {
-        'nsdInfoId': 'nsdInfoId',
-        'nsdId': 'nsdId',
-    }
-    logger.debug('Notify request data = %s' % data)
-    logger.debug('Notify request filters = %s' % filters)
-    NotificationsUtil().send_notification(data, filters, False)
+    notify = NsdNotifications(type, nsd_info_id, nsd_id,
+                              failure_details=failure_details,
+                              operational_state=operational_state)
+    notify.send_notification()
index 6f45729..dd6a236 100644 (file)
@@ -25,7 +25,7 @@ from catalog.pub.database.models import NSPackageModel, PnfPackageModel
 from catalog.pub.exceptions import CatalogException, ResourceNotFoundException
 from catalog.pub.utils import fileutil, toscaparser
 from catalog.pub.utils.values import ignore_case_get
-from catalog.packages.biz.notificationsutil import prepare_pnfd_notification, NotificationsUtil
+from catalog.packages.biz.notificationsutil import PnfNotifications
 from catalog.packages import const
 
 logger = logging.getLogger(__name__)
@@ -237,14 +237,5 @@ class PnfDescriptor(object):
 
 
 def send_notification(type, pnfd_info_id, pnfd_id=None, failure_details=None):
-    data = prepare_pnfd_notification(pnfd_info_id=pnfd_info_id,
-                                     pnfd_id=pnfd_id,
-                                     notification_type=type,
-                                     failure_details=failure_details)
-    filters = {
-        'pnfdId': 'pnfdId',
-        'pnfdInfoIds': 'pnfdInfoIds',
-    }
-    logger.debug('Notify request data = %s' % data)
-    logger.debug('Notify request filters = %s' % filters)
-    NotificationsUtil().send_notification(data, filters, False)
+    notify = PnfNotifications(type, pnfd_info_id, pnfd_id, failure_details=failure_details)
+    notify.send_notification()
index be73595..daf2fb2 100644 (file)
@@ -24,7 +24,7 @@ import zipfile
 
 from catalog.packages import const
 from catalog.packages.biz.common import parse_file_range, read, save
-from catalog.packages.biz.notificationsutil import prepare_vnfpkg_notification, NotificationsUtil
+from catalog.packages.biz.notificationsutil import PkgNotifications
 from catalog.pub.config.config import CATALOG_ROOT_PATH
 from catalog.pub.database.models import VnfPackageModel, NSPackageModel
 from catalog.pub.exceptions import CatalogException, ResourceNotFoundException
@@ -293,14 +293,6 @@ def handle_upload_failed(vnf_pkg_id):
 
 
 def send_notification(pkg_id, type, pkg_change_type, operational_state=None):
-    data = prepare_vnfpkg_notification(vnf_pkg_id=pkg_id,
-                                       notification_type=type,
-                                       pkg_change_type=pkg_change_type,
-                                       operational_state=operational_state)
-    filters = {
-        'vnfdId': 'vnfd_id',
-        'vnfPkgId': 'vnf_pkg_id'
-    }
-    logger.debug('Notify request data = %s' % data)
-    logger.debug('Notify request filters = %s' % filters)
-    NotificationsUtil().send_notification(data, filters, True)
+    notify = PkgNotifications(type, pkg_id, change_type=pkg_change_type,
+                              operational_state=operational_state)
+    notify.send_notification()
index 2a73aa3..a0fd495 100644 (file)
@@ -149,12 +149,18 @@ class PkgChangeNotificationSerializer(serializers.Serializer):
         required=True,
         allow_null=False
     )
-    notificationTypes = serializers.ChoiceField(
+    notificationType = serializers.ChoiceField(
         help_text="Discriminator for the different notification types.",
         choices=["VnfPackageChangeNotification"],
         required=True,
         allow_null=False
     )
+    timeStamp = serializers.DateTimeField(
+        help_text="Date-time of the generation of the notification.",
+        format="%Y-%m-%d %H:%M:%S",
+        required=True,
+        allow_null=False
+    )
     subscriptionId = serializers.CharField(
         help_text="Identifier of the subscription that this notification relates to.",
         required=True,
@@ -202,7 +208,7 @@ class PkgOnboardingNotificationSerializer(serializers.Serializer):
         required=True,
         allow_null=False
     )
-    notificationTypes = serializers.ChoiceField(
+    notificationType = serializers.ChoiceField(
         help_text="Discriminator for the different notification types.",
         choices=["VnfPackageOnboardingNotification"],
         required=True,
@@ -213,6 +219,12 @@ class PkgOnboardingNotificationSerializer(serializers.Serializer):
         required=True,
         allow_null=False
     )
+    timeStamp = serializers.DateTimeField(
+        help_text="Date-time of the generation of the notification.",
+        format="%Y-%m-%d %H:%M:%S",
+        required=True,
+        allow_null=False
+    )
     vnfPkgId = serializers.UUIDField(
         help_text="Identifier of the VNF package.",
         required=True,
index 98ad9c1..d1e8770 100644 (file)
@@ -22,7 +22,7 @@ from rest_framework import status
 
 from catalog.packages.biz.nsdm_subscription import NsdmSubscription
 from catalog.pub.database.models import NsdmSubscriptionModel
-from catalog.packages.biz.notificationsutil import NotificationsUtil, prepare_nsd_notification, prepare_pnfd_notification
+from catalog.packages.biz.notificationsutil import NsdNotifications, PnfNotifications
 from catalog.packages import const
 from catalog.pub.config import config as pub_config
 import catalog.pub.utils.timeutil
@@ -607,8 +607,6 @@ class TestNsdmSubscription(TestCase):
             'timeStamp': "nowtime()",
             'nsdInfoId': "d0ea5ec3-0b98-438a-9bea-488230cff174",
             'nsdId': "b632bddc-bccd-4180-bd8d-4e8a9578eff7",
-            'onboardingFailureDetails': None,
-            'nsdOperationalState': None,
             "subscriptionId": "1111",
             '_links': {
                 'subscription': {
@@ -647,14 +645,11 @@ class NotificationTest(TestCase):
     def test_nsdpkg_notify(self, mock_nowtime, mock_uuid, mock_requests_post):
         mock_nowtime.return_value = "nowtime()"
         mock_uuid.return_value = "1111"
-        notification_content = prepare_nsd_notification("nsdinfoid1", "nsdid1",
-                                                        const.NSD_NOTIFICATION_TYPE.NSD_ONBOARDING_FAILURE,
-                                                        "NSD(nsdid1) already exists.", operational_state=None)
-        filters = {
-            'nsdInfoId': 'nsdInfoId',
-            'nsdId': 'nsdId',
-        }
-        NotificationsUtil().send_notification(notification_content, filters, False)
+        notify = NsdNotifications(const.NSD_NOTIFICATION_TYPE.NSD_ONBOARDING_FAILURE,
+                                  nsd_info_id="nsdinfoid1",
+                                  nsd_id="nsdid1",
+                                  failure_details="NSD(nsdid1) already exists.", operational_state=None)
+        notify.send_notification()
         expect_callbackuri = "http://127.0.0.1/self"
         expect_notification = {
             'id': "1111",
@@ -663,7 +658,6 @@ class NotificationTest(TestCase):
             'nsdInfoId': "nsdinfoid1",
             'nsdId': "nsdid1",
             'onboardingFailureDetails': "NSD(nsdid1) already exists.",
-            'nsdOperationalState': None,
             "subscriptionId": "1",
             '_links': {
                 'subscription': {
@@ -687,13 +681,11 @@ class NotificationTest(TestCase):
     def test_pnfpkg_notify(self, mock_nowtime, mock_uuid, mock_requests_post):
         mock_nowtime.return_value = "nowtime()"
         mock_uuid.return_value = "1111"
-        notification_content = prepare_pnfd_notification("pnfdInfoIds1", 'pnfdId1',
-                                                         const.NSD_NOTIFICATION_TYPE.PNFD_ONBOARDING)
-        filters = {
-            'pnfdId': 'pnfdId',
-            'pnfdInfoIds': 'pnfdInfoIds',
-        }
-        NotificationsUtil().send_notification(notification_content, filters, False)
+        notify = PnfNotifications(const.NSD_NOTIFICATION_TYPE.PNFD_ONBOARDING,
+                                  pnfd_info_id="pnfdInfoIds1",
+                                  pnfd_id='pnfdId1',
+                                  failure_details=None)
+        notify.send_notification()
         expect_callbackuri = "http://127.0.0.1/self"
         expect_notification = {
             'id': "1111",
@@ -701,7 +693,6 @@ class NotificationTest(TestCase):
             'timeStamp': "nowtime()",
             'pnfdInfoIds': "pnfdInfoIds1",
             'pnfdId': "pnfdId1",
-            'onboardingFailureDetails': None,
             "subscriptionId": "1",
             '_links': {
                 'subscription': {
index f00e2ac..bc7ee49 100644 (file)
@@ -22,7 +22,7 @@ from django.test import TestCase
 
 from catalog.pub.database.models import VnfPkgSubscriptionModel, VnfPackageModel
 from .const import vnf_subscription_data, vnfd_data
-from catalog.packages.biz.notificationsutil import NotificationsUtil, prepare_vnfpkg_notification
+from catalog.packages.biz.notificationsutil import PkgNotifications
 from catalog.packages import const
 from catalog.pub.config import config as pub_config
 import catalog.pub.utils.timeutil
@@ -197,7 +197,7 @@ class TestNfPackageSubscription(TestCase):
     @mock.patch("uuid.uuid4")
     @mock.patch.object(catalog.pub.utils.timeutil, "now_time")
     def test_vnfpkg_subscript_notify(self, mock_nowtime, mock_uuid, mock_requests_post, mock_parse_vnfd, mock_requests_get):
-        mock_nowtime.return_value = "nowtime()"
+        mock_nowtime.return_value = "2019-02-16 14:41:16"
         uuid_subscriptid = "99442b18-a5c7-11e8-998c-bf1755941f13"
         uuid_vnfPackageId = "3fa85f64-5717-4562-b3fc-2c963f66afa6"
         uuid_vnfdid = "00342b18-a5c7-11e8-998c-bf1755941f12"
@@ -226,7 +226,7 @@ class TestNfPackageSubscription(TestCase):
         expect_notification = {
             'id': "1111",
             'notificationType': const.PKG_NOTIFICATION_TYPE.ONBOARDING,
-            'timeStamp': "nowtime()",
+            'timeStamp': "2019-02-16 14:41:16",
             'vnfPkgId': uuid_vnfPackageId,
             'vnfdId': uuid_vnfdid,
             "subscriptionId": uuid_subscriptid,
@@ -271,20 +271,17 @@ class NotificationTest(TestCase):
                                 vnfd_id="vnfdid1",
                                 vnf_pkg_id="vnfpkgid1"
                                 ).save()
-        mock_nowtime.return_value = "nowtime()"
+        mock_nowtime.return_value = "2019-12-16 14:41:16"
         mock_uuid.return_value = "1111"
-        notification_content = prepare_vnfpkg_notification("vnfpkgid1", const.PKG_NOTIFICATION_TYPE.CHANGE,
-                                                           const.PKG_CHANGE_TYPE.OP_STATE_CHANGE, operational_state=None)
-        filters = {
-            'vnfdId': 'vnfd_id',
-            'vnfPkgId': 'vnf_pkg_id'
-        }
-        NotificationsUtil().send_notification(notification_content, filters, True)
+        notify = PkgNotifications(const.PKG_NOTIFICATION_TYPE.CHANGE, "vnfpkgid1",
+                                  const.PKG_CHANGE_TYPE.OP_STATE_CHANGE, operational_state=None)
+
+        notify.send_notification()
         expect_callbackuri = "http://127.0.0.1/self"
         expect_notification = {
             'id': "1111",
             'notificationType': const.PKG_NOTIFICATION_TYPE.CHANGE,
-            'timeStamp': "nowtime()",
+            'timeStamp': "2019-12-16 14:41:16",
             'vnfPkgId': "vnfpkgid1",
             'vnfdId': "vnfdid1",
             'changeType': const.PKG_CHANGE_TYPE.OP_STATE_CHANGE,
index 9f0b498..950d667 100644 (file)
@@ -198,6 +198,9 @@ class NsdmSubscriptionModel(models.Model):
         import json
         return json.dumps(dict([(attr, getattr(self, attr)) for attr in [f.name for f in self._meta.fields]]))
 
+    def get_subscription_id(self):
+        return self.subscriptionid
+
 
 class VnfPkgSubscriptionModel(models.Model):
     subscription_id = models.CharField(max_length=255, primary_key=True, db_column='SUBSCRIPTION_ID')
@@ -232,3 +235,6 @@ class VnfPkgSubscriptionModel(models.Model):
         }
         subscription_obj["filter"] = filter_obj
         return subscription_obj
+
+    def get_subscription_id(self):
+        return self.subscription_id
index b42d9dd..104ac97 100644 (file)
@@ -1 +1 @@
-{"swagger": "2.0", "info": {"title": "Modeling etsicatalog API", "description": "\n\nThe `swagger-ui` view can be found [here](/api/catalog/v1/swagger).\nThe `ReDoc` view can be found [here](/api/catalog/v1/redoc).\nThe swagger YAML document can be found [here](/api/catalog/v1/swagger.yaml).\nThe swagger JSON document can be found [here](/api/catalog/v1/swagger.json).", "version": "v1"}, "host": "127.0.0.1:8000", "schemes": ["http"], "basePath": "/", "consumes": ["application/json"], "produces": ["application/json"], "securityDefinitions": {"Basic": {"type": "basic"}}, "security": [{"Basic": []}], "paths": {"/URI-is-provided-by-the-client-when-creating-the-subscription-VnfPackageChangeNotification": {"get": {"operationId": "URI-is-provided-by-the-client-when-creating-the-subscription-VnfPackageChangeNotification_list", "description": "", "parameters": [], "responses": {"204": {"description": ""}, "500": {"description": "error message", "schema": {"type": "string"}}}, "tags": ["VNF Package Management interface"]}, "post": {"operationId": "URI-is-provided-by-the-client-when-creating-the-subscription-VnfPackageChangeNotification_create", "description": "", "parameters": [{"name": "data", "in": "body", "required": true, "schema": {"$ref": "#/definitions/PkgChangeNotification"}}], "responses": {"204": {"description": ""}}, "tags": ["VNF Package Management interface"]}, "parameters": []}, "/URI-is-provided-by-the-client-when-creating-the-subscription-VnfPackageOnboardingNotification": {"get": {"operationId": "URI-is-provided-by-the-client-when-creating-the-subscription-VnfPackageOnboardingNotification_list", "description": "", "parameters": [], "responses": {"204": {"description": ""}, "500": {"description": "error message", "schema": {"type": "string"}}}, "tags": ["VNF Package Management interface"]}, "post": {"operationId": "URI-is-provided-by-the-client-when-creating-the-subscription-VnfPackageOnboardingNotification_create", "description": "", "parameters": [{"name": "data", "in": "body", "required": true, "schema": {"$ref": "#/definitions/PkgOnboardingNotification"}}], "responses": {"204": {"description": ""}}, "tags": ["VNF Package Management interface"]}, "parameters": []}}, "definitions": {"NOTIFICATION_LINKSERIALIZER": {"title": "Vnfpackage", "description": "Link to the resource representing the VNF package to which the notified change applies.", "required": ["href"], "type": "object", "properties": {"href": {"title": "Href", "description": "URI of the referenced resource.", "type": "string", "minLength": 1}}}, "PkgmLinks": {"title": " links", "description": "Links to resources related to this resource.", "type": "object", "properties": {"vnfPackage": {"$ref": "#/definitions/NOTIFICATION_LINKSERIALIZER"}, "subscription": {"$ref": "#/definitions/NOTIFICATION_LINKSERIALIZER"}}}, "PkgChangeNotification": {"required": ["id", "notificationTypes", "subscriptionId", "vnfPkgId", "changeType", "vnfdId", "_links"], "type": "object", "properties": {"id": {"title": "Id", "description": "Identifier of this notification.", "type": "string", "minLength": 1}, "notificationTypes": {"title": "Notificationtypes", "description": "Discriminator for the different notification types.", "type": "string", "enum": ["VnfPackageChangeNotification"]}, "subscriptionId": {"title": "Subscriptionid", "description": "Identifier of the subscription that this notification relates to.", "type": "string", "minLength": 1}, "vnfPkgId": {"title": "Vnfpkgid", "description": "Identifier of the VNF package.", "type": "string", "format": "uuid"}, "changeType": {"title": "Changetype", "description": "The type of change of the VNF package.", "type": "string", "enum": ["OP_STATE_CHANGE", "PKG_DELETE"]}, "operationalState": {"title": "Operationalstate", "description": "New operational state of the VNF package.", "type": "string", "enum": ["ENABLED", "DISABLED"]}, "vnfdId": {"title": "Vnfdid", "description": "This identifier, which is managed by the VNF provider, identifies the VNF package and the VNFD in a globally unique way.", "type": "string", "minLength": 1}, "_links": {"$ref": "#/definitions/PkgmLinks"}}}, "PkgOnboardingNotification": {"required": ["id", "notificationTypes", "subscriptionId", "vnfPkgId", "vnfdId", "_links"], "type": "object", "properties": {"id": {"title": "Id", "description": "Identifier of this notification.", "type": "string", "minLength": 1}, "notificationTypes": {"title": "Notificationtypes", "description": "Discriminator for the different notification types.", "type": "string", "enum": ["VnfPackageOnboardingNotification"]}, "subscriptionId": {"title": "Subscriptionid", "description": "Identifier of the subscription that this notification relates to.", "type": "string", "minLength": 1}, "vnfPkgId": {"title": "Vnfpkgid", "description": "Identifier of the VNF package.", "type": "string", "format": "uuid"}, "vnfdId": {"title": "Vnfdid", "description": "This identifier, which is managed by the VNF provider, identifies the VNF package and the VNFD in a globally unique way.", "type": "string", "format": "uuid"}, "_links": {"$ref": "#/definitions/PkgmLinks"}}}}}
\ No newline at end of file
+{"swagger": "2.0", "info": {"title": "Modeling etsicatalog API", "description": "\n\nThe `swagger-ui` view can be found [here](/api/catalog/v1/swagger).\nThe `ReDoc` view can be found [here](/api/catalog/v1/redoc).\nThe swagger YAML document can be found [here](/api/catalog/v1/swagger.yaml).\nThe swagger JSON document can be found [here](/api/catalog/v1/swagger.json).", "version": "v1"}, "host": "127.0.0.1:8000", "schemes": ["http"], "basePath": "/", "consumes": ["application/json"], "produces": ["application/json"], "securityDefinitions": {"Basic": {"type": "basic"}}, "security": [{"Basic": []}], "paths": {"/URI-is-provided-by-the-client-when-creating-the-subscription-VnfPackageChangeNotification": {"get": {"operationId": "URI-is-provided-by-the-client-when-creating-the-subscription-VnfPackageChangeNotification_list", "description": "", "parameters": [], "responses": {"204": {"description": ""}, "500": {"description": "error message", "schema": {"type": "string"}}}, "tags": ["VNF Package Management interface"]}, "post": {"operationId": "URI-is-provided-by-the-client-when-creating-the-subscription-VnfPackageChangeNotification_create", "description": "", "parameters": [{"name": "data", "in": "body", "required": true, "schema": {"$ref": "#/definitions/PkgChangeNotification"}}], "responses": {"204": {"description": ""}}, "tags": ["VNF Package Management interface"]}, "parameters": []}, "/URI-is-provided-by-the-client-when-creating-the-subscription-VnfPackageOnboardingNotification": {"get": {"operationId": "URI-is-provided-by-the-client-when-creating-the-subscription-VnfPackageOnboardingNotification_list", "description": "", "parameters": [], "responses": {"204": {"description": ""}, "500": {"description": "error message", "schema": {"type": "string"}}}, "tags": ["VNF Package Management interface"]}, "post": {"operationId": "URI-is-provided-by-the-client-when-creating-the-subscription-VnfPackageOnboardingNotification_create", "description": "", "parameters": [{"name": "data", "in": "body", "required": true, "schema": {"$ref": "#/definitions/PkgOnboardingNotification"}}], "responses": {"204": {"description": ""}}, "tags": ["VNF Package Management interface"]}, "parameters": []}}, "definitions": {"NOTIFICATION_LINKSERIALIZER": {"title": "Vnfpackage", "description": "Link to the resource representing the VNF package to which the notified change applies.", "required": ["href"], "type": "object", "properties": {"href": {"title": "Href", "description": "URI of the referenced resource.", "type": "string", "minLength": 1}}}, "PkgmLinks": {"title": " links", "description": "Links to resources related to this resource.", "type": "object", "properties": {"vnfPackage": {"$ref": "#/definitions/NOTIFICATION_LINKSERIALIZER"}, "subscription": {"$ref": "#/definitions/NOTIFICATION_LINKSERIALIZER"}}}, "PkgChangeNotification": {"required": ["id", "notificationType", "timeStamp", "subscriptionId", "vnfPkgId", "changeType", "vnfdId", "_links"], "type": "object", "properties": {"id": {"title": "Id", "description": "Identifier of this notification.", "type": "string", "minLength": 1}, "notificationType": {"title": "Notificationtype", "description": "Discriminator for the different notification types.", "type": "string", "enum": ["VnfPackageChangeNotification"]}, "timeStamp": {"title": "Timestamp", "description": "Date-time of the generation of the notification.", "type": "string", "format": "date-time"}, "subscriptionId": {"title": "Subscriptionid", "description": "Identifier of the subscription that this notification relates to.", "type": "string", "minLength": 1}, "vnfPkgId": {"title": "Vnfpkgid", "description": "Identifier of the VNF package.", "type": "string", "format": "uuid"}, "changeType": {"title": "Changetype", "description": "The type of change of the VNF package.", "type": "string", "enum": ["OP_STATE_CHANGE", "PKG_DELETE"]}, "operationalState": {"title": "Operationalstate", "description": "New operational state of the VNF package.", "type": "string", "enum": ["ENABLED", "DISABLED"]}, "vnfdId": {"title": "Vnfdid", "description": "This identifier, which is managed by the VNF provider, identifies the VNF package and the VNFD in a globally unique way.", "type": "string", "minLength": 1}, "_links": {"$ref": "#/definitions/PkgmLinks"}}}, "PkgOnboardingNotification": {"required": ["id", "notificationType", "subscriptionId", "timeStamp", "vnfPkgId", "vnfdId", "_links"], "type": "object", "properties": {"id": {"title": "Id", "description": "Identifier of this notification.", "type": "string", "minLength": 1}, "notificationType": {"title": "Notificationtype", "description": "Discriminator for the different notification types.", "type": "string", "enum": ["VnfPackageOnboardingNotification"]}, "subscriptionId": {"title": "Subscriptionid", "description": "Identifier of the subscription that this notification relates to.", "type": "string", "minLength": 1}, "timeStamp": {"title": "Timestamp", "description": "Date-time of the generation of the notification.", "type": "string", "format": "date-time"}, "vnfPkgId": {"title": "Vnfpkgid", "description": "Identifier of the VNF package.", "type": "string", "format": "uuid"}, "vnfdId": {"title": "Vnfdid", "description": "This identifier, which is managed by the VNF provider, identifies the VNF package and the VNFD in a globally unique way.", "type": "string", "format": "uuid"}, "_links": {"$ref": "#/definitions/PkgmLinks"}}}}}
\ No newline at end of file
diff --git a/tox.ini b/tox.ini
index 3745940..f9b7824 100644 (file)
--- a/tox.ini
+++ b/tox.ini
@@ -22,5 +22,5 @@ commands =
   {[testenv]commands}
 
 [testenv:cov]
-deps = coverage
+deps = coverage==4.2
 commands = coverage xml --omit="*test*,*__init__.py,*site-packages*"