Remove six

Replace the following items with Python 3 style code.

- six.next
- six.text_type
- six.add_metaclass
- six.moves

Implements: blueprint six-removal

Change-Id: Id572aec8a6fda7676eb03d17c66fd33f9801f25d
This commit is contained in:
xuanyandong
2020-09-30 11:00:38 +08:00
committed by Pierre Riteau
parent 4f642c877f
commit ae43ea3adf
22 changed files with 44 additions and 74 deletions

View File

@@ -14,7 +14,6 @@
# limitations under the License.
from oslo_serialization import jsonutils
import six
from blazar.api.v1 import app as v1_app
from blazar.api.v2 import app as v2_app
@@ -36,7 +35,7 @@ class VersionSelectorApplication(object):
# whereas in case of v2, it returns list.
# So convert it to iterator to get the versions.
app_iter = iter(tmp_versions)
tmp_versions = jsonutils.loads(six.next(app_iter))
tmp_versions = jsonutils.loads(next(app_iter))
versions['versions'].extend(tmp_versions['versions'])
return tmp_versions

View File

@@ -14,7 +14,6 @@
# limitations under the License.
from oslo_serialization import jsonutils
import six
from blazar import context
from blazar import exceptions
@@ -35,7 +34,7 @@ def ctx_from_headers(headers):
"user_name": headers['X-User-Name'],
"project_name": headers['X-Project-Name'],
"roles": list(
map(six.text_type.strip, headers['X-Roles'].split(',')))}
map(str.strip, headers['X-Roles'].split(',')))}
# For v1 only, request_id and global_request_id will be available.
if headers.environ['PATH_INFO'].startswith('/v1'):

View File

@@ -18,15 +18,12 @@ import abc
from oslo_config import cfg
from oslo_log import log as logging
from pecan import rest
import six
LOG = logging.getLogger(__name__)
CONF = cfg.CONF
@six.add_metaclass(abc.ABCMeta)
class BaseController(rest.RestController):
class BaseController(rest.RestController, metaclass=abc.ABCMeta):
"""Mandatory API method name."""
name = None

View File

@@ -17,7 +17,6 @@ import datetime
import uuid
from oslo_serialization import jsonutils
import six
from wsme import types as wtypes
from wsme import utils as wutils
@@ -40,7 +39,7 @@ class UuidType(wtypes.UserType):
def validate(self, value):
try:
valid_uuid = six.text_type(uuid.UUID(value))
valid_uuid = str(uuid.UUID(value))
if self.without_dashes:
valid_uuid = valid_uuid.replace('-', '')
return valid_uuid
@@ -98,8 +97,7 @@ class TextOrInteger(wtypes.UserType):
@staticmethod
def validate(value):
# NOTE(sbauza): We need to accept non-unicoded Python2 strings
if (isinstance(value, six.text_type) or isinstance(value, str)
or isinstance(value, int)):
if (isinstance(value, str) or isinstance(value, int)):
return value
else:
raise exceptions.InvalidInput(cls=TextOrInteger.name, value=value)

View File

@@ -28,13 +28,12 @@ down_revision = None
import uuid
from alembic import op
import six
import sqlalchemy as sa
from sqlalchemy.dialects.mysql import MEDIUMTEXT
def _generate_unicode_uuid():
return six.text_type(str(uuid.uuid4()))
return str(uuid.uuid4())
def MediumText():

View File

@@ -15,7 +15,6 @@
from oslo_utils import uuidutils
import six
import sqlalchemy as sa
from sqlalchemy.dialects.mysql import MEDIUMTEXT
from sqlalchemy.orm import relationship
@@ -26,7 +25,7 @@ from blazar.db.sqlalchemy import model_base as mb
def _generate_unicode_uuid():
return six.text_type(uuidutils.generate_uuid())
return str(uuidutils.generate_uuid())
def MediumText():

View File

@@ -17,14 +17,12 @@ import abc
from oslo_config import cfg
from oslo_log import log as logging
import six
LOG = logging.getLogger(__name__)
CONF = cfg.CONF
@six.add_metaclass(abc.ABCMeta)
class BasePlugin(object):
class BasePlugin(object, metaclass=abc.ABCMeta):
resource_type = 'none'
title = None
@@ -106,8 +104,7 @@ class BasePlugin(object):
return options
@six.add_metaclass(abc.ABCMeta)
class BaseMonitorPlugin():
class BaseMonitorPlugin(metaclass=abc.ABCMeta):
"""Base class of monitor plugin."""
@abc.abstractmethod
def is_notification_enabled(self):

View File

@@ -15,7 +15,6 @@
import collections
import datetime
import retrying
import six
from novaclient import exceptions as nova_exceptions
from oslo_config import cfg
@@ -399,7 +398,7 @@ class VirtualInstancePlugin(base.BasePlugin, nova.NovaClientWrapper):
values['amount'] = strutils.validate_integer(
values['amount'], "amount", 1, db_api.DB_MAX_INT)
except ValueError as e:
raise mgr_exceptions.MalformedParameter(six.text_type(e))
raise mgr_exceptions.MalformedParameter(str(e))
if 'affinity' in values:
if (values['affinity'] not in NONE_VALUES and

View File

@@ -18,7 +18,6 @@ from keystonemiddleware import fixture
from oslo_utils import uuidutils
import pecan
import pecan.testing
import six
from blazar.api import context as api_context
from blazar import context
@@ -42,7 +41,7 @@ class APITest(tests.TestCase):
if not headers:
return context.BlazarContext(
user_id='fake', project_id='fake', roles=['member'])
roles = headers.get('X-Roles', six.text_type('member')).split(',')
roles = headers.get('X-Roles', str('member')).split(',')
return context.BlazarContext(
user_id=headers.get('X-User-Id', 'fake'),
project_id=headers.get('X-Project-Id', 'fake'),

View File

@@ -15,7 +15,6 @@
import flask
from oslo_utils import uuidutils
import six
from testtools import matchers
from oslo_middleware import request_id as id
@@ -82,7 +81,7 @@ class LeaseAPITestCase(tests.TestCase):
self.app = make_app()
self.headers = {'Accept': 'application/json',
'OpenStack-API-Version': 'reservation 1.0'}
self.lease_uuid = six.text_type(uuidutils.generate_uuid())
self.lease_uuid = str(uuidutils.generate_uuid())
self.mock_ctx = self.patch(api_context, 'ctx_from_headers')
self.mock_ctx.return_value = context.BlazarContext(
user_id='fake', project_id='fake', roles=['member'])

View File

@@ -16,7 +16,6 @@
import ddt
import flask
from oslo_utils import uuidutils
import six
from testtools import matchers
from oslo_middleware import request_id as id
@@ -85,7 +84,7 @@ class OsHostAPITestCase(tests.TestCase):
self.app = make_app()
self.headers = {'Accept': 'application/json',
'OpenStack-API-Version': 'reservation 1.0'}
self.host_id = six.text_type('1')
self.host_id = str('1')
self.mock_ctx = self.patch(api_context, 'ctx_from_headers')
self.mock_ctx.return_value = context.BlazarContext(
user_id='fake', project_id='fake', roles=['member'])
@@ -223,16 +222,16 @@ class OsHostAPITestCase(tests.TestCase):
headers=self.headers)
self._assert_response(res, 200, {}, key='allocation')
@ddt.data({'lease_id': six.text_type(uuidutils.generate_uuid()),
'reservation_id': six.text_type(uuidutils.generate_uuid())})
@ddt.data({'lease_id': str(uuidutils.generate_uuid()),
'reservation_id': str(uuidutils.generate_uuid())})
def test_allocation_list_with_query_params(self, query_params):
with self.app.test_client() as c:
res = c.get('/v1/allocations?{0}'.format(query_params),
headers=self.headers)
self._assert_response(res, 200, {}, key='allocations')
@ddt.data({'lease_id': six.text_type(uuidutils.generate_uuid()),
'reservation_id': six.text_type(uuidutils.generate_uuid())})
@ddt.data({'lease_id': str(uuidutils.generate_uuid()),
'reservation_id': str(uuidutils.generate_uuid())})
def test_allocation_get_with_query_params(self, query_params):
with self.app.test_client() as c:
res = c.get('/v1/{0}/allocation?{1}'.format(

View File

@@ -14,7 +14,6 @@
# limitations under the License.
import ddt
import six
from blazar.api.v1 import api_version_request
from blazar import exceptions
@@ -114,7 +113,7 @@ class APIVersionRequestTests(tests.TestCase):
def test_str(self, major, minor):
request_input = '%s.%s' % (major, minor)
request = api_version_request.APIVersionRequest(request_input)
request_string = six.text_type(request)
request_string = str(request)
self.assertEqual('API Version Request '
'Major: %s, Minor: %s' % (major, minor),

View File

@@ -15,8 +15,6 @@
Tests for API /os-hosts/ methods
"""
from oslo_utils import uuidutils
import six
from blazar.tests import api
from blazar.utils import trusts
@@ -121,8 +119,8 @@ class TestListHosts(api.APITest):
self.assertEqual([fake_computehost(id=1)], response)
def test_multiple(self):
id1 = six.text_type('1')
id2 = six.text_type('2')
id1 = str('1')
id2 = str('2')
self.patch(
self.hosts_rpcapi, 'list_computehosts').return_value = [
fake_computehost_from_rpc(id=id1),
@@ -155,7 +153,7 @@ class TestShowHost(api.APITest):
def setUp(self):
super(TestShowHost, self).setUp()
self.id1 = six.text_type('1')
self.id1 = str('1')
self.path = '/os-hosts/{0}'.format(self.id1)
self.patch(
self.hosts_rpcapi, 'get_computehost'
@@ -204,7 +202,7 @@ class TestCreateHost(api.APITest):
def setUp(self):
super(TestCreateHost, self).setUp()
self.id1 = six.text_type(uuidutils.generate_uuid())
self.id1 = str(uuidutils.generate_uuid())
self.fake_computehost = fake_computehost(id=self.id1)
self.fake_computehost_body = fake_computehost_request_body(id=self.id1)
self.path = '/os-hosts'
@@ -290,7 +288,7 @@ class TestUpdateHost(api.APITest):
def setUp(self):
super(TestUpdateHost, self).setUp()
self.id1 = six.text_type('1')
self.id1 = str('1')
self.fake_computehost = fake_computehost(id=self.id1, name='updated')
self.fake_computehost_body = fake_computehost_request_body(
exclude=['reservations', 'events'],
@@ -362,7 +360,7 @@ class TestDeleteHost(api.APITest):
def setUp(self):
super(TestDeleteHost, self).setUp()
self.id1 = six.text_type('1')
self.id1 = str('1')
self.path = '/os-hosts/{0}'.format(self.id1)
self.patch(self.hosts_rpcapi, 'delete_computehost')
self.headers = {'X-Roles': 'admin'}

View File

@@ -15,8 +15,6 @@
Tests for API /leases/ methods
"""
from oslo_utils import uuidutils
import six
from blazar.tests import api
from blazar.utils import trusts
@@ -102,8 +100,8 @@ class TestListLeases(api.APITest):
self.assertEqual([self.fake_lease], response)
def test_multiple(self):
id1 = six.text_type(uuidutils.generate_uuid())
id2 = six.text_type(uuidutils.generate_uuid())
id1 = str(uuidutils.generate_uuid())
id2 = str(uuidutils.generate_uuid())
self.patch(
self.rpcapi, 'list_leases').return_value = [
fake_lease(id=id1),
@@ -133,7 +131,7 @@ class TestShowLease(api.APITest):
def setUp(self):
super(TestShowLease, self).setUp()
self.id1 = six.text_type(uuidutils.generate_uuid())
self.id1 = str(uuidutils.generate_uuid())
self.fake_lease = fake_lease(id=self.id1)
self.path = '/leases/{0}'.format(self.id1)
self.patch(self.rpcapi, 'get_lease').return_value = self.fake_lease
@@ -178,7 +176,7 @@ class TestCreateLease(api.APITest):
def setUp(self):
super(TestCreateLease, self).setUp()
self.id1 = six.text_type(uuidutils.generate_uuid())
self.id1 = str(uuidutils.generate_uuid())
self.fake_lease = fake_lease(id=self.id1)
self.fake_lease_body = fake_lease_request_body(id=self.id1)
self.path = '/leases'
@@ -256,7 +254,7 @@ class TestUpdateLease(api.APITest):
def setUp(self):
super(TestUpdateLease, self).setUp()
self.id1 = six.text_type(uuidutils.generate_uuid())
self.id1 = str(uuidutils.generate_uuid())
self.fake_lease = fake_lease(id=self.id1, name='updated')
self.fake_lease_body = fake_lease_request_body(
exclude=['reservations', 'events'],
@@ -336,7 +334,7 @@ class TestDeleteLease(api.APITest):
def setUp(self):
super(TestDeleteLease, self).setUp()
self.id1 = six.text_type(uuidutils.generate_uuid())
self.id1 = str(uuidutils.generate_uuid())
self.path = '/leases/{0}'.format(self.id1)
self.patch(self.rpcapi, 'delete_lease')

View File

@@ -22,11 +22,11 @@
# There is an ongoing work to extact similar code to oslo incubator. Once it is
# extracted we'll be able to remove this file and use oslo.
import configparser
import io
import os
from six.moves import configparser
from six.moves.urllib import parse as urlparse
import subprocess
from urllib import parse as urlparse
from alembic import command
from alembic import config as alembic_config

View File

@@ -18,7 +18,6 @@ import datetime
from oslo_context import context
from oslo_utils import uuidutils
import six
from blazar.db.sqlalchemy import api as db_api
from blazar.db.sqlalchemy import utils as db_utils
@@ -27,7 +26,7 @@ from blazar import tests
def _get_fake_random_uuid():
return six.text_type(uuidutils.generate_uuid())
return str(uuidutils.generate_uuid())
def _get_fake_lease_uuid():

View File

@@ -18,9 +18,9 @@ from unittest import mock
import ddt
import eventlet
import importlib
from oslo_config import cfg
import oslo_messaging as messaging
from six.moves import reload_module
from stevedore import enabled
import testtools
@@ -130,7 +130,7 @@ class ServiceTestCase(tests.TestCase):
with mock.patch('blazar.status.lease.lease_status',
FakeLeaseStatus.lease_status):
reload_module(service)
importlib.reload(service)
self.service = service
self.manager = self.service.ManagerService()

View File

@@ -19,7 +19,6 @@ import uuid
import ddt
from novaclient import exceptions as nova_exceptions
import six
from blazar import context
from blazar.db import api as db_api
@@ -78,7 +77,7 @@ class TestVirtualInstancePlugin(tests.TestCase):
}
def get_uuid(self):
return six.text_type(str(uuid.uuid4()))
return str(uuid.uuid4())
def generate_basic_events(self, lease_id, start, before_end, end):
return [

View File

@@ -13,8 +13,6 @@
# See the License for the specific language governing permissions and
# limitations under the License.
import six
from blazar import exceptions
from blazar import tests
@@ -25,18 +23,17 @@ class BlazarExceptionTestCase(tests.TestCase):
msg_fmt = "default message"
exc = FakeBlazarException()
self.assertEqual('default message', six.text_type(exc))
self.assertEqual('default message', str(exc))
def test_error_msg(self):
self.assertEqual('test',
six.text_type(exceptions.BlazarException('test')))
str(exceptions.BlazarException('test')))
def test_default_error_msg_with_kwargs(self):
class FakeBlazarException(exceptions.BlazarException):
msg_fmt = "default message: %(code)s"
exc = FakeBlazarException(code=500)
self.assertEqual('default message: 500', six.text_type(exc))
self.assertEqual('default message: 500', str(exc))
def test_error_msg_exception_with_kwargs(self):
@@ -44,7 +41,6 @@ class BlazarExceptionTestCase(tests.TestCase):
msg_fmt = "default message: %(mispelled_code)s"
exc = FakeBlazarException(code=500, mispelled_code='blah')
self.assertEqual('default message: blah', six.text_type(exc))
self.assertEqual('default message: blah', str(exc))
def test_default_error_code(self):
@@ -64,5 +60,5 @@ class BlazarExceptionTestCase(tests.TestCase):
def test_policynotauthorized_exception(self):
exc = exceptions.PolicyNotAuthorized(action='foo')
self.assertEqual("Policy doesn't allow foo to be performed",
six.text_type(exc))
str(exc))
self.assertEqual(403, exc.kwargs['code'])

View File

@@ -15,7 +15,6 @@
import copy
from oslo_serialization import jsonutils
import six
from blazar.manager import exceptions as manager_ex
@@ -28,7 +27,7 @@ def convert_requirements(requirements):
"""
# TODO(frossigneux) Support the "or" operator
# Convert text to json
if isinstance(requirements, six.string_types):
if isinstance(requirements, str):
# Treat empty string as an empty JSON array, to avoid raising a
# ValueError exception while loading JSON
#
@@ -64,9 +63,9 @@ def _requirements_with_three_elements(requirements):
"""Return true if requirement list looks like ['<', '$ram', '1024']."""
return (isinstance(requirements, list) and
len(requirements) == 3 and
isinstance(requirements[0], six.string_types) and
isinstance(requirements[1], six.string_types) and
isinstance(requirements[2], six.string_types) and
isinstance(requirements[0], str) and
isinstance(requirements[1], str) and
isinstance(requirements[2], str) and
requirements[0] in ['==', '=', '!=', '>=', '<=', '>', '<'] and
len(requirements[1]) > 1 and requirements[1][0] == '$' and
len(requirements[2]) > 0)
@@ -74,7 +73,7 @@ def _requirements_with_three_elements(requirements):
def _requirements_with_and_keyword(requirements):
return (len(requirements) > 1 and
isinstance(requirements[0], six.string_types) and
isinstance(requirements[0], str) and
requirements[0] == 'and' and
all(convert_requirements(x) for x in requirements[1:]))

View File

@@ -91,7 +91,6 @@ rfc3986==1.1.0
Routes==2.3.1
simplegeneric==0.8.1
simplejson==3.13.2
six==1.10.0
snowballstemmer==1.2.1
Sphinx==2.0.0
sphinxcontrib-websupport==1.0.1

View File

@@ -32,7 +32,6 @@ sqlalchemy-migrate>=0.11.0 # Apache-2.0
requests>=2.18.4 # Apache-2.0
retrying>=1.3.3,!=1.3.0 # Apache-2.0
Routes>=2.3.1 # MIT
six>=1.10.0 # MIT
SQLAlchemy!=1.1.5,!=1.1.6,!=1.1.7,!=1.1.8,>=1.0.10 # MIT
stevedore>=1.20.0 # Apache-2.0
WebOb>=1.7.1 # MIT