]> git-server-git.apps.pok.os.sepia.ceph.com Git - ceph-ci.git/commitdiff
mgr/dashboard: increase API test coverage in API controllers
authorAashish Sharma <aashishsharma@localhost.localdomain>
Mon, 6 Jul 2020 08:03:33 +0000 (13:33 +0530)
committerAashish Sharma <aashishsharma@localhost.localdomain>
Mon, 6 Jul 2020 08:03:33 +0000 (13:33 +0530)
Added test cases for the missing endpoints

Fixes: https://tracker.ceph.com/issues/45901
Signed-off-by: Aashish Sharma <aasharma@redhat.com>
src/pybind/mgr/dashboard/controllers/cephfs.py
src/pybind/mgr/dashboard/controllers/host.py
src/pybind/mgr/dashboard/controllers/nfsganesha.py
src/pybind/mgr/dashboard/controllers/orchestrator.py
src/pybind/mgr/dashboard/controllers/osd.py
src/pybind/mgr/dashboard/controllers/rgw.py
src/pybind/mgr/dashboard/controllers/settings.py
src/pybind/mgr/dashboard/controllers/summary.py
src/pybind/mgr/dashboard/module.py

index 1f08090fd0ffea8ee4764408a423fd6fbdf67c07..5330b76d415e82753f20cdb3584410c4e91b556e 100644 (file)
@@ -19,7 +19,7 @@ from ..tools import ViewCache
 
 @ApiController('/cephfs', Scope.CEPHFS)
 class CephFS(RESTController):
-    def __init__(self): #pragma: no cover
+    def __init__(self):  # pragma: no cover
         super(CephFS, self).__init__()
 
         # Stateful instances of CephFSClients, hold cached results.  Key to
@@ -179,7 +179,7 @@ class CephFS(RESTController):
                                                     info['name'],
                                                     "mds_server.handle_client_request")
                 else:
-                    activity = 0.0 #pragma: no cover
+                    activity = 0.0  # pragma: no cover
 
                 self._append_mds_metadata(mds_versions, info['name'])
                 rank_table.append(
@@ -285,15 +285,15 @@ class CephFS(RESTController):
         # indepdendent of whether it's a kernel or userspace
         # client, so that the javascript doesn't have to grok that.
         for client in clients:
-            if "ceph_version" in client['client_metadata']: #pragma: no cover - no complexity there
+            if "ceph_version" in client['client_metadata']:  # pragma: no cover - no complexity
                 client['type'] = "userspace"
                 client['version'] = client['client_metadata']['ceph_version']
                 client['hostname'] = client['client_metadata']['hostname']
-            elif "kernel_version" in client['client_metadata']: #pragma: no cover - no complexity there
+            elif "kernel_version" in client['client_metadata']:  # pragma: no cover - no complexity
                 client['type'] = "kernel"
                 client['version'] = client['client_metadata']['kernel_version']
                 client['hostname'] = client['client_metadata']['hostname']
-            else: #pragma: no cover - no complexity there
+            else:  # pragma: no cover - no complexity there
                 client['type'] = "unknown"
                 client['version'] = ""
                 client['hostname'] = ""
@@ -334,7 +334,7 @@ class CephFS(RESTController):
         """
         try:
             return self._get_root_directory(self._cephfs_instance(fs_id))
-        except (cephfs.PermissionError, cephfs.ObjectNotFound): #pragma: no cover - the handling is too obvious
+        except (cephfs.PermissionError, cephfs.ObjectNotFound):  # pragma: no cover
             return None
 
     def _get_root_directory(self, cfs):
@@ -365,7 +365,7 @@ class CephFS(RESTController):
         try:
             cfs = self._cephfs_instance(fs_id)
             paths = cfs.ls_dir(path, depth)
-        except (cephfs.PermissionError, cephfs.ObjectNotFound): #pragma: no cover - the handling is too obvious
+        except (cephfs.PermissionError, cephfs.ObjectNotFound):  # pragma: no cover
             paths = []
         return paths
 
@@ -515,6 +515,6 @@ class CephFsUi(CephFS):
             paths = cfs.ls_dir(path, depth)
             if path == os.sep:
                 paths = [self._get_root_directory(cfs)] + paths
-        except (cephfs.PermissionError, cephfs.ObjectNotFound): #pragma: no cover - the handling is too obvious
+        except (cephfs.PermissionError, cephfs.ObjectNotFound):  # pragma: no cover
             paths = []
         return paths
index d720c7621e2bb50a5ac038baac6920de631d2d37..b5713162b2dc4179a1fa3fe68e1262412420936d 100644 (file)
@@ -96,7 +96,7 @@ class Host(RESTController):
     @raise_if_no_orchestrator
     @handle_orchestrator_error('host')
     @host_task('create', {'hostname': '{hostname}'})
-    def create(self, hostname): #pragma: no cover - requires realtime env
+    def create(self, hostname):  # pragma: no cover - requires realtime env
         orch_client = OrchClient.instance()
         self._check_orchestrator_host_op(orch_client, hostname, True)
         orch_client.hosts.add(hostname)
@@ -104,12 +104,12 @@ class Host(RESTController):
     @raise_if_no_orchestrator
     @handle_orchestrator_error('host')
     @host_task('delete', {'hostname': '{hostname}'})
-    def delete(self, hostname): #pragma: no cover - requires realtime env
+    def delete(self, hostname):  # pragma: no cover - requires realtime env
         orch_client = OrchClient.instance()
         self._check_orchestrator_host_op(orch_client, hostname, False)
         orch_client.hosts.remove(hostname)
 
-    def _check_orchestrator_host_op(self, orch_client, hostname, add_host=True): #pragma: no cover - requires realtime env
+    def _check_orchestrator_host_op(self, orch_client, hostname, add_host=True):  # pragma:no cover
         """Check if we can adding or removing a host with orchestrator
 
         :param orch_client: Orchestrator client
index 0ef5f6f372092e5c39c78be31317f08120cc64d3..1219f78b95c238611f72f61f1cfe60bb8bcd9934 100644 (file)
@@ -181,7 +181,7 @@ class NFSGaneshaExports(RESTController):
         ganesha_conf = GaneshaConf.instance(cluster_id)
 
         if not ganesha_conf.has_export(export_id):
-            raise cherrypy.HTTPError(404) #pragma: no cover - the handling is too obvious
+            raise cherrypy.HTTPError(404)  # pragma: no cover - the handling is too obvious
 
         if fsal['name'] not in Ganesha.fsals_available():
             raise NFSException("Cannot make modifications to this export. "
@@ -227,7 +227,7 @@ class NFSGaneshaExports(RESTController):
         ganesha_conf = GaneshaConf.instance(cluster_id)
 
         if not ganesha_conf.has_export(export_id):
-            raise cherrypy.HTTPError(404) #pragma: no cover - the handling is too obvious
+            raise cherrypy.HTTPError(404)  # pragma: no cover - the handling is too obvious
         export = ganesha_conf.remove_export(export_id)
         if reload_daemons:
             ganesha_conf.reload_daemons(export.daemons)
@@ -279,7 +279,7 @@ class NFSGaneshaUi(BaseController):
         return Ganesha.fsals_available()
 
     @Endpoint('GET', '/lsdir')
-    def lsdir(self, root_dir=None, depth=1): #pragma: no cover
+    def lsdir(self, root_dir=None, depth=1):  # pragma: no cover
         if root_dir is None:
             root_dir = "/"
         depth = int(depth)
index 17c31158e56ca7956f3fa97d57cbf0f9eeeb970e..a7fda9f85081c7706c2c77143f7320e11d6a30fc 100644 (file)
@@ -57,7 +57,7 @@ def raise_if_no_orchestrator(method):
     def inner(self, *args, **kwargs):
         orch = OrchClient.instance()
         if not orch.available():
-            raise DashboardException(code='orchestrator_status_unavailable', #pragma: no cover
+            raise DashboardException(code='orchestrator_status_unavailable',  # pragma: no cover
                                      msg='Orchestrator is unavailable',
                                      component='orchestrator',
                                      http_status_code=503)
@@ -78,7 +78,7 @@ class Orchestrator(RESTController):
     @raise_if_no_orchestrator
     @handle_orchestrator_error('osd')
     @orchestrator_task('identify_device', ['{hostname}', '{device}'])
-    def identify_device(self, hostname, device, duration): #pragma: no cover - requires realtime env
+    def identify_device(self, hostname, device, duration):  # pragma: no cover
         # type: (str, str, int) -> None
         """
         Identify a device by switching on the device light for N seconds.
@@ -110,7 +110,7 @@ class OrchestratorInventory(RESTController):
         for inventory_host in inventory_hosts:
             host_osds = device_osd_map.get(inventory_host['name'])
             for device in inventory_host['devices']:
-                if host_osds: #pragma: no cover
+                if host_osds:  # pragma: no cover
                     dev_name = os.path.basename(device['path'])
                     device['osd_ids'] = sorted(host_osds.get(dev_name, []))
                 else:
index 5be3110c346ad85cc56cc6f23310933a63bc2e4e..1688f2697c459b91f4dcb3139ff3dc0f0a0968cb 100644 (file)
@@ -19,8 +19,8 @@ from ..services.orchestrator import OrchClient
 from ..tools import str_to_bool
 try:
     from typing import Dict, List, Any, Union  # noqa: F401 pylint: disable=unused-import
-except ImportError: #pragma: no cover
-    pass  # For typing only #pragma: no cover
+except ImportError:  # pragma: no cover
+    pass  # For typing only
 
 
 logger = logging.getLogger('controllers.osd')
@@ -58,7 +58,7 @@ class Osd(RESTController):
             osd['stats_history'] = {}
             osd_spec = str(osd_id)
             if 'osd' not in osd:
-                continue #pragma: no cover - simple early continue
+                continue  # pragma: no cover - simple early continue
             for stat in ['osd.op_w', 'osd.op_in_bytes', 'osd.op_r', 'osd.op_out_bytes']:
                 prop = stat.split('.')[1]
                 rates = CephService.get_rates('osd', osd_spec, stat)
@@ -105,10 +105,10 @@ class Osd(RESTController):
         try:
             histogram = CephService.send_command(
                 'osd', srv_spec=svc_id, prefix='perf histogram dump')
-        except SendCommandError as e: #pragma: no cover - the handling is too obvious
-            if 'osd down' in str(e): #pragma: no cover - no complexity there
+        except SendCommandError as e:  # pragma: no cover - the handling is too obvious
+            if 'osd down' in str(e):  # pragma: no cover - no complexity there
                 histogram = str(e)
-            else: #pragma: no cover - no complexity there
+            else:  # pragma: no cover - no complexity there
                 raise
 
         return {
@@ -117,7 +117,7 @@ class Osd(RESTController):
             'histogram': histogram,
         }
 
-    def set(self, svc_id, device_class): #pragma: no cover
+    def set(self, svc_id, device_class):  # pragma: no cover
         old_device_class = CephService.send_command('mon', 'osd crush get-device-class',
                                                     ids=[svc_id])
         old_device_class = old_device_class[0]['device_class']
@@ -157,7 +157,7 @@ class Osd(RESTController):
     @raise_if_no_orchestrator
     @handle_orchestrator_error('osd')
     @osd_task('delete', {'svc_id': '{svc_id}'})
-    def delete(self, svc_id, force=None): #pragma: no cover - requires realtime env
+    def delete(self, svc_id, force=None):  # pragma: no cover - requires realtime env
         orch = OrchClient.instance()
         if not force:
             logger.info('Check for removing osd.%s...', svc_id)
index 060b14fb1051b0b3080b473ca7408ce27d8f5ff6..a0dc444dcabff7d497f294c3ed1b9972352a8a8c 100644 (file)
@@ -17,8 +17,8 @@ from ..tools import json_str_to_object, str_to_bool
 
 try:
     from typing import List
-except ImportError: #pragma: no cover
-    pass  # Just for type checking #pragma: no cover
+except ImportError:  # pragma: no cover
+    pass  # Just for type checking
 
 logger = logging.getLogger('controllers.rgw')
 
@@ -32,7 +32,7 @@ class Rgw(BaseController):
         try:
             instance = RgwClient.admin_instance()
             # Check if the service is online.
-            if not instance.is_service_online(): #pragma: no cover - no complexity there
+            if not instance.is_service_online():  # pragma: no cover - no complexity there
                 msg = 'Failed to connect to the Object Gateway\'s Admin Ops API.'
                 raise RequestException(msg)
             # Ensure the API user ID is known by the RGW.
@@ -41,7 +41,7 @@ class Rgw(BaseController):
                     instance.userid)
                 raise RequestException(msg)
             # Ensure the system flag is set for the API user ID.
-            if not instance.is_system_user(): #pragma: no cover - no complexity there
+            if not instance.is_system_user():  # pragma: no cover - no complexity there
                 msg = 'The system flag is not set for user "{}".'.format(
                     instance.userid)
                 raise RequestException(msg)
@@ -228,7 +228,7 @@ class RgwBucket(RgwRESTController):
                                   lock_retention_period_days,
                                   lock_retention_period_years)
             return result
-        except RequestException as e: #pragma: no cover - handling is too obvious
+        except RequestException as e:  # pragma: no cover - handling is too obvious
             raise DashboardException(e, http_status_code=500, component='rgw')
 
     def set(self, bucket, bucket_id, uid, versioning_state=None,
@@ -379,7 +379,7 @@ class RgwUser(RgwRESTController):
                                              'Object Gateway'.format(uid))
             # Finally redirect request to the RGW proxy.
             return self.proxy('DELETE', 'user', {'uid': uid}, json_response=False)
-        except (DashboardException, RequestException) as e: #pragma: no cover - handling is too obvious
+        except (DashboardException, RequestException) as e:  # pragma: no cover
             raise DashboardException(e, component='rgw')
 
     # pylint: disable=redefined-builtin
index a26e6ffe68298f428ee583aa0a50d8b27f768555..5235992a1741ae28ba3320c593bda55ebd48e8b1 100644 (file)
@@ -30,8 +30,8 @@ class Settings(RESTController):
 
         try:
             yield result
-        except AttributeError: #pragma: no cover - handling is too obvious
-            raise cherrypy.NotFound(result) #pragma: no cover - handling is too obvious
+        except AttributeError:  # pragma: no cover - handling is too obvious
+            raise cherrypy.NotFound(result)  # pragma: no cover - handling is too obvious
 
     @staticmethod
     def _to_native(setting):
@@ -98,7 +98,7 @@ class StandardSettings(RESTController):
             settings.
         :rtype: dict
         """
-        return { #pragma: no cover - no complexity there
+        return {  # pragma: no cover - no complexity there
             'user_pwd_expiration_span':
             SettingsModule.USER_PWD_EXPIRATION_SPAN,
             'user_pwd_expiration_warning_1':
index 8ef10e68fe431de05cece72d4a769d0d1445bed4..3b181cb4d4e4eed49e898342766578e46d83414b 100644 (file)
@@ -21,8 +21,8 @@ class Summary(BaseController):
     def _rbd_mirroring(self):
         try:
             _, data = get_daemons_and_pools()
-        except ViewCacheNoDataException: #pragma:no cover
-            return {} # pragma: no cover
+        except ViewCacheNoDataException:  # pragma: no cover
+            return {}  # pragma: no cover
 
         daemons = data.get('daemons', [])
         pools = data.get('pools', {})
@@ -30,18 +30,18 @@ class Summary(BaseController):
         warnings = 0
         errors = 0
         for daemon in daemons:
-            if daemon['health_color'] == 'error': #pragma:no cover
+            if daemon['health_color'] == 'error':  # pragma: no cover
                 errors += 1
-            elif daemon['health_color'] == 'warning': #pragma:no cover
+            elif daemon['health_color'] == 'warning':  # pragma: no cover
                 warnings += 1
         for _, pool in pools.items():
-            if pool['health_color'] == 'error': #pragma:no cover
+            if pool['health_color'] == 'error':  # pragma: no cover
                 errors += 1
-            elif pool['health_color'] == 'warning': #pragma:no cover
+            elif pool['health_color'] == 'warning':  # pragma: no cover
                 warnings += 1
         return {'warnings': warnings, 'errors': errors}
 
-    def _task_permissions(self, name): #pragma:no cover
+    def _task_permissions(self, name):  # pragma: no cover
         result = True
         if name == 'pool/create':
             result = self._has_permissions(Permission.CREATE, Scope.POOL)
index 337230179bfdfa115983cb309579cf4965e42463..2f8dfdb876f53b53f5f0fd6727573e35357c97b4 100644 (file)
@@ -290,8 +290,8 @@ class Module(MgrModule, CherryPyConfig):
 
         if 'COVERAGE_ENABLED' in os.environ:
             import coverage
-            __cov = coverage.Coverage(config_file="{}/.coveragerc".format(os.path.dirname(__file__)),
-                                      data_suffix=True)
+            __cov = coverage.Coverage(config_file="{}/.coveragerc".format
+            (os.path.dirname(__file__)),data_suffix=True)
             __cov.start()
             cherrypy.engine.subscribe('after_request', __cov.save)