]> git.apps.os.sepia.ceph.com Git - ceph.git/commitdiff
qa/tasks: use next(iter(..)) for accessing first element in a view
authorKefu Chai <kchai@redhat.com>
Tue, 31 Mar 2020 02:16:40 +0000 (10:16 +0800)
committerKefu Chai <kchai@redhat.com>
Tue, 7 Apr 2020 12:33:47 +0000 (20:33 +0800)
in python2, dict.values() and dict.keys() return lists. but in python3,
they return views, which cannot be indexed directly using an integer index.

there are three use cases when we access these views in python3:

1. get the first element
2. get all the elements and then *might* want to access them by index
3. get the first element assuming there is only a single element in
   the view
4. iterate thru the view

in the 1st case, we cannot assume the number of elements, so to be
python3 compatible, we should use `next(iter(a_dict))` instead.

in the 2nd case, in this change, the view is materialized using
`list(a_dict)`.

in the 3rd case, we can just continue using the short hand of
```py
(first_element,) = a_dict.keys()
```
to unpack the view. this works in both python2 and python3.

in the 4th case, the existing code works in both python2 and python3, as
both list and view can be iterated using `iter`, and `len` works as
well.

Signed-off-by: Kefu Chai <kchai@redhat.com>
13 files changed:
qa/tasks/barbican.py
qa/tasks/cbt.py
qa/tasks/ceph_manager.py
qa/tasks/ceph_objectstore_tool.py
qa/tasks/cephfs/filesystem.py
qa/tasks/check_counter.py
qa/tasks/devstack.py
qa/tasks/dnsmasq.py
qa/tasks/filestore_idempotent.py
qa/tasks/mgr/test_crash.py
qa/tasks/radosgw_admin.py
qa/tasks/radosgw_admin_rest.py
qa/tasks/vault.py

index 32bce350e3a55be81d1c73d74d60a762939b1d1a..51a9af1f9ebb3f31e38ce23fbf638aabc6761902 100644 (file)
@@ -172,7 +172,7 @@ def configure_barbican(ctx, config):
     Configure barbican paste-api and barbican-api.
     """
     assert isinstance(config, dict)
-    (cclient, cconfig) = config.items()[0]
+    (cclient, cconfig) = next(iter(config.items()))
 
     keystone_role = cconfig.get('use-keystone-role', None)
     if keystone_role is None:
@@ -239,7 +239,7 @@ def create_secrets(ctx, config):
     Create a main and an alternate s3 user.
     """
     assert isinstance(config, dict)
-    (cclient, cconfig) = config.items()[0]
+    (cclient, cconfig) = next(iter(config.items()))
 
     rgw_user = cconfig['rgw_user']
 
index c5567a05d020efa6f8f9dcc7d8c97172602c3616..3255107add602b87a6ff220fe6bbde76db9e483e 100644 (file)
@@ -44,7 +44,7 @@ class CBT(Task):
             )
 
         benchmark_config = self.config.get('benchmarks')
-        benchmark_type = benchmark_config.keys()[0]
+        benchmark_type = next(iter(benchmark_config.keys()))
         if benchmark_type in ['librbdfio', 'fio']:
           testdir = misc.get_testdir(self.ctx)
           benchmark_config[benchmark_type]['cmd_path'] = os.path.join(testdir, 'fio/fio')
@@ -80,7 +80,7 @@ class CBT(Task):
             cbt_depends = ['python3-yaml', 'python3-lxml', 'librbd-dev', 'collectl']
         self.first_mon.run(args=install_cmd + cbt_depends)
 
-        benchmark_type = self.cbt_config.get('benchmarks').keys()[0]
+        benchmark_type = next(iter(self.cbt_config.get('benchmarks').keys()))
         self.log.info('benchmark: %s', benchmark_type)
 
         if benchmark_type in ['librbdfio', 'fio']:
@@ -201,7 +201,7 @@ class CBT(Task):
 
     def setup(self):
         super(CBT, self).setup()
-        self.first_mon = self.ctx.cluster.only(misc.get_first_mon(self.ctx, self.config)).remotes.keys()[0]
+        self.first_mon = next(iter(self.ctx.cluster.only(misc.get_first_mon(self.ctx, self.config)).remotes.keys()))
         self.cbt_config = self.generate_cbt_config()
         self.log.info('cbt configuration is %s', self.cbt_config)
         self.cbt_dir = os.path.join(misc.get_archive_dir(self.ctx), 'cbt')
@@ -233,7 +233,7 @@ class CBT(Task):
                 '{tdir}/cbt'.format(tdir=testdir),
             ]
         )
-        benchmark_type = self.cbt_config.get('benchmarks').keys()[0]
+        benchmark_type = next(iter(self.cbt_config.get('benchmarks').keys()))
         if benchmark_type in ['librbdfio', 'fio']:
             self.first_mon.run(
                 args=[
index 5742cff7528662386d3f6ca22ffb9a1f186ea0ba..3d41c2e3f482c4707bc85a6f6f83f1b54c0c8730 100644 (file)
@@ -1239,8 +1239,8 @@ class ObjectStoreTool:
             self.pgid = self.manager.get_object_pg_with_shard(self.pool,
                                                               self.object_name,
                                                               self.osd)
-        self.remote = self.manager.ctx.\
-            cluster.only('osd.{o}'.format(o=self.osd)).remotes.keys()[0]
+        self.remote = next(iter(self.manager.ctx.\
+            cluster.only('osd.{o}'.format(o=self.osd)).remotes.keys()))
         path = self.manager.get_filepath().format(id=self.osd)
         self.paths = ("--data-path {path} --journal-path {path}/journal".
                       format(path=path))
index e08d0d4b3ec997ba99e719ad007fc7d3803aa121..23eb9d69a3157694d17b4b0935c2d9b57fd90b3a 100644 (file)
@@ -242,7 +242,7 @@ def test_objectstore(ctx, config, cli_remote, REP_POOL, REP_NAME, ec=False):
                          REP_NAME, DATALINECOUNT)
     allremote = []
     allremote.append(cli_remote)
-    allremote += osds.remotes.keys()
+    allremote += list(osds.remotes.keys())
     allremote = list(set(allremote))
     for remote in allremote:
         cod_setup_remote_data(log, ctx, remote, NUM_OBJECTS, DATADIR,
index f48d38f94ed5330461ac458b68a3bb052c2a0d3c..dc00e49dee7610871f8b137212cc6270a10a41e7 100644 (file)
@@ -691,7 +691,7 @@ class Filesystem(MDSCluster):
         if refresh or self.data_pools is None:
             self.get_pool_names(refresh = True)
         assert(len(self.data_pools) == 1)
-        return self.data_pools.values()[0]
+        return next(iter(self.data_pools.values()))
 
     def get_data_pool_id(self, refresh = False):
         """
@@ -701,12 +701,12 @@ class Filesystem(MDSCluster):
         if refresh or self.data_pools is None:
             self.get_pool_names(refresh = True)
         assert(len(self.data_pools) == 1)
-        return self.data_pools.keys()[0]
+        return next(iter(self.data_pools.keys()))
 
     def get_data_pool_names(self, refresh = False):
         if refresh or self.data_pools is None:
             self.get_pool_names(refresh = True)
-        return self.data_pools.values()
+        return list(self.data_pools.values())
 
     def get_metadata_pool_name(self):
         return self.metadata_pool_name
index fc877f285b6c8174204ef23f2c4b084f2f7e22f5..daa81973be7358256646eb8dddcdb1b8251ca2f9 100644 (file)
@@ -45,7 +45,7 @@ class CheckCounter(Task):
         targets = self.config.get('counters', {})
 
         if cluster_name is None:
-            cluster_name = self.ctx.managers.keys()[0]
+            cluster_name = next(iter(self.ctx.managers.keys()))
 
         for daemon_type, counters in targets.items():
             # List of 'a', 'b', 'c'...
index 8e08c0389310f6afebd03981de65c9379c478df6..9243071a4bf01136dda4ed844394e755334b35e7 100644 (file)
@@ -60,8 +60,8 @@ def install(ctx, config):
     if not isinstance(config, dict):
         raise TypeError("config must be a dict")
 
-    devstack_node = ctx.cluster.only(is_devstack_node).remotes.keys()[0]
-    an_osd_node = ctx.cluster.only(is_osd_node).remotes.keys()[0]
+    devstack_node = next(iter(ctx.cluster.only(is_devstack_node).remotes.keys()))
+    an_osd_node = next(iter(ctx.cluster.only(is_osd_node).remotes.keys()))
 
     devstack_branch = config.get("branch", "master")
     install_devstack(devstack_node, devstack_branch)
@@ -301,7 +301,7 @@ def exercise(ctx, config):
     if not isinstance(config, dict):
         raise TypeError("config must be a dict")
 
-    devstack_node = ctx.cluster.only(is_devstack_node).remotes.keys()[0]
+    devstack_node = next(iter(ctx.cluster.only(is_devstack_node).remotes.keys()))
 
     # TODO: save the log *and* preserve failures
     #devstack_archive_dir = create_devstack_archive(ctx, devstack_node)
@@ -328,8 +328,8 @@ def create_devstack_archive(ctx, devstack_node):
 def smoke(ctx, config):
     log.info("Running a basic smoketest...")
 
-    devstack_node = ctx.cluster.only(is_devstack_node).remotes.keys()[0]
-    an_osd_node = ctx.cluster.only(is_osd_node).remotes.keys()[0]
+    devstack_node = next(iter(ctx.cluster.only(is_devstack_node).remotes.keys()))
+    an_osd_node = next(iter(ctx.cluster.only(is_osd_node).remotes.keys()))
 
     try:
         create_volume(devstack_node, an_osd_node, 'smoke0', 1)
index 717c9f01930ae4c379d04e48a85e53229c0ffa13..352ed246b6eb48a930e245563081e1b5399334fa 100644 (file)
@@ -83,7 +83,7 @@ def setup_dnsmasq(remote, testdir, cnames):
     # restart dnsmasq
     remote.run(args=['sudo', 'systemctl', 'restart', 'dnsmasq'])
     # verify dns name is set
-    remote.run(args=['ping', '-c', '4', cnames.keys()[0]])
+    remote.run(args=['ping', '-c', '4', next(iter(cnames.keys()))])
 
     try:
         yield
index 01b562905b212408f09d89060a689e875035cdfc..319bef7686c71d8ad0a25b62a6607411a1ff354c 100644 (file)
@@ -31,7 +31,7 @@ def task(ctx, config):
     clients = config.keys()
 
     # just use the first client...
-    client = clients[0];
+    client = next(iter(clients))
     (remote,) = ctx.cluster.only(client).remotes.keys()
 
     testdir = teuthology.get_testdir(ctx)
index 16663f4cd85d13ba41d6e080f78e13ef08800fc9..49191127f24b4cf1ceec36bf18d3eda0210c9bba 100644 (file)
@@ -73,7 +73,7 @@ class TestCrash(MgrTestCase):
             self.assertIn(crash['crash_id'], retstr)
 
     def test_rm(self):
-        crashid = self.crashes.keys()[0]
+        crashid = next(iter(self.crashes.keys()))
         self.assertEqual(
             0,
             self.mgr_cluster.mon_manager.raw_cluster_cmd_result(
index 9f4529c43f7d51b147a54cb5387fbf71a89677fc..6f7e193c64181da11a557d7b21155719efc1c535 100644 (file)
@@ -272,7 +272,7 @@ def task(ctx, config):
     clients_from_config = config.keys()
 
     # choose first client as default
-    client = clients_from_config[0]
+    client = next(iter(clients_from_config))
 
     # once the client is chosen, pull the host name and  assigned port out of
     # the role_endpoints that were assigned by the rgw task
index 377144db4403af9cc8933b2b083b7661ceb99a6c..df3fa7a1d1737ea727602245918ceae6f15c663e 100644 (file)
@@ -130,7 +130,7 @@ def task(ctx, config):
     clients = config.keys()
 
     # just use the first client...
-    client = clients[0]
+    client = next(iter(clients))
 
     ##
     admin_user = 'ada'
index f0a0b7ceefbc1bd6a9eb552d24ddb87d1ef45d3f..6af7c074f6d99386372d7fb54834080df5d9e548 100644 (file)
@@ -128,7 +128,7 @@ def setup_vault(ctx, config):
     """
     Mount Transit or KV version 2 secrets engine
     """
-    (cclient, cconfig) = config.items()[0]
+    (cclient, cconfig) = next(iter(config.items()))
     engine = cconfig.get('engine')
 
     if engine == 'kv':
@@ -169,7 +169,7 @@ def send_req(ctx, cconfig, client, path, body, method='POST'):
 
 @contextlib.contextmanager
 def create_secrets(ctx, config):
-    (cclient, cconfig) = config.items()[0]
+    (cclient, cconfig) = next(iter(config.items()))
     engine = cconfig.get('engine')
     prefix = cconfig.get('prefix')
     secrets = cconfig.get('secrets')