Repository: softlayer/softlayer-python
Pull request #1268 (2020-04-29 22:31:59)

fix the isue 1262
https://github.com/softlayer/softlayer-python/issues/1262


Patch:
diff --git a/SoftLayer/CLI/account/events.py b/SoftLayer/CLI/account/events.py
index b5d8960c..5cc91144 100644
--- a/SoftLayer/CLI/account/events.py
+++ b/SoftLayer/CLI/account/events.py
@@ -16,90 +16,39 @@ def cli(env, ack_all):
     """Summary and acknowledgement of upcoming and ongoing maintenance events"""
 
     manager = AccountManager(env.client)
-    planned_events = manager.get_upcoming_events("PLANNED")
-    unplanned_events = manager.get_upcoming_events("UNPLANNED_INCIDENT")
-    announcement_events = manager.get_upcoming_events("ANNOUNCEMENT")
+    events = manager.get_upcoming_events()
 
-    add_ack_flag(planned_events, manager, ack_all)
-    env.fout(planned_event_table(planned_events))
-
-    add_ack_flag(unplanned_events, manager, ack_all)
-    env.fout(unplanned_event_table(unplanned_events))
-
-    add_ack_flag(announcement_events, manager, ack_all)
-    env.fout(announcement_event_table(announcement_events))
-
-
-def add_ack_flag(events, manager, ack_all):
-    """Add acknowledgedFlag to the event"""
     if ack_all:
         for event in events:
             result = manager.ack_event(event['id'])
             event['acknowledgedFlag'] = result
+    env.fout(event_table(events))
 
 
-def planned_event_table(events):
+def event_table(events):
     """Formats a table for events"""
-    planned_table = formatting.Table(['Event Data', 'Id', 'Event ID', 'Subject', 'Status', 'Items', 'Start Date',
-                                      'End Date', 'Acknowledged', 'Updates'], title="Planned Events")
-    planned_table.align['Subject'] = 'l'
-    planned_table.align['Impacted Resources'] = 'l'
+    table = formatting.Table([
+        "Id",
+        "Start Date",
+        "End Date",
+        "Subject",
+        "Status",
+        "Acknowledged",
+        "Updates",
+        "Impacted Resources"
+    ], title="Upcoming Events")
+    table.align['Subject'] = 'l'
+    table.align['Impacted Resources'] = 'l'
     for event in events:
-        planned_table.add_row([
-            utils.clean_time(event.get('startDate')),
+        table.add_row([
             event.get('id'),
-            event.get('systemTicketId'),
-            # Some subjects can have \r\n for some reason.
-            utils.clean_splitlines(event.get('subject')),
-            utils.lookup(event, 'statusCode', 'name'),
-            event.get('impactedResourceCount'),
             utils.clean_time(event.get('startDate')),
             utils.clean_time(event.get('endDate')),
-            event.get('acknowledgedFlag'),
-            event.get('updateCount'),
-
-        ])
-    return planned_table
-
-
-def unplanned_event_table(events):
-    """Formats a table for events"""
-    unplanned_table = formatting.Table(['Id', 'Event ID', 'Subject', 'Status', 'Items', 'Start Date',
-                                        'Last Updated', 'Acknowledged', 'Updates'], title="Unplanned Events")
-    unplanned_table.align['Subject'] = 'l'
-    unplanned_table.align['Impacted Resources'] = 'l'
-    for event in events:
-        print(event.get('modifyDate'))
-        unplanned_table.add_row([
-            event.get('id'),
-            event.get('systemTicketId'),
             # Some subjects can have \r\n for some reason.
             utils.clean_splitlines(event.get('subject')),
             utils.lookup(event, 'statusCode', 'name'),
-            event.get('impactedResourceCount'),
-            utils.clean_time(event.get('startDate')),
-            utils.clean_time(event.get('modifyDate')),
             event.get('acknowledgedFlag'),
             event.get('updateCount'),
+            event.get('impactedResourceCount')
         ])
-    return unplanned_table
-
-
-def announcement_event_table(events):
-    """Formats a table for events"""
-    announcement_table = formatting.Table(
-        ['Id', 'Event ID', 'Subject', 'Status', 'Items', 'Acknowledged', 'Updates'], title="Announcement Events")
-    announcement_table.align['Subject'] = 'l'
-    announcement_table.align['Impacted Resources'] = 'l'
-    for event in events:
-        announcement_table.add_row([
-            event.get('id'),
-            event.get('systemTicketId'),
-            # Some subjects can have \r\n for some reason.
-            utils.clean_splitlines(event.get('subject')),
-            utils.lookup(event, 'statusCode', 'name'),
-            event.get('impactedResourceCount'),
-            event.get('acknowledgedFlag'),
-            event.get('updateCount')
-        ])
-    return announcement_table
+    return table
diff --git a/SoftLayer/managers/account.py b/SoftLayer/managers/account.py
index 56f951c2..4269bc7a 100644
--- a/SoftLayer/managers/account.py
+++ b/SoftLayer/managers/account.py
@@ -47,61 +47,25 @@ def get_summary(self):
         """
         return self.client.call('Account', 'getObject', mask=mask)
 
-    def get_upcoming_events(self, event_type):
-        """Retrieves a list of Notification_Occurrence_Events that have not ended yet
+    def get_upcoming_events(self):
+        """Retreives a list of Notification_Occurrence_Events that have not ended yet
 
-        :param: String event_type: notification event type.
         :return: SoftLayer_Notification_Occurrence_Event
         """
-        mask = "mask[id, subject, startDate, endDate, modifyDate, statusCode, acknowledgedFlag, " \
-               "impactedResourceCount, updateCount, systemTicketId, notificationOccurrenceEventType[keyName]]"
-
+        mask = "mask[id, subject, startDate, endDate, statusCode, acknowledgedFlag, impactedResourceCount, updateCount]"
         _filter = {
-            'notificationOccurrenceEventType': {
-                'keyName': {
-                    'operation': event_type
-                }
-            }
-        }
-
-        self.add_event_filter(_filter, event_type)
-
-        return self.client.call('Notification_Occurrence_Event', 'getAllObjects', filter=_filter, mask=mask, iter=True)
-
-    @staticmethod
-    def add_event_filter(_filter, event_type):
-        """Add data to the object filter.
-
-        :param: _filter: event filter.
-        :param: string event_type: event type.
-        """
-        if event_type == 'PLANNED':
-            _filter['endDate'] = {
-                'operation': '> sysdate - 2'
-            }
-            _filter['startDate'] = {
+            'endDate': {
+                'operation': '> sysdate'
+            },
+            'startDate': {
                 'operation': 'orderBy',
                 'options': [{
                     'name': 'sort',
-                    'value': ['DESC']
+                    'value': ['ASC']
                 }]
             }
-
-        if event_type == 'UNPLANNED_INCIDENT':
-            _filter['modifyDate'] = {
-                'operation': '> sysdate - 2'
-            }
-
-        if event_type == 'ANNOUNCEMENT':
-            _filter['statusCode'] = {
-                'keyName': {
-                    'operation': 'in',
-                    'options': [{
-                        'name': 'data',
-                        'value': ['PUBLISHED']
-                    }]
-                }
-            }
+        }
+        return self.client.call('Notification_Occurrence_Event', 'getAllObjects', filter=_filter, mask=mask, iter=True)
 
     def ack_event(self, event_id):
         """Acknowledge an event. This mostly prevents it from appearing as a notification in the control portal.
diff --git a/SoftLayer/managers/dedicated_host.py b/SoftLayer/managers/dedicated_host.py
index 89246da2..86258416 100644
--- a/SoftLayer/managers/dedicated_host.py
+++ b/SoftLayer/managers/dedicated_host.py
@@ -5,10 +5,10 @@
 
     :license: MIT, see License for more details.
 """
+
 import logging
+import SoftLayer
 
-from SoftLayer.exceptions import SoftLayerAPIError
-from SoftLayer.exceptions import SoftLayerError
 from SoftLayer.managers import ordering
 from SoftLayer import utils
 
@@ -395,7 +395,7 @@ def _get_location(self, regions, datacenter):
             if region['location']['location']['name'] == datacenter:
                 return region
 
-        raise SoftLayerError("Could not find valid location for: '%s'" % datacenter)
+        raise SoftLayer.SoftLayerError("Could not find valid location for: '%s'" % datacenter)
 
     def get_create_options(self):
         """Returns valid options for ordering a dedicated host."""
@@ -426,7 +426,7 @@ def _get_price(self, package):
             if not price.get('locationGroupId'):
                 return price['id']
 
-        raise SoftLayerError("Could not find valid price")
+        raise SoftLayer.SoftLayerError("Could not find valid price")
 
     def _get_item(self, package, flavor):
         """Returns the item for ordering a dedicated host."""
@@ -435,7 +435,7 @@ def _get_item(self, package, flavor):
             if item['keyName'] == flavor:
                 return item
 
-        raise SoftLayerError("Could not find valid item for: '%s'" % flavor)
+        raise SoftLayer.SoftLayerError("Could not find valid item for: '%s'" % flavor)
 
     def _get_backend_router(self, locations, item):
         """Returns valid router options for ordering a dedicated host."""
@@ -495,7 +495,7 @@ def _get_backend_router(self, locations, item):
                     routers = self.host.getAvailableRouters(host, mask=mask)
                     return routers
 
-        raise SoftLayerError("Could not find available routers")
+        raise SoftLayer.SoftLayerError("Could not find available routers")
 
     def _get_default_router(self, routers, router_name=None):
         """Returns the default router for ordering a dedicated host."""
@@ -508,7 +508,7 @@ def _get_default_router(self, routers, router_name=None):
                 if router['hostname'] == router_name:
                     return router['id']
 
-        raise SoftLayerError("Could not find valid default router")
+        raise SoftLayer.SoftLayerError("Could not find valid default router")
 
     def get_router_options(self, datacenter=None, flavor=None):
         """Returns available backend routers for the dedicated host."""
@@ -524,7 +524,7 @@ def _delete_guest(self, guest_id):
         msg = 'Cancelled'
         try:
             self.guest.deleteObject(id=guest_id)
-        except SoftLayerAPIError as e:
+        except SoftLayer.SoftLayerAPIError as e:
             msg = 'Exception: ' + e.faultString
 
         return msg
diff --git a/SoftLayer/managers/hardware.py b/SoftLayer/managers/hardware.py
index 9d7cbf3f..99ab45b9 100644
--- a/SoftLayer/managers/hardware.py
+++ b/SoftLayer/managers/hardware.py
@@ -9,10 +9,9 @@
 import socket
 import time
 
+import SoftLayer
 from SoftLayer.decoration import retry
-from SoftLayer.exceptions import SoftLayerError
 from SoftLayer.managers import ordering
-from SoftLayer.managers.ticket import TicketManager
 from SoftLayer import utils
 
 LOGGER = logging.getLogger(__name__)
@@ -78,18 +77,19 @@ def cancel_hardware(self, hardware_id, reason='unneeded', comment='', immediate=
         # Get cancel reason
         reasons = self.get_cancellation_reasons()
         cancel_reason = reasons.get(reason, reasons['unneeded'])
-        ticket_mgr = TicketManager(self.client)
+        ticket_mgr = SoftLayer.TicketManager(self.client)
         mask = 'mask[id, hourlyBillingFlag, billingItem[id], openCancellationTicket[id], activeTransaction]'
         hw_billing = self.get_hardware(hardware_id, mask=mask)
 
         if 'activeTransaction' in hw_billing:
-            raise SoftLayerError("Unable to cancel hardware with running transaction")
+            raise SoftLayer.SoftLayerError("Unable to cancel hardware with running transaction")
 
         if 'billingItem' not in hw_billing:
             if utils.lookup(hw_billing, 'openCancellationTicket', 'id'):
-                raise SoftLayerError("Ticket #%s already exists for this server" %
-                                     hw_billing['openCancellationTicket']['id'])
-            raise SoftLayerError("Cannot locate billing for the server. The server may already be cancelled.")
+                raise SoftLayer.SoftLayerError("Ticket #%s already exists for this server" %
+                                               hw_billing['openCancellationTicket']['id'])
+            raise SoftLayer.SoftLayerError("Cannot locate billing for the server. "
+                                           "The server may already be cancelled.")
 
         billing_id = hw_billing['billingItem']['id']
 
@@ -744,7 +744,7 @@ def _get_extra_price_id(items, key_name, hourly, location):
 
             return price['id']
 
-    raise SoftLayerError(
+    raise SoftLayer.SoftLayerError(
         "Could not find valid price for extra option, '%s'" % key_name)
 
 
@@ -762,7 +762,7 @@ def _get_default_price_id(items, option, hourly, location):
                     _matches_location(price, location)]):
                 return price['id']
 
-    raise SoftLayerError(
+    raise SoftLayer.SoftLayerError(
         "Could not find valid price for '%s' option" % option)
 
 
@@ -792,7 +792,7 @@ def _get_bandwidth_price_id(items,
 
             return price['id']
 
-    raise SoftLayerError(
+    raise SoftLayer.SoftLayerError(
         "Could not find valid price for bandwidth option")
 
 
@@ -800,8 +800,11 @@ def _get_os_price_id(items, os, location):
     """Returns the price id matching."""
 
     for item in items:
-        if any([utils.lookup(item, 'itemCategory', 'categoryCode') != 'os',
-                utils.lookup(item, 'keyName') != os]):
+        if any([utils.lookup(item,
+                             'itemCategory',
+                             'categoryCode') != 'os',
+                utils.lookup(item,
+                             'keyName') != os]):
             continue
 
         for price in item['prices']:
@@ -810,14 +813,17 @@ def _get_os_price_id(items, os, location):
 
             return price['id']
 
-    raise SoftLayerError("Could not find valid price for os: '%s'" % os)
+    raise SoftLayer.SoftLayerError("Could not find valid price for os: '%s'" %
+                                   os)
 
 
 def _get_port_speed_price_id(items, port_speed, no_public, location):
     """Choose a valid price id for port speed."""
 
     for item in items:
-        if utils.lookup(item, 'itemCategory', 'categoryCode') != 'port_speed':
+        if utils.lookup(item,
+                        'itemCategory',
+                        'categoryCode') != 'port_speed':
             continue
 
         # Check for correct capacity and if the item matches private only
@@ -832,7 +838,7 @@ def _get_port_speed_price_id(items, port_speed, no_public, location):
 
             return price['id']
 
-    raise SoftLayerError(
+    raise SoftLayer.SoftLayerError(
         "Could not find valid price for port speed: '%s'" % port_speed)
 
 
@@ -881,7 +887,7 @@ def _get_location(package, location):
         if region['location']['location']['name'] == location:
             return region
 
-    raise SoftLayerError("Could not find valid location for: '%s'" % location)
+    raise SoftLayer.SoftLayerError("Could not find valid location for: '%s'" % location)
 
 
 def _get_preset_id(package, size):
@@ -890,4 +896,4 @@ def _get_preset_id(package, size):
         if preset['keyName'] == size or preset['id'] == size:
             return preset['id']
 
-    raise SoftLayerError("Could not find valid size for: '%s'" % size)
+    raise SoftLayer.SoftLayerError("Could not find valid size for: '%s'" % size)
diff --git a/SoftLayer/managers/metadata.py b/SoftLayer/managers/metadata.py
index 13f350ad..cdc02151 100644
--- a/SoftLayer/managers/metadata.py
+++ b/SoftLayer/managers/metadata.py
@@ -5,7 +5,7 @@
 
     :license: MIT, see LICENSE for more details.
 """
-from SoftLayer.API import BaseClient
+import SoftLayer
 from SoftLayer import consts
 from SoftLayer import exceptions
 from SoftLayer import transports
@@ -66,7 +66,7 @@ def __init__(self, client=None, timeout=5):
                 timeout=timeout,
                 endpoint_url=consts.API_PRIVATE_ENDPOINT_REST,
             )
-            client = BaseClient(transport=transport)
+            client = SoftLayer.BaseClient(transport=transport)
 
         self.client = client
 
diff --git a/SoftLayer/managers/ordering.py b/SoftLayer/managers/ordering.py
index 7e4e81db..b5e659ee 100644
--- a/SoftLayer/managers/ordering.py
+++ b/SoftLayer/managers/ordering.py
@@ -251,14 +251,13 @@ def list_categories(self, package_keyname, **kwargs):
         :param str package_keyname: The package for which to get the categories.
         :returns: List of categories associated with the package
         """
-        get_kwargs = {}
-        get_kwargs['mask'] = kwargs.get('mask', CATEGORY_MASK)
+        kwargs['mask'] = kwargs.get('mask', CATEGORY_MASK)
 
         if 'filter' in kwargs:
-            get_kwargs['filter'] = kwargs['filter']
+            kwargs['filter'] = kwargs['filter']
 
         package = self.get_package_by_key(package_keyname, mask='id')
-        categories = self.package_svc.getConfiguration(id=package['id'], **get_kwargs)
+        categories = self.package_svc.getConfiguration(id=package['id'], **kwargs)
         return categories
 
     def list_items(self, package_keyname, **kwargs):
@@ -268,14 +267,11 @@ def list_items(self, package_keyname, **kwargs):
         :returns: List of items in the package
 
         """
-        get_kwargs = {}
-        get_kwargs['mask'] = kwargs.get('mask', ITEM_MASK)
-
-        if 'filter' in kwargs:
-            get_kwargs['filter'] = kwargs['filter']
+        if 'mask' not in kwargs:
+            kwargs['mask'] = ITEM_MASK
 
         package = self.get_package_by_key(package_keyname, mask='id')
-        items = self.package_svc.getItems(id=package['id'], **get_kwargs)
+        items = self.package_svc.getItems(id=package['id'], **kwargs)
         return items
 
     def list_packages(self, **kwargs):
@@ -284,13 +280,12 @@ def list_packages(self, **kwargs):
         :returns: List of active packages.
 
         """
-        get_kwargs = {}
-        get_kwargs['mask'] = kwargs.get('mask', PACKAGE_MASK)
+        kwargs['mask'] = kwargs.get('mask', PACKAGE_MASK)
 
         if 'filter' in kwargs:
-            get_kwargs['filter'] = kwargs['filter']
+            kwargs['filter'] = kwargs['filter']
 
-        packages = self.package_svc.getAllObjects(**get_kwargs)
+        packages = self.package_svc.getAllObjects(**kwargs)
 
         return [package for package in packages if package['isActive']]
 
@@ -301,15 +296,15 @@ def list_presets(self, package_keyname, **kwargs):
         :returns: A list of package presets that can be used for ordering
 
         """
-        get_kwargs = {}
-        get_kwargs['mask'] = kwargs.get('mask', PRESET_MASK)
+
+        kwargs['mask'] = kwargs.get('mask', PRESET_MASK)
 
         if 'filter' in kwargs:
-            get_kwargs['filter'] = kwargs['filter']
+            kwargs['filter'] = kwargs['filter']
 
         package = self.get_package_by_key(package_keyname, mask='id')
-        acc_presets = self.package_svc.getAccountRestrictedActivePresets(id=package['id'], **get_kwargs)
-        active_presets = self.package_svc.getActivePresets(id=package['id'], **get_kwargs)
+        acc_presets = self.package_svc.getAccountRestrictedActivePresets(id=package['id'], **kwargs)
+        active_presets = self.package_svc.getActivePresets(id=package['id'], **kwargs)
         return active_presets + acc_presets
 
     def get_preset_by_key(self, package_keyname, preset_keyname, mask=None):
diff --git a/SoftLayer/managers/vs_capacity.py b/SoftLayer/managers/vs_capacity.py
index 3f6574f1..c2be6a61 100644
--- a/SoftLayer/managers/vs_capacity.py
+++ b/SoftLayer/managers/vs_capacity.py
@@ -7,8 +7,8 @@
 """
 
 import logging
+import SoftLayer
 
-from SoftLayer.exceptions import SoftLayerError
 from SoftLayer.managers import ordering
 from SoftLayer.managers.vs import VSManager
 from SoftLayer import utils
@@ -144,7 +144,7 @@ def create_guest(self, capacity_id, test, guest_object):
             capacity_flavor = capacity['instances'][0]['billingItem']['item']['keyName']
             flavor = _flavor_string(capacity_flavor, guest_object['primary_disk'])
         except KeyError:
-            raise SoftLayerError("Unable to find capacity Flavor.")
+            raise SoftLayer.SoftLayerError("Unable to find capacity Flavor.")
 
         guest_object['flavor'] = flavor
         guest_object['datacenter'] = capacity['backendRouter']['datacenter']['name']


Test patch:
diff --git a/tests/managers/account_tests.py b/tests/managers/account_tests.py
index b47ec6ab..513aa44f 100644
--- a/tests/managers/account_tests.py
+++ b/tests/managers/account_tests.py
@@ -18,51 +18,10 @@ def test_get_summary(self):
         self.manager.get_summary()
         self.assert_called_with('SoftLayer_Account', 'getObject')
 
-    def test_get_planned_upcoming_events(self):
-        self.manager.get_upcoming_events("PLANNED")
+    def test_get_upcoming_events(self):
+        self.manager.get_upcoming_events()
         self.assert_called_with(self.SLNOE, 'getAllObjects')
 
-    def test_get_unplanned_upcoming_events(self):
-        self.manager.get_upcoming_events("UNPLANNED_INCIDENT")
-        self.assert_called_with(self.SLNOE, 'getAllObjects')
-
-    def test_get_announcement_upcoming_events(self):
-        self.manager.get_upcoming_events("ANNOUNCEMENT")
-        self.assert_called_with(self.SLNOE, 'getAllObjects')
-
-    def test_add_planned_event_filter(self):
-        event_type = 'PLANNED'
-        _filter = {
-            'notificationOccurrenceEventType': {
-                'keyName': {
-                    'operation': event_type
-                }
-            }
-        }
-        self.manager.add_event_filter(_filter, event_type)
-
-    def test_add_unplanned_event_filter(self):
-        event_type = 'UNPLANNED_INCIDENT'
-        _filter = {
-            'notificationOccurrenceEventType': {
-                'keyName': {
-                    'operation': event_type
-                }
-            }
-        }
-        self.manager.add_event_filter(_filter, event_type)
-
-    def test_add_announcement_event_filter(self):
-        event_type = 'ANNOUNCEMENT'
-        _filter = {
-            'notificationOccurrenceEventType': {
-                'keyName': {
-                    'operation': event_type
-                }
-            }
-        }
-        self.manager.add_event_filter(_filter, event_type)
-
     def test_ack_event(self):
         self.manager.ack_event(12345)
         self.assert_called_with(self.SLNOE, 'acknowledgeNotification', identifier=12345)