Remove all usage of six library

Replace six with Python 3 style code.

Change-Id: I4b97e040f3e790ac114dcd43c68e6b67b1079adf
This commit is contained in:
haixin 2020-09-30 10:40:31 +08:00
parent 1abc1b5d40
commit cea1f674ae
32 changed files with 83 additions and 164 deletions

View File

@ -27,7 +27,7 @@ import abc
import copy import copy
from requests import Response from requests import Response
import six
from cinderclient.apiclient import exceptions from cinderclient.apiclient import exceptions
from cinderclient import utils from cinderclient import utils
@ -199,8 +199,7 @@ class BaseManager(HookableMixin):
return self.client.delete(url) return self.client.delete(url)
@six.add_metaclass(abc.ABCMeta) class ManagerWithFind(BaseManager, metaclass=abc.ABCMeta):
class ManagerWithFind(BaseManager):
"""Manager with additional `find()`/`findall()` methods.""" """Manager with additional `find()`/`findall()` methods."""
@abc.abstractmethod @abc.abstractmethod

View File

@ -23,8 +23,6 @@ import contextlib
import hashlib import hashlib
import os import os
import six
from cinderclient.apiclient import base as common_base from cinderclient.apiclient import base as common_base
from cinderclient import exceptions from cinderclient import exceptions
from cinderclient import utils from cinderclient import utils
@ -153,7 +151,7 @@ class Manager(common_base.HookableMixin):
if offset: if offset:
query_params['offset'] = offset query_params['offset'] = offset
query_params = utils.unicode_key_value_to_string(query_params) query_params = query_params
# Transform the dict to a sequence of two-element tuples in fixed # Transform the dict to a sequence of two-element tuples in fixed
# order, then the encoded string will be consistent in Python 2&3. # order, then the encoded string will be consistent in Python 2&3.
@ -188,7 +186,7 @@ class Manager(common_base.HookableMixin):
if not sort: if not sort:
return None return None
if isinstance(sort, six.string_types): if isinstance(sort, str):
# Convert the string into a list for consistent validation # Convert the string into a list for consistent validation
sort = [s for s in sort.split(',') if s] sort = [s for s in sort.split(',') if s]
@ -352,7 +350,7 @@ class Manager(common_base.HookableMixin):
self.api.client.delete_with_base_url(url) self.api.client.delete_with_base_url(url)
class ManagerWithFind(six.with_metaclass(abc.ABCMeta, Manager)): class ManagerWithFind(Manager, metaclass=abc.ABCMeta):
""" """
Like a `Manager`, but with additional `find()`/`findall()` methods. Like a `Manager`, but with additional `find()`/`findall()` methods.
""" """

View File

@ -24,7 +24,8 @@ import logging
import os import os
import pkgutil import pkgutil
import re import re
import six import urllib
from urllib import parse as urlparse
from keystoneauth1 import access from keystoneauth1 import access
from keystoneauth1 import adapter from keystoneauth1 import adapter
@ -34,8 +35,6 @@ from oslo_utils import encodeutils
from oslo_utils import importutils from oslo_utils import importutils
from oslo_utils import strutils from oslo_utils import strutils
import requests import requests
from six.moves import urllib
import six.moves.urllib.parse as urlparse
from cinderclient._i18n import _ from cinderclient._i18n import _
from cinderclient import api_versions from cinderclient import api_versions
@ -131,7 +130,7 @@ def get_server_version(url, insecure=False, cacert=None):
current_version = '2.0' current_version = '2.0'
except exceptions.ClientException as e: except exceptions.ClientException as e:
logger.warning("Error in server version query:%s\n" logger.warning("Error in server version query:%s\n"
"Returning APIVersion 2.0", six.text_type(e.message)) "Returning APIVersion 2.0", str(e.message))
return (api_versions.APIVersion(min_version), return (api_versions.APIVersion(min_version),
api_versions.APIVersion(current_version)) api_versions.APIVersion(current_version))
@ -239,7 +238,7 @@ class SessionClient(adapter.LegacyJsonAdapter):
version = get_volume_api_from_url(self.get_endpoint()) version = get_volume_api_from_url(self.get_endpoint())
except exceptions.UnsupportedVersion as e: except exceptions.UnsupportedVersion as e:
msg = (_("Service catalog returned invalid url.\n" msg = (_("Service catalog returned invalid url.\n"
"%s") % six.text_type(e)) "%s") % str(e))
raise exceptions.UnsupportedVersion(msg) raise exceptions.UnsupportedVersion(msg)
return version return version
@ -496,10 +495,10 @@ class HTTPClient(object):
except exceptions.UnsupportedVersion as e: except exceptions.UnsupportedVersion as e:
if self.management_url == self.os_endpoint: if self.management_url == self.os_endpoint:
msg = (_("Invalid url was specified in --os-endpoint %s") msg = (_("Invalid url was specified in --os-endpoint %s")
% six.text_type(e)) % str(e))
else: else:
msg = (_("Service catalog returned invalid url.\n" msg = (_("Service catalog returned invalid url.\n"
"%s") % six.text_type(e)) "%s") % str(e))
raise exceptions.UnsupportedVersion(msg) raise exceptions.UnsupportedVersion(msg)

View File

@ -32,8 +32,7 @@ from keystoneauth1 import session
from oslo_utils import encodeutils from oslo_utils import encodeutils
from oslo_utils import importutils from oslo_utils import importutils
import requests import requests
import six from urllib import parse as urlparse
import six.moves.urllib.parse as urlparse
import cinderclient import cinderclient
from cinderclient._i18n import _ from cinderclient._i18n import _
@ -395,7 +394,7 @@ class OpenStackCinderShell(object):
else: else:
msg = (_(" (Supported until API version %(end)s)") msg = (_(" (Supported until API version %(end)s)")
% {"end": end_version.get_string()}) % {"end": end_version.get_string()})
return six.text_type(msg) return str(msg)
def _find_actions(self, subparsers, actions_module, version, def _find_actions(self, subparsers, actions_module, version,
do_help, input_args): do_help, input_args):
@ -1026,7 +1025,7 @@ def main():
sys.exit(130) sys.exit(130)
except Exception as e: except Exception as e:
logger.debug(e, exc_info=1) logger.debug(e, exc_info=1)
print("ERROR: %s" % six.text_type(e), file=sys.stderr) print("ERROR: %s" % str(e), file=sys.stderr)
sys.exit(1) sys.exit(1)

View File

@ -201,7 +201,7 @@ def print_resource_filter_list(filters):
def quota_show(quotas): def quota_show(quotas):
quotas_info_dict = utils.unicode_key_value_to_string(quotas._info) quotas_info_dict = quotas._info
quota_dict = {} quota_dict = {}
for resource in quotas_info_dict.keys(): for resource in quotas_info_dict.keys():
good_name = False good_name = False
@ -216,7 +216,7 @@ def quota_show(quotas):
def quota_usage_show(quotas): def quota_usage_show(quotas):
quota_list = [] quota_list = []
quotas_info_dict = utils.unicode_key_value_to_string(quotas._info) quotas_info_dict = quotas._info
for resource in quotas_info_dict.keys(): for resource in quotas_info_dict.keys():
good_name = False good_name = False
for name in _quota_resources: for name in _quota_resources:

View File

@ -10,10 +10,10 @@
# License for the specific language governing permissions and limitations # License for the specific language governing permissions and limitations
# under the License. # under the License.
import configparser
import os import os
import time import time
import six
from tempest.lib.cli import base from tempest.lib.cli import base
from tempest.lib.cli import output_parser from tempest.lib.cli import output_parser
from tempest.lib import exceptions from tempest.lib import exceptions
@ -38,7 +38,7 @@ def credentials():
os.environ.get('OS_PROJECT_NAME')) os.environ.get('OS_PROJECT_NAME'))
auth_url = os.environ.get('OS_AUTH_URL') auth_url = os.environ.get('OS_AUTH_URL')
config = six.moves.configparser.RawConfigParser() config = configparser.RawConfigParser()
if config.read(_CREDS_FILE): if config.read(_CREDS_FILE):
username = username or config.get('admin', 'user') username = username or config.get('admin', 'user')
password = password or config.get('admin', 'pass') password = password or config.get('admin', 'pass')
@ -101,7 +101,7 @@ class ClientTestBase(base.ClientTestBase):
obj = {} obj = {}
items = self.parser.listing(output) items = self.parser.listing(output)
for item in items: for item in items:
obj[item['Property']] = six.text_type(item['Value']) obj[item['Property']] = str(item['Value'])
return obj return obj
def object_cmd(self, object_name, cmd): def object_cmd(self, object_name, cmd):

View File

@ -10,7 +10,7 @@
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations # License for the specific language governing permissions and limitations
# under the License. # under the License.
import six
from cinderclient.tests.functional import base from cinderclient.tests.functional import base
@ -47,7 +47,7 @@ class CinderSnapshotTests(base.ClientTestBase):
'snapshot', 'snapshot',
params='--metadata test_metadata=test_date {0}'.format( params='--metadata test_metadata=test_date {0}'.format(
self.volume['id'])) self.volume['id']))
self.assertEqual(six.text_type({u'test_metadata': u'test_date'}), self.assertEqual(str({'test_metadata': 'test_date'}),
snapshot['metadata']) snapshot['metadata'])
self.object_delete('snapshot', snapshot['id']) self.object_delete('snapshot', snapshot['id'])
self.check_object_deleted('snapshot', snapshot['id']) self.check_object_deleted('snapshot', snapshot['id'])

View File

@ -11,7 +11,6 @@
# under the License. # under the License.
import ddt import ddt
import six
from tempest.lib import exceptions from tempest.lib import exceptions
from cinderclient.tests.functional import base from cinderclient.tests.functional import base
@ -32,9 +31,9 @@ class CinderVolumeNegativeTests(base.ClientTestBase):
) )
@ddt.unpack @ddt.unpack
def test_volume_create_with_incorrect_size(self, value, ex_text): def test_volume_create_with_incorrect_size(self, value, ex_text):
self.assertRaisesRegex(exceptions.CommandFailed,
six.assertRaisesRegex(self, exceptions.CommandFailed, ex_text, ex_text, self.object_create,
self.object_create, 'volume', params=value) 'volume', params=value)
class CinderVolumeTests(base.ClientTestBase): class CinderVolumeTests(base.ClientTestBase):
@ -96,5 +95,5 @@ class CinderVolumeTestsWithParameters(base.ClientTestBase):
""" """
volume = self.object_create( volume = self.object_create(
'volume', params='--metadata test_metadata=test_date 1') 'volume', params='--metadata test_metadata=test_date 1')
self.assertEqual(six.text_type({u'test_metadata': u'test_date'}), self.assertEqual(str({'test_metadata': 'test_date'}),
volume['metadata']) volume['metadata'])

View File

@ -11,8 +11,6 @@
# under the License. # under the License.
import ddt import ddt
import six
from tempest.lib import exceptions from tempest.lib import exceptions
from cinderclient.tests.functional import base from cinderclient.tests.functional import base
@ -39,9 +37,8 @@ class CinderVolumeExtendNegativeTests(base.ClientTestBase):
) )
@ddt.unpack @ddt.unpack
def test_volume_extend_with_incorrect_size(self, value, ex_text): def test_volume_extend_with_incorrect_size(self, value, ex_text):
self.assertRaisesRegex(
six.assertRaisesRegex( exceptions.CommandFailed, ex_text, self.cinder, 'extend',
self, exceptions.CommandFailed, ex_text, self.cinder, 'extend',
params='{0} {1}'.format(self.volume['id'], value)) params='{0} {1}'.format(self.volume['id'], value))
@ddt.data( @ddt.data(
@ -52,7 +49,6 @@ class CinderVolumeExtendNegativeTests(base.ClientTestBase):
) )
@ddt.unpack @ddt.unpack
def test_volume_extend_with_incorrect_volume_id(self, value, ex_text): def test_volume_extend_with_incorrect_volume_id(self, value, ex_text):
self.assertRaisesRegex(
six.assertRaisesRegex( exceptions.CommandFailed, ex_text, self.cinder, 'extend',
self, exceptions.CommandFailed, ex_text, self.cinder, 'extend',
params='{0} 2'.format(value)) params='{0} 2'.format(value))

View File

@ -16,7 +16,6 @@
from unittest import mock from unittest import mock
import ddt import ddt
import six
from cinderclient import api_versions from cinderclient import api_versions
from cinderclient import client as base_client from cinderclient import client as base_client
@ -273,4 +272,4 @@ class DiscoverVersionTestCase(utils.TestCase):
v2_client = base_client.Client('2.0') v2_client = base_client.Client('2.0')
ex = self.assertRaises(exceptions.UnsupportedVersion, ex = self.assertRaises(exceptions.UnsupportedVersion,
api_versions.get_highest_version, v2_client) api_versions.get_highest_version, v2_client)
self.assertIn('Invalid client version 2.0 to get', six.text_type(ex)) self.assertIn('Invalid client version 2.0 to get', str(ex))

View File

@ -15,7 +15,6 @@
from unittest import mock from unittest import mock
import requests import requests
import six
from cinderclient import api_versions from cinderclient import api_versions
from cinderclient.apiclient import base as common_base from cinderclient.apiclient import base as common_base
@ -111,20 +110,6 @@ class BaseTest(utils.TestCase):
r1 = base.Resource(manager, {'id': 1}) r1 = base.Resource(manager, {'id': 1})
self.assertEqual(version, r1.api_version) self.assertEqual(version, r1.api_version)
@mock.patch('cinderclient.utils.unicode_key_value_to_string',
side_effect=lambda x: x)
def test_build_list_url_failed(self, fake_encode):
# NOTE(mdovgal): This test is reasonable only for py27 version,
# due to issue with parse.urlencode method only in py27
if six.PY2:
arguments = dict(resource_type = 'volumes',
search_opts = {'all_tenants': 1,
'name': u'ффф'})
manager = base.Manager(None)
self.assertRaises(UnicodeEncodeError,
manager._build_list_url,
**arguments)
def test__list_no_link(self): def test__list_no_link(self):
api = mock.Mock() api = mock.Mock()
api.client.get.return_value = (mock.sentinel.resp, api.client.get.return_value = (mock.sentinel.resp,

View File

@ -20,7 +20,6 @@ import fixtures
from keystoneauth1 import adapter from keystoneauth1 import adapter
from keystoneauth1 import exceptions as keystone_exception from keystoneauth1 import exceptions as keystone_exception
from oslo_serialization import jsonutils from oslo_serialization import jsonutils
import six
from cinderclient import api_versions from cinderclient import api_versions
import cinderclient.client import cinderclient.client
@ -136,7 +135,7 @@ class ClientTest(utils.TestCase):
request_id = "req-f551871a-4950-4225-9b2c-29a14c8f075e" request_id = "req-f551871a-4950-4225-9b2c-29a14c8f075e"
mock_response = utils.TestResponse({ mock_response = utils.TestResponse({
"status_code": 202, "status_code": 202,
"text": six.b(json.dumps(resp)), "text": json.dumps(resp).encode("latin-1"),
"headers": {"x-openstack-request-id": request_id}, "headers": {"x-openstack-request-id": request_id},
}) })
@ -176,7 +175,7 @@ class ClientTest(utils.TestCase):
mock_response = utils.TestResponse({ mock_response = utils.TestResponse({
"status_code": 400, "status_code": 400,
"text": six.b(json.dumps(resp)), "text": json.dumps(resp).encode("latin-1"),
}) })
# 'request' method of Adaptor will return 400 response # 'request' method of Adaptor will return 400 response
@ -202,7 +201,7 @@ class ClientTest(utils.TestCase):
mock_response = utils.TestResponse({ mock_response = utils.TestResponse({
"status_code": 413, "status_code": 413,
"text": six.b(json.dumps(resp)), "text": json.dumps(resp).encode("latin-1"),
}) })
# 'request' method of Adaptor will return 413 response # 'request' method of Adaptor will return 413 response

View File

@ -12,6 +12,7 @@
# limitations under the License. # limitations under the License.
import argparse import argparse
import io
import re import re
import sys import sys
import unittest import unittest
@ -24,7 +25,6 @@ from keystoneauth1.exceptions import DiscoveryFailure
from keystoneauth1.identity.generic.password import Password as ks_password from keystoneauth1.identity.generic.password import Password as ks_password
from keystoneauth1 import session from keystoneauth1 import session
import requests_mock import requests_mock
from six import moves
from testtools import matchers from testtools import matchers
import cinderclient import cinderclient
@ -64,7 +64,7 @@ class ShellTest(utils.TestCase):
def shell(self, argstr): def shell(self, argstr):
orig = sys.stdout orig = sys.stdout
try: try:
sys.stdout = moves.StringIO() sys.stdout = io.StringIO()
_shell = shell.OpenStackCinderShell() _shell = shell.OpenStackCinderShell()
_shell.main(argstr.split()) _shell.main(argstr.split())
except SystemExit: except SystemExit:

View File

@ -12,12 +12,11 @@
# limitations under the License. # limitations under the License.
import collections import collections
import io
import sys import sys
from unittest import mock from unittest import mock
import ddt import ddt
import six
from six import moves
from cinderclient import api_versions from cinderclient import api_versions
from cinderclient.apiclient import base as common_base from cinderclient.apiclient import base as common_base
@ -151,7 +150,7 @@ class CaptureStdout(object):
"""Context manager for capturing stdout from statements in its block.""" """Context manager for capturing stdout from statements in its block."""
def __enter__(self): def __enter__(self):
self.real_stdout = sys.stdout self.real_stdout = sys.stdout
self.stringio = moves.StringIO() self.stringio = io.StringIO()
sys.stdout = self.stringio sys.stdout = self.stringio
return self return self
@ -309,16 +308,6 @@ class PrintListTestCase(test_utils.TestCase):
+---+-----+ +---+-----+
""", cso.read()) """, cso.read())
def test_unicode_key_value_to_string(self):
src = {u'key': u'\u70fd\u7231\u5a77'}
expected = {'key': '\xe7\x83\xbd\xe7\x88\xb1\xe5\xa9\xb7'}
if six.PY2:
self.assertEqual(expected, utils.unicode_key_value_to_string(src))
else:
# u'xxxx' in PY3 is str, we will not get extra 'u' from cli
# output in PY3
self.assertEqual(src, utils.unicode_key_value_to_string(src))
class PrintDictTestCase(test_utils.TestCase): class PrintDictTestCase(test_utils.TestCase):

View File

@ -18,7 +18,6 @@ from unittest import mock
import fixtures import fixtures
import requests import requests
from requests_mock.contrib import fixture as requests_mock_fixture from requests_mock.contrib import fixture as requests_mock_fixture
import six
import testtools import testtools
@ -92,9 +91,9 @@ class FixturedTestCase(TestCase):
if body: if body:
req_data = self.requests.last_request.body req_data = self.requests.last_request.body
if isinstance(req_data, six.binary_type): if isinstance(req_data, bytes):
req_data = req_data.decode('utf-8') req_data = req_data.decode('utf-8')
if not isinstance(body, six.string_types): if not isinstance(body, str):
# json load if the input body to match against is not a string # json load if the input body to match against is not a string
req_data = json.loads(req_data) req_data = json.loads(req_data)
self.assertEqual(body, req_data) self.assertEqual(body, req_data)

View File

@ -14,7 +14,7 @@
from datetime import datetime from datetime import datetime
import six.moves.urllib.parse as urlparse from urllib import parse as urlparse
from cinderclient import client as base_client from cinderclient import client as base_client
from cinderclient.tests.unit import fakes from cinderclient.tests.unit import fakes

View File

@ -14,8 +14,6 @@
# License for the specific language governing permissions and limitations # License for the specific language governing permissions and limitations
# under the License. # under the License.
import six
from cinderclient.v2 import availability_zones from cinderclient.v2 import availability_zones
from cinderclient.v2 import shell from cinderclient.v2 import shell
@ -44,8 +42,8 @@ class AvailabilityZoneTest(utils.FixturedTestCase):
self.assertEqual(2, len(zones)) self.assertEqual(2, len(zones))
l0 = [six.u('zone-1'), six.u('available')] l0 = ['zone-1', 'available']
l1 = [six.u('zone-2'), six.u('not available')] l1 = ['zone-2', 'not available']
z0 = shell.treeizeAvailabilityZone(zones[0]) z0 = shell.treeizeAvailabilityZone(zones[0])
z1 = shell.treeizeAvailabilityZone(zones[1]) z1 = shell.treeizeAvailabilityZone(zones[1])
@ -66,15 +64,15 @@ class AvailabilityZoneTest(utils.FixturedTestCase):
self.assertEqual(3, len(zones)) self.assertEqual(3, len(zones))
l0 = [six.u('zone-1'), six.u('available')] l0 = ['zone-1', 'available']
l1 = [six.u('|- fake_host-1'), six.u('')] l1 = ['|- fake_host-1', '']
l2 = [six.u('| |- cinder-volume'), l2 = ['| |- cinder-volume',
six.u('enabled :-) 2012-12-26 14:45:25')] 'enabled :-) 2012-12-26 14:45:25']
l3 = [six.u('internal'), six.u('available')] l3 = ['internal', 'available']
l4 = [six.u('|- fake_host-1'), six.u('')] l4 = ['|- fake_host-1', '']
l5 = [six.u('| |- cinder-sched'), l5 = ['| |- cinder-sched',
six.u('enabled :-) 2012-12-26 14:45:24')] 'enabled :-) 2012-12-26 14:45:24']
l6 = [six.u('zone-2'), six.u('not available')] l6 = ['zone-2', 'not available']
z0 = shell.treeizeAvailabilityZone(zones[0]) z0 = shell.treeizeAvailabilityZone(zones[0])
z1 = shell.treeizeAvailabilityZone(zones[1]) z1 = shell.treeizeAvailabilityZone(zones[1])

View File

@ -18,7 +18,7 @@ from unittest import mock
import ddt import ddt
import fixtures import fixtures
from requests_mock.contrib import fixture as requests_mock_fixture from requests_mock.contrib import fixture as requests_mock_fixture
from six.moves.urllib import parse from urllib import parse
from cinderclient import client from cinderclient import client
from cinderclient import exceptions from cinderclient import exceptions

View File

@ -9,9 +9,9 @@
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations # License for the specific language governing permissions and limitations
# under the License. # under the License.
from urllib import parse
import ddt import ddt
from six.moves.urllib import parse
from cinderclient import api_versions from cinderclient import api_versions
from cinderclient.tests.unit import utils from cinderclient.tests.unit import utils

View File

@ -39,12 +39,11 @@
# return original(manager, name_or_id, **kwargs) # return original(manager, name_or_id, **kwargs)
from unittest import mock from unittest import mock
from urllib import parse
import ddt import ddt
import fixtures import fixtures
from requests_mock.contrib import fixture as requests_mock_fixture from requests_mock.contrib import fixture as requests_mock_fixture
import six
from six.moves.urllib import parse
import cinderclient import cinderclient
from cinderclient import api_versions from cinderclient import api_versions
@ -322,7 +321,7 @@ class ShellTest(utils.TestCase):
self.assert_call_contained( self.assert_call_contained(
parse.urlencode( parse.urlencode(
{'extra_specs': {'extra_specs':
{six.text_type('key'): six.text_type('value')}})) {'key': 'value'}}))
self.assert_call_contained(parse.urlencode({'is_public': None})) self.assert_call_contained(parse.urlencode({'is_public': None}))
def test_type_list_public(self): def test_type_list_public(self):
@ -1150,11 +1149,7 @@ class ShellTest(utils.TestCase):
self.run_command, '--os-volume-api-version 3.32 ' self.run_command, '--os-volume-api-version 3.32 '
'service-set-log') 'service-set-log')
set_levels_mock.assert_not_called() set_levels_mock.assert_not_called()
# Different error message from argparse library in Python 2 and 3 msg = 'the following arguments are required: <log-level>'
if six.PY3:
msg = 'the following arguments are required: <log-level>'
else:
msg = 'too few arguments'
error_mock.assert_called_once_with(msg) error_mock.assert_called_once_with(msg)
@ddt.data('debug', 'DEBUG', 'info', 'INFO', 'warning', 'WARNING', 'error', @ddt.data('debug', 'DEBUG', 'info', 'INFO', 'warning', 'WARNING', 'error',

View File

@ -14,6 +14,7 @@
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations # License for the specific language governing permissions and limitations
# under the License. # under the License.
from urllib import parse
import ddt import ddt
@ -24,8 +25,6 @@ from cinderclient.tests.unit.v3 import fakes
from cinderclient.v3 import volume_snapshots from cinderclient.v3 import volume_snapshots
from cinderclient.v3 import volumes from cinderclient.v3 import volumes
from six.moves.urllib import parse
@ddt.ddt @ddt.ddt
class VolumesTest(utils.TestCase): class VolumesTest(utils.TestCase):

View File

@ -12,15 +12,14 @@
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations # License for the specific language governing permissions and limitations
# under the License. # under the License.
import collections
import collections
import os import os
import sys import sys
from urllib import parse
import uuid import uuid
import prettytable import prettytable
import six
from six.moves.urllib import parse
import stevedore import stevedore
from cinderclient import exceptions from cinderclient import exceptions
@ -156,7 +155,7 @@ def print_list(objs, fields, exclude_unavailable=False, formatters=None,
data = getattr(o, field_name, '') data = getattr(o, field_name, '')
if data is None: if data is None:
data = '-' data = '-'
if isinstance(data, six.string_types) and "\r" in data: if isinstance(data, str) and "\r" in data:
data = data.replace("\r", " ") data = data.replace("\r", " ")
row.append(data) row.append(data)
rows.append(row) rows.append(row)
@ -172,7 +171,6 @@ def print_list(objs, fields, exclude_unavailable=False, formatters=None,
for part in row: for part in row:
count = count + 1 count = count + 1
if isinstance(part, dict): if isinstance(part, dict):
part = unicode_key_value_to_string(part)
row[count - 1] = part row[count - 1] = part
pt.add_row(row) pt.add_row(row)
@ -183,24 +181,6 @@ def print_list(objs, fields, exclude_unavailable=False, formatters=None,
_print(pt, order_by) _print(pt, order_by)
def _encode(src):
"""remove extra 'u' in PY2."""
if six.PY2 and isinstance(src, six.text_type):
return src.encode('utf-8')
return src
def unicode_key_value_to_string(src):
"""Recursively converts dictionary keys to strings."""
if isinstance(src, dict):
return dict((_encode(k),
_encode(unicode_key_value_to_string(v)))
for k, v in src.items())
if isinstance(src, list):
return [unicode_key_value_to_string(item) for item in src]
return _encode(src)
def build_query_param(params, sort=False): def build_query_param(params, sort=False):
"""parse list to url query parameters""" """parse list to url query parameters"""
@ -249,10 +229,9 @@ def print_dict(d, property="Property", formatters=None):
r = list(r) r = list(r)
if r[0] in formatters: if r[0] in formatters:
r[1] = unicode_key_value_to_string(r[1])
if isinstance(r[1], dict): if isinstance(r[1], dict):
r[1] = _pretty_format_dict(r[1]) r[1] = _pretty_format_dict(r[1])
if isinstance(r[1], six.string_types) and "\r" in r[1]: if isinstance(r[1], str) and "\r" in r[1]:
r[1] = r[1].replace("\r", " ") r[1] = r[1].replace("\r", " ")
pt.add_row(r) pt.add_row(r)
_print(pt, property) _print(pt, property)
@ -343,10 +322,4 @@ def _load_entry_point(ep_name, name=None):
def get_function_name(func): def get_function_name(func):
if six.PY2: return "%s.%s" % (func.__module__, func.__qualname__)
if hasattr(func, "im_class"):
return "%s.%s" % (func.im_class, func.__name__)
else:
return "%s.%s" % (func.__module__, func.__name__)
else:
return "%s.%s" % (func.__module__, func.__qualname__)

View File

@ -20,7 +20,6 @@ import copy
import os import os
from oslo_utils import strutils from oslo_utils import strutils
import six
from cinderclient import base from cinderclient import base
from cinderclient import exceptions from cinderclient import exceptions
@ -295,7 +294,7 @@ def do_create(cs, args):
# NOTE(vish): multiple copies of same hint will # NOTE(vish): multiple copies of same hint will
# result in a list of values # result in a list of values
if key in hints: if key in hints:
if isinstance(hints[key], six.string_types): if isinstance(hints[key], str):
hints[key] = [hints[key]] hints[key] = [hints[key]]
hints[key] += [value] hints[key] += [value]
else: else:
@ -1113,8 +1112,7 @@ def do_migrate(cs, args):
args.lock_volume) args.lock_volume)
print("Request to migrate volume %s has been accepted." % (volume.id)) print("Request to migrate volume %s has been accepted." % (volume.id))
except Exception as e: except Exception as e:
print("Migration for volume %s failed: %s." % (volume.id, print("Migration for volume %s failed: %s." % (volume.id, e))
six.text_type(e)))
@utils.arg('volume', metavar='<volume>', @utils.arg('volume', metavar='<volume>',

View File

@ -16,7 +16,7 @@
"""Group Type interface.""" """Group Type interface."""
from six.moves.urllib import parse from urllib import parse
from cinderclient import api_versions from cinderclient import api_versions
from cinderclient import base from cinderclient import base

View File

@ -137,7 +137,7 @@ class GroupManager(base.ManagerWithFind):
:param group_id: The ID of the group to get. :param group_id: The ID of the group to get.
:rtype: :class:`Group` :rtype: :class:`Group`
""" """
query_params = utils.unicode_key_value_to_string(kwargs) query_params = kwargs
query_string = utils.build_query_param(query_params, sort=True) query_string = utils.build_query_param(query_params, sort=True)
return self._get("/groups/%s" % group_id + query_string, return self._get("/groups/%s" % group_id + query_string,

View File

@ -19,7 +19,6 @@ import collections
import os import os
from oslo_utils import strutils from oslo_utils import strutils
import six
import cinderclient import cinderclient
from cinderclient import api_versions from cinderclient import api_versions
@ -60,7 +59,7 @@ def do_list_filters(cs, args):
@utils.arg('--filters', @utils.arg('--filters',
action=AppendFilters, action=AppendFilters,
type=six.text_type, type=str,
nargs='*', nargs='*',
start_version='3.52', start_version='3.52',
metavar='<key=value>', metavar='<key=value>',
@ -142,7 +141,7 @@ def do_type_list(cs, args):
'Default=None.') % ', '.join(base.SORT_KEY_VALUES))) 'Default=None.') % ', '.join(base.SORT_KEY_VALUES)))
@utils.arg('--filters', @utils.arg('--filters',
action=AppendFilters, action=AppendFilters,
type=six.text_type, type=str,
nargs='*', nargs='*',
start_version='3.33', start_version='3.33',
metavar='<key=value>', metavar='<key=value>',
@ -223,7 +222,7 @@ def do_backup_list(cs, args):
help='Show detailed information about pools.') help='Show detailed information about pools.')
@utils.arg('--filters', @utils.arg('--filters',
action=AppendFilters, action=AppendFilters,
type=six.text_type, type=str,
nargs='*', nargs='*',
start_version='3.33', start_version='3.33',
metavar='<key=value>', metavar='<key=value>',
@ -351,7 +350,7 @@ RESET_STATE_RESOURCES = {'volume': utils.find_volume,
help='Display information from single tenant (Admin only).') help='Display information from single tenant (Admin only).')
@utils.arg('--filters', @utils.arg('--filters',
action=AppendFilters, action=AppendFilters,
type=six.text_type, type=str,
nargs='*', nargs='*',
start_version='3.33', start_version='3.33',
metavar='<key=value>', metavar='<key=value>',
@ -629,7 +628,7 @@ def do_create(cs, args):
# NOTE(vish): multiple copies of same hint will # NOTE(vish): multiple copies of same hint will
# result in a list of values # result in a list of values
if key in hints: if key in hints:
if isinstance(hints[key], six.string_types): if isinstance(hints[key], str):
hints[key] = [hints[key]] hints[key] = [hints[key]]
hints[key] += [value] hints[key] += [value]
else: else:
@ -748,7 +747,7 @@ def do_summary(cs, args):
@api_versions.wraps('3.11') @api_versions.wraps('3.11')
@utils.arg('--filters', @utils.arg('--filters',
action=AppendFilters, action=AppendFilters,
type=six.text_type, type=str,
nargs='*', nargs='*',
start_version='3.52', start_version='3.52',
metavar='<key=value>', metavar='<key=value>',
@ -1031,7 +1030,7 @@ def do_migrate(cs, args):
print("Request to migrate volume %s has been accepted." % (volume.id)) print("Request to migrate volume %s has been accepted." % (volume.id))
except Exception as e: except Exception as e:
print("Migration for volume %s failed: %s." % (volume.id, print("Migration for volume %s failed: %s." % (volume.id,
six.text_type(e))) str(e)))
@api_versions.wraps('3.9') @api_versions.wraps('3.9')
@ -1338,7 +1337,7 @@ def do_manageable_list(cs, args):
help='Shows details for all tenants. Admin only.') help='Shows details for all tenants. Admin only.')
@utils.arg('--filters', @utils.arg('--filters',
action=AppendFilters, action=AppendFilters,
type=six.text_type, type=str,
nargs='*', nargs='*',
start_version='3.33', start_version='3.33',
metavar='<key=value>', metavar='<key=value>',
@ -1650,7 +1649,7 @@ def do_group_list_replication_targets(cs, args):
"%s" % FILTER_DEPRECATED) "%s" % FILTER_DEPRECATED)
@utils.arg('--filters', @utils.arg('--filters',
action=AppendFilters, action=AppendFilters,
type=six.text_type, type=str,
nargs='*', nargs='*',
start_version='3.33', start_version='3.33',
metavar='<key=value>', metavar='<key=value>',
@ -1902,7 +1901,7 @@ def do_revert_to_snapshot(cs, args):
"%s" % FILTER_DEPRECATED) "%s" % FILTER_DEPRECATED)
@utils.arg('--filters', @utils.arg('--filters',
action=AppendFilters, action=AppendFilters,
type=six.text_type, type=str,
nargs='*', nargs='*',
start_version='3.33', start_version='3.33',
metavar='<key=value>', metavar='<key=value>',
@ -2042,7 +2041,7 @@ def do_message_delete(cs, args):
"%s" % FILTER_DEPRECATED) "%s" % FILTER_DEPRECATED)
@utils.arg('--filters', @utils.arg('--filters',
action=AppendFilters, action=AppendFilters,
type=six.text_type, type=str,
nargs='*', nargs='*',
start_version='3.33', start_version='3.33',
metavar='<key=value>', metavar='<key=value>',
@ -2171,7 +2170,7 @@ def do_snapshot_list(cs, args):
help='Display information from single tenant (Admin only).') help='Display information from single tenant (Admin only).')
@utils.arg('--filters', @utils.arg('--filters',
action=AppendFilters, action=AppendFilters,
type=six.text_type, type=str,
nargs='*', nargs='*',
start_version='3.33', start_version='3.33',
metavar='<key=value>', metavar='<key=value>',
@ -2571,7 +2570,7 @@ def do_transfer_create(cs, args):
start_version='3.59') start_version='3.59')
@utils.arg('--filters', @utils.arg('--filters',
action=AppendFilters, action=AppendFilters,
type=six.text_type, type=str,
nargs='*', nargs='*',
start_version='3.52', start_version='3.52',
metavar='<key=value>', metavar='<key=value>',

View File

@ -15,7 +15,7 @@
"""Volume Type interface.""" """Volume Type interface."""
from six.moves.urllib import parse from urllib import parse
from cinderclient.apiclient import base as common_base from cinderclient.apiclient import base as common_base
from cinderclient import base from cinderclient import base

View File

@ -52,7 +52,6 @@ requests-mock==1.2.0
requests==2.23.0 requests==2.23.0
rfc3986==1.4.0 rfc3986==1.4.0
simplejson==3.5.1 simplejson==3.5.1
six==1.15.0
stestr==3.0.1 stestr==3.0.1
stevedore==3.2.2 stevedore==3.2.2
tempest==26.0.0 tempest==26.0.0

View File

@ -5,7 +5,6 @@ pbr>=5.5.0 # Apache-2.0
PrettyTable<0.8,>=0.7.2 # BSD PrettyTable<0.8,>=0.7.2 # BSD
keystoneauth1>=4.2.1 # Apache-2.0 keystoneauth1>=4.2.1 # Apache-2.0
simplejson>=3.5.1 # MIT simplejson>=3.5.1 # MIT
six>=1.15.0 # MIT
oslo.i18n>=5.0.1 # Apache-2.0 oslo.i18n>=5.0.1 # Apache-2.0
oslo.utils>=4.7.0 # Apache-2.0 oslo.utils>=4.7.0 # Apache-2.0
requests>=2.23.0 # Apache-2.0 requests>=2.23.0 # Apache-2.0

View File

@ -46,7 +46,6 @@ import subunit
import sys import sys
import unittest import unittest
import six
import testtools import testtools
@ -277,7 +276,7 @@ class NovaTestResult(testtools.TestResult):
self.stopTestRun() self.stopTestRun()
def stopTestRun(self): def stopTestRun(self):
for cls in list(six.iterkeys(self.results)): for cls in list(self.results.keys()):
self.writeTestCase(cls) self.writeTestCase(cls)
self.stream.writeln() self.stream.writeln()
self.writeSlowTests() self.writeSlowTests()

View File

@ -18,11 +18,10 @@
# License for the specific language governing permissions and limitations # License for the specific language governing permissions and limitations
# under the License. # under the License.
import configparser
import os import os
import sys import sys
from six.moves import configparser
import install_venv_common as install_venv import install_venv_common as install_venv

View File

@ -16,13 +16,13 @@
"""pylint error checking.""" """pylint error checking."""
from io import StringIO
import json import json
import re import re
import sys import sys
from pylint import lint from pylint import lint
from pylint.reporters import text from pylint.reporters import text
from six.moves import cStringIO as StringIO
ignore_codes = [ ignore_codes = [
# Note(maoy): E1103 is error code related to partial type inference # Note(maoy): E1103 is error code related to partial type inference